The best way to control Claude Code, Codex and more from any computer or phone
test(web): provider, usage and relationship tests run in a real browser (#20914)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 07:10 UTC
133f57a8321767d51610c50a16edb8b7181ededf
8 files changed
+1116
-1436
apps/web/src/components/chat/ThreadRelationshipsControl.agents.browser.test.tsx
renamed
+228
-264
@@ -1,5 +1,5 @@
1
import { act, cloneElement, type ReactElement, type ReactNode } from "react";
2
-import { create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
2
+import { createRoot, type Root } from "react-dom/client";
3
import {
4
EnvironmentId,
5
ThreadId,
@@ -8,9 +8,12 @@ import {
8
type OrchestrationV2ContextTransfer,
9
} from "@t3tools/contracts";
10
import * as DateTime from "effect/DateTime";
11
-import { afterEach, expect, it, vi } from "vite-plus/test";
11
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12
+
13
+import "~/index.css";
14
15
const state = vi.hoisted(() => ({
16
+ stopWorkflowLabel: "environment-data:orchestration:stop-workflow",
17
projection: null as unknown,
18
navigate: vi.fn(),
19
shells: [] as unknown[],
@@ -22,56 +25,124 @@ const state = vi.hoisted(() => ({
25
toast: vi.fn(),
26
}));
27
25
-vi.mock("@tanstack/react-router", () => ({ useNavigate: () => state.navigate }));
26
-vi.mock("../../state/entities", () => ({
27
- useThreadProjection: () => ({ projection: state.projection }),
28
- useThreadRelationshipShells: (ref: { readonly environmentId: string }) =>
28
+vi.mock(import("@tanstack/react-router"), async (original) => ({
29
+ ...(await original()),
30
+ useNavigate: (() => state.navigate) as never,
31
+}));
32
+vi.mock(import("../../state/entities"), async (original) => ({
33
+ ...(await original()),
34
+ useThreadProjection: (() => ({ projection: state.projection })) as never,
35
+ useThreadRelationshipShells: ((ref: { readonly environmentId: string }) =>
36
(state.shells as ReadonlyArray<{ readonly environmentId: string; readonly source: unknown }>)
37
.filter((shell) => shell.environmentId === ref.environmentId)
31
- .map((shell) => shell.source),
32
- useProjects: () => state.projects,
38
+ .map((shell) => shell.source)) as never,
39
+ useProjects: (() => state.projects) as never,
40
}));
34
-vi.mock("../../state/environments", () => ({
35
- useEnvironmentProviders: () =>
41
+vi.mock(import("../../state/environments"), async (original) => ({
42
+ ...(await original()),
43
+ useEnvironmentProviders: (() =>
44
new Map(
45
[...state.configs].map(([id, config]) => [id, (config as { providers: unknown }).providers]),
38
- ),
46
+ )) as never,
47
}));
40
-vi.mock("../../lib/archivedThreadsState", () => ({
41
- useArchivedThreadSnapshots: () => ({ snapshots: [] }),
48
+vi.mock(import("../../lib/archivedThreadsState"), async (original) => ({
49
+ ...(await original()),
50
+ useArchivedThreadSnapshots: (() => ({ snapshots: [] })) as never,
51
}));
43
-vi.mock("../../state/use-atom-command", () => ({
44
- useAtomCommand: (command: { label: string }) =>
45
- command.label === "environment-data:orchestration:stop-workflow"
46
- ? state.workflowCommand
47
- : state.command,
52
+vi.mock(import("../../state/use-atom-command"), async (original) => ({
53
+ ...(await original()),
54
+ useAtomCommand: ((command: { label?: string }) =>
55
+ command.label === state.stopWorkflowLabel ? state.workflowCommand : state.command) as never,
56
}));
49
-vi.mock("../ui/toast", () => ({ toastManager: { add: state.toast } }));
50
-vi.mock("../../state/orchestration", async () => {
57
+vi.mock(import("../ui/toast"), async (original) => {
58
+ const actual = await original();
59
+ return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } as never };
60
+});
61
+vi.mock(import("../../state/orchestration"), async (original) => {
62
+ const actual = await original();
63
const { Atom } = await import("effect/reactivity");
64
const granted = Atom.make(true);
65
+ const stopWorkflow = actual.orchestrationEnvironment.stopWorkflow;
66
return {
54
- orchestrationEnvironment: {
55
- stopWorkflow: {
56
- label: "environment-data:orchestration:stop-workflow",
67
+ ...actual,
68
+ orchestrationEnvironment: Object.assign(Object.create(actual.orchestrationEnvironment), {
69
+ stopWorkflow: Object.assign(Object.create(stopWorkflow), {
70
+ label: state.stopWorkflowLabel,
71
permissionAtom: () => granted,
58
- },
59
- },
72
+ }),
73
+ }),
74
+ };
75
+});
76
+// Tooltip and hover card content renders inline so the suite can read every row's agent
77
+// details across many states without hovering each row.
78
+vi.mock(import("../ui/tooltip"), async () => {
79
+ const { cloneElement } = await import("react");
80
+ return {
81
+ Tooltip: (({ children }: { children: ReactNode }) => children) as never,
82
+ TooltipTrigger: (({ render, children }: { render: ReactElement; children: ReactNode }) =>
83
+ cloneElement(render, {}, children)) as never,
84
+ TooltipPopup: (({ children }: { children: ReactNode }) =>
85
+ state.showTooltips ? children : null) as never,
86
};
87
});
62
-vi.mock("../ui/tooltip", () => ({
63
- Tooltip: ({ children }: { children: ReactNode }) => children,
64
- TooltipTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>
65
- cloneElement(render, {}, children),
66
- TooltipPopup: ({ children }: { children: ReactNode }) => (state.showTooltips ? children : null),
67
-}));
88
89
import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
90
71
-let renderer: ReactTestRenderer;
91
+let root: Root;
92
+let container: HTMLDivElement;
93
+let current: ReactElement;
94
+
95
+async function render(element: ReactElement) {
96
+ current = element;
97
+ await act(async () => root.render(element));
98
+}
99
+// The mocked hooks read `state` while rendering, so a new element picks up changes.
100
+const update = () => act(async () => root.render(cloneElement(current)));
101
+const click = (element: HTMLElement) => act(async () => element.click());
102
+const buttons = () => [...container.querySelectorAll("button")];
103
+const allByLabel = (label: string) =>
104
+ buttons().filter((button) => button.getAttribute("aria-label") === label);
105
+function byLabel(label: string) {
106
+ const matches = allByLabel(label);
107
+ if (matches.length !== 1)
108
+ throw new Error(`Expected one "${label}" button, got ${matches.length}`);
109
+ return matches[0]!;
110
+}
111
+const sectionToggles = (expanded: boolean) =>
112
+ buttons().filter(
113
+ (button) =>
114
+ button.getAttribute("aria-expanded") === String(expanded) &&
115
+ !button.hasAttribute("aria-label"),
116
+ );
117
+function sectionToggle(expanded: boolean) {
118
+ const [toggle] = sectionToggles(expanded);
119
+ if (!toggle) throw new Error(`No ${expanded ? "expanded" : "collapsed"} section toggle`);
120
+ return toggle;
121
+}
122
+const heading = () => container.querySelector("h3")?.textContent;
123
+const buttonsWithLabel = (matches: (label: string) => boolean) =>
124
+ buttons().filter((button) => matches(button.getAttribute("aria-label") ?? ""));
125
+// Joins rendered text nodes; `visibleOnly` drops screen-reader-only text.
126
+function textNodes(separator: string, visibleOnly = false) {
127
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
128
+ const parts: string[] = [];
129
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
130
+ if (visibleOnly && node.parentElement?.closest(".sr-only")) continue;
131
+ parts.push(node.textContent ?? "");
132
+ }
133
+ return parts.join(separator);
134
+}
135
+
136
+beforeEach(() => {
137
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
138
+ container = document.createElement("div");
139
+ document.body.append(container);
140
+ root = createRoot(container);
141
+});
142
143
afterEach(async () => {
74
- await act(async () => renderer?.unmount());
144
+ await act(async () => root.unmount());
145
+ container.remove();
146
vi.unstubAllGlobals();
147
state.shells = [];
148
state.projects = [];
@@ -85,7 +156,6 @@ afterEach(async () => {
156
});
157
158
it("stops the entire native workflow through its parent without changing state before acknowledgement", async () => {
88
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
159
const coordinator = {
160
id: "workflow",
161
origin: "provider_native",
@@ -132,24 +202,15 @@ it("stops the entire native workflow through its parent without changing state b
202
},
203
},
204
];
135
- await act(async () => {
136
- renderer = create(
137
- <ThreadRelationshipsPanel
138
- environmentId={EnvironmentId.make("remote")}
139
- threadId={ThreadId.make("parent")}
140
- />,
141
- );
142
- });
143
- await act(async () =>
144
- renderer.root.findByProps({ "aria-label": "Expand Checkout review" }).props.onClick(),
205
+ await render(
206
+ <ThreadRelationshipsPanel
207
+ environmentId={EnvironmentId.make("remote")}
208
+ threadId={ThreadId.make("parent")}
209
+ />,
210
);
146
- const stopButton = () =>
147
- renderer.root.findByProps({ "aria-label": "Stop workflow Checkout review" });
148
- expect(
149
- renderer.root.findAll(
150
- (node) => node.type === "button" && String(node.props["aria-label"]).startsWith("Stop "),
151
- ),
152
- ).toHaveLength(2);
211
+ await click(byLabel("Expand Checkout review"));
212
+ const stopButton = () => byLabel("Stop workflow Checkout review");
213
+ expect(buttonsWithLabel((label) => label.startsWith("Stop "))).toHaveLength(2);
214
let acknowledge!: (result: { _tag: string }) => void;
215
state.workflowCommand.mockImplementationOnce(
216
() =>
@@ -157,35 +218,29 @@ it("stops the entire native workflow through its parent without changing state b
218
acknowledge = resolve;
219
}),
220
);
160
- await act(async () => {
161
- stopButton().props.onClick();
162
- });
221
+ await click(stopButton());
222
expect(state.workflowCommand).toHaveBeenCalledExactlyOnceWith({
223
environmentId: "remote",
224
input: { threadId: "parent", subagentId: "workflow" },
225
});
226
expect(state.command).not.toHaveBeenCalled();
227
expect(state.navigate).not.toHaveBeenCalled();
169
- expect(stopButton().props.disabled).toBe(true);
170
- expect(renderer.root.findByProps({ "aria-label": "Stop subagent Worker" }).props.disabled).toBe(
171
- true,
172
- );
173
- expect(renderer.root.findByProps({ "aria-label": "Open Checker chat" })).toBeDefined();
174
- expect(renderer.root.findByType("h3").children).toEqual(["Lineage · 2 running"]);
228
+ expect(stopButton().disabled).toBe(true);
229
+ expect(byLabel("Stop subagent Worker").disabled).toBe(true);
230
+ expect(byLabel("Open Checker chat")).toBeDefined();
231
+ expect(heading()).toBe("Lineage · 2 running");
232
await act(async () => {
233
acknowledge({ _tag: "Success" });
234
});
178
- expect(stopButton().props.disabled).toBe(false);
179
- expect(renderer.root.findByType("h3").children).toEqual(["Lineage · 2 running"]);
235
+ expect(stopButton().disabled).toBe(false);
236
+ expect(heading()).toBe("Lineage · 2 running");
237
state.workflowCommand.mockResolvedValueOnce({ _tag: "Failure" });
181
- await act(async () => {
182
- stopButton().props.onClick();
183
- });
238
+ await click(stopButton());
239
expect(state.toast).toHaveBeenCalledExactlyOnceWith({
240
type: "error",
241
title: "Could not stop workflow",
242
});
188
- expect(stopButton().props.disabled).toBe(false);
243
+ expect(stopButton().disabled).toBe(false);
244
expect(state.command).not.toHaveBeenCalled();
245
expect(state.navigate).not.toHaveBeenCalled();
246
});
@@ -198,7 +253,6 @@ it.each([
253
["codex", "provider_native", "running"],
254
["claudeAgent", "app_owned", "running"],
255
])("does not offer workflow stop for %s %s %s", async (driver, origin, status) => {
201
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
256
state.projection = {
257
thread: { id: "parent", lineage: { relationshipToParent: null } },
258
runs: [],
@@ -221,28 +275,20 @@ it.each([
275
},
276
],
277
};
224
- await act(async () => {
225
- renderer = create(
226
- <ThreadRelationshipsPanel
227
- environmentId={EnvironmentId.make("remote")}
228
- threadId={ThreadId.make("parent")}
229
- />,
230
- );
231
- });
232
- const previousAgents = renderer.root.findAll(
233
- (node) =>
234
- node.type === "button" && node.props["aria-expanded"] === false && !node.props["aria-label"],
278
+ await render(
279
+ <ThreadRelationshipsPanel
280
+ environmentId={EnvironmentId.make("remote")}
281
+ threadId={ThreadId.make("parent")}
282
+ />,
283
);
236
- if (previousAgents.length > 0) await act(async () => previousAgents[0]!.props.onClick());
237
- expect(renderer.root.findByProps({ "aria-label": "Expand Checkout review" })).toBeDefined();
238
- expect(
239
- renderer.root.findAllByProps({ "aria-label": "Stop workflow Checkout review" }),
240
- ).toHaveLength(0);
284
+ const previousAgents = sectionToggles(false);
285
+ if (previousAgents.length > 0) await click(previousAgents[0]!);
286
+ expect(byLabel("Expand Checkout review")).toBeDefined();
287
+ expect(allByLabel("Stop workflow Checkout review")).toHaveLength(0);
288
expect(state.workflowCommand).not.toHaveBeenCalled();
289
});
290
291
it("opens the correct chat for every workflow phase and unphased member", async () => {
245
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
292
state.showTooltips = true;
293
state.configs.set("remote", {
294
providers: [
@@ -310,92 +356,70 @@ it("opens the correct chat for every workflow phase and unphased member", async
356
threadId={ThreadId.make("parent")}
357
/>
358
);
313
- await act(async () => {
314
- renderer = create(panel);
315
- });
316
- await act(async () =>
317
- renderer.root.findByProps({ "aria-label": "Expand Checkout review" }).props.onClick(),
318
- );
319
- const memberButtons = () =>
320
- renderer.root.findAll(
321
- (node) =>
322
- node.type === "button" && String(node.props["aria-label"]).startsWith("Open Member"),
323
- );
359
+ await render(panel);
360
+ await click(byLabel("Expand Checkout review"));
361
+ const memberButtons = () => buttonsWithLabel((label) => label.startsWith("Open Member"));
362
const phaseButtons = () =>
325
- renderer.root.findAll(
326
- (node) =>
327
- node.type === "button" &&
328
- typeof node.props["aria-expanded"] === "boolean" &&
329
- String(node.props["aria-label"]).includes(" phase, "),
363
+ buttonsWithLabel((label) => label.includes(" phase, ")).filter((button) =>
364
+ button.hasAttribute("aria-expanded"),
365
);
366
expect(memberButtons()).toHaveLength(3);
367
expect(phaseButtons()).toHaveLength(3);
333
- expect(renderer.root.findByProps({ "aria-label": "Expand Inspect phase, done" })).toBeDefined();
334
- expect(
335
- renderer.root.findByProps({ "aria-label": "Expand Improve phase, stopped" }),
336
- ).toBeDefined();
337
- expect(
338
- renderer.root.findByProps({ "aria-label": "Collapse Verify phase, running" }),
339
- ).toBeDefined();
340
- for (const phase of phaseButtons().slice(0, 2)) await act(async () => phase.props.onClick());
368
+ expect(byLabel("Expand Inspect phase, done")).toBeDefined();
369
+ expect(byLabel("Expand Improve phase, stopped")).toBeDefined();
370
+ expect(byLabel("Collapse Verify phase, running")).toBeDefined();
371
+ for (const phase of phaseButtons().slice(0, 2)) await click(phase);
372
expect(memberButtons()).toHaveLength(7);
373
for (const button of memberButtons()) {
343
- expect(button.props.disabled).toBe(true);
344
- await act(async () => button.props.onClick());
374
+ expect(button.disabled).toBe(true);
375
+ await click(button);
376
}
377
expect(state.navigate).not.toHaveBeenCalled();
378
state.shells = memberShells.map((source) => ({ environmentId: "remote", source }));
348
- await act(async () => renderer.update(cloneElement(panel)));
349
- for (const button of memberButtons()) expect(button.props.disabled).toBe(false);
379
+ await update();
380
+ for (const button of memberButtons()) expect(button.disabled).toBe(false);
381
for (const agent of agents) {
351
- await act(async () =>
352
- renderer.root.findByProps({ "aria-label": `Open ${agent.label} chat` }).props.onClick(),
353
- );
382
+ await click(byLabel(`Open ${agent.label} chat`));
383
expect(state.navigate).toHaveBeenLastCalledWith({
384
to: "/$environmentId/$threadId",
385
params: { environmentId: "remote", threadId: agent.childThreadId },
386
});
387
}
359
- const rendered = JSON.stringify(renderer.toJSON());
388
+ const rendered = textNodes("|");
389
expect(rendered.match(/Sonnet · Work account/g)).toHaveLength(7);
390
expect(rendered).not.toContain("Personal account");
391
for (const phase of phases) expect(rendered).toContain(phase.title);
392
expect(rendered).not.toContain(" phases");
364
- expect(rendered).toContain('"1","/","2"," ","agents"');
393
+ expect(rendered).toContain("1|/|2| |agents");
394
expect(rendered).toContain("Running");
395
expect(rendered).toContain("running");
367
- expect(rendered).toContain("done");
368
- expect(rendered).toContain("stopped");
369
- expect(rendered).toContain('"6s"');
396
+ expect(buttonsWithLabel((label) => label.endsWith("phase, done"))).toHaveLength(1);
397
+ expect(buttonsWithLabel((label) => label.endsWith("phase, stopped"))).toHaveLength(1);
398
+ expect(rendered).toContain("|6s|");
399
for (const phase of phaseButtons()) {
371
- const label = String(phase.props["aria-label"]).slice("Collapse ".length);
372
- await act(async () => phase.props.onClick());
400
+ const label = String(phase.getAttribute("aria-label")).slice("Collapse ".length);
401
+ await click(phase);
402
expect(memberButtons()).toHaveLength(5);
374
- await act(async () =>
375
- renderer.root.findByProps({ "aria-label": `Expand ${label}` }).props.onClick(),
376
- );
403
+ await click(byLabel(`Expand ${label}`));
404
expect(memberButtons()).toHaveLength(7);
405
}
379
- await act(async () => phaseButtons()[0]!.props.onClick());
406
+ await click(phaseButtons()[0]!);
407
expect(memberButtons()).toHaveLength(5);
408
const restarted = agents.map((agent) =>
409
agent.index === 0 ? { ...agent, state: "running" } : agent,
410
);
411
state.projection = project(restarted);
385
- await act(async () => renderer.update(cloneElement(panel)));
412
+ await update();
413
expect(memberButtons()).toHaveLength(5);
414
state.projection = project(agents);
388
- await act(async () => renderer.update(cloneElement(panel)));
415
+ await update();
416
expect(memberButtons()).toHaveLength(5);
390
- await act(async () =>
391
- renderer.root.findByProps({ "aria-label": "Collapse Checkout review" }).props.onClick(),
392
- );
417
+ await click(byLabel("Collapse Checkout review"));
418
expect(memberButtons()).toHaveLength(0);
419
expect(state.navigate).toHaveBeenCalledTimes(7);
420
});
421
422
it("groups and counts a workflow by its run status instead of its coordinator chat", async () => {
398
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
423
state.showTooltips = true;
424
const coordinator = {
425
id: "workflow",
@@ -438,22 +462,14 @@ it("groups and counts a workflow by its run status instead of its coordinator ch
462
threadId={ThreadId.make("parent")}
463
/>
464
);
441
- await act(async () => {
442
- renderer = create(panel);
443
- });
444
- const text = () =>
445
- renderer.root
446
- .findAll((node) => typeof node.type === "string")
447
- .flatMap((node) => node.children.filter((child) => typeof child === "string"))
448
- .join("");
449
- expect(renderer.root.findByType("h3").children).toEqual(["Lineage · 1 running"]);
450
- await act(async () =>
451
- renderer.root.findByProps({ "aria-label": "Expand Checkout review" }).props.onClick(),
452
- );
453
- expect(renderer.root.findByProps({ "aria-label": "Open Checker chat" })).toBeDefined();
465
+ await render(panel);
466
+ const text = () => textNodes("");
467
+ expect(heading()).toBe("Lineage · 1 running");
468
+ await click(byLabel("Expand Checkout review"));
469
+ expect(byLabel("Open Checker chat")).toBeDefined();
470
state.shells = [{ environmentId: "test", source: { ...child, activityRunStatus: "waiting" } }];
455
- await act(async () => renderer.update(cloneElement(panel)));
456
- expect(renderer.root.findByType("h3").children).toEqual(["Lineage · 1 running"]);
471
+ await update();
472
+ expect(heading()).toBe("Lineage · 1 running");
473
expect(text()).toContain("Inspecting the checkout workflow");
474
state.projection = {
475
...projection,
@@ -465,14 +481,12 @@ it("groups and counts a workflow by its run status instead of its coordinator ch
481
},
482
],
483
};
468
- await act(async () => renderer.update(cloneElement(panel)));
469
- expect(renderer.root.findByType("h3").children).toEqual(["Lineage"]);
484
+ await update();
485
+ expect(heading()).toBe("Lineage");
486
expect(text()).toContain("Previous agents");
471
- expect(renderer.root.findAllByProps({ "aria-label": "Open Checker chat" })).toHaveLength(0);
472
- await act(async () =>
473
- renderer.root.findByProps({ type: "button", "aria-expanded": false }).props.onClick(),
474
- );
475
- expect(renderer.root.findByProps({ "aria-label": "Expand Checkout review" })).toBeDefined();
487
+ expect(allByLabel("Open Checker chat")).toHaveLength(0);
488
+ await click(sectionToggle(false));
489
+ expect(byLabel("Expand Checkout review")).toBeDefined();
490
expect(text()).toContain("Workflow checks complete");
491
expect(text()).toContain("10m");
492
});
@@ -485,7 +499,6 @@ it.each([
499
])(
500
"offers individual Stop for supported $origin $driver subagents with run $runId",
501
async ({ driver, origin, runId, canStop }) => {
488
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
502
const parent = {
503
id: "parent",
504
lineage: { relationshipToParent: null },
@@ -531,17 +544,13 @@ it.each([
544
threadId={ThreadId.make("parent")}
545
/>
546
);
534
- await act(async () => {
535
- renderer = create(panel);
536
- });
547
+ await render(panel);
548
if (!canStop) {
538
- expect(renderer.root.findAllByProps({ "aria-label": "Stop subagent Worker" })).toHaveLength(
539
- 0,
540
- );
549
+ expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
550
return;
551
}
543
- const stopButton = () => renderer.root.findByProps({ "aria-label": "Stop subagent Worker" });
544
- await act(async () => stopButton().props.onClick());
552
+ const stopButton = () => byLabel("Stop subagent Worker");
553
+ await click(stopButton());
554
expect(state.command).toHaveBeenCalledWith({
555
environmentId: "test",
556
input:
@@ -567,19 +576,15 @@ it.each([
576
...projection,
577
subagents: [{ ...agent, origin: "provider_native", status: "completed" }],
578
};
570
- await act(async () => renderer.update(cloneElement(panel)));
571
- expect(renderer.root.findAllByProps({ "aria-label": "Stop subagent Worker" })).toHaveLength(
572
- 0,
573
- );
579
+ await update();
580
+ expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
581
state.projection = { ...projection, subagents: [{ ...agent, status: "completed" }] };
575
- await act(async () => renderer.update(cloneElement(panel)));
582
+ await update();
583
if (origin === "provider_native") {
577
- expect(renderer.root.findAllByProps({ "aria-label": "Stop subagent Worker" })).toHaveLength(
578
- 0,
579
- );
584
+ expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
585
continue;
586
}
582
- await act(async () => stopButton().props.onClick());
587
+ await click(stopButton());
588
expect(state.command).toHaveBeenCalledTimes(1);
589
expect(state.command).toHaveBeenLastCalledWith({
590
environmentId: "test",
@@ -589,25 +594,22 @@ it.each([
594
state.shells = [{ environmentId: "test", source: child }];
595
for (const status of ["completed", "failed", "interrupted"]) {
596
state.projection = { ...projection, subagents: [{ ...agent, status }] };
592
- await act(async () => renderer.update(cloneElement(panel)));
593
- expect(renderer.root.findAllByProps({ "aria-label": "Stop subagent Worker" })).toHaveLength(
594
- 0,
595
- );
597
+ await update();
598
+ expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
599
}
600
state.projection = { ...projection, subagents: [{ ...agent, startedAt: null }] };
598
- await act(async () => renderer.update(cloneElement(panel)));
599
- expect(renderer.root.findAllByProps({ "aria-label": "Stop subagent Worker" })).toHaveLength(0);
601
+ await update();
602
+ expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
603
state.projection = {
604
...projection,
605
subagents: [{ ...agent, origin: "provider_native", driver: "codex" }],
606
};
604
- await act(async () => renderer.update(cloneElement(panel)));
605
- expect(renderer.root.findAllByProps({ "aria-label": "Stop subagent Worker" })).toHaveLength(0);
607
+ await update();
608
+ expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
609
},
610
);
611
612
it("shows the matching child agent details and refreshes them when the agent settles", async () => {
610
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
613
const agent = {
614
id: "agent-1",
615
driver: "codex",
@@ -646,15 +648,8 @@ it("shows the matching child agent details and refreshes them when the agent set
648
threadId={ThreadId.make("parent")}
649
/>
650
);
649
- await act(async () => {
650
- renderer = create(panel);
651
- });
652
- const text = () =>
653
- renderer.root
654
- .findAll((node) => typeof node.type === "string")
655
- .flatMap((node) => node.children.filter((child) => typeof child === "string"))
656
- .join(" ")
657
- .replace(/\s+/g, " ");
651
+ await render(panel);
652
+ const text = () => textNodes(" ").replace(/\s+/g, " ");
653
expect(text()).toContain("Checker");
654
expect(text()).toContain("Lineage · 3 running");
655
expect(text()).toContain("running");
@@ -663,7 +658,7 @@ it("shows the matching child agent details and refreshes them when the agent set
658
expect(text()).not.toContain("tok");
659
expect(text()).not.toContain("Unlinked agent");
660
expect(text()).not.toContain("Active agents");
666
- expect(renderer.root.findAllByProps({ type: "button", "aria-expanded": true })).toHaveLength(0);
661
+ expect(sectionToggles(true)).toHaveLength(0);
662
663
state.projection = {
664
...projection,
@@ -677,27 +672,21 @@ it("shows the matching child agent details and refreshes them when the agent set
672
},
673
],
674
};
680
- await act(async () => renderer.update(cloneElement(panel)));
681
- expect(renderer.root.findByType("h3").children).toEqual(["Lineage"]);
675
+ await update();
676
+ expect(heading()).toBe("Lineage");
677
expect(text()).toContain("Previous agents (1)");
678
expect(text()).not.toContain("Checker");
684
- await act(async () =>
685
- renderer.root.findByProps({ type: "button", "aria-expanded": false }).props.onClick(),
686
- );
679
+ await click(sectionToggle(false));
680
expect(text()).toContain("Checker");
681
expect(text()).toContain("Checker 2m");
682
expect(text()).not.toContain("(1)");
683
expect(text()).not.toContain("Done");
684
expect(text()).not.toContain("running");
685
expect(text()).not.toContain("Worker");
693
- await act(async () =>
694
- renderer.root.findByProps({ type: "button", "aria-expanded": true }).props.onClick(),
695
- );
686
+ await click(sectionToggle(true));
687
expect(text()).not.toContain("Checker");
688
expect(text()).toContain("Previous agents (1)");
698
- await act(async () =>
699
- renderer.root.findByProps({ type: "button", "aria-expanded": false }).props.onClick(),
700
- );
689
+ await click(sectionToggle(false));
690
expect(text()).toContain("Checker");
691
692
state.projection = {
@@ -708,7 +697,7 @@ it("shows the matching child agent details and refreshes them when the agent set
697
childThreadId: `running-child-${index}`,
698
})),
699
};
711
- await act(async () => renderer.update(cloneElement(panel)));
700
+ await update();
701
expect(text()).toContain("Lineage · 8 running");
702
703
state.projection = {
@@ -723,27 +712,21 @@ it("shows the matching child agent details and refreshes them when the agent set
712
completedAt: DateTime.makeUnsafe("2026-09-16T12:02:15Z"),
713
})),
714
};
726
- await act(async () => renderer.update(cloneElement(panel)));
715
+ await update();
716
expect(text()).toContain("1 failed");
717
expect(text()).not.toContain("Old agent 7");
729
- await act(async () =>
730
- renderer.root
731
- .findAllByType("button")
732
- .find((button) => button.children.includes("Show "))!
733
- .props.onClick(),
734
- );
718
+ await click(buttons().find((button) => button.textContent?.startsWith("Show "))!);
719
expect(text()).toContain("Old agent 7");
720
721
state.projection = {
722
...projection,
723
subagents: [{ ...agent, childThreadId: null }],
724
};
741
- await act(async () => renderer.update(cloneElement(panel)));
725
+ await update();
726
expect(text()).toContain("Lineage · 1 running");
727
});
728
729
it("shows readable models and only differing workspace details in agent tooltips", async () => {
746
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
730
state.showTooltips = true;
731
const parent = {
732
id: "parent",
@@ -817,20 +800,20 @@ it("shows readable models and only differing workspace details in agent tooltips
800
threadId={ThreadId.make("parent")}
801
/>
802
);
820
- await act(async () => {
821
- renderer = create(panel);
822
- });
823
- const text = (visibleOnly = false) => {
824
- const read = (node: ReactTestInstance | string): string => {
825
- if (typeof node === "string") return node;
826
- if (visibleOnly && node.props.className === "sr-only") return "";
827
- return node.children.map(read).join("");
828
- };
829
- return read(renderer.root);
830
- };
803
+ await render(panel);
804
+ const text = (visibleOnly = false) => textNodes("", visibleOnly);
805
const rerender = async (source = child) => {
832
- state.shells = [{ environmentId: "test", source: { ...source } }];
833
- await act(async () => renderer.update(cloneElement(panel)));
806
+ // Fresh objects, as real shells are: the compiled component memoizes on identity.
807
+ state.shells = [
808
+ {
809
+ environmentId: "test",
810
+ source: {
811
+ ...source,
812
+ modelSelection: { ...source.modelSelection, options: source.modelSelection.options },
813
+ },
814
+ },
815
+ ];
816
+ await update();
817
};
818
const nativeProjection = {
819
...projection,
@@ -838,11 +821,11 @@ it("shows readable models and only differing workspace details in agent tooltips
821
};
822
expect(text()).toContain("My GPT · high");
823
state.projection = nativeProjection;
841
- await act(async () => renderer.update(cloneElement(panel)));
824
+ await update();
825
expect(text()).toContain("My GPT");
826
expect(text()).not.toContain("My GPT · high");
827
state.projection = projection;
845
- await act(async () => renderer.update(cloneElement(panel)));
828
+ await update();
829
expect(text()).not.toContain("Tokens");
830
expect(text()).not.toContain("Open subagent");
831
expect(text()).not.toContain("Project");
@@ -861,7 +844,7 @@ it("shows readable models and only differing workspace details in agent tooltips
844
...projection,
845
subagents: [{ ...projection.subagents[0], model }],
846
};
864
- await act(async () => renderer.update(cloneElement(panel)));
847
+ await update();
848
expect(text()).toContain(expected);
849
if (!model?.trim() || model === "gpt-5.5" || model === "custom/model-v1") {
850
expect(text()).not.toContain(" · high");
@@ -886,7 +869,7 @@ it("shows readable models and only differing workspace details in agent tooltips
869
...projection,
870
subagents: [{ ...projection.subagents[0], driver, model: null }],
871
};
889
- await act(async () => renderer.update(cloneElement(panel)));
872
+ await update();
873
expect(text()).toContain("Not reported");
874
expect(text()).not.toContain("My GPT");
875
}
@@ -1012,7 +995,7 @@ it("shows readable models and only differing workspace details in agent tooltips
995
expect(text()).toContain("My GPT · Work account · Fast mode onhigh");
996
expect(text()).not.toContain("Personal account");
997
state.projection = nativeProjection;
1015
- await act(async () => renderer.update(cloneElement(panel)));
998
+ await update();
999
expect(text()).not.toMatch(/Fast|Ultrafast|Normal|Standard|Flex| · high/);
1000
state.projection = projection;
1001
for (const modelSelection of [
@@ -1042,18 +1025,14 @@ it("shows readable models and only differing workspace details in agent tooltips
1025
},
1026
],
1027
};
1045
- await act(async () => renderer.update(cloneElement(panel)));
1028
+ await update();
1029
if (status === "completed") {
1047
- await act(async () =>
1048
- renderer.root.findByProps({ type: "button", "aria-expanded": false }).props.onClick(),
1049
- );
1030
+ await click(sectionToggle(false));
1031
}
1032
expect(text()).toContain("My GPT · Work account · Ultrafast mode onlow");
1033
expect(text()).not.toContain(" · high");
1034
}
1054
- await act(async () =>
1055
- renderer.root.findByProps({ type: "button", "aria-expanded": true }).props.onClick(),
1056
- );
1035
+ await click(sectionToggle(true));
1036
state.projection = projection;
1037
state.configs.set("test", speedConfig);
1038
child.modelSelection.options = [{ id: "reasoningEffort", value: "high" }];
@@ -1061,7 +1040,7 @@ it("shows readable models and only differing workspace details in agent tooltips
1040
expect(text()).not.toContain("My GPT ·");
1041
const config = state.configs.get("test");
1042
state.configs.clear();
1064
- await act(async () => renderer.update(cloneElement(panel)));
1043
+ await update();
1044
expect(text()).toContain("GPT-5.4");
1045
expect(text()).not.toContain("GPT-5.4 ·");
1046
await rerender();
@@ -1089,7 +1068,7 @@ it("shows readable models and only differing workspace details in agent tooltips
1068
},
1069
],
1070
};
1092
- await act(async () => renderer.update(cloneElement(panel)));
1071
+ await update();
1072
expect(text()).toContain("Checking the latest changes");
1073
expect(text()).not.toContain("Old intermediate result");
1074
const result = "Final checks passed. " + "More detail. ".repeat(50) + "Hidden tail";
@@ -1099,10 +1078,8 @@ it("shows readable models and only differing workspace details in agent tooltips
1078
{ ...projection.subagents[0], status: "failed", progress: "Stale progress", result },
1079
],
1080
};
1102
- await act(async () => renderer.update(cloneElement(panel)));
1103
- await act(async () =>
1104
- renderer.root.findByProps({ type: "button", "aria-expanded": false }).props.onClick(),
1105
- );
1081
+ await update();
1082
+ await click(sectionToggle(false));
1083
expect(text()).toContain("Final checks passed.");
1084
expect(text()).not.toContain("Stale progress");
1085
expect(text()).not.toContain("Hidden tail");
@@ -1136,7 +1113,7 @@ it("shows readable models and only differing workspace details in agent tooltips
1113
1114
state.shells = [];
1115
state.configs.clear();
1139
- await act(async () => renderer.update(cloneElement(panel)));
1116
+ await update();
1117
expect(text()).toContain("GPT-5.4");
1118
expect(text()).not.toContain("GPT-5.4 ·");
1119
expect(text()).not.toContain("gpt-5.4");
@@ -1158,13 +1135,12 @@ it("shows readable models and only differing workspace details in agent tooltips
1135
...projection,
1136
subagents: [{ ...projection.subagents[0], driver, model }],
1137
};
1161
- await act(async () => renderer.update(cloneElement(panel)));
1138
+ await update();
1139
expect(text()).toContain(expected);
1140
}
1141
});
1142
1143
it("shows the parent's own visible status as parent and child activity change", async () => {
1167
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1144
const environmentId = EnvironmentId.make("test");
1145
const parent = {
1146
id: "parent",
@@ -1195,21 +1171,15 @@ it("shows the parent's own visible status as parent and child activity change",
1171
const panel = (
1172
<ThreadRelationshipsPanel environmentId={environmentId} threadId={ThreadId.make("child")} />
1173
);
1198
- await act(async () => {
1199
- renderer = create(panel);
1200
- });
1201
- const visibleText = () =>
1202
- renderer.root
1203
- .findAll((node) => typeof node.type === "string" && node.props.className !== "sr-only")
1204
- .flatMap((node) => node.children.filter((child) => typeof child === "string"))
1205
- .join(" ");
1174
+ await render(panel);
1175
+ const visibleText = () => textNodes(" ", true);
1176
expect(visibleText()).toContain("Parent conversation");
1177
expect(visibleText()).toContain("Running");
1178
state.shells = shells(
1179
{ ...parent, activityRunStatus: "completed" },
1180
{ ...child, status: "running" },
1181
);
1212
- await act(async () => renderer.update(cloneElement(panel)));
1182
+ await update();
1183
expect(visibleText()).toContain("Done");
1184
expect(visibleText()).not.toContain("Running");
1185
});
@@ -1217,7 +1187,6 @@ it("shows the parent's own visible status as parent and child activity change",
1187
it.each(["source", "target"])(
1188
"shows transfer lifecycle states when viewing the %s thread",
1189
async (currentThreadId) => {
1220
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
1190
const environmentId = EnvironmentId.make("test");
1191
const threads = ["source", "target"].map((id) => ({
1192
id,
@@ -1253,14 +1222,9 @@ it.each(["source", "target"])(
1222
subagents: [],
1223
contextTransfers: [{ sourceThreadId: "source", targetThreadId: "target", status }],
1224
};
1256
- await act(async () => {
1257
- if (status === "pending") renderer = create(panel);
1258
- else renderer.update(cloneElement(panel));
1259
- });
1260
- const visibleText = renderer.root
1261
- .findAll((node) => typeof node.type === "string")
1262
- .flatMap((node) => node.children.filter((child) => typeof child === "string"))
1263
- .join(" ");
1225
+ if (status === "pending") await render(panel);
1226
+ else await update();
1227
+ const visibleText = textNodes(" ");
1228
expect(visibleText).toContain(
1229
currentThreadId === "source" ? "target conversation" : "source conversation",
1230
);
apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx
new
+558
@@ -0,0 +1,558 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import {
3
+ DEFAULT_UNIFIED_SETTINGS,
4
+ EnvironmentId,
5
+ ProviderDriverKind,
6
+ ProviderInstanceId,
7
+ type ServerProvider,
8
+ type UnifiedSettings,
9
+} from "@t3tools/contracts";
10
+import { AsyncResult, type Atom } from "effect/reactivity";
11
+import { act, type ReactNode } from "react";
12
+import { createRoot, type Root } from "react-dom/client";
13
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
14
+import { page, userEvent } from "vite-plus/test/browser";
15
+
16
+import "~/index.css";
17
+
18
+const state = vi.hoisted(() => ({
19
+ providers: null as unknown as Atom.Writable<ReadonlyArray<ServerProvider>>,
20
+ settings: null as unknown as UnifiedSettings,
21
+ canManageProviders: true,
22
+ canWriteSettings: true,
23
+ searchTargetId: null as string | null,
24
+ readEnvironmentIds: [] as string[],
25
+ updateEnvironmentIds: [] as string[],
26
+ mutationEnvironmentIds: [] as string[],
27
+ refresh: vi.fn(),
28
+ updateProvider: vi.fn(),
29
+ uninstall: vi.fn(),
30
+ acceptUrlAuth: vi.fn(),
31
+ updateSettings: vi.fn(),
32
+ updateModelPreferences: vi.fn(),
33
+ toggleFavorite: vi.fn(),
34
+ mutateProviderInstance: vi.fn(),
35
+}));
36
+
37
+vi.mock(import("../../state/server"), async (original) => {
38
+ const actual = await original();
39
+ const { Atom } = await import("effect/reactivity");
40
+ const providers = Atom.make<ReadonlyArray<ServerProvider>>([]).pipe(Atom.keepAlive);
41
+ state.providers = providers;
42
+ const config = Atom.make(null);
43
+ const commandLabels = {
44
+ refreshProviders: "refresh",
45
+ updateProvider: "update",
46
+ uninstallAcpRegistryManagedBinary: "uninstall",
47
+ acceptAcpRegistryUrlAuth: "accept-url-auth",
48
+ } as const;
49
+ const labelled = Object.fromEntries(
50
+ Object.entries(commandLabels).map(([key, label]) => [
51
+ key,
52
+ { ...actual.serverEnvironment[key as keyof typeof commandLabels], label },
53
+ ]),
54
+ );
55
+ return {
56
+ ...actual,
57
+ providersIgnoringCheckedAtAtom: (() => providers) as never,
58
+ serverEnvironment: {
59
+ ...actual.serverEnvironment,
60
+ ...labelled,
61
+ configValueAtom: (() => config) as never,
62
+ providersValueAtom: (() => providers) as never,
63
+ } as never,
64
+ };
65
+});
66
+vi.mock(import("../../state/use-atom-command"), async (original) => ({
67
+ ...(await original()),
68
+ useAtomCommand: ((command: { label?: string }) =>
69
+ ({
70
+ refresh: state.refresh,
71
+ update: state.updateProvider,
72
+ uninstall: state.uninstall,
73
+ "accept-url-auth": state.acceptUrlAuth,
74
+ })[command.label ?? ""] ?? vi.fn()) as never,
75
+}));
76
+vi.mock(import("../../state/query"), async (original) => ({
77
+ ...(await original()),
78
+ useEnvironmentQuery: (() => ({
79
+ data: null,
80
+ error: null,
81
+ isPending: false,
82
+ refresh: vi.fn(),
83
+ })) as never,
84
+}));
85
+vi.mock(import("../../hooks/useSettings"), async (original) => ({
86
+ ...(await original()),
87
+ useEnvironmentSettings: ((environmentId: string) => {
88
+ state.readEnvironmentIds.push(environmentId);
89
+ return state.settings;
90
+ }) as never,
91
+ useUpdateEnvironmentSettings: ((environmentId: string) => {
92
+ state.updateEnvironmentIds.push(environmentId);
93
+ return state.updateSettings;
94
+ }) as never,
95
+ useUpdateEnvironmentModelPreferences: (() => state.updateModelPreferences) as never,
96
+ useToggleEnvironmentModelFavorite: (() => state.toggleFavorite) as never,
97
+ usePersistEnvironmentProviderInstanceMutation: ((environmentId: string) => {
98
+ state.mutationEnvironmentIds.push(environmentId);
99
+ return state.mutateProviderInstance;
100
+ }) as never,
101
+}));
102
+vi.mock(import("../../state/session"), async (original) => {
103
+ const scope = (environmentId: string, requested: string) =>
104
+ environmentId === "remote-device" &&
105
+ (requested === "providers:manage"
106
+ ? state.canManageProviders
107
+ : requested === "settings:write"
108
+ ? state.canWriteSettings
109
+ : requested === "orchestration:read");
110
+ return {
111
+ ...(await original()),
112
+ useEnvironmentScope: scope as never,
113
+ readEnvironmentScope: scope as never,
114
+ };
115
+});
116
+vi.mock(import("../../state/entities"), async (original) => ({
117
+ ...(await original()),
118
+ useProjects: (() => []) as never,
119
+}));
120
+vi.mock(import("./settingsLayout"), async (original) => ({
121
+ ...(await original()),
122
+ useSettingsSearchTargetId: () => state.searchTargetId,
123
+ // The real row reads write permission and overrides from live environment state.
124
+ SettingsRow: (({
125
+ id,
126
+ title,
127
+ description,
128
+ status,
129
+ control,
130
+ children,
131
+ }: {
132
+ id?: string;
133
+ title: ReactNode;
134
+ description?: ReactNode;
135
+ status?: ReactNode;
136
+ control?: ReactNode;
137
+ children?: ReactNode;
138
+ }) => (
139
+ <div id={id}>
140
+ <h4>{title}</h4>
141
+ {description}
142
+ {status}
143
+ {control}
144
+ {children}
145
+ </div>
146
+ )) as never,
147
+}));
148
+// Its own data flows are covered by its suite; this one is about the panel.
149
+vi.mock(import("./UsageProviderSettings"), async (original) => ({
150
+ ...(await original()),
151
+ UsageProviderSettings: (() => null) as never,
152
+}));
153
+vi.mock(import("../ProviderUpdatesAction"), async (original) => ({
154
+ ...(await original()),
155
+ ProviderUpdatesAction: (() => null) as never,
156
+}));
157
+
158
+import { appAtomRegistry } from "~/rpc/atomRegistry";
159
+import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
160
+
161
+const environmentId = EnvironmentId.make("remote-device");
162
+const codexId = ProviderInstanceId.make("codex");
163
+const customId = ProviderInstanceId.make("codex_work");
164
+
165
+function provider(): ServerProvider {
166
+ return {
167
+ instanceId: codexId,
168
+ driver: ProviderDriverKind.make("codex"),
169
+ enabled: true,
170
+ installed: true,
171
+ version: "1.0.0",
172
+ status: "ready",
173
+ auth: { status: "authenticated" },
174
+ checkedAt: "2026-07-24T12:00:00.000Z",
175
+ models: [{ slug: "chosen", name: "Chosen", isCustom: false, capabilities: null }],
176
+ slashCommands: [],
177
+ skills: [],
178
+ versionAdvisory: {
179
+ status: "behind_latest",
180
+ currentVersion: "1.0.0",
181
+ latestVersion: "1.1.0",
182
+ updateCommand: "pnpm add -g @openai/codex@latest",
183
+ canUpdate: true,
184
+ checkedAt: "2026-07-24T12:00:00.000Z",
185
+ message: "Update available.",
186
+ },
187
+ };
188
+}
189
+
190
+let root: Root;
191
+let container: HTMLDivElement;
192
+
193
+const setProviders = (providers: ReadonlyArray<ServerProvider>) =>
194
+ act(async () => appAtomRegistry.set(state.providers, providers));
195
+
196
+async function render(options?: {
197
+ readonly readOnly?: boolean;
198
+ readonly targetInstanceId?: ProviderInstanceId;
199
+}) {
200
+ await act(async () =>
201
+ root.render(
202
+ <RegistryContext.Provider value={appAtomRegistry}>
203
+ <div className="@container/providers">
204
+ <EnvironmentProviderSettings
205
+ environmentId={environmentId}
206
+ environmentLabel="Remote device"
207
+ {...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly })}
208
+ {...(options?.targetInstanceId === undefined
209
+ ? {}
210
+ : { targetInstanceId: options.targetInstanceId })}
211
+ />
212
+ </div>
213
+ </RegistryContext.Provider>,
214
+ ),
215
+ );
216
+}
217
+
218
+const button = (name: string) => page.getByRole("button", { name, exact: true });
219
+const refreshButton = () => page.getByRole("button", { name: /^Refresh provider status/ });
220
+// The section header and the end of the provider list both offer Add provider.
221
+const addProvider = () => page.getByRole("button", { name: "Add provider" }).first();
222
+const select = (name: string) => button(`Select ${name}`);
223
+const deleteButton = (id: string) => button(`Delete instance ${id}`);
224
+
225
+beforeEach(async () => {
226
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
227
+ await page.viewport(1280, 900);
228
+ state.settings = DEFAULT_UNIFIED_SETTINGS;
229
+ state.canManageProviders = true;
230
+ state.canWriteSettings = true;
231
+ state.searchTargetId = null;
232
+ state.readEnvironmentIds = [];
233
+ state.updateEnvironmentIds = [];
234
+ state.mutationEnvironmentIds = [];
235
+ state.updateSettings.mockReset();
236
+ state.updateModelPreferences.mockReset();
237
+ state.toggleFavorite.mockReset();
238
+ state.mutateProviderInstance.mockReset().mockResolvedValue(AsyncResult.success({}));
239
+ state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined));
240
+ state.updateProvider.mockReset().mockResolvedValue(AsyncResult.success(undefined));
241
+ state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({}));
242
+ state.acceptUrlAuth.mockReset().mockResolvedValue(AsyncResult.success({ accepted: true }));
243
+ await setProviders([]);
244
+ container = document.createElement("div");
245
+ document.body.append(container);
246
+ root = createRoot(container);
247
+});
248
+
249
+afterEach(async () => {
250
+ await act(async () => root.unmount());
251
+ container.remove();
252
+ vi.unstubAllGlobals();
253
+});
254
+
255
+describe("EnvironmentProviderSettings routing", () => {
256
+ it("shows Codex and Claude while hiding untouched disabled provider slots", async () => {
257
+ await render();
258
+ await expect.element(select("Codex")).toBeVisible();
259
+ await expect.element(select("Claude")).toBeVisible();
260
+ for (const label of ["Cursor", "Grok", "Pi", "OpenCode", "Antigravity"]) {
261
+ await expect.element(select(label)).not.toBeInTheDocument();
262
+ }
263
+ });
264
+
265
+ it("keeps explicitly configured providers visible when disabled", async () => {
266
+ state.settings = {
267
+ ...DEFAULT_UNIFIED_SETTINGS,
268
+ providerInstances: {
269
+ [ProviderInstanceId.make("grok")]: {
270
+ driver: ProviderDriverKind.make("grok"),
271
+ enabled: false,
272
+ },
273
+ },
274
+ };
275
+ await render();
276
+ await expect.element(select("Grok")).toBeVisible();
277
+ });
278
+
279
+ it("keeps legacy provider configuration visible when disabled", async () => {
280
+ state.settings = {
281
+ ...DEFAULT_UNIFIED_SETTINGS,
282
+ providerInstances: {
283
+ [ProviderInstanceId.make("grok")]: {
284
+ driver: ProviderDriverKind.make("grok"),
285
+ enabled: false,
286
+ config: { binaryPath: "/custom/grok" },
287
+ },
288
+ },
289
+ };
290
+ await render();
291
+ await expect.element(select("Grok")).toBeVisible();
292
+ });
293
+
294
+ it("reads and writes settings on the selected environment", async () => {
295
+ await render();
296
+ await expect.element(select("Codex")).toBeVisible();
297
+ expect(new Set(state.readEnvironmentIds)).toEqual(new Set([environmentId]));
298
+ expect(new Set(state.updateEnvironmentIds)).toEqual(new Set([environmentId]));
299
+ expect(new Set(state.mutationEnvironmentIds)).toEqual(new Set([environmentId]));
300
+ });
301
+
302
+ it("routes refresh and provider update commands to the selected environment", async () => {
303
+ await setProviders([provider()]);
304
+ await render();
305
+
306
+ await userEvent.click(refreshButton());
307
+ expect(state.refresh).toHaveBeenCalledWith({
308
+ environmentId,
309
+ input: { refreshModels: true },
310
+ });
311
+
312
+ await userEvent.click(page.getByRole("button", { name: /view details/ }).last());
313
+ await userEvent.click(button("Update now"));
314
+ expect(state.updateProvider).toHaveBeenCalledWith({
315
+ environmentId,
316
+ input: { provider: ProviderDriverKind.make("codex"), instanceId: codexId },
317
+ });
318
+ });
319
+
320
+ it("opens the requested provider instance instead of the first provider", async () => {
321
+ state.settings = {
322
+ ...DEFAULT_UNIFIED_SETTINGS,
323
+ providerInstances: {
324
+ [customId]: {
325
+ driver: ProviderDriverKind.make("codex"),
326
+ enabled: true,
327
+ displayName: "Work",
328
+ },
329
+ },
330
+ };
331
+ await setProviders([provider()]);
332
+ await render({ targetInstanceId: customId });
333
+ await expect.element(deleteButton(customId)).toBeVisible();
334
+ });
335
+
336
+ it("saves model favorites and visibility on the selected environment", async () => {
337
+ await setProviders([provider()]);
338
+ await render();
339
+
340
+ await userEvent.click(button("Add Chosen to favorites"));
341
+ expect(state.toggleFavorite).toHaveBeenCalledExactlyOnceWith(codexId, "chosen");
342
+
343
+ await userEvent.click(page.getByRole("switch", { name: "Show Chosen in the model picker" }));
344
+ expect(state.updateModelPreferences).toHaveBeenCalledExactlyOnceWith({
345
+ setModelsHidden: [{ provider: codexId, model: "chosen", hidden: true }],
346
+ });
347
+ expect(state.updateSettings).not.toHaveBeenCalled();
348
+ });
349
+
350
+ it("does not substitute another account when the requested instance was removed", async () => {
351
+ await setProviders([provider()]);
352
+ await render({ targetInstanceId: customId });
353
+ await expect
354
+ .element(page.getByText("This provider instance is no longer available on this device."))
355
+ .toBeVisible();
356
+ expect(state.updateSettings).not.toHaveBeenCalled();
357
+ });
358
+
359
+ it("keeps provider selection available while write controls are read only", async () => {
360
+ state.canWriteSettings = false;
361
+ state.settings = {
362
+ ...DEFAULT_UNIFIED_SETTINGS,
363
+ providerInstances: {
364
+ [customId]: {
365
+ driver: ProviderDriverKind.make("codex"),
366
+ enabled: true,
367
+ displayName: "Work",
368
+ },
369
+ },
370
+ };
371
+ await setProviders([provider()]);
372
+ await render({ readOnly: true });
373
+
374
+ await expect.element(page.getByRole("heading", { name: "Limited permissions" })).toBeVisible();
375
+ await userEvent.click(select("Work"));
376
+ await expect.element(deleteButton(customId)).toBeInTheDocument();
377
+ expect(container.querySelector("[inert]")).not.toBeNull();
378
+ await expect.element(refreshButton()).toBeVisible();
379
+ await expect.element(addProvider()).not.toBeInTheDocument();
380
+ });
381
+
382
+ it("keeps the editable layout interactive when not read only", async () => {
383
+ await setProviders([provider()]);
384
+ await render();
385
+ await expect.element(page.getByText("Limited permissions")).not.toBeInTheDocument();
386
+ await expect.element(refreshButton()).toBeVisible();
387
+ await expect.element(addProvider()).toBeVisible();
388
+ await expect.element(page.getByRole("switch", { name: "Enable Codex" }).first()).toBeEnabled();
389
+ });
390
+
391
+ it("removes an open add-instance dialog when the provider grant is revoked", async () => {
392
+ await render();
393
+ await userEvent.click(addProvider());
394
+ await expect.element(page.getByRole("dialog")).toBeVisible();
395
+
396
+ state.canManageProviders = false;
397
+ await render({ readOnly: true });
398
+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
399
+ expect(state.updateSettings).not.toHaveBeenCalled();
400
+ });
401
+
402
+ it("keeps Advanced visible when search targets the provider health interval", async () => {
403
+ await render();
404
+ await expect.element(page.getByText("Advanced", { exact: true })).toBeVisible();
405
+ expect(container.querySelector("#provider-health-check-interval")).not.toBeNull();
406
+
407
+ state.searchTargetId = "provider-health-check-interval";
408
+ await render();
409
+ await expect.element(page.getByText("Advanced", { exact: true })).toBeVisible();
410
+ expect(container.querySelector("#provider-health-check-interval")).not.toBeNull();
411
+ });
412
+
413
+ it("deletes and resets provider configuration without erasing shared preferences", async () => {
414
+ state.settings = {
415
+ ...DEFAULT_UNIFIED_SETTINGS,
416
+ providerInstances: {
417
+ [codexId]: { driver: ProviderDriverKind.make("codex"), enabled: false },
418
+ [customId]: {
419
+ driver: ProviderDriverKind.make("codex"),
420
+ enabled: true,
421
+ displayName: "Work",
422
+ },
423
+ },
424
+ providerModelPreferences: {
425
+ [customId]: { hiddenModels: ["hidden"], modelOrder: ["model"] },
426
+ },
427
+ favorites: [{ provider: customId, model: "favorite" }],
428
+ };
429
+ await render();
430
+ await userEvent.click(select("Work"));
431
+ await userEvent.click(deleteButton(customId));
432
+ expect(state.mutateProviderInstance).toHaveBeenLastCalledWith({
433
+ operation: "remove",
434
+ instanceId: customId,
435
+ });
436
+
437
+ state.mutateProviderInstance.mockClear();
438
+ await userEvent.click(select("Codex"));
439
+ await userEvent.click(button("Reset Codex provider settings to default"));
440
+ const [resetMutation, resetPatch] = state.mutateProviderInstance.mock.lastCall ?? [];
441
+ expect(resetMutation).toEqual({ operation: "remove", instanceId: codexId });
442
+ expect(resetPatch ?? {}).toEqual({});
443
+ });
444
+
445
+ it("updates one provider instance without sending a stale whole map", async () => {
446
+ state.settings = {
447
+ ...DEFAULT_UNIFIED_SETTINGS,
448
+ providerInstances: {
449
+ [customId]: {
450
+ driver: ProviderDriverKind.make("codex"),
451
+ enabled: true,
452
+ displayName: "Work",
453
+ },
454
+ },
455
+ };
456
+ await render();
457
+ await userEvent.click(page.getByRole("switch", { name: "Enable Work" }).first());
458
+
459
+ expect(state.mutateProviderInstance).toHaveBeenCalledWith(
460
+ {
461
+ operation: "upsert",
462
+ instanceId: customId,
463
+ instance: { driver: ProviderDriverKind.make("codex"), enabled: false, displayName: "Work" },
464
+ },
465
+ {},
466
+ );
467
+ });
468
+
469
+ it("lets the server decide managed ACP cleanup after an atomic delete", async () => {
470
+ const firstId = ProviderInstanceId.make("acpRegistry_kilo_one");
471
+ const secondId = ProviderInstanceId.make("acpRegistry_kilo_two");
472
+ const registryInstance = (displayName: string) => ({
473
+ driver: ProviderDriverKind.make("acpRegistry"),
474
+ enabled: true,
475
+ displayName,
476
+ config: { agentId: "kilo" },
477
+ });
478
+ state.settings = {
479
+ ...DEFAULT_UNIFIED_SETTINGS,
480
+ providerInstances: {
481
+ [firstId]: registryInstance("Kilo one"),
482
+ [secondId]: registryInstance("Kilo two"),
483
+ },
484
+ };
485
+ await render();
486
+ await userEvent.click(select("Kilo one"));
487
+ await userEvent.click(deleteButton(firstId));
488
+
489
+ expect(state.mutateProviderInstance).toHaveBeenCalledWith({
490
+ operation: "remove",
491
+ instanceId: firstId,
492
+ });
493
+ await vi.waitFor(() =>
494
+ expect(state.uninstall).toHaveBeenCalledWith({ environmentId, input: { agentId: "kilo" } }),
495
+ );
496
+ });
497
+
498
+ it("keeps the signed-in ACP account visible when login methods are no longer advertised", async () => {
499
+ const instanceId = ProviderInstanceId.make("acpRegistry_devin");
500
+ state.settings = {
501
+ ...DEFAULT_UNIFIED_SETTINGS,
502
+ providerInstances: {
503
+ [instanceId]: {
504
+ driver: ProviderDriverKind.make("acpRegistry"),
505
+ enabled: true,
506
+ config: { agentId: "devin" },
507
+ },
508
+ },
509
+ };
510
+ await setProviders([
511
+ {
512
+ ...provider(),
513
+ instanceId,
514
+ driver: ProviderDriverKind.make("acpRegistry"),
515
+ auth: { status: "authenticated", canLogout: false },
516
+ setup: { canAuthenticate: false, canInstall: false },
517
+ },
518
+ ]);
519
+ await render({ targetInstanceId: instanceId });
520
+ await expect.element(page.getByRole("heading", { name: "Account" })).toBeVisible();
521
+ });
522
+
523
+ it("routes explicit ACP browser authentication consent to the selected environment", async () => {
524
+ const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
525
+ const action = {
526
+ elicitationId: "google-login-1",
527
+ url: "https://accounts.google.com/login",
528
+ message: "Continue with Google",
529
+ };
530
+ state.settings = {
531
+ ...DEFAULT_UNIFIED_SETTINGS,
532
+ providerInstances: {
533
+ [instanceId]: {
534
+ driver: ProviderDriverKind.make("acpRegistry"),
535
+ enabled: true,
536
+ config: { agentId: "antigravity" },
537
+ },
538
+ },
539
+ };
540
+ await setProviders([
541
+ {
542
+ ...provider(),
543
+ instanceId,
544
+ driver: ProviderDriverKind.make("acpRegistry"),
545
+ auth: { status: "unauthenticated", action },
546
+ },
547
+ ]);
548
+ await render({ targetInstanceId: instanceId });
549
+ const link = page.getByRole("link", { name: "Continue authentication" });
550
+ link.element().addEventListener("click", (event) => event.preventDefault());
551
+ await userEvent.click(link);
552
+
553
+ expect(state.acceptUrlAuth).toHaveBeenCalledWith({
554
+ environmentId,
555
+ input: { instanceId, elicitationId: action.elicitationId },
556
+ });
557
+ });
558
+});
apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx
deleted
-688
@@ -1,688 +0,0 @@
1
-import { cloneElement, isValidElement, type ReactElement } from "react";
2
-import {
3
- DEFAULT_UNIFIED_SETTINGS,
4
- EnvironmentId,
5
- ProviderDriverKind,
6
- ProviderInstanceId,
7
- type ServerProvider,
8
- type UnifiedSettings,
9
-} from "@t3tools/contracts";
10
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11
-
12
-import { visitElements } from "../../test/reactElementTree";
13
-import { reactHookHarness as hooks } from "../../test/reactHookHarness";
14
-
15
-const atoms = vi.hoisted(() => ({
16
- providers: null as ReadonlyArray<ServerProvider> | null,
17
- providersAtom: Symbol("providers"),
18
- refreshProviders: Symbol("refreshProviders"),
19
- updateProvider: Symbol("updateProvider"),
20
- uninstallAcpRegistryManagedBinary: Symbol("uninstallAcpRegistryManagedBinary"),
21
- acceptAcpRegistryUrlAuth: Symbol("acceptAcpRegistryUrlAuth"),
22
-}));
23
-
24
-const commands = vi.hoisted(() => ({
25
- refresh: vi.fn(),
26
- updateProvider: vi.fn(),
27
- uninstall: vi.fn(),
28
- acceptUrlAuth: vi.fn(),
29
- canManageProviders: true,
30
- canWriteSettings: true,
31
-}));
32
-
33
-const settingsState = vi.hoisted(() => ({
34
- value: null as UnifiedSettings | null,
35
- readEnvironmentIds: [] as EnvironmentId[],
36
- updateEnvironmentIds: [] as EnvironmentId[],
37
- mutationEnvironmentIds: [] as EnvironmentId[],
38
- updateSettings: vi.fn(),
39
- mutateProviderInstance: vi.fn(),
40
- updateClientSettings: vi.fn(),
41
-}));
42
-
43
-const settingsSearchState = vi.hoisted(() => ({
44
- targetId: null as string | null,
45
- effects: [] as Array<() => void>,
46
-}));
47
-
48
-vi.mock("react", async (importOriginal) => {
49
- const actual = await importOriginal<typeof import("react")>();
50
- const { reactHookHarness } = await import("../../test/reactHookHarness");
51
- return {
52
- ...actual,
53
- useCallback: reactHookHarness.useCallback,
54
- useEffect: (effect: () => void) => settingsSearchState.effects.push(effect),
55
- useMemo: reactHookHarness.useMemo,
56
- useRef: reactHookHarness.useRef,
57
- useState: reactHookHarness.useState,
58
- };
59
-});
60
-
61
-vi.mock("./settingsLayout", async (importOriginal) => {
62
- const actual = await importOriginal<typeof import("./settingsLayout")>();
63
- return {
64
- ...actual,
65
- useSettingsSearchTargetId: () => settingsSearchState.targetId,
66
- };
67
-});
68
-
69
-vi.mock("../../hooks/useStableCallback", () => ({
70
- useStableCallback: <F,>(fn: F) => fn,
71
-}));
72
-vi.mock("./SettingsScopeSentence", () => ({ SettingsScopeSentence: () => null }));
73
-vi.mock("react/compiler-runtime", async () => {
74
- const { reactHookHarness } = await import("../../test/reactHookHarness");
75
- return { c: reactHookHarness.useMemoCache };
76
-});
77
-
78
-vi.mock("@effect/atom-react", () => ({
79
- useAtomValue: (atom: unknown, select?: (value: null) => unknown) =>
80
- select ? select(null) : atom === atoms.providersAtom ? (atoms.providers ?? []) : null,
81
-}));
82
-
83
-vi.mock("../../state/server", () => ({
84
- EMPTY_SERVER_PROVIDERS: [],
85
- providersIgnoringCheckedAtAtom: () => atoms.providersAtom,
86
- serverEnvironment: {
87
- configValueAtom: () => atoms.providersAtom,
88
- providersValueAtom: () => atoms.providersAtom,
89
- refreshProviders: atoms.refreshProviders,
90
- updateProvider: atoms.updateProvider,
91
- uninstallAcpRegistryManagedBinary: atoms.uninstallAcpRegistryManagedBinary,
92
- acceptAcpRegistryUrlAuth: atoms.acceptAcpRegistryUrlAuth,
93
- },
94
-}));
95
-
96
-vi.mock("../../state/use-atom-command", () => ({
97
- useAtomCommand: (atom: symbol) =>
98
- atom === atoms.refreshProviders
99
- ? commands.refresh
100
- : atom === atoms.uninstallAcpRegistryManagedBinary
101
- ? commands.uninstall
102
- : atom === atoms.acceptAcpRegistryUrlAuth
103
- ? commands.acceptUrlAuth
104
- : commands.updateProvider,
105
-}));
106
-
107
-vi.mock("../../hooks/useSettings", () => ({
108
- useUpdateClientSettings: () => settingsState.updateClientSettings,
109
- useEnvironmentSettings: (environmentId: EnvironmentId) => {
110
- settingsState.readEnvironmentIds.push(environmentId);
111
- return settingsState.value;
112
- },
113
- useUpdateEnvironmentSettings: (environmentId: EnvironmentId) => {
114
- settingsState.updateEnvironmentIds.push(environmentId);
115
- return settingsState.updateSettings;
116
- },
117
- useUpdateEnvironmentModelPreferences: () => settingsState.updateSettings,
118
- useToggleEnvironmentModelFavorite: () => () => undefined,
119
- usePersistEnvironmentProviderInstanceMutation: (environmentId: EnvironmentId) => {
120
- settingsState.mutationEnvironmentIds.push(environmentId);
121
- return settingsState.mutateProviderInstance;
122
- },
123
-}));
124
-
125
-vi.mock("../../environments/primary", () => ({
126
- usePrimarySessionState: () => ({ data: null, error: null, isPending: false, refresh: vi.fn() }),
127
-}));
128
-
129
-vi.mock("../../state/session", () => ({
130
- useEnvironmentSessionState: () => ({ data: null, hasError: false, isPending: true }),
131
- useEnvironmentScope: (environmentId: EnvironmentId, scope: string) =>
132
- environmentId === "remote-device" &&
133
- (scope === "providers:manage"
134
- ? commands.canManageProviders
135
- : scope === "settings:write"
136
- ? commands.canWriteSettings
137
- : scope === "orchestration:read"),
138
- readEnvironmentScope: (environmentId: EnvironmentId, scope: string) =>
139
- environmentId === "remote-device" &&
140
- (scope === "providers:manage"
141
- ? commands.canManageProviders
142
- : scope === "settings:write"
143
- ? commands.canWriteSettings
144
- : scope === "orchestration:read"),
145
-}));
146
-
147
-vi.mock("../../state/entities", () => ({
148
- useProjects: () => [],
149
- useServerConfigs: () => new Map(),
150
-}));
151
-
152
-import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
153
-import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
154
-
155
-const environmentId = EnvironmentId.make("remote-device");
156
-const codexId = ProviderInstanceId.make("codex");
157
-const customId = ProviderInstanceId.make("codex_work");
158
-
159
-function provider(): ServerProvider {
160
- return {
161
- instanceId: codexId,
162
- driver: ProviderDriverKind.make("codex"),
163
- enabled: true,
164
- installed: true,
165
- version: "1.0.0",
166
- status: "ready",
167
- auth: { status: "authenticated" },
168
- checkedAt: "2026-07-24T12:00:00.000Z",
169
- models: [],
170
- slashCommands: [],
171
- skills: [],
172
- versionAdvisory: {
173
- status: "behind_latest",
174
- currentVersion: "1.0.0",
175
- latestVersion: "1.1.0",
176
- updateCommand: "pnpm add -g @openai/codex@latest",
177
- canUpdate: true,
178
- checkedAt: "2026-07-24T12:00:00.000Z",
179
- message: "Update available.",
180
- },
181
- };
182
-}
183
-
184
-function renderPanel(options?: {
185
- readonly readOnly?: boolean;
186
- readonly targetInstanceId?: ProviderInstanceId;
187
-}): ReactElement<Record<string, unknown>> {
188
- hooks.beginRender();
189
- return expandProviderRows(
190
- EnvironmentProviderSettings({
191
- environmentId,
192
- environmentLabel: "Remote device",
193
- ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),
194
- ...(options?.targetInstanceId === undefined
195
- ? {}
196
- : { targetInstanceId: options.targetInstanceId }),
197
- }),
198
- ) as ReactElement<Record<string, unknown>>;
199
-}
200
-
201
-// Renders the row components inline so assertions see the cards they return.
202
-function expandProviderRows(node: unknown): unknown {
203
- if (Array.isArray(node)) return node.map(expandProviderRows);
204
- if (!isValidElement<Record<string, unknown>>(node)) return node;
205
- if (typeof node.type === "function" && node.type.name === "ProviderInstanceRow") {
206
- return expandProviderRows((node.type as (props: unknown) => unknown)(node.props));
207
- }
208
- const props: Record<string, unknown> = {};
209
- let changed = false;
210
- for (const [key, value] of Object.entries(node.props)) {
211
- const expanded = expandProviderRows(value);
212
- if (expanded !== value) changed = true;
213
- props[key] = expanded;
214
- }
215
- return changed ? cloneElement(node, props) : node;
216
-}
217
-
218
-function isRefreshButton(element: ReactElement<Record<string, unknown>>): boolean {
219
- const children = element.props.children;
220
- return (
221
- Array.isArray(children) &&
222
- children.some(
223
- (child) =>
224
- typeof child === "object" &&
225
- child !== null &&
226
- (child as ReactElement<Record<string, unknown>>).props?.className === "sr-only" &&
227
- (child as ReactElement<Record<string, unknown>>).props?.children ===
228
- "Refresh provider status",
229
- )
230
- );
231
-}
232
-
233
-function isAddProviderButton(element: ReactElement<Record<string, unknown>>): boolean {
234
- return element.props["aria-label"] === "Add provider";
235
-}
236
-
237
-async function flushPromises(): Promise<void> {
238
- await Promise.resolve();
239
- await Promise.resolve();
240
-}
241
-
242
-describe("EnvironmentProviderSettings routing", () => {
243
- beforeEach(() => {
244
- hooks.reset();
245
- atoms.providers = null;
246
- settingsState.value = DEFAULT_UNIFIED_SETTINGS;
247
- settingsState.readEnvironmentIds = [];
248
- settingsState.updateEnvironmentIds = [];
249
- settingsState.mutationEnvironmentIds = [];
250
- settingsState.updateSettings.mockReset();
251
- settingsState.updateClientSettings.mockReset();
252
- settingsSearchState.targetId = null;
253
- settingsSearchState.effects = [];
254
- settingsState.mutateProviderInstance
255
- .mockReset()
256
- .mockResolvedValue({ _tag: "Success", value: {} });
257
- commands.canManageProviders = true;
258
- commands.canWriteSettings = true;
259
- commands.refresh.mockReset().mockResolvedValue({ _tag: "Success" });
260
- commands.updateProvider.mockReset().mockResolvedValue({ _tag: "Success" });
261
- commands.uninstall.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
262
- commands.acceptUrlAuth
263
- .mockReset()
264
- .mockResolvedValue({ _tag: "Success", value: { accepted: true } });
265
- });
266
-
267
- it("shows Codex and Claude while hiding untouched disabled provider slots", () => {
268
- const panel = renderPanel();
269
- for (const driver of ["codex", "claudeAgent"] as const) {
270
- expect(
271
- visitElements(
272
- panel,
273
- (element) => element.props.instanceId === driver && element.props.mode === "list",
274
- ),
275
- ).not.toBeNull();
276
- }
277
- for (const driver of ["cursor", "grok", "pi", "opencode", "antigravity"] as const) {
278
- expect(
279
- visitElements(
280
- panel,
281
- (element) => element.props.instanceId === driver && element.props.mode === "list",
282
- ),
283
- ).toBeNull();
284
- }
285
- });
286
-
287
- it("keeps explicitly configured providers visible when disabled", () => {
288
- const grokId = ProviderInstanceId.make("grok");
289
- settingsState.value = {
290
- ...DEFAULT_UNIFIED_SETTINGS,
291
- providerInstances: {
292
- [grokId]: { driver: ProviderDriverKind.make("grok"), enabled: false },
293
- },
294
- };
295
- const panel = renderPanel();
296
- expect(
297
- visitElements(
298
- panel,
299
- (element) => element.props.instanceId === grokId && element.props.mode === "list",
300
- ),
301
- ).not.toBeNull();
302
- });
303
-
304
- it("keeps legacy provider configuration visible when disabled", () => {
305
- settingsState.value = {
306
- ...DEFAULT_UNIFIED_SETTINGS,
307
- providerInstances: {
308
- [ProviderInstanceId.make("grok")]: {
309
- driver: ProviderDriverKind.make("grok"),
310
- enabled: false,
311
- config: {
312
- binaryPath: "/custom/grok",
313
- },
314
- },
315
- },
316
- };
317
- const panel = renderPanel();
318
- expect(
319
- visitElements(
320
- panel,
321
- (element) => element.props.instanceId === "grok" && element.props.mode === "list",
322
- ),
323
- ).not.toBeNull();
324
- });
325
-
326
- it("coalesces a nullable provider snapshot before rendering array-backed UI", () => {
327
- expect(() => renderPanel()).not.toThrow();
328
- expect(settingsState.readEnvironmentIds).toEqual([environmentId]);
329
- expect(settingsState.updateEnvironmentIds).toEqual([environmentId]);
330
- expect(settingsState.mutationEnvironmentIds).toEqual([environmentId]);
331
- });
332
-
333
- it("routes refresh and provider update commands to the selected environment", async () => {
334
- atoms.providers = [provider()];
335
- const panel = renderPanel();
336
- const refreshButton = visitElements(panel, isRefreshButton);
337
- expect(refreshButton).not.toBeNull();
338
- (refreshButton?.props.onClick as (() => void) | undefined)?.();
339
- await flushPromises();
340
-
341
- expect(commands.refresh).toHaveBeenCalledWith({
342
- environmentId,
343
- input: { refreshModels: true },
344
- });
345
-
346
- const providerCard = visitElements(
347
- panel,
348
- (element) =>
349
- element.props.instanceId === codexId && typeof element.props.onRunUpdate === "function",
350
- );
351
- expect(providerCard).not.toBeNull();
352
- (providerCard?.props.onRunUpdate as (() => void) | undefined)?.();
353
- await flushPromises();
354
-
355
- expect(commands.updateProvider).toHaveBeenCalledWith({
356
- environmentId,
357
- input: { provider: ProviderDriverKind.make("codex"), instanceId: codexId },
358
- });
359
- });
360
-
361
- it("opens the requested provider instance instead of the first provider", () => {
362
- settingsState.value = {
363
- ...DEFAULT_UNIFIED_SETTINGS,
364
- providerInstances: {
365
- [customId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
366
- },
367
- };
368
- atoms.providers = [provider()];
369
- const panel = renderPanel({ targetInstanceId: customId });
370
- const editor = visitElements(panel, (element) => element.props.mode === "editor");
371
- expect(editor?.props.instanceId).toBe(customId);
372
- });
373
-
374
- it.each([
375
- [
376
- "onFavoriteModelsChange",
377
- { setModelFavorites: [{ provider: codexId, model: "chosen", favorite: true }] },
378
- ],
379
- [
380
- "onHiddenModelsChange",
381
- { setModelsHidden: [{ provider: codexId, model: "chosen", hidden: true }] },
382
- ],
383
- [
384
- "onModelOrderChange",
385
- { setProviderModelOrder: { provider: codexId, modelOrder: ["chosen"] } },
386
- ],
387
- ])("saves %s on the selected environment for every connected client", (action, expected) => {
388
- atoms.providers = [provider()];
389
- const panel = renderPanel();
390
- const editor = visitElements(
391
- panel,
392
- (element) => element.props.instanceId === codexId && element.props.mode === "editor",
393
- );
394
- expect(editor).not.toBeNull();
395
- if (!editor) throw new Error("Provider editor was not rendered");
396
- (editor.props[action] as (models: string[]) => void)(["chosen"]);
397
- expect(settingsState.updateSettings).toHaveBeenCalledExactlyOnceWith(expected);
398
- expect(settingsState.updateClientSettings).not.toHaveBeenCalled();
399
- });
400
-
401
- it("does not substitute another account when the requested instance was removed", () => {
402
- atoms.providers = [provider()];
403
- const panel = renderPanel({ targetInstanceId: customId });
404
- expect(visitElements(panel, (element) => element.props.mode === "editor")).toBeNull();
405
- expect(settingsState.updateSettings).not.toHaveBeenCalled();
406
- });
407
-
408
- it("keeps provider selection available while write controls are read only", () => {
409
- commands.canWriteSettings = false;
410
- settingsState.value = {
411
- ...DEFAULT_UNIFIED_SETTINGS,
412
- providerInstances: {
413
- [customId]: {
414
- driver: ProviderDriverKind.make("codex"),
415
- enabled: true,
416
- },
417
- },
418
- };
419
- atoms.providers = [provider()];
420
- let panel = renderPanel({ readOnly: true });
421
-
422
- const inertWrapper = visitElements(panel, (element) => element.props.inert === true);
423
- expect(inertWrapper).not.toBeNull();
424
-
425
- const customRow = visitElements(
426
- panel,
427
- (element) => element.props.instanceId === customId && element.props.mode === "list",
428
- );
429
- expect(customRow?.props.readOnly).toBe(true);
430
- expect(customRow?.props.onSelect).toBeTypeOf("function");
431
- (customRow?.props.onSelect as (() => void) | undefined)?.();
432
-
433
- panel = renderPanel({ readOnly: true });
434
- const customEditor = visitElements(
435
- panel,
436
- (element) => element.props.instanceId === customId && element.props.mode === "editor",
437
- );
438
- expect(customEditor).not.toBeNull();
439
-
440
- const notice = visitElements(panel, (element) => element.props.title === "Limited permissions");
441
- expect(notice).not.toBeNull();
442
-
443
- expect(visitElements(panel, isRefreshButton)).not.toBeNull();
444
- expect(visitElements(panel, isAddProviderButton)).toBeNull();
445
- });
446
-
447
- it("keeps the editable layout interactive when not read only", () => {
448
- atoms.providers = [provider()];
449
- const panel = renderPanel();
450
- expect(visitElements(panel, (element) => element.props.inert === true)).toBeNull();
451
- expect(
452
- visitElements(panel, (element) => element.props.title === "Limited permissions"),
453
- ).toBeNull();
454
- expect(visitElements(panel, isRefreshButton)).not.toBeNull();
455
- expect(visitElements(panel, isAddProviderButton)).not.toBeNull();
456
- });
457
-
458
- it("removes an open add-instance dialog when the provider grant is revoked", () => {
459
- let panel = renderPanel();
460
- const add = visitElements(panel, isAddProviderButton);
461
- if (!add) throw new Error("Missing Add provider action.");
462
- (add.props.onClick as () => void)();
463
- panel = renderPanel();
464
- expect(
465
- visitElements(panel, (element) => element.type === AddProviderInstanceDialog),
466
- ).not.toBeNull();
467
-
468
- commands.canManageProviders = false;
469
- panel = renderPanel({ readOnly: true });
470
- expect(
471
- visitElements(panel, (element) => element.type === AddProviderInstanceDialog),
472
- ).toBeNull();
473
- expect(settingsState.updateSettings).not.toHaveBeenCalled();
474
- });
475
-
476
- it("keeps Advanced visible when search targets the provider health interval", () => {
477
- let panel = renderPanel();
478
- expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
479
- expect(
480
- visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
481
- ).not.toBeNull();
482
-
483
- settingsSearchState.targetId = "provider-health-check-interval";
484
- panel = renderPanel();
485
- expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
486
- expect(
487
- visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
488
- ).not.toBeNull();
489
- });
490
-
491
- it("deletes and resets provider configuration without erasing shared preferences", async () => {
492
- settingsState.value = {
493
- ...DEFAULT_UNIFIED_SETTINGS,
494
- providerInstances: {
495
- [codexId]: {
496
- driver: ProviderDriverKind.make("codex"),
497
- enabled: false,
498
- },
499
- [customId]: {
500
- driver: ProviderDriverKind.make("codex"),
501
- enabled: true,
502
- },
503
- },
504
- providerModelPreferences: {
505
- [customId]: { hiddenModels: ["hidden"], modelOrder: ["model"] },
506
- },
507
- favorites: [{ provider: customId, model: "favorite" }],
508
- };
509
- let panel = renderPanel();
510
- const customRow = visitElements(
511
- panel,
512
- (element) => element.props.instanceId === customId && element.props.mode === "list",
513
- );
514
- (customRow?.props.onSelect as (() => void) | undefined)?.();
515
- panel = renderPanel();
516
- const customCard = visitElements(
517
- panel,
518
- (element) => element.props.instanceId === customId && element.props.mode === "editor",
519
- );
520
- expect(customCard).not.toBeNull();
521
- (customCard?.props.onDelete as (() => void) | undefined)?.();
522
- await flushPromises();
523
-
524
- expect(settingsState.mutateProviderInstance).toHaveBeenLastCalledWith({
525
- operation: "remove",
526
- instanceId: customId,
527
- });
528
-
529
- settingsState.mutateProviderInstance.mockClear();
530
- const defaultRow = visitElements(
531
- panel,
532
- (element) => element.props.instanceId === codexId && element.props.mode === "list",
533
- );
534
- (defaultRow?.props.onSelect as (() => void) | undefined)?.();
535
- panel = renderPanel();
536
- const defaultCard = visitElements(
537
- panel,
538
- (element) => element.props.instanceId === codexId && element.props.mode === "editor",
539
- );
540
- const resetAction = defaultCard?.props.headerAction;
541
- const resetButton = visitElements(
542
- resetAction,
543
- (element) => typeof element.props.onClick === "function",
544
- );
545
- expect(resetButton).not.toBeNull();
546
- (resetButton?.props.onClick as (() => void) | undefined)?.();
547
- await flushPromises();
548
-
549
- const [resetMutation, resetPatch] = settingsState.mutateProviderInstance.mock.lastCall ?? [];
550
- expect(resetMutation).toEqual({ operation: "remove", instanceId: codexId });
551
- expect(resetPatch ?? {}).toEqual({});
552
- });
553
-
554
- it("updates one provider instance without sending a stale whole map", async () => {
555
- settingsState.value = {
556
- ...DEFAULT_UNIFIED_SETTINGS,
557
- providerInstances: {
558
- [customId]: {
559
- driver: ProviderDriverKind.make("codex"),
560
- enabled: true,
561
- displayName: "Work",
562
- },
563
- },
564
- };
565
- const panel = renderPanel();
566
- const card = visitElements(panel, (element) => element.props.instanceId === customId);
567
- const next = {
568
- driver: ProviderDriverKind.make("codex"),
569
- enabled: false,
570
- displayName: "Work",
571
- };
572
- (card?.props.onUpdate as ((instance: typeof next) => void) | undefined)?.(next);
573
- await flushPromises();
574
-
575
- expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith(
576
- { operation: "upsert", instanceId: customId, instance: next },
577
- {},
578
- );
579
- });
580
-
581
- it("lets the server decide managed ACP cleanup after an atomic delete", async () => {
582
- const firstId = ProviderInstanceId.make("acpRegistry_kilo_one");
583
- const secondId = ProviderInstanceId.make("acpRegistry_kilo_two");
584
- const registryInstance = {
585
- driver: ProviderDriverKind.make("acpRegistry"),
586
- enabled: true,
587
- config: { agentId: "kilo" },
588
- };
589
- settingsState.value = {
590
- ...DEFAULT_UNIFIED_SETTINGS,
591
- providerInstances: {
592
- [firstId]: registryInstance,
593
- [secondId]: registryInstance,
594
- },
595
- };
596
- let panel = renderPanel();
597
- const row = visitElements(
598
- panel,
599
- (element) => element.props.instanceId === firstId && element.props.mode === "list",
600
- );
601
- (row?.props.onSelect as (() => void) | undefined)?.();
602
- panel = renderPanel();
603
- const card = visitElements(
604
- panel,
605
- (element) => element.props.instanceId === firstId && element.props.mode === "editor",
606
- );
607
- (card?.props.onDelete as (() => void) | undefined)?.();
608
- await flushPromises();
609
-
610
- expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith({
611
- operation: "remove",
612
- instanceId: firstId,
613
- });
614
- expect(commands.uninstall).toHaveBeenCalledWith({
615
- environmentId,
616
- input: { agentId: "kilo" },
617
- });
618
- });
619
-
620
- it("keeps the signed-in ACP account visible when login methods are no longer advertised", () => {
621
- const instanceId = ProviderInstanceId.make("acpRegistry_devin");
622
- settingsState.value = {
623
- ...DEFAULT_UNIFIED_SETTINGS,
624
- providerInstances: {
625
- [instanceId]: {
626
- driver: ProviderDriverKind.make("acpRegistry"),
627
- enabled: true,
628
- config: { agentId: "devin" },
629
- },
630
- },
631
- };
632
- atoms.providers = [
633
- {
634
- ...provider(),
635
- instanceId,
636
- driver: ProviderDriverKind.make("acpRegistry"),
637
- auth: { status: "authenticated", canLogout: false },
638
- setup: { canAuthenticate: false, canInstall: false },
639
- },
640
- ];
641
- const panel = renderPanel({ targetInstanceId: instanceId });
642
- expect(
643
- visitElements(
644
- panel,
645
- (element) =>
646
- typeof element.type === "function" &&
647
- element.type.name === "ProviderAuthenticationSection",
648
- ),
649
- ).not.toBeNull();
650
- });
651
-
652
- it("routes explicit ACP browser authentication consent to the selected environment", async () => {
653
- const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
654
- const action = {
655
- elicitationId: "google-login-1",
656
- url: "https://accounts.google.com/login",
657
- message: "Continue with Google",
658
- };
659
- settingsState.value = {
660
- ...DEFAULT_UNIFIED_SETTINGS,
661
- providerInstances: {
662
- [instanceId]: {
663
- driver: ProviderDriverKind.make("acpRegistry"),
664
- enabled: true,
665
- config: { agentId: "antigravity" },
666
- },
667
- },
668
- };
669
- atoms.providers = [
670
- {
671
- ...provider(),
672
- instanceId,
673
- driver: ProviderDriverKind.make("acpRegistry"),
674
- auth: { status: "unauthenticated", action },
675
- },
676
- ];
677
-
678
- const panel = renderPanel();
679
- const card = visitElements(panel, (element) => element.props.instanceId === instanceId);
680
- (card?.props.onAcceptUrlAuth as ((candidate: typeof action) => void) | undefined)?.(action);
681
- await flushPromises();
682
-
683
- expect(commands.acceptUrlAuth).toHaveBeenCalledWith({
684
- environmentId,
685
- input: { instanceId, elicitationId: action.elicitationId },
686
- });
687
- });
688
-});
apps/web/src/components/settings/SourceControlWritingSettings.browser.test.tsx
renamed
+81
-100
@@ -1,8 +1,10 @@
1
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
2
import { act, StrictMode, type ReactNode } from "react";
3
-import { create, type ReactTestRenderer } from "react-test-renderer";
3
+import { createRoot, type Root } from "react-dom/client";
4
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5
+import { page, userEvent } from "vite-plus/test/browser";
6
7
+import "../../index.css";
8
import type { ScopedSettingsPatch } from "./scopedSettings";
9
10
type WritingStyle = typeof DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
@@ -11,90 +13,77 @@ const state = vi.hoisted(() => ({
13
updateSettings: vi.fn<(patch: ScopedSettingsPatch) => void>(),
14
}));
15
14
-vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
15
-vi.mock("./useScopedSettings", () => ({
16
- useScopedSettings: () => ({
16
+vi.mock(import("@tanstack/react-router"), async (original) => ({
17
+ ...(await original()),
18
+ useNavigate: (() => vi.fn()) as never,
19
+}));
20
+vi.mock(import("./useScopedSettings"), async (original) => ({
21
+ ...(await original()),
22
+ useScopedSettings: (() => ({
23
...DEFAULT_UNIFIED_SETTINGS,
24
sourceControlWritingStyle: state.styles[0],
19
- }),
20
- useScopedSettingsMixed: (keys: ReadonlyArray<string>) =>
25
+ })) as never,
26
+ useScopedSettingsMixed: (keys) =>
27
!keys.includes("reviewGuidesEnabled") &&
28
JSON.stringify(state.styles[0]) !== JSON.stringify(state.styles[1]),
29
useUpdateScopedSettings: () => state.updateSettings,
30
}));
25
-vi.mock("./SettingsScopeContext", () => ({
26
- useSettingsScope: () => ({
31
+vi.mock(import("./SettingsScopeContext"), async (original) => ({
32
+ ...(await original()),
33
+ useSettingsScope: (() => ({
34
scope: { kind: "all", environmentIds: [] },
35
environment: null,
36
connectedEnvironments: [],
37
targets: state.styles.map((style) => ({
38
settings: { ...DEFAULT_UNIFIED_SETTINGS, sourceControlWritingStyle: style },
39
})),
33
- }),
40
+ target: null,
41
+ })) as never,
42
}));
35
-vi.mock("./useScopedModelAvailability", () => ({
36
- useScopedModelDisabledReason: () => () => null,
43
+vi.mock(import("../../state/environments"), async (original) => ({
44
+ ...(await original()),
45
+ useEnvironmentProviders: () => new Map(),
46
}));
38
-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
39
-vi.mock("../../state/server", () => ({ EMPTY_SERVER_PROVIDERS: [] }));
40
-vi.mock("../../state/environments", () => ({ useEnvironmentProviders: () => new Map() }));
41
-vi.mock("../chat/ProviderModelPicker", () => ({ ProviderModelPicker: () => null }));
42
-vi.mock("./settingsSearch", () => ({ searchableSetting: (id: string) => ({ id, title: id }) }));
43
-vi.mock("./settingsLayout", () => ({
44
- SETTINGS_PICKER_TRIGGER_CLASSNAME: "",
45
- SettingResetButton: ({ label, onClick }: { label: string; onClick: () => void }) => (
46
- <button onClick={onClick}>{`Reset ${label}`}</button>
47
- ),
48
- SettingsSection: ({ children }: { children: ReactNode }) => children,
49
- SettingsRow: ({
50
- children,
51
- control,
52
- resetAction,
53
- }: {
54
- children: ReactNode;
55
- control: ReactNode;
56
- resetAction: ReactNode;
57
- }) => (
47
+// The real row reads write permission and overrides from live environment state; this
48
+// suite is about how the section writes mixed writing styles.
49
+vi.mock(import("./settingsLayout"), async (original) => ({
50
+ ...(await original()),
51
+ SettingsRow: ({ title, control, resetAction, children }) => (
52
<div>
53
+ <h3>{title}</h3>
54
{control}
55
{resetAction}
56
{children}
57
</div>
58
),
59
+ SettingsSection: (({ children }: { children: ReactNode }) => children) as never,
60
}));
65
-vi.mock("../ui/select", () => ({
66
- Select: ({ children }: { children: ReactNode }) => children,
67
- SelectItem: "span",
68
- SelectPopup: "div",
69
- SelectTrigger: "div",
70
- SelectValue: "span",
71
-}));
72
-vi.mock("../ui/switch", () => ({ Switch: "input" }));
73
-vi.mock("../ui/textarea", () => ({ Textarea: "textarea" }));
74
-vi.mock("../ui/button", () => ({ Button: "button" }));
61
62
import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
63
78
-let renderer: ReactTestRenderer | null;
79
-
80
-function button(label: string) {
81
- return renderer!.root.findAllByType("button").find((item) => item.children.includes(label))!;
82
-}
64
+let root: Root;
65
+let container: HTMLDivElement;
66
84
-function openEditor() {
85
- act(() => button("Write custom instructions for all").props.onClick());
86
-}
87
-
88
-function editInstructions(value: string) {
89
- act(() => renderer!.root.findByType("textarea").props.onChange({ target: { value } }));
90
-}
67
+const resetButton = (label: string) =>
68
+ page.getByRole("button", { name: `Reset ${label} to default` });
69
+const writeForAll = () => page.getByRole("button", { name: "Write custom instructions for all" });
70
+const applyToAll = () => page.getByRole("button", { name: "Apply instructions to all" });
71
+const bulkEditor = () =>
72
+ page.getByRole("textbox", {
73
+ name: "Custom source control instructions for all selected environments",
74
+ });
75
92
-function applyInstructions() {
93
- act(() => button("Apply instructions to all").props.onClick());
76
+async function render() {
77
+ await act(async () =>
78
+ root.render(
79
+ <StrictMode>
80
+ <SourceControlWritingSettingsSection />
81
+ </StrictMode>,
82
+ ),
83
+ );
84
}
85
96
-beforeEach(() => {
97
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
86
+beforeEach(async () => {
87
state.styles = [
88
{
89
...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle,
@@ -111,30 +100,27 @@ beforeEach(() => {
100
];
101
state.updateSettings.mockReset().mockImplementation((patch) => {
102
state.styles = state.styles.map((style) => ({ ...style, ...patch.sourceControlWritingStyle }));
103
+ void render();
104
});
115
- act(() => {
116
- renderer = create(
117
- <StrictMode>
118
- <SourceControlWritingSettingsSection />
119
- </StrictMode>,
120
- );
121
- });
105
+ container = document.createElement("div");
106
+ document.body.append(container);
107
+ root = createRoot(container);
108
+ await render();
109
});
110
111
afterEach(async () => {
125
- await act(async () => renderer?.unmount());
126
- renderer = null;
127
- vi.unstubAllGlobals();
112
+ await act(async () => root.unmount());
113
+ container.remove();
114
});
115
116
describe("mixed source control instructions", () => {
131
- it("resets mixed template preferences without replacing each environment's instructions", () => {
117
+ it("resets mixed template preferences without replacing each environment's instructions", async () => {
118
const initialInstructions = state.styles.map(({ mode, customInstructions }) => ({
119
mode,
120
customInstructions,
121
}));
122
137
- act(() => button("Reset change request templates").props.onClick());
123
+ await userEvent.click(resetButton("change request templates"));
124
125
expect(state.updateSettings).toHaveBeenCalledTimes(1);
126
expect(state.styles.map((style) => style.followChangeRequestTemplates)).toEqual([
@@ -146,17 +132,11 @@ describe("mixed source control instructions", () => {
132
).toEqual(initialInstructions);
133
});
134
149
- it("resets every environment even when the representative already has default instructions", () => {
135
+ it("resets every environment even when the representative already has default instructions", async () => {
136
state.styles[0] = { ...DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle };
151
- act(() => {
152
- renderer!.update(
153
- <StrictMode>
154
- <SourceControlWritingSettingsSection />
155
- </StrictMode>,
156
- );
157
- });
137
+ await render();
138
159
- act(() => button("Reset source control writing style").props.onClick());
139
+ await userEvent.click(resetButton("source control writing style"));
140
141
expect(state.updateSettings).toHaveBeenCalledTimes(1);
142
expect(
@@ -170,22 +150,21 @@ describe("mixed source control instructions", () => {
150
expect(state.styles[1]!.followChangeRequestTemplates).toBe(false);
151
});
152
173
- it("does not write an untouched bulk draft", () => {
153
+ it("does not write an untouched bulk draft", async () => {
154
const initialStyles = state.styles;
175
- openEditor();
176
- expect(renderer!.root.findByType("textarea").props.value).toBe("");
177
- expect(button("Apply instructions to all").props.disabled).toBe(true);
155
+ await userEvent.click(writeForAll());
156
+ await expect.element(bulkEditor()).toHaveValue("");
157
+ await expect.element(applyToAll()).toBeDisabled();
158
179
- applyInstructions();
159
expect(state.updateSettings).not.toHaveBeenCalled();
160
expect(state.styles).toEqual(initialStyles);
161
});
162
184
- it("applies edited instructions to every selected environment", () => {
185
- openEditor();
186
- editInstructions(" Keep titles concise. ");
187
- expect(button("Apply instructions to all").props.disabled).toBe(false);
188
- applyInstructions();
163
+ it("applies edited instructions to every selected environment", async () => {
164
+ await userEvent.click(writeForAll());
165
+ await userEvent.fill(bulkEditor(), " Keep titles concise. ");
166
+ await expect.element(applyToAll()).toBeEnabled();
167
+ await userEvent.click(applyToAll());
168
169
expect(state.updateSettings).toHaveBeenCalledTimes(1);
170
expect(state.styles.map((style) => style.customInstructions)).toEqual([
@@ -195,28 +174,30 @@ describe("mixed source control instructions", () => {
174
expect(state.styles.map((style) => style.followChangeRequestTemplates)).toEqual([true, false]);
175
});
176
198
- it("allows an intentional clear after editing", () => {
199
- openEditor();
200
- editInstructions("Temporary instructions");
201
- editInstructions("");
202
- expect(button("Apply instructions to all").props.disabled).toBe(false);
203
- applyInstructions();
177
+ it("allows an intentional clear after editing", async () => {
178
+ await userEvent.click(writeForAll());
179
+ await userEvent.fill(bulkEditor(), "Temporary instructions");
180
+ await userEvent.clear(bulkEditor());
181
+ await expect.element(applyToAll()).toBeEnabled();
182
+ await userEvent.click(applyToAll());
183
184
expect(state.updateSettings).toHaveBeenCalledTimes(1);
185
expect(state.styles.map((style) => style.customInstructions)).toEqual(["", ""]);
186
});
187
209
- it("shows the plain editor once instructions agree, even while templates differ", () => {
210
- openEditor();
211
- editInstructions("Shared instructions");
212
- applyInstructions();
188
+ it("shows the plain editor once instructions agree, even while templates differ", async () => {
189
+ await userEvent.click(writeForAll());
190
+ await userEvent.fill(bulkEditor(), "Shared instructions");
191
+ await userEvent.click(applyToAll());
192
193
expect(state.updateSettings).toHaveBeenCalledTimes(1);
194
expect(state.styles.map((style) => style.customInstructions)).toEqual([
195
"Shared instructions",
196
"Shared instructions",
197
]);
219
- expect(button("Write custom instructions for all")).toBeUndefined();
220
- expect(renderer!.root.findByType("textarea").props.defaultValue).toBe("Shared instructions");
198
+ await expect.element(writeForAll()).not.toBeInTheDocument();
199
+ await expect
200
+ .element(page.getByRole("textbox", { name: "Custom source control writing instructions" }))
201
+ .toHaveValue("Shared instructions");
202
});
203
});
apps/web/src/components/usage/UsagePage.refresh.browser.test.tsx
new
+249
@@ -0,0 +1,249 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { EnvironmentId, ProviderInstanceId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
3
+import { mergeUsage } from "@t3tools/shared/usageMerge";
4
+import type { Atom } from "effect/reactivity";
5
+import { act, StrictMode } from "react";
6
+import { createRoot, type Root } from "react-dom/client";
7
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
8
+import { page, userEvent } from "vite-plus/test/browser";
9
+
10
+import "~/index.css";
11
+
12
+type Presentations = ReadonlyMap<EnvironmentId, Record<string, unknown>>;
13
+const state = vi.hoisted(() => ({
14
+ presentations: null as unknown as Atom.Writable<Presentations>,
15
+ refreshProviders: vi.fn<(input: unknown) => Promise<undefined>>(),
16
+}));
17
+
18
+vi.mock(import("@tanstack/react-router"), async (original) => ({
19
+ ...(await original()),
20
+ useNavigate: (() => vi.fn()) as never,
21
+ useCanGoBack: () => false,
22
+}));
23
+// Real presentations come from live connections; these tests drive them directly.
24
+vi.mock(import("../../state/presentation"), async (original) => {
25
+ const actual = await original();
26
+ const { Atom } = await import("effect/reactivity");
27
+ const presentations = Atom.make<Presentations>(new Map()).pipe(Atom.keepAlive);
28
+ state.presentations = presentations;
29
+ const providers = Atom.make(
30
+ (get) =>
31
+ new Map(
32
+ [...get(presentations)].map(([id, presentation]) => [
33
+ id,
34
+ (presentation.serverConfig as { providers: unknown }).providers,
35
+ ]),
36
+ ),
37
+ );
38
+ return {
39
+ ...actual,
40
+ environmentPresentations: {
41
+ ...actual.environmentPresentations,
42
+ presentationsAtom: presentations as never,
43
+ presentationsWithProvidersAtom: presentations as never,
44
+ providersByEnvironmentAtom: providers as never,
45
+ },
46
+ };
47
+});
48
+vi.mock(import("../../state/use-atom-command"), async (original) => ({
49
+ ...(await original()),
50
+ useAtomCommand: (() => state.refreshProviders) as never,
51
+}));
52
+vi.mock(import("../../state/usage"), async (original) => {
53
+ const environment = {
54
+ environmentId: EnvironmentId.make("test"),
55
+ label: "Test",
56
+ isPending: false,
57
+ canReadDiagnostics: true,
58
+ error: null,
59
+ summary: null,
60
+ };
61
+ return {
62
+ ...(await original()),
63
+ useUsage: (() => ({
64
+ merged: mergeUsage([], USAGE_CONTRACT_VERSION),
65
+ environments: [environment],
66
+ selectedEnvironments: [environment],
67
+ isPending: false,
68
+ shown: null,
69
+ isPartial: false,
70
+ refresh: async () => undefined,
71
+ })) as never,
72
+ };
73
+});
74
+
75
+import { appAtomRegistry } from "~/rpc/atomRegistry";
76
+import { UsagePage } from "./UsagePage";
77
+
78
+const PREFERENCES_KEY = "t3code:usage-page-preferences:v1";
79
+let root: Root;
80
+let container: HTMLDivElement;
81
+// Limits refreshes are throttled per environment for the whole session, so each test
82
+// gets fresh environment ids.
83
+let environmentNumber = 0;
84
+let environmentId: EnvironmentId;
85
+
86
+function presentation(phase = "connected") {
87
+ return {
88
+ entry: { target: { label: "Test" } },
89
+ connection: { phase, error: null, traceId: null },
90
+ serverConfig: {
91
+ providers: [
92
+ {
93
+ instanceId: ProviderInstanceId.make("codex"),
94
+ driver: "codex",
95
+ enabled: true,
96
+ installed: true,
97
+ version: null,
98
+ status: "ready",
99
+ auth: { status: "authenticated" },
100
+ checkedAt: "2026-09-11T12:00:00Z",
101
+ models: [],
102
+ slashCommands: [],
103
+ skills: [],
104
+ usageLimits: {
105
+ checkedAt: "2026-09-11T12:00:00Z",
106
+ windows: [
107
+ {
108
+ id: "five_hour",
109
+ kind: "session",
110
+ label: "Session",
111
+ usedPercent: 40,
112
+ windowDurationMins: 300,
113
+ resetsAt: "2026-09-11T14:00:00Z",
114
+ },
115
+ ],
116
+ },
117
+ },
118
+ ],
119
+ },
120
+ };
121
+}
122
+
123
+const setPresentations = (entries: ReadonlyArray<readonly [EnvironmentId, object]>) =>
124
+ act(async () => appAtomRegistry.set(state.presentations, new Map(entries) as Presentations));
125
+const setNow = (iso: string) => vi.mocked(Date.now).mockReturnValue(Date.parse(iso));
126
+const resetsIn = (countdown: string) =>
127
+ page.getByRole("button", { name: `codex: 60% left, resets in ${countdown}` });
128
+const refreshButton = () => page.getByRole("button", { name: "Refresh limits" });
129
+const selectMetric = (label: string) => userEvent.click(page.getByRole("button", { name: label }));
130
+
131
+async function render({ strict = false } = {}) {
132
+ const content = (
133
+ <RegistryContext.Provider value={appAtomRegistry}>
134
+ <UsagePage />
135
+ </RegistryContext.Provider>
136
+ );
137
+ await act(async () => root.render(strict ? <StrictMode>{content}</StrictMode> : content));
138
+}
139
+
140
+beforeEach(async () => {
141
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
142
+ // The metric toggle and its refresh button only show on wide screens.
143
+ await page.viewport(1440, 900);
144
+ vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-11T12:00:00Z"));
145
+ environmentNumber += 1;
146
+ environmentId = EnvironmentId.make(`test-${environmentNumber}`);
147
+ localStorage.setItem(PREFERENCES_KEY, JSON.stringify({ metric: "limits", windowDays: 30 }));
148
+ state.refreshProviders.mockReset().mockResolvedValue(undefined);
149
+ await setPresentations([[environmentId, presentation()]]);
150
+ container = document.createElement("div");
151
+ document.body.append(container);
152
+ root = createRoot(container);
153
+});
154
+
155
+afterEach(async () => {
156
+ await act(async () => root.unmount());
157
+ container.remove();
158
+ localStorage.clear();
159
+ vi.restoreAllMocks();
160
+ vi.unstubAllGlobals();
161
+});
162
+
163
+it.each([
164
+ ["wide", 1440],
165
+ ["compact", 800],
166
+])(
167
+ "refreshes the visible limits countdown from the %s toolbar without switching tabs, even when quota is unchanged",
168
+ async (_layout, width) => {
169
+ await page.viewport(width, 900);
170
+ await render();
171
+ await expect.element(resetsIn("2h 0m")).toBeVisible();
172
+ setNow("2026-09-11T12:30:00Z");
173
+
174
+ await userEvent.click(refreshButton());
175
+
176
+ expect(state.refreshProviders).toHaveBeenCalledWith({ environmentId, input: {} });
177
+ await expect.element(resetsIn("1h 30m")).toBeVisible();
178
+ await expect.element(resetsIn("2h 0m")).not.toBeInTheDocument();
179
+ },
180
+);
181
+
182
+it("uses the current time when returning to limits from tokens", async () => {
183
+ await render();
184
+ await selectMetric("Tokens");
185
+ setNow("2026-09-11T13:00:00Z");
186
+ await selectMetric("Limits");
187
+
188
+ await expect.element(resetsIn("1h 0m")).toBeVisible();
189
+ expect(state.refreshProviders).toHaveBeenCalledTimes(2);
190
+});
191
+
192
+it("refreshes once on opening Limits and suppresses rapid returns and remounts", async () => {
193
+ localStorage.setItem(PREFERENCES_KEY, JSON.stringify({ metric: "tokens", windowDays: 30 }));
194
+ await render({ strict: true });
195
+ expect(state.refreshProviders).not.toHaveBeenCalled();
196
+
197
+ await selectMetric("Limits");
198
+ await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(1));
199
+ await selectMetric("Tokens");
200
+ await selectMetric("Limits");
201
+ await act(async () => root.unmount());
202
+ root = createRoot(container);
203
+ await render({ strict: true });
204
+ expect(state.refreshProviders).toHaveBeenCalledTimes(1);
205
+
206
+ await selectMetric("Tokens");
207
+ setNow("2026-09-11T12:05:00Z");
208
+ await selectMetric("Limits");
209
+ await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(2));
210
+});
211
+
212
+it("waits for connection and refreshes new environments during a slow refresh", async () => {
213
+ await setPresentations([[environmentId, presentation("disconnected")]]);
214
+ await render();
215
+ expect(state.refreshProviders).not.toHaveBeenCalled();
216
+
217
+ let finishRefresh!: () => void;
218
+ state.refreshProviders.mockImplementationOnce(
219
+ () => new Promise((resolve) => (finishRefresh = () => resolve(undefined))),
220
+ );
221
+ await setPresentations([[environmentId, presentation()]]);
222
+ await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(1));
223
+
224
+ const nextId = EnvironmentId.make(`${environmentId}-next`);
225
+ await setPresentations([
226
+ [environmentId, presentation()],
227
+ [nextId, presentation()],
228
+ ]);
229
+ await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(2));
230
+ expect(state.refreshProviders).toHaveBeenLastCalledWith({ environmentId: nextId, input: {} });
231
+ await act(async () => finishRefresh());
232
+});
233
+
234
+it("keeps manual refresh busy until the already-running automatic check settles", async () => {
235
+ let finishRefresh!: () => void;
236
+ state.refreshProviders.mockImplementationOnce(
237
+ () => new Promise((resolve) => (finishRefresh = () => resolve(undefined))),
238
+ );
239
+ await render();
240
+ await vi.waitFor(() => expect(state.refreshProviders).toHaveBeenCalledTimes(1));
241
+
242
+ await userEvent.click(refreshButton());
243
+ await expect.element(refreshButton()).toHaveAttribute("aria-busy", "true");
244
+ await expect.element(refreshButton()).toBeDisabled();
245
+ expect(state.refreshProviders).toHaveBeenCalledTimes(1);
246
+
247
+ await act(async () => finishRefresh());
248
+ await expect.element(refreshButton()).toHaveAttribute("aria-busy", "false");
249
+});
apps/web/src/components/usage/UsagePage.refresh.test.tsx
deleted
-301
@@ -1,301 +0,0 @@
1
-import { EnvironmentId, ProviderInstanceId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
2
-import { mergeUsage } from "@t3tools/shared/usageMerge";
3
-import { StrictMode, act } from "react";
4
-import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
5
-import { create, type ReactTestRenderer } from "react-test-renderer";
6
-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
7
-
8
-const state = vi.hoisted(() => ({
9
- presentations: new Map(),
10
- refreshProviders: vi.fn(async () => undefined),
11
- metric: "limits",
12
-}));
13
-vi.mock("@effect/atom-react", () => ({
14
- useAtomValue: (atom: unknown) =>
15
- atom === "keybindings"
16
- ? DEFAULT_RESOLVED_KEYBINDINGS
17
- : atom === "providers"
18
- ? new Map(
19
- [...state.presentations].map(([id, presentation]) => [
20
- id,
21
- presentation.serverConfig.providers,
22
- ]),
23
- )
24
- : state.presentations,
25
-}));
26
-vi.mock("@tanstack/react-router", () => ({
27
- useNavigate: () => vi.fn(),
28
- useCanGoBack: () => false,
29
-}));
30
-vi.mock("../../state/presentation", () => ({
31
- environmentPresentations: {
32
- presentationsAtom: null,
33
- presentationsWithProvidersAtom: null,
34
- providersByEnvironmentAtom: "providers",
35
- },
36
-}));
37
-vi.mock("../../state/server", () => ({
38
- serverEnvironment: { refreshProviders: null },
39
- primaryServerKeybindingsAtom: "keybindings",
40
-}));
41
-vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.refreshProviders }));
42
-vi.mock("../../env", () => ({ isElectron: false }));
43
-vi.mock("../../hooks/useSettings", () => ({ usePrimarySettings: () => "24h" }));
44
-vi.mock("../../state/usage", () => ({
45
- useUsage: () => ({
46
- merged: mergeUsage([], USAGE_CONTRACT_VERSION),
47
- environments: [
48
- {
49
- environmentId: EnvironmentId.make("test"),
50
- label: "Test",
51
- isPending: false,
52
- error: null,
53
- summary: null,
54
- },
55
- ],
56
- selectedEnvironments: [
57
- {
58
- environmentId: EnvironmentId.make("test"),
59
- label: "Test",
60
- isPending: false,
61
- error: null,
62
- summary: null,
63
- },
64
- ],
65
- isPending: false,
66
- shown: null,
67
- isPartial: false,
68
- refresh: async () => undefined,
69
- }),
70
-}));
71
-vi.mock("./usagePagePreferences", () => ({
72
- readUsagePagePreferences: () => ({ metric: state.metric, windowDays: 30 }),
73
- saveUsagePagePreferences: vi.fn(),
74
-}));
75
-vi.mock("../ui/button", () => ({ Button: "button", InlineButton: "button" }));
76
-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
77
-vi.mock("../ui/select", () => ({
78
- Select: "select",
79
- SelectItem: "option",
80
- SelectPopup: "div",
81
- SelectTrigger: "div",
82
- SelectValue: "span",
83
-}));
84
-vi.mock("../ui/sidebar", () => ({ SidebarInset: "div" }));
85
-vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
86
-vi.mock("../ui/tooltip", () => ({ Tooltip: "div", TooltipPopup: "div", TooltipTrigger: "div" }));
87
-vi.mock("../ui/popover", () => ({ Popover: "div", PopoverPopup: "div", PopoverTrigger: "div" }));
88
-vi.mock("../ui/menu", () => ({
89
- Menu: "div",
90
- MenuCheckboxItem: "div",
91
- MenuItem: "div",
92
- MenuPopup: "div",
93
- MenuSeparator: "hr",
94
- MenuTrigger: "div",
95
-}));
96
-vi.mock("../WorkspaceBreadcrumb", () => ({
97
- WorkspaceBreadcrumb: "div",
98
- WorkspaceBreadcrumbItem: "div",
99
- WorkspaceBreadcrumbSeparator: "span",
100
- WorkspaceBreadcrumbText: "span",
101
-}));
102
-vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));
103
-vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));
104
-vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));
105
-vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));
106
-vi.mock("../chat/ProviderInstanceIcon", () => ({ ProviderInstanceIcon: () => null }));
107
-vi.mock("../settings/RedactedSensitiveText", () => ({ RedactedSensitiveText: "span" }));
108
-vi.mock("../settings/providerDriverMeta", () => ({
109
- providerClients: { get: () => ({ label: "Codex" }) },
110
-}));
111
-
112
-import { UsagePage } from "./UsagePage";
113
-
114
-let renderer: ReactTestRenderer;
115
-let environmentNumber = 0;
116
-beforeEach(() => {
117
- vi.stubGlobal("window", new EventTarget());
118
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
119
- vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-11T12:00:00Z"));
120
- environmentNumber += 1;
121
- state.metric = "limits";
122
- state.refreshProviders.mockClear();
123
- state.presentations = new Map([
124
- [
125
- EnvironmentId.make(`test-${environmentNumber}`),
126
- {
127
- entry: { target: { label: "Test" } },
128
- connection: { phase: "connected" },
129
- serverConfig: {
130
- providers: [
131
- {
132
- instanceId: ProviderInstanceId.make("codex"),
133
- driver: "codex",
134
- enabled: true,
135
- installed: true,
136
- version: null,
137
- status: "ready",
138
- auth: { status: "authenticated" },
139
- checkedAt: "2026-09-11T12:00:00Z",
140
- models: [],
141
- slashCommands: [],
142
- skills: [],
143
- usageLimits: {
144
- checkedAt: "2026-09-11T12:00:00Z",
145
- windows: [
146
- {
147
- id: "five_hour",
148
- kind: "session",
149
- label: "Session",
150
- usedPercent: 40,
151
- windowDurationMins: 300,
152
- resetsAt: "2026-09-11T14:00:00Z",
153
- },
154
- ],
155
- },
156
- },
157
- ],
158
- },
159
- },
160
- ],
161
- ]);
162
-});
163
-afterEach(async () => {
164
- await act(() => renderer?.unmount());
165
- vi.restoreAllMocks();
166
- vi.unstubAllGlobals();
167
-});
168
-
169
-it.each([0, 1])(
170
- "refreshes the visible limits countdown with refresh button %i without switching tabs, even when quota is unchanged",
171
- async (buttonIndex) => {
172
- await act(() => {
173
- renderer = create(<UsagePage />);
174
- });
175
- expect(
176
- JSON.stringify(renderer.toJSON(), (key, value) => (key === "props" ? undefined : value)),
177
- ).toContain("in 2h 0m");
178
- vi.mocked(Date.now).mockReturnValue(Date.parse("2026-09-11T12:30:00Z"));
179
- await act(async () => {
180
- renderer.root
181
- .findAllByProps({ "aria-label": "Refresh limits" })
182
- .filter((node) => node.type === "button")
183
- .at(buttonIndex)!
184
- .props.onClick();
185
- });
186
- expect(state.refreshProviders).toHaveBeenCalledWith({
187
- environmentId: `test-${environmentNumber}`,
188
- input: {},
189
- });
190
- expect(
191
- JSON.stringify(renderer.toJSON(), (key, value) => (key === "props" ? undefined : value)),
192
- ).toContain("in 1h 30m");
193
- expect(
194
- JSON.stringify(renderer.toJSON(), (key, value) => (key === "props" ? undefined : value)),
195
- ).not.toContain("in 2h 0m");
196
- },
197
-);
198
-
199
-it("uses the current time when returning to limits from tokens", async () => {
200
- await act(() => {
201
- renderer = create(<UsagePage />);
202
- });
203
- const selectMetric = (metric: string) => {
204
- renderer.root
205
- .findAll((node) => node.type === "div" && node.props["aria-label"] === "Usage metric")[0]!
206
- .props.onValueChange([metric]);
207
- };
208
- await act(() => selectMetric("tokens"));
209
- vi.mocked(Date.now).mockReturnValue(Date.parse("2026-09-11T13:00:00Z"));
210
- await act(() => selectMetric("limits"));
211
- expect(
212
- JSON.stringify(renderer.toJSON(), (key, value) => (key === "props" ? undefined : value)),
213
- ).toContain("in 1h 0m");
214
- expect(state.refreshProviders).toHaveBeenCalledTimes(2);
215
-});
216
-
217
-it("refreshes once on opening Limits and suppresses rapid returns and remounts", async () => {
218
- state.metric = "tokens";
219
- await act(() => {
220
- renderer = create(
221
- <StrictMode>
222
- <UsagePage />
223
- </StrictMode>,
224
- );
225
- });
226
- expect(state.refreshProviders).not.toHaveBeenCalled();
227
- const selectMetric = (metric: string) =>
228
- renderer.root
229
- .findAll((node) => node.type === "div" && node.props["aria-label"] === "Usage metric")[0]!
230
- .props.onValueChange([metric]);
231
- await act(() => selectMetric("limits"));
232
- expect(state.refreshProviders).toHaveBeenCalledTimes(1);
233
- await act(() => selectMetric("tokens"));
234
- await act(() => selectMetric("limits"));
235
- await act(() => renderer.unmount());
236
- state.metric = "limits";
237
- await act(() => {
238
- renderer = create(
239
- <StrictMode>
240
- <UsagePage />
241
- </StrictMode>,
242
- );
243
- });
244
- expect(state.refreshProviders).toHaveBeenCalledTimes(1);
245
- await act(() => selectMetric("tokens"));
246
- vi.mocked(Date.now).mockReturnValue(Date.parse("2026-09-11T12:05:00Z"));
247
- await act(() => selectMetric("limits"));
248
- expect(state.refreshProviders).toHaveBeenCalledTimes(2);
249
-});
250
-
251
-it("waits for connection and refreshes new environments during a slow refresh", async () => {
252
- const [id, presentation] = [...state.presentations][0]!;
253
- state.presentations = new Map([[id, { ...presentation, connection: { phase: "disconnected" } }]]);
254
- await act(() => {
255
- renderer = create(<UsagePage />);
256
- });
257
- expect(state.refreshProviders).not.toHaveBeenCalled();
258
- let finishRefresh!: () => void;
259
- state.refreshProviders.mockImplementationOnce(
260
- () =>
261
- new Promise<undefined>((resolve) => {
262
- finishRefresh = () => resolve(undefined);
263
- }),
264
- );
265
- state.presentations = new Map([[id, presentation]]);
266
- await act(() => renderer.update(<UsagePage />));
267
- expect(state.refreshProviders).toHaveBeenCalledTimes(1);
268
- const nextId = EnvironmentId.make(`${id}-next`);
269
- state.presentations = new Map([...state.presentations, [nextId, presentation]]);
270
- await act(() => renderer.update(<UsagePage />));
271
- expect(state.refreshProviders).toHaveBeenCalledTimes(2);
272
- expect(state.refreshProviders).toHaveBeenLastCalledWith({ environmentId: nextId, input: {} });
273
- await act(() => finishRefresh());
274
-});
275
-
276
-it("keeps manual refresh busy until the already-running automatic check settles", async () => {
277
- let finishRefresh!: () => void;
278
- const pending = new Promise<undefined>((resolve) => {
279
- finishRefresh = () => resolve(undefined);
280
- });
281
- state.refreshProviders.mockImplementationOnce(() => pending);
282
- await act(() => {
283
- renderer = create(<UsagePage />);
284
- });
285
- const button = () =>
286
- renderer.root.findAll(
287
- (node) => node.type === "button" && node.props["aria-label"] === "Refresh limits",
288
- )[0]!;
289
- expect(state.refreshProviders).toHaveBeenCalledTimes(1);
290
- await act(() => button().props.onClick());
291
- try {
292
- expect(button().props["aria-busy"]).toBe(true);
293
- expect(state.refreshProviders).toHaveBeenCalledTimes(1);
294
- } finally {
295
- await act(async () => {
296
- finishRefresh();
297
- await pending;
298
- });
299
- }
300
- expect(button().props["aria-busy"]).toBe(false);
301
-});
apps/web/src/test/reactElementTree.ts
deleted
-21
@@ -1,21 +0,0 @@
1
-import { isValidElement, type ReactElement } from "react";
2
-
3
-export function visitElements(
4
- node: unknown,
5
- visitor: (element: ReactElement<Record<string, unknown>>) => boolean,
6
-): ReactElement<Record<string, unknown>> | null {
7
- if (Array.isArray(node)) {
8
- for (const child of node) {
9
- const found = visitElements(child, visitor);
10
- if (found) return found;
11
- }
12
- return null;
13
- }
14
- if (!isValidElement<Record<string, unknown>>(node)) return null;
15
- if (visitor(node)) return node;
16
- for (const value of Object.values(node.props)) {
17
- const found = visitElements(value, visitor);
18
- if (found) return found;
19
- }
20
- return null;
21
-}
apps/web/src/test/reactHookHarness.ts
deleted
-62
@@ -1,62 +0,0 @@
1
-import type { Dispatch, SetStateAction } from "react";
2
-
3
-/**
4
- * This module must stay free of runtime `react` imports: it is loaded from
5
- * inside `vi.mock("react", ...)` factories, and a value import would recurse
6
- * into the in-progress mock.
7
- *
8
- * Call `beginRender()` before each component invocation and `reset()` in
9
- * `beforeEach` to drop persisted state between tests.
10
- */
11
-function createReactHookHarness() {
12
- let cursor = 0;
13
- let slots: unknown[] = [];
14
- const nextIndex = () => cursor++;
15
-
16
- return {
17
- beginRender() {
18
- cursor = 0;
19
- },
20
- reset() {
21
- cursor = 0;
22
- slots = [];
23
- },
24
- useCallback<T>(callback: T): T {
25
- nextIndex();
26
- return callback;
27
- },
28
- useMemo<T>(factory: () => T): T {
29
- nextIndex();
30
- return factory();
31
- },
32
- useMemoCache(size: number): unknown[] {
33
- const index = nextIndex();
34
- if (!slots[index]) {
35
- slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
36
- }
37
- return slots[index] as unknown[];
38
- },
39
- useRef<T>(initialValue: T): { current: T } {
40
- const index = nextIndex();
41
- if (!slots[index]) {
42
- slots[index] = { current: initialValue };
43
- }
44
- return slots[index] as { current: T };
45
- },
46
- useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
47
- const index = nextIndex();
48
- if (index >= slots.length) {
49
- slots[index] =
50
- typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
51
- }
52
- const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
53
- const previous = slots[index] as T;
54
- slots[index] =
55
- typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
56
- };
57
- return [slots[index] as T, setValue];
58
- },
59
- };
60
-}
61
-
62
-export const reactHookHarness = createReactHookHarness();