-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathEntryShell.amr-workspace-race.test.tsx
More file actions
301 lines (278 loc) · 9.6 KB
/
Copy pathEntryShell.amr-workspace-race.test.tsx
File metadata and controls
301 lines (278 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import {
buildWorkspacePermissions,
buildWorkspaceSeatSummary,
type WorkspaceCollabContext,
} from '@open-design/contracts';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { EntryShell } from '../../src/components/EntryShell';
import {
notifyWorkspaceContextRefresh,
resetTeamProjectsCache,
resetWorkspaceBillingCache,
resetWorkspaceContextCache,
} from '../../src/collab/useWorkspaceContext';
import { I18nProvider } from '../../src/i18n';
import { checkAmrBalanceGate } from '../../src/runtime/amr-balance-gate';
import type { AgentInfo, AppConfig } from '../../src/types';
import { setHomeHeroPrompt } from '../helpers/home-hero-lexical';
vi.mock('../../src/runtime/amr-balance-gate', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/runtime/amr-balance-gate')>();
return {
...actual,
checkAmrBalanceGate: vi.fn(),
};
});
const mockedCheckAmrBalanceGate = vi.mocked(checkAmrBalanceGate);
const originalFetch = globalThis.fetch;
const originalResizeObserver = globalThis.ResizeObserver;
class ResizeObserverMock {
observe() {}
disconnect() {}
unobserve() {}
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((next) => {
resolve = next;
});
return { promise, resolve };
}
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}
function teamContext(workspaceId: string, workspaceMemberId: string): WorkspaceCollabContext {
const role = 'member' as const;
const lifecycleState = 'active' as const;
return {
workspaceId,
workspaceType: 'team',
workspaceMemberId,
role,
memberStatus: 'active',
lifecycleState,
billingState: 'active',
planId: 'team_plus',
providerMode: 'platform_credits',
seatSummary: buildWorkspaceSeatSummary({ seatLimit: 5, usedSeats: 1 }),
permissions: buildWorkspacePermissions({ role, lifecycleState }),
};
}
function amrAgent(): AgentInfo {
return {
id: 'amr',
name: 'Open Design AMR',
bin: 'amr',
available: true,
models: [{ id: 'glm-5', label: 'GLM 5' }],
};
}
function amrConfig(): AppConfig {
return {
mode: 'daemon',
agentId: 'amr',
agentModels: { amr: { model: 'glm-5' } },
apiProtocol: 'anthropic',
apiProtocolConfigs: {},
apiKey: '',
baseUrl: '',
model: '',
skillId: null,
designSystemId: null,
theme: 'system',
};
}
describe('EntryShell AMR workspace precheck race', () => {
beforeEach(() => {
globalThis.ResizeObserver = ResizeObserverMock as typeof ResizeObserver;
resetWorkspaceContextCache();
resetWorkspaceBillingCache();
resetTeamProjectsCache();
});
afterEach(() => {
cleanup();
globalThis.fetch = originalFetch;
globalThis.ResizeObserver = originalResizeObserver;
mockedCheckAmrBalanceGate.mockReset();
resetWorkspaceContextCache();
resetWorkspaceBillingCache();
resetTeamProjectsCache();
});
it('keeps a locally signed-in account in syncing state while Cloud is unavailable', async () => {
window.history.replaceState(null, '', '/');
const contextFailure = deferred<Response>();
let contextReads = 0;
globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith('/api/workspace/context')) {
contextReads += 1;
return contextFailure.promise;
}
if (url.endsWith('/api/plugins')) return jsonResponse({ plugins: [] });
if (url.endsWith('/api/mcp/servers')) return jsonResponse({ servers: [] });
if (url.endsWith('/api/community/discord')) return jsonResponse({ stale: true });
if (url.endsWith('/api/github/open-design')) return jsonResponse({ stale: true });
return jsonResponse({});
}) as typeof fetch;
render(
<I18nProvider initial="en">
<EntryShell
skills={[]}
designTemplates={[]}
designSystems={[]}
projects={[]}
templates={[]}
promptTemplates={[]}
defaultDesignSystemId={null}
connectors={[]}
connectorsLoading={false}
config={amrConfig()}
agents={[amrAgent()]}
amrLoggedIn
daemonLive
onModeChange={vi.fn()}
onAgentChange={vi.fn()}
onAgentModelChange={vi.fn()}
onApiProtocolChange={vi.fn()}
onApiModelChange={vi.fn()}
onConfigPersist={vi.fn()}
onRefreshAgents={vi.fn(() => [amrAgent()])}
onCreateProject={vi.fn()}
onCreatePluginShareProject={vi.fn()}
onImportClaudeDesign={vi.fn()}
onOpenProject={vi.fn()}
onOpenLiveArtifact={vi.fn()}
onDeleteProject={vi.fn()}
onRenameProject={vi.fn()}
onChangeDefaultDesignSystem={vi.fn()}
onPersistComposioKey={vi.fn()}
onOpenSettings={vi.fn()}
onCompleteOnboarding={vi.fn()}
/>
</I18nProvider>,
);
expect(await screen.findByTestId('entry-rail-account-sync-tip')).toBeTruthy();
expect(contextReads).toBe(1);
await act(async () => {
contextFailure.resolve(new Response(null, { status: 503 }));
await contextFailure.promise;
await Promise.resolve();
});
expect(screen.queryByTestId('entry-cloud-signin-tip')).toBeNull();
expect(screen.getByTestId('entry-rail-account-sync-tip')).toBeTruthy();
});
it('rechecks workspace B when the workspace switches after workspace A passes the gate', async () => {
window.history.replaceState(null, '', '/');
const workspaceA = teamContext('workspace-a', 'member-a');
const workspaceB = teamContext('workspace-b', 'member-b');
let currentContext = workspaceA;
let contextReads = 0;
globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith('/api/workspace/context')) {
contextReads += 1;
return jsonResponse({ context: currentContext });
}
if (url.includes('/api/workspace/billing?')) {
return jsonResponse({
summary: null,
workspaceBalance: {
billingScopeVersion: 2,
workspaceId: currentContext.workspaceId,
workspaceMemberId: currentContext.workspaceMemberId,
balanceUsd: '25.00',
expiresAt: null,
updatedAt: null,
},
});
}
if (url.endsWith('/api/workspace/projects/team')) {
return jsonResponse({ projects: [] });
}
if (url.endsWith('/api/plugins')) return jsonResponse({ plugins: [] });
if (url.endsWith('/api/mcp/servers')) return jsonResponse({ servers: [] });
if (url.endsWith('/api/community/discord')) return jsonResponse({ stale: true });
if (url.endsWith('/api/github/open-design')) return jsonResponse({ stale: true });
return jsonResponse({});
}) as typeof fetch;
const gateA = deferred<{ kind: 'allow' }>();
mockedCheckAmrBalanceGate
.mockImplementationOnce(() => gateA.promise)
.mockResolvedValueOnce({ kind: 'allow' });
const onCreateProject = vi.fn(async () => true);
render(
<I18nProvider initial="en">
<EntryShell
skills={[]}
designTemplates={[]}
designSystems={[]}
projects={[]}
templates={[]}
promptTemplates={[]}
defaultDesignSystemId={null}
connectors={[]}
connectorsLoading={false}
config={amrConfig()}
agents={[amrAgent()]}
daemonLive
onModeChange={vi.fn()}
onAgentChange={vi.fn()}
onAgentModelChange={vi.fn()}
onApiProtocolChange={vi.fn()}
onApiModelChange={vi.fn()}
onConfigPersist={vi.fn()}
onRefreshAgents={vi.fn(() => [amrAgent()])}
onCreateProject={onCreateProject}
onCreatePluginShareProject={vi.fn()}
onImportClaudeDesign={vi.fn()}
onOpenProject={vi.fn()}
onOpenLiveArtifact={vi.fn()}
onDeleteProject={vi.fn()}
onRenameProject={vi.fn()}
onChangeDefaultDesignSystem={vi.fn()}
onPersistComposioKey={vi.fn()}
onOpenSettings={vi.fn()}
onCompleteOnboarding={vi.fn()}
/>
</I18nProvider>,
);
await waitFor(() => expect(contextReads).toBeGreaterThan(0));
setHomeHeroPrompt('Build a workspace-scoped landing page');
fireEvent.click(await screen.findByTestId('home-hero-submit'));
await waitFor(() => {
expect(mockedCheckAmrBalanceGate).toHaveBeenNthCalledWith(1, {
workspaceType: 'team',
workspaceId: 'workspace-a',
workspaceMemberId: 'member-a',
});
});
currentContext = workspaceB;
act(() => notifyWorkspaceContextRefresh());
await waitFor(() => expect(contextReads).toBeGreaterThan(1));
await act(async () => {
gateA.resolve({ kind: 'allow' });
await gateA.promise;
});
await waitFor(() => {
expect(mockedCheckAmrBalanceGate).toHaveBeenNthCalledWith(2, {
workspaceType: 'team',
workspaceId: 'workspace-b',
workspaceMemberId: 'member-b',
});
});
await waitFor(() => expect(onCreateProject).toHaveBeenCalledTimes(1));
expect(onCreateProject).toHaveBeenCalledWith(
expect.objectContaining({
amrGatePrecheckWitness: {
workspaceType: 'team',
workspaceId: 'workspace-b',
workspaceMemberId: 'member-b',
},
}),
);
});
});