Repository navigation
Expand file tree
/
Copy pathApp.test.tsx
More file actions
1618 lines (1590 loc) · 56.4 KB
/
Copy pathApp.test.tsx
File metadata and controls
1618 lines (1590 loc) · 56.4 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { providerFixture } from "./providerFixture";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
cleanup,
act,
fireEvent,
render,
screen,
waitFor,
within,
} from "@testing-library/react";
import App from "./App";
import { QuotaWindow } from "./views/Usage";
import { conversationEvents, eventText } from "./ui";
import { ApiError, remainingPercent, request } from "./api";
import { demoState } from "./demo";
import type { DockState } from "./types";
import { StrictMode } from "react";
const state: DockState = {
projects: [
{ id: "project-a", name: "Demo project", path: "/example/workspace" },
],
agents: [
{
id: "agent-a",
project_id: "project-a",
provider: "codex",
name: "Review agent",
role: "Review changes",
},
],
sessions: [
{
id: "session-a",
project_id: "project-a",
agent_id: "agent-a",
title: "First task",
status: "idle",
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
],
messages: [],
memories: [
{
id: "memory-a",
project_id: "project-a",
key: "project.stack",
content: "Original reviewed content",
version: 3,
},
],
proposals: [],
quotas: [],
approvals: [],
subscriptions: [],
runtime: { enabled: false, version: "0.1.0" },
};
function response(value: unknown, status = 200) {
return {
ok: status >= 200 && status < 300,
status,
json: async () => value,
} as Response;
}
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
fetchMock = vi.fn(async (path: string) =>
response(
path.startsWith("/api/providers?")
? providerFixture(path)
: path.includes("/events?")
? { events: [] }
: state,
),
);
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
cleanup();
delete window.__AGENTDOCK_DESKTOP_TOKEN__;
delete window.__AGENTDOCK_DESKTOP_LANGUAGE__;
delete window.webkit;
window.history.replaceState({}, "", "/");
vi.unstubAllGlobals();
});
function openProjects() {
fireEvent.click(
within(screen.getByRole("navigation", { name: "主导航" })).getByRole(
"button",
{ name: "项目" },
),
);
}
function openProject(name = "Demo project") {
openProjects();
fireEvent.click(screen.getByRole("button", { name: `打开项目 ${name}` }));
}
describe("desktop connection and built-in usage", () => {
it("restores the desktop language and keeps the native menu in sync", async () => {
const postMessage = vi.fn();
window.__AGENTDOCK_DESKTOP_TOKEN__ = "native-fixture-token";
window.__AGENTDOCK_DESKTOP_LANGUAGE__ = "en";
window.webkit = { messageHandlers: { agentdockLanguage: { postMessage } } };
render(<App />);
await screen.findByRole("heading", { name: "Workspace" });
expect(postMessage).toHaveBeenCalledWith("en");
fireEvent.click(screen.getByRole("button", { name: "切换为中文" }));
expect(postMessage).toHaveBeenLastCalledWith("zh");
expect(screen.getByRole("heading", { name: "协作工作台" })).toBeTruthy();
});
it("localizes expired cache guidance without hiding the last known quota", async () => {
fetchMock.mockImplementation(async () =>
response({
...state,
quotas: [
{
provider: "codex",
source: "AgentDock",
status: "stale",
error_code: "outdated_cache",
error: "Cached quota is outdated. Refresh to read current limits.",
windows: [{ label: "Weekly", remaining_percent: 95 }],
},
],
}),
);
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
expect(await screen.findByText("待更新")).toBeTruthy();
expect(
screen.queryByText(
"Cached quota is outdated. Refresh to read current limits.",
),
).toBeNull();
expect(screen.getByText(/95%/)).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Switch to English" }));
expect(screen.getByText("Update pending")).toBeTruthy();
});
it("connects from the native in-memory credential in StrictMode without persisting it", async () => {
window.__AGENTDOCK_DESKTOP_TOKEN__ = "native-fixture-token";
render(
<StrictMode>
<App />
</StrictMode>,
);
await screen.findByRole("heading", { name: "协作工作台" });
expect(window.__AGENTDOCK_DESKTOP_TOKEN__).toBeUndefined();
expect(window.location.href).not.toContain("native-fixture-token");
expect(JSON.stringify(localStorage)).not.toContain("native-fixture-token");
expect(document.body.textContent).not.toContain("native-fixture-token");
expect(
fetchMock.mock.calls.some(
([, options]) =>
options?.headers?.Authorization === "Bearer native-fixture-token",
),
).toBe(true);
});
it("never exposes Keychain authorization and labels the local source time", async () => {
fetchMock.mockImplementation(async () =>
response({
...state,
agents: [{ ...state.agents[0], provider: "claude" }],
quotas: [
{
provider: "claude",
source: "legacy_snapshot",
windows: [],
status: "stale",
fetched_at: "2026-01-01T00:00:00Z",
},
],
}),
);
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
expect(screen.queryByRole("button", { name: /连接 Claude/ })).toBeNull();
expect(screen.getByText(/来源:升级前记录/)).toBeTruthy();
expect(
fetchMock.mock.calls.every(([path]) => path !== "/api/quotas/authorize"),
).toBe(true);
});
});
async function connect() {
fireEvent.change(screen.getByLabelText("访问令牌"), {
target: { value: "example-admin-token-not-a-real-secret" },
});
fireEvent.click(screen.getByRole("button", { name: "进入工作台" }));
await screen.findByRole("heading", { name: "协作工作台" });
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
async function chooseProvider(provider: string) {
fireEvent.click(screen.getByRole("combobox", { name: "服务" }));
fireEvent.click(
await screen.findByRole("option", {
name: provider === "claude" ? "Claude Code" : "Codex",
}),
);
}
describe("user-defined agent roles", () => {
it.each(["codex", "claude"])(
"creates %s agents without assigning a role",
async (provider) => {
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: "添加 Agent" }));
const name = screen.getByLabelText("名称") as HTMLInputElement;
const role = screen.getByLabelText(
"角色说明(可选)",
) as HTMLTextAreaElement;
expect(name.value).toBe("");
expect(role.value).toBe("");
fireEvent.change(name, { target: { value: "My helper" } });
fireEvent.change(role, { target: { value: "Research requirements" } });
await chooseProvider("claude");
await chooseProvider("codex");
expect(role.value).toBe("Research requirements");
await chooseProvider(provider);
fireEvent.change(role, { target: { value: "" } });
fireEvent.click(screen.getByRole("button", { name: "创建 Agent" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.some(([path]) => path === "/api/agents"),
).toBe(true),
);
const call = fetchMock.mock.calls.find(
([path]) => path === "/api/agents",
)!;
expect(JSON.parse(call[1].body)).toEqual({
environment_id: "local",
project_id: null,
workspace: null,
model: null,
effort: null,
permission_mode: "ask",
run_timeout: null,
name: "My helper",
provider,
role: "",
});
},
);
it("saves a new name and clears the role while keeping the selected native session", async () => {
let current = {
...state,
sessions: [
{ ...state.sessions[0], native_session_id: "existing-native-session" },
],
};
fetchMock.mockImplementation(
async (path: string, options?: RequestInit) => {
if (path === "/api/agents/agent-a") {
const agent = {
...current.agents[0],
...JSON.parse(options!.body as string),
};
current = { ...current, agents: [agent] };
return response(agent);
}
return response(path.includes("/events?") ? { events: [] } : current);
},
);
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: /^Review agent/ }));
fireEvent.click(screen.getByRole("button", { name: "设置 Review agent" }));
expect((screen.getByLabelText("服务") as HTMLButtonElement).disabled).toBe(
true,
);
expect(
(screen.getByLabelText("角色说明(可选)") as HTMLTextAreaElement).value,
).toBe("Review changes");
fireEvent.change(screen.getByLabelText("名称"), {
target: { value: "Custom helper" },
});
fireEvent.change(screen.getByLabelText("角色说明(可选)"), {
target: { value: "" },
});
fireEvent.click(screen.getByRole("button", { name: "保存设置" }));
await screen.findByRole("button", { name: "设置 Custom helper" });
await waitFor(() =>
expect(screen.queryByRole("button", { name: "保存设置" })).toBeNull(),
);
expect(current.agents[0].role).toBe("");
expect(current.sessions[0].native_session_id).toBe(
"existing-native-session",
);
expect(screen.getByRole("heading", { name: "First task" })).toBeTruthy();
const call = fetchMock.mock.calls.find(
([path]) => path === "/api/agents/agent-a",
)!;
expect(JSON.parse(call[1].body)).toEqual({
run_timeout: null,
name: "Custom helper",
role: "",
environment_id: "local",
model: null,
effort: null,
permission_mode: "ask",
});
expect(current.agents[0].provider).toBe("codex");
fireEvent.click(screen.getByRole("button", { name: "设置 Custom helper" }));
expect(
(screen.getByLabelText("角色说明(可选)") as HTMLTextAreaElement).value,
).toBe("");
});
it("keeps an unsuccessful edit as a draft and lets the user cancel without writing", async () => {
fetchMock.mockImplementation(async (path: string) => {
if (path.startsWith("/api/providers?"))
return response(providerFixture(path));
if (path === "/api/agents/agent-a")
return response({ error: "Temporary save failure" }, 500);
return response(
path.startsWith("/api/providers?")
? providerFixture(path)
: path.includes("/events?")
? { events: [] }
: state,
);
});
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: /^Review agent/ }));
fireEvent.click(screen.getByRole("button", { name: "设置 Review agent" }));
fireEvent.change(screen.getByLabelText("角色说明(可选)"), {
target: { value: "My unsaved role" },
});
fireEvent.click(screen.getByRole("button", { name: "保存设置" }));
await screen.findByText("Temporary save failure");
expect(
(screen.getByLabelText("角色说明(可选)") as HTMLTextAreaElement).value,
).toBe("My unsaved role");
expect(state.agents[0].role).toBe("Review changes");
fireEvent.click(screen.getByRole("button", { name: "取消编辑 Agent" }));
fireEvent.click(screen.getByRole("button", { name: "返回 Agent 列表" }));
fireEvent.click(screen.getByRole("button", { name: "添加 Agent" }));
expect((screen.getByLabelText("名称") as HTMLInputElement).value).toBe("");
expect(
(screen.getByLabelText("角色说明(可选)") as HTMLTextAreaElement).value,
).toBe("");
expect((screen.getByLabelText("服务") as HTMLButtonElement).disabled).toBe(
false,
);
expect(
fetchMock.mock.calls.filter(([path]) => path === "/api/agents/agent-a"),
).toHaveLength(1);
});
it("translates role controls without changing user content", async () => {
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: /^Review agent/ }));
fireEvent.click(screen.getByRole("button", { name: "设置 Review agent" }));
fireEvent.click(screen.getByRole("button", { name: "Switch to English" }));
expect(
screen.getByRole("heading", { name: "Edit agent · Review agent" }),
).toBeTruthy();
expect(
(screen.getByLabelText("Role (optional)") as HTMLTextAreaElement).value,
).toBe("Review changes");
expect(screen.getByRole("button", { name: "Save settings" })).toBeTruthy();
expect(screen.queryByText("角色说明(可选)")).toBeNull();
});
it("shows no fixed provider roles in either demo language and never saves demo edits", async () => {
for (const lang of ["zh", "en"] as const) {
expect(
demoState(lang).agents.map((agent) => [agent.name, agent.role]),
).toEqual([
["Agent A", ""],
["Agent B", ""],
]);
}
window.history.replaceState({}, "", "/?demo=1");
render(<App />);
await screen.findByRole("heading", { name: "协作工作台" });
fireEvent.click(screen.getByRole("button", { name: /^Agent A/ }));
fireEvent.click(screen.getByRole("button", { name: "设置 Agent A" }));
expect(
(screen.getByRole("button", { name: "保存设置" }) as HTMLButtonElement)
.disabled,
).toBe(true);
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("selection after delayed mutation refresh", () => {
it("selects a new project only after its refreshed state is available", async () => {
const project = {
id: "project-new",
name: "New project",
path: "/example/new",
};
const refreshed = deferred<Response>();
let created = false;
fetchMock.mockImplementation(async (path: string) => {
if (path.startsWith("/api/providers?"))
return response(providerFixture(path));
if (path === "/api/projects") {
created = true;
return response(project);
}
if (path === "/api/state")
return created ? refreshed.promise : response(state);
return response({ events: [] });
});
render(<App />);
await connect();
openProjects();
fireEvent.click(screen.getByRole("button", { name: "新建项目" }));
fireEvent.change(screen.getByLabelText("项目名称"), {
target: { value: project.name },
});
fireEvent.change(screen.getByLabelText("工作目录(绝对路径)"), {
target: { value: project.path },
});
fireEvent.click(screen.getByRole("button", { name: "创建项目" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.filter(([path]) => path === "/api/state"),
).toHaveLength(2),
);
expect(window.location.hash).toBe("#/projects");
expect(screen.getByLabelText("项目名称")).toBeTruthy();
await act(async () => {
refreshed.resolve(
response({ ...state, projects: [...state.projects, project] }),
);
});
await waitFor(() =>
expect(
(screen.getByLabelText("切换项目") as HTMLSelectElement).value,
).toBe(project.id),
);
expect(screen.queryByRole("button", { name: /Review agent/ })).toBeNull();
});
it("keeps the newly created agent selected after delayed refresh", async () => {
const agent = {
id: "agent-new",
project_id: "project-a",
provider: "claude",
name: "New helper",
role: "Review",
};
const refreshed = deferred<Response>();
let created = false;
fetchMock.mockImplementation(async (path: string) => {
if (path.startsWith("/api/providers?"))
return response(providerFixture(path));
if (path === "/api/projects/project-a/agents") {
created = true;
return response(agent);
}
if (path === "/api/state")
return created ? refreshed.promise : response(state);
return response({ events: [] });
});
render(<App />);
await connect();
openProject();
fireEvent.click(screen.getByRole("button", { name: "Agent" }));
fireEvent.click(screen.getByRole("button", { name: "添加 Agent" }));
fireEvent.change(screen.getByLabelText("项目内名称"), {
target: { value: agent.name },
});
fireEvent.change(screen.getByLabelText("使用 Agent"), {
target: { value: "agent-a" },
});
fireEvent.change(screen.getByLabelText("项目内名称"), {
target: { value: agent.name },
});
fireEvent.click(screen.getByRole("button", { name: "添加到项目" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.filter(([path]) => path === "/api/state"),
).toHaveLength(2),
);
await act(async () => {
refreshed.resolve(
response({ ...state, agents: [...state.agents, agent] }),
);
});
await screen.findByRole("heading", { name: "New helper", level: 1 });
expect(window.location.hash).toBe("#/agents/agent-new?project=project-a");
expect(screen.queryByRole("button", { name: "运行任务" })).toBeNull();
});
it("ignores an older poll and sends the next task to the newly created session", async () => {
const enabled = { ...state, runtime: { enabled: true, version: "0.1.0" } };
const session = {
...state.sessions[0],
id: "session-new",
title: "New task",
};
const olderPoll = deferred<Response>();
const refreshed = deferred<Response>();
const intervalSpy = vi.spyOn(window, "setInterval");
let stateReads = 0;
let created = false;
fetchMock.mockImplementation(async (path: string) => {
if (path.startsWith("/api/providers?"))
return response(providerFixture(path));
if (path === "/api/sessions") {
created = true;
return response(session);
}
if (path === "/api/state") {
stateReads += 1;
if (stateReads === 1) return response(enabled);
if (stateReads === 2) return olderPoll.promise;
if (stateReads === 3) return refreshed.promise;
return response({ ...enabled, sessions: [...state.sessions, session] });
}
if (path.endsWith("/run"))
return response({ id: "run-new", status: "running" });
return response({ events: [] });
});
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: /^Review agent/ }));
await screen.findByLabelText("给 Agent 的任务");
const poll = intervalSpy.mock.calls.find(
([, delay]) => delay === 8000,
)?.[0] as () => Promise<void>;
expect(poll).toBeTypeOf("function");
act(() => {
void poll();
});
fireEvent.change(screen.getByLabelText("新会话标题"), {
target: { value: session.title },
});
fireEvent.click(screen.getByRole("button", { name: "创建会话" }));
await waitFor(() => expect(created && stateReads === 3).toBe(true));
expect(
(screen.getByRole("button", { name: "运行任务" }) as HTMLButtonElement)
.disabled,
).toBe(true);
await act(async () => {
refreshed.resolve(
response({ ...enabled, sessions: [...state.sessions, session] }),
);
});
await screen.findByRole("heading", { name: session.title });
await act(async () => {
olderPoll.resolve(response(enabled));
});
expect(screen.getByRole("heading", { name: session.title })).toBeTruthy();
fireEvent.change(screen.getByLabelText("给 Agent 的任务"), {
target: { value: "Run in the new session only" },
});
fireEvent.click(screen.getByRole("button", { name: "运行任务" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.some(
([path]) => path === "/api/sessions/session-new/run",
),
).toBe(true),
);
expect(
fetchMock.mock.calls.some(
([path]) => path === "/api/sessions/session-a/run",
),
).toBe(false);
});
});
describe("connection boundaries", () => {
it("starts in Chinese without any network call, execution, or quota read", () => {
render(<App />);
expect(
screen.getByRole("heading", { name: "连接本地工作台" }),
).toBeTruthy();
expect(fetchMock).not.toHaveBeenCalled();
expect(document.documentElement.lang).toBe("zh-CN");
});
it("switches language without connecting", () => {
render(<App />);
fireEvent.click(screen.getByRole("button", { name: "Switch to English" }));
expect(
screen.getByRole("heading", { name: "Connect your local workspace" }),
).toBeTruthy();
expect(document.documentElement.lang).toBe("en");
expect(fetchMock).not.toHaveBeenCalled();
});
it("keeps the token out of browser storage and erases the UI on disconnect", async () => {
const storage = vi.spyOn(Storage.prototype, "setItem");
render(<App />);
await connect();
expect(storage).not.toHaveBeenCalled();
expect(fetchMock.mock.calls[0][0]).toBe("/api/state");
expect(
(fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].headers,
).toMatchObject({
Authorization: "Bearer example-admin-token-not-a-real-secret",
});
expect(document.body.textContent).not.toContain("example-admin-token");
fireEvent.click(screen.getByRole("button", { name: "退出工作台" }));
expect(screen.getByLabelText("访问令牌").getAttribute("value")).toBe("");
expect(screen.queryByText("Demo project")).toBeNull();
});
it("does not fetch usage implicitly and disables execution while runtime is off", async () => {
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: /^Review agent/ }));
fireEvent.change(await screen.findByLabelText("给 Agent 的任务"), {
target: { value: "Do work" },
});
expect(
(screen.getByRole("button", { name: "运行任务" }) as HTMLButtonElement)
.disabled,
).toBe(true);
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
expect(screen.queryByRole("button", { name: "读取额度" })).toBeNull();
expect(screen.queryByText("执行未启用,自动刷新已暂停。")).toBeNull();
expect(
fetchMock.mock.calls.some(([path]) => /quotas|\/run$/.test(String(path))),
).toBe(false);
});
});
describe("reviewed memory and messages", () => {
it("uses compare-and-swap version and preserves the draft after a conflict", async () => {
fetchMock.mockImplementation(async (path: string) =>
path === "/api/memories"
? response({ error: "Version conflict" }, 409)
: response(
path.startsWith("/api/providers?")
? providerFixture(path)
: path.includes("/events?")
? { events: [] }
: state,
),
);
render(<App />);
await connect();
openProject(
window.location.search.includes("demo=1") ? "Orbit" : "Demo project",
);
fireEvent.click(screen.getByRole("button", { name: "记忆" }));
fireEvent.click(screen.getByRole("button", { name: "编辑" }));
fireEvent.change(screen.getByLabelText("内容"), {
target: { value: "Keep this draft" },
});
fireEvent.click(screen.getByRole("button", { name: "保存已审阅记忆" }));
await screen.findByRole("alert");
const call = fetchMock.mock.calls.find(
([path]) => path === "/api/memories",
) as unknown as [string, RequestInit];
expect(JSON.parse(call[1].body as string)).toEqual({
project_id: "project-a",
key: "project.stack",
content: "Keep this draft",
expected_version: 3,
});
expect((screen.getByLabelText("内容") as HTMLTextAreaElement).value).toBe(
"Keep this draft",
);
expect(screen.getByRole("alert").textContent).toContain("操作未应用");
});
it("disables dispatch when execution is off", async () => {
render(<App />);
await connect();
openProject(
window.location.search.includes("demo=1") ? "Orbit" : "Demo project",
);
fireEvent.click(screen.getByRole("button", { name: "任务" }));
fireEvent.click(screen.getByRole("button", { name: "派工记录" }));
fireEvent.change(screen.getByLabelText("任务说明"), {
target: { value: "Review the change" },
});
const button = screen.getByRole("button", {
name: "派发任务",
}) as HTMLButtonElement;
expect(button.disabled).toBe(true);
fireEvent.click(button);
expect(
fetchMock.mock.calls.some(([path]) => path === "/api/messages"),
).toBe(false);
});
it("dispatches to a selected native session with an idempotency key", async () => {
fetchMock.mockImplementation(async (path: string) =>
response(
path.includes("/events?")
? { events: [] }
: { ...state, runtime: { enabled: true, version: "0.2.0" } },
),
);
render(<App />);
await connect();
openProject(
window.location.search.includes("demo=1") ? "Orbit" : "Demo project",
);
fireEvent.click(screen.getByRole("button", { name: "任务" }));
fireEvent.click(screen.getByRole("button", { name: "派工记录" }));
fireEvent.change(screen.getByLabelText("目标会话"), {
target: { value: "session-a" },
});
fireEvent.change(screen.getByLabelText("任务说明"), {
target: { value: "Review this change." },
});
fireEvent.click(screen.getByRole("button", { name: "派发任务" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.some(([path]) => path === "/api/messages"),
).toBe(true),
);
const call = fetchMock.mock.calls.find(
([path]) => path === "/api/messages",
) as unknown as [string, RequestInit];
expect(JSON.parse(call[1].body as string)).toEqual({
project_id: "project-a",
recipient_id: "agent-a",
recipient_session_id: "session-a",
body: "Review this change.",
idempotency_key: expect.any(String),
});
expect(
fetchMock.mock.calls.some(([path]) => String(path).endsWith("/run")),
).toBe(false);
});
it("renders untrusted memory as literal text, never markup", async () => {
const hostile = '<img src=x onerror="alert(1)">';
fetchMock.mockImplementation(async (path: string) =>
response(
path.includes("/events?")
? { events: [] }
: {
...state,
memories: [{ ...state.memories[0], content: hostile }],
},
),
);
render(<App />);
await connect();
openProject(
window.location.search.includes("demo=1") ? "Orbit" : "Demo project",
);
fireEvent.click(screen.getByRole("button", { name: "记忆" }));
expect(screen.getByText(hostile)).toBeTruthy();
expect(document.querySelector("img")).toBeNull();
});
it("rejects stale proposals in the UI instead of overwriting reviewed memory", async () => {
fetchMock.mockImplementation(async (path: string) =>
response(
path.includes("/events?")
? { events: [] }
: {
...state,
proposals: [
{
id: "proposal-a",
project_id: "project-a",
agent_id: "agent-a",
key: "project.stack",
content: "Old suggestion",
expected_version: 2,
status: "pending",
created_at: "2026-01-01T00:00:00Z",
},
],
},
),
);
render(<App />);
await connect();
openProject(
window.location.search.includes("demo=1") ? "Orbit" : "Demo project",
);
fireEvent.click(screen.getByRole("button", { name: "记忆" }));
expect(
(screen.getByRole("button", { name: "批准写入" }) as HTMLButtonElement)
.disabled,
).toBe(true);
expect(
(screen.getByRole("button", { name: "拒绝提案" }) as HTMLButtonElement)
.disabled,
).toBe(false);
});
});
describe("usage semantics and transport", () => {
it("hides unconfigured providers and unrelated historical usage, and performs no quota probes", async () => {
fetchMock.mockImplementation(async (path: string) =>
response(
path === "/api/metrics"
? {
providers: { codex: { total_tokens: 99000000 } },
total: { total_tokens: 99000000, sessions: 172 },
agents: {},
}
: {
...state,
projects: [],
agents: [],
sessions: [],
runtime: { enabled: true, version: "0.3.0" },
quotas: [
{
provider: "claude",
windows: [],
status: "available",
source: "local",
},
],
},
),
);
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
expect(screen.getByText("暂无 Agent")).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Codex" })).toBeNull();
expect(screen.queryByRole("heading", { name: "Claude" })).toBeNull();
expect(
fetchMock.mock.calls.some(([p]) => p === "/api/quotas/refresh"),
).toBe(false);
fireEvent.click(screen.getByRole("button", { name: "Token 统计" }));
expect(screen.getByText("暂无 Agent")).toBeTruthy();
expect(screen.queryByText("99M")).toBeNull();
});
it("only refreshes the provider of a configured agent", async () => {
fetchMock.mockImplementation(
async (path: string, options?: RequestInit) => {
if (path === "/api/quotas/refresh")
return response({
provider: JSON.parse(String(options?.body)).provider,
windows: [],
status: "unknown",
});
return response({
...state,
runtime: { enabled: true, version: "0.3.0" },
});
},
);
render(<App />);
await connect();
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
await waitFor(() =>
expect(
fetchMock.mock.calls.filter(([p]) => p === "/api/quotas/refresh"),
).toHaveLength(1),
);
const refresh = fetchMock.mock.calls.find(
([p]) => p === "/api/quotas/refresh",
)!;
expect(JSON.parse(String(refresh[1].body))).toEqual({ provider: "codex" });
expect(screen.queryByRole("heading", { name: "Claude" })).toBeNull();
});
it("refreshes both quotas on every usage navigation without exposing refresh or connection buttons", async () => {
fetchMock.mockImplementation(
async (path: string, options?: RequestInit) => {
if (path === "/api/quotas/refresh") {
const { provider } = JSON.parse(String(options?.body));
return response({
provider,
source: "AgentDock",
status: "available",
windows: [
{
label: "Weekly",
remaining_percent: provider === "codex" ? 42 : 71,
},
],
});
}
return response({
...state,
agents: [
...state.agents,
{
...state.agents[0],
id: "agent-b",
provider: "claude",
name: "Writer",
},
],
runtime: { ...state.runtime, enabled: true },
});
},
);
render(<App />);
await connect();
expect(
fetchMock.mock.calls.some(([path]) => path === "/api/quotas/refresh"),
).toBe(false);
const openUsage = () =>
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
const calls = () =>
fetchMock.mock.calls.filter(([path]) => path === "/api/quotas/refresh");
openUsage();
expect(await screen.findByText(/42%/)).toBeTruthy();
expect(await screen.findByText(/71%/)).toBeTruthy();
await waitFor(() => expect(screen.queryByText("更新中")).toBeNull());
expect(
calls().map(([, options]) => JSON.parse(String(options.body)).provider),
).toEqual(["codex", "claude"]);
expect(screen.queryByRole("button", { name: "读取额度" })).toBeNull();
expect(screen.queryByRole("button", { name: /连接 Claude/ })).toBeNull();
expect(screen.queryByRole("button", { name: "刷新工作台状态" })).toBeNull();
openUsage();
await waitFor(() => expect(calls()).toHaveLength(4));
await waitFor(() => expect(screen.queryByText("更新中")).toBeNull());
fireEvent.click(screen.getByRole("button", { name: "协作工作台" }));
openUsage();
await waitFor(() => expect(calls()).toHaveLength(6));
await waitFor(() => expect(screen.queryByText("更新中")).toBeNull());
fireEvent.click(screen.getByRole("button", { name: "Switch to English" }));
expect(screen.queryByText("Automatic refresh is on")).toBeNull();
expect(calls()).toHaveLength(6);
});
it("coalesces repeated clicks, keeps unrelated controls enabled, and ignores late results after disconnect", async () => {
const pending: ((value: Response) => void)[] = [];
const signals: AbortSignal[] = [];
fetchMock.mockImplementation((path: string, options?: RequestInit) => {
if (path === "/api/quotas/refresh") {
signals.push(options?.signal as AbortSignal);
return new Promise<Response>((resolve) => pending.push(resolve));
}
return Promise.resolve(
response({
...state,
agents: [
...state.agents,
{
...state.agents[0],
id: "agent-b",
provider: "claude",
name: "Writer",
},
],
runtime: { ...state.runtime, enabled: true },
}),
);
});
render(<App />);
await connect();
for (let i = 0; i < 3; i++)
fireEvent.click(screen.getByRole("button", { name: "额度与订阅" }));
expect(pending).toHaveLength(2);
expect(screen.getAllByText("更新中")).toHaveLength(2);
expect(
(screen.getAllByRole("button", { name: "编辑" })[0] as HTMLButtonElement)
.disabled,
).toBe(false);
fireEvent.click(screen.getByRole("button", { name: "退出工作台" }));
expect(signals.every((signal) => signal.aborted)).toBe(true);
await act(async () => {
pending.forEach((resolve, i) =>
resolve(
response({
provider: i ? "claude" : "codex",
windows: [{ label: "Weekly", remaining_percent: 82 }],
status: "available",
source: "AgentDock",
}),
),
);
});
expect(
screen.getByRole("heading", { name: "连接本地工作台" }),
).toBeTruthy();
expect(screen.queryByText(/82%/)).toBeNull();
});
it("updates a successful provider even if the other request fails and preserves its previous data", async () => {
fetchMock.mockImplementation(
async (path: string, options?: RequestInit) => {
if (path === "/api/quotas/refresh") {
const { provider } = JSON.parse(String(options?.body));
if (provider === "codex") throw new Error("offline");
return response({
provider,
source: "AgentDock",
status: "available",
windows: [{ label: "Weekly", remaining_percent: 55 }],
});
}