@devries-cameron20 / t3code-1 / commits / 476a010fdc
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

test(web): settings tests run in a real browser (#20872)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 17, 2026 at 02:51 UTC 476a010fdc0bbe8ad7bfd856661d0515b913c5cc
18 files changed +1291 -1362
apps/web/src/components/device/DeviceSetup.test.ts new
+95
@@ -0,0 +1,95 @@
1 +import type { DeviceServiceState } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { deviceHubReadiness, platformSetupStatus } from "./DeviceSetup";
5 +
6 +const deviceState = (overrides: Partial<DeviceServiceState> = {}): DeviceServiceState => ({
7 + hosts: [
8 + {
9 + id: "local",
10 + kind: "local",
11 + label: "This machine",
12 + hubInstalled: false,
13 + agentDeviceInstalled: false,
14 + platforms: [
15 + { platform: "ios", available: true },
16 + { platform: "android", available: true },
17 + ],
18 + },
19 + ],
20 + hostStatus: "ready",
21 + hostStatuses: {},
22 + devices: [],
23 + sessions: [],
24 + onboardingCompleted: false,
25 + agentAccessEnabled: false,
26 + hubBasePath: "/api/device-hub",
27 + revision: 0,
28 + ...overrides,
29 +});
30 +
31 +describe("device setup guidance", () => {
32 + it("directs users to install an iOS runtime and create an Android virtual device", () => {
33 + expect(platformSetupStatus(deviceState(), "ios").message).toContain("Xcode Settings");
34 + expect(platformSetupStatus(deviceState(), "android").message).toContain("Device Manager");
35 + });
36 +
37 + it("preserves a specific missing-tool explanation from the server", () => {
38 + const state = deviceState({
39 + hosts: [
40 + {
41 + ...deviceState().hosts[0]!,
42 + platforms: [
43 + { platform: "ios", available: true },
44 + { platform: "android", available: false, reason: "Android Emulator is missing." },
45 + ],
46 + },
47 + ],
48 + });
49 + expect(platformSetupStatus(state, "android").message).toBe("Android Emulator is missing.");
50 + });
51 +
52 + it("counts a remote device host when this machine has no simulator tooling", () => {
53 + const state = deviceState({
54 + hostStatus: "idle",
55 + hostStatuses: { macmini: { status: "ready" } },
56 + hosts: [
57 + {
58 + ...deviceState().hosts[0]!,
59 + platforms: [
60 + { platform: "ios", available: false, reason: "Xcode was not found." },
61 + { platform: "android", available: false, reason: "Android SDK was not found." },
62 + ],
63 + },
64 + {
65 + id: "macmini",
66 + kind: "ssh",
67 + label: "Mac Mini",
68 + hubInstalled: true,
69 + agentDeviceInstalled: true,
70 + platforms: [
71 + { platform: "ios", available: true },
72 + { platform: "android", available: false, reason: "Android SDK was not found." },
73 + ],
74 + },
75 + ],
76 + devices: [
77 + {
78 + hostId: "macmini",
79 + id: "iphone",
80 + platform: "ios",
81 + name: "iPhone 16 Pro",
82 + version: "iOS 27.0",
83 + booted: true,
84 + physical: false,
85 + },
86 + ],
87 + });
88 + expect(deviceHubReadiness(state).ready).toBe(true);
89 + expect(platformSetupStatus(state, "ios")).toEqual({
90 + ready: true,
91 + message: "Xcode and iOS Simulator are available on Mac Mini.",
92 + });
93 + expect(platformSetupStatus(state, "android").ready).toBe(false);
94 + });
95 +});
apps/web/src/components/settings/IntegrationsSettings.browser.test.tsx new
+102
@@ -0,0 +1,102 @@
1 +import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts";
2 +import {
3 + createMemoryHistory,
4 + createRootRoute,
5 + createRouter,
6 + RouterProvider,
7 +} from "@tanstack/react-router";
8 +import { act, StrictMode } from "react";
9 +import { createRoot, type Root } from "react-dom/client";
10 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
11 +
12 +const { listBrowserImportSources } = vi.hoisted(() => ({
13 + listBrowserImportSources: vi.fn().mockResolvedValue([]),
14 +}));
15 +
16 +vi.mock(import("../preview/previewBridge"), async (original) => {
17 + const actual = await original();
18 + return {
19 + ...actual,
20 + previewBridge: { ...actual.previewBridge, listBrowserImportSources } as never,
21 + };
22 +});
23 +vi.mock(import("../../env"), async (original) => ({ ...(await original()), isElectron: true }));
24 +vi.mock(import("../../state/environments"), async (original) => ({
25 + ...(await original()),
26 + useEnvironments: (() => ({ environments: [], isReady: true })) as never,
27 + usePrimaryEnvironment: () => null,
28 + usePrimaryEnvironmentId: () => null,
29 +}));
30 +vi.mock(import("../../hooks/useSettings"), async (original) => ({
31 + ...(await original()),
32 + useClientSettings: ((selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
33 + selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS) as never,
34 + useClientSettingsHydrated: () => true,
35 + usePrimarySettingsAvailable: () => true,
36 + usePrimarySettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,
37 + useUpdatePrimarySettings: (() => vi.fn()) as never,
38 +}));
39 +vi.mock(import("./ProjectDefaultsSettings"), async (original) => ({
40 + ...(await original()),
41 + ProjectDefaultsSettings: (() => null) as never,
42 +}));
43 +vi.mock(import("./SettingsScopeContext"), async (original) => ({
44 + ...(await original()),
45 + useSettingsScope: (() => ({
46 + scope: { kind: "all", environmentIds: [] },
47 + search: {},
48 + environment: null,
49 + environments: [],
50 + target: null,
51 + connectedEnvironments: [],
52 + targets: [],
53 + })) as never,
54 + useOptionalSettingsScope: () => null,
55 +}));
56 +
57 +import { IntegrationsSettingsPanel } from "./IntegrationsSettings";
58 +
59 +let root: Root;
60 +let container: HTMLDivElement;
61 +
62 +beforeEach(() => {
63 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
64 + listBrowserImportSources.mockClear();
65 + container = document.createElement("div");
66 + document.body.append(container);
67 + root = createRoot(container);
68 +});
69 +
70 +afterEach(async () => {
71 + await act(async () => root.unmount());
72 + container.remove();
73 + vi.unstubAllGlobals();
74 +});
75 +
76 +async function openSettings() {
77 + const router = createRouter({
78 + routeTree: createRootRoute({ component: IntegrationsSettingsPanel }),
79 + history: createMemoryHistory(),
80 + });
81 + await router.load();
82 + await act(async () =>
83 + root.render(
84 + <StrictMode>
85 + <RouterProvider router={router} />
86 + </StrictMode>,
87 + ),
88 + );
89 + await vi.waitFor(() => expect(container.querySelector("section#browser")).not.toBeNull());
90 +}
91 +
92 +describe("Integrations browser discovery", () => {
93 + it("does not scan browser files when entering or revisiting settings", async () => {
94 + await openSettings();
95 + expect(listBrowserImportSources).not.toHaveBeenCalled();
96 +
97 + await act(async () => root.unmount());
98 + root = createRoot(container);
99 + await openSettings();
100 + expect(listBrowserImportSources).not.toHaveBeenCalled();
101 + });
102 +});
apps/web/src/components/settings/IntegrationsSettings.test.tsx deleted
-207
@@ -1,207 +0,0 @@
1 -import {
2 - DEFAULT_CLIENT_SETTINGS,
3 - DEFAULT_UNIFIED_SETTINGS,
4 - type DeviceServiceState,
5 -} from "@t3tools/contracts";
6 -import {
7 - createMemoryHistory,
8 - createRootRoute,
9 - createRouter,
10 - RouterProvider,
11 -} from "@tanstack/react-router";
12 -import { act, StrictMode, type ReactNode } from "react";
13 -import { create, type ReactTestRenderer } from "react-test-renderer";
14 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
15 -
16 -const { listBrowserImportSources } = vi.hoisted(() => ({
17 - listBrowserImportSources: vi.fn().mockResolvedValue([]),
18 -}));
19 -
20 -vi.mock("../ui/tooltip", () => ({
21 - Tooltip: ({ children }: { children: ReactNode }) => children,
22 - TooltipTrigger: ({ render, children }: { render: ReactNode; children: ReactNode }) => (
23 - <>
24 - {render}
25 - {children}
26 - </>
27 - ),
28 - TooltipPopup: () => null,
29 -}));
30 -vi.mock("../preview/previewBridge", () => ({
31 - previewBridge: { listBrowserImportSources },
32 -}));
33 -vi.mock("../../env", () => ({ isElectron: true }));
34 -vi.mock("../../state/environments", () => ({
35 - useEnvironments: () => ({ environments: [], isReady: true }),
36 - usePrimaryEnvironment: () => null,
37 - usePrimaryEnvironmentId: () => null,
38 -}));
39 -vi.mock("../../hooks/useSettings", async (importOriginal) => ({
40 - ...(await importOriginal<typeof import("../../hooks/useSettings")>()),
41 - PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE: "Connect to an environment",
42 - useClientSettings: (selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
43 - selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS,
44 - useClientSettingsHydrated: () => true,
45 - usePrimarySettingsAvailable: () => true,
46 - usePrimarySettings: () => DEFAULT_UNIFIED_SETTINGS,
47 - useUpdatePrimarySettings: () => vi.fn(),
48 -}));
49 -vi.mock("./settingsLayout", async (importOriginal) => ({
50 - ...(await importOriginal<typeof import("./settingsLayout")>()),
51 - SettingsPageContainer: ({ children }: { children: ReactNode }) => children,
52 -}));
53 -vi.mock("./ProjectDefaultsSettings", () => ({ ProjectDefaultsSettings: () => null }));
54 -vi.mock("./SettingsScopeContext", () => ({
55 - useSettingsScope: () => ({
56 - scope: { kind: "all", environmentIds: [] },
57 - search: {},
58 - environment: null,
59 - environments: [],
60 - target: null,
61 - connectedEnvironments: [],
62 - targets: [],
63 - }),
64 - useOptionalSettingsScope: () => null,
65 -}));
66 -
67 -import { IntegrationsSettingsPanel } from "./IntegrationsSettings";
68 -import { deviceHubReadiness, platformSetupStatus } from "../device/DeviceSetup";
69 -
70 -let renderer: ReactTestRenderer | undefined;
71 -
72 -beforeEach(() => {
73 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
74 - listBrowserImportSources.mockClear();
75 -});
76 -
77 -afterEach(async () => {
78 - await act(() => renderer?.unmount());
79 - vi.unstubAllGlobals();
80 -});
81 -
82 -async function openSettings() {
83 - const router = createRouter({
84 - routeTree: createRootRoute({ component: IntegrationsSettingsPanel }),
85 - history: createMemoryHistory(),
86 - });
87 - await router.load();
88 - await act(() => {
89 - renderer = create(
90 - <StrictMode>
91 - <RouterProvider router={router} />
92 - </StrictMode>,
93 - );
94 - });
95 - expect(renderer!.root.findByType(IntegrationsSettingsPanel)).toBeDefined();
96 -}
97 -
98 -describe("Integrations browser discovery", () => {
99 - it("does not scan browser files when entering or revisiting settings", async () => {
100 - await openSettings();
101 - expect(listBrowserImportSources).not.toHaveBeenCalled();
102 -
103 - await act(() => renderer?.unmount());
104 - await openSettings();
105 - expect(listBrowserImportSources).not.toHaveBeenCalled();
106 - });
107 -
108 - it("places device settings directly after browser settings", async () => {
109 - await openSettings();
110 - const sections = renderer!.root
111 - .findAll((node) => node.type === "section")
112 - .map((node) => node.props.id)
113 - .filter(Boolean);
114 - expect(sections.indexOf("devices")).toBeGreaterThan(sections.indexOf("browser"));
115 - });
116 -});
117 -
118 -const deviceState = (overrides: Partial<DeviceServiceState> = {}): DeviceServiceState => ({
119 - hosts: [
120 - {
121 - id: "local",
122 - kind: "local",
123 - label: "This machine",
124 - hubInstalled: false,
125 - agentDeviceInstalled: false,
126 - platforms: [
127 - { platform: "ios", available: true },
128 - { platform: "android", available: true },
129 - ],
130 - },
131 - ],
132 - hostStatus: "ready",
133 - hostStatuses: {},
134 - devices: [],
135 - sessions: [],
136 - onboardingCompleted: false,
137 - agentAccessEnabled: false,
138 - hubBasePath: "/api/device-hub",
139 - revision: 0,
140 - ...overrides,
141 -});
142 -
143 -describe("device setup guidance", () => {
144 - it("directs users to install an iOS runtime and create an Android virtual device", () => {
145 - expect(platformSetupStatus(deviceState(), "ios").message).toContain("Xcode Settings");
146 - expect(platformSetupStatus(deviceState(), "android").message).toContain("Device Manager");
147 - });
148 -
149 - it("preserves a specific missing-tool explanation from the server", () => {
150 - const state = deviceState({
151 - hosts: [
152 - {
153 - ...deviceState().hosts[0]!,
154 - platforms: [
155 - { platform: "ios", available: true },
156 - { platform: "android", available: false, reason: "Android Emulator is missing." },
157 - ],
158 - },
159 - ],
160 - });
161 - expect(platformSetupStatus(state, "android").message).toBe("Android Emulator is missing.");
162 - });
163 -
164 - it("counts a remote device host when this machine has no simulator tooling", () => {
165 - const state = deviceState({
166 - hostStatus: "idle",
167 - hostStatuses: { macmini: { status: "ready" } },
168 - hosts: [
169 - {
170 - ...deviceState().hosts[0]!,
171 - platforms: [
172 - { platform: "ios", available: false, reason: "Xcode was not found." },
173 - { platform: "android", available: false, reason: "Android SDK was not found." },
174 - ],
175 - },
176 - {
177 - id: "macmini",
178 - kind: "ssh",
179 - label: "Mac Mini",
180 - hubInstalled: true,
181 - agentDeviceInstalled: true,
182 - platforms: [
183 - { platform: "ios", available: true },
184 - { platform: "android", available: false, reason: "Android SDK was not found." },
185 - ],
186 - },
187 - ],
188 - devices: [
189 - {
190 - hostId: "macmini",
191 - id: "iphone",
192 - platform: "ios",
193 - name: "iPhone 16 Pro",
194 - version: "iOS 27.0",
195 - booted: true,
196 - physical: false,
197 - },
198 - ],
199 - });
200 - expect(deviceHubReadiness(state).ready).toBe(true);
201 - expect(platformSetupStatus(state, "ios")).toEqual({
202 - ready: true,
203 - message: "Xcode and iOS Simulator are available on Mac Mini.",
204 - });
205 - expect(platformSetupStatus(state, "android").ready).toBe(false);
206 - });
207 -});
apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx new
+100
@@ -0,0 +1,100 @@
1 +import { act } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { userEvent } from "vite-plus/test/browser";
5 +
6 +import { deriveProjectIdentity } from "../../projectIdentity";
7 +import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog";
8 +
9 +let root: Root;
10 +let container: HTMLDivElement;
11 +
12 +beforeEach(() => {
13 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14 + container = document.createElement("div");
15 + document.body.append(container);
16 + root = createRoot(container);
17 +});
18 +
19 +afterEach(async () => {
20 + await act(async () => root.unmount());
21 + container.remove();
22 + vi.unstubAllGlobals();
23 +});
24 +
25 +function button(name: string) {
26 + return vi.waitFor(() => {
27 + const match = [...document.querySelectorAll<HTMLElement>("button, [role='radio']")].find(
28 + (element) => element.getAttribute("aria-label") === name || element.textContent === name,
29 + );
30 + if (!match) throw new Error(`No button ${name}`);
31 + return match;
32 + });
33 +}
34 +
35 +// The modal's inert backdrop covers the unstyled popup, so Playwright pointer clicks land on it.
36 +async function click(name: string) {
37 + const target = await button(name);
38 + await act(async () => target.click());
39 +}
40 +
41 +async function openPicker() {
42 + const onSelect = vi.fn();
43 + const onOpenChange = vi.fn();
44 + await act(async () =>
45 + root.render(
46 + <ProjectIconPickerDialog
47 + current={null}
48 + projectName="Test"
49 + open
50 + onOpenChange={onOpenChange}
51 + onSelect={onSelect}
52 + />,
53 + ),
54 + );
55 + return { onSelect, onOpenChange };
56 +}
57 +
58 +describe("ProjectIconPickerDialog", () => {
59 + it("starts an automatic project on icons in its derived color and saves the picked icon", async () => {
60 + const { onSelect, onOpenChange } = await openPicker();
61 + const { color } = deriveProjectIdentity("Test");
62 + expect((await button("Icons")).getAttribute("aria-pressed")).toBe("true");
63 + expect(
64 + document.querySelector('[aria-label="Icon color"] [aria-pressed="true"]'),
65 + ).not.toBeNull();
66 +
67 + await userEvent.fill(searchBox(), "rocket");
68 + await click("Rocket");
69 + await click("Save icon");
70 +
71 + expect(onSelect).toHaveBeenCalledExactlyOnceWith({ kind: "lucide", name: "rocket", color });
72 + expect(onOpenChange).toHaveBeenCalledWith(false);
73 + });
74 +
75 + it("saves a monogram only once the letters are letters or numbers", async () => {
76 + const { onSelect } = await openPicker();
77 + await click("Monogram");
78 + const letters = await vi.waitFor(() => {
79 + const input = document.querySelector<HTMLInputElement>("#project-monogram");
80 + if (!input) throw new Error("No monogram input");
81 + return input;
82 + });
83 +
84 + await userEvent.fill(letters, "t-3");
85 + await click("Save icon");
86 + expect(onSelect).not.toHaveBeenCalled();
87 +
88 + await userEvent.fill(letters, "t3");
89 + await click("Save icon");
90 + expect(onSelect).toHaveBeenCalledExactlyOnceWith({
91 + kind: "monogram",
92 + text: "T3",
93 + color: deriveProjectIdentity("Test").color,
94 + });
95 + });
96 +});
97 +
98 +function searchBox() {
99 + return document.querySelector<HTMLInputElement>('input[aria-label="Search Lucide icons"]')!;
100 +}
apps/web/src/components/settings/ProjectIconPickerDialog.test.tsx deleted
-57
@@ -1,57 +0,0 @@
1 -import type { ReactNode } from "react";
2 -import { renderToStaticMarkup } from "react-dom/server";
3 -import { describe, expect, it, vi } from "vite-plus/test";
4 -
5 -vi.mock("../ui/button", () => ({
6 - Button: ({ children }: { readonly children?: ReactNode }) => <button>{children}</button>,
7 -}));
8 -
9 -vi.mock("../ui/dialog", () => {
10 - const Container = ({ children }: { readonly children?: ReactNode }) => <div>{children}</div>;
11 - return {
12 - Dialog: Container,
13 - DialogDescription: Container,
14 - DialogFooter: Container,
15 - DialogHeader: Container,
16 - DialogPanel: Container,
17 - DialogPopup: Container,
18 - DialogTitle: Container,
19 - };
20 -});
21 -
22 -vi.mock("../ui/input", () => ({ Input: () => <input /> }));
23 -vi.mock("../ui/scroll-area", () => ({
24 - ScrollArea: ({ children }: { readonly children?: ReactNode }) => <div>{children}</div>,
25 -}));
26 -vi.mock("../ui/toggle-group", () => ({
27 - Toggle: ({ children, value }: { readonly children?: ReactNode; readonly value: string }) => (
28 - <button data-value={value}>{children}</button>
29 - ),
30 - ToggleGroup: ({
31 - children,
32 - value,
33 - }: {
34 - readonly children?: ReactNode;
35 - readonly value: readonly string[];
36 - }) => <div data-current={value.join(",")}>{children}</div>,
37 -}));
38 -
39 -import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog";
40 -
41 -describe("ProjectIconPickerDialog", () => {
42 - it("shows icons first and selects them for an automatic project", () => {
43 - const markup = renderToStaticMarkup(
44 - <ProjectIconPickerDialog
45 - current={null}
46 - projectName="Test"
47 - open
48 - onOpenChange={() => {}}
49 - onSelect={() => {}}
50 - />,
51 - );
52 -
53 - expect(markup).toContain('data-current="lucide"');
54 - expect(markup.indexOf(">Icons<")).toBeLessThan(markup.indexOf(">Emoji<"));
55 - expect(markup).toContain('aria-label="Icon color"');
56 - });
57 -});
apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx new
+358
@@ -0,0 +1,358 @@
1 +import { RegistryContext } from "@effect/atom-react";
2 +import type {
3 + DeleteProjectInput,
4 + UpdateProjectInput,
5 +} from "@t3tools/client-runtime/state/projects";
6 +import {
7 + AuthOrchestrationOperateScope,
8 + AuthSettingsWriteScope,
9 + EnvironmentId,
10 + ProjectId,
11 + ProviderInstanceId,
12 + type AuthEnvironmentScope,
13 + type AuthSessionState,
14 +} from "@t3tools/contracts";
15 +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
16 +import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
17 +import {
18 + createMemoryHistory,
19 + createRootRoute,
20 + createRouter,
21 + RouterProvider,
22 +} from "@tanstack/react-router";
23 +import * as Cause from "effect/Cause";
24 +import { AsyncResult, Atom } from "effect/reactivity";
25 +import { act } from "react";
26 +import { createRoot, type Root } from "react-dom/client";
27 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
28 +import { userEvent } from "vite-plus/test/browser";
29 +
30 +import type { Project } from "../../types";
31 +
32 +type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
33 +const state = vi.hoisted(() => ({
34 + sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
35 + projects: [] as Project[],
36 + update:
37 + vi.fn<
38 + (request: {
39 + environmentId: EnvironmentId;
40 + input: UpdateProjectInput;
41 + }) => Promise<AsyncResult.Success<void>>
42 + >(),
43 + delete:
44 + vi.fn<
45 + (request: {
46 + environmentId: EnvironmentId;
47 + input: DeleteProjectInput;
48 + }) => Promise<AsyncResult.Success<void>>
49 + >(),
50 + confirm: vi.fn<() => Promise<boolean>>(),
51 + releaseUploads: vi.fn(),
52 + clearDraft: vi.fn(),
53 +}));
54 +
55 +// Session grants come from the server; each test drives them through these atoms.
56 +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
57 + const actual = await original();
58 + return {
59 + ...actual,
60 + createEnvironmentSessionAtoms: ((
61 + ...args: Parameters<typeof actual.createEnvironmentSessionAtoms>
62 + ) => ({
63 + ...actual.createEnvironmentSessionAtoms(...args),
64 + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
65 + })) as typeof actual.createEnvironmentSessionAtoms,
66 + };
67 +});
68 +vi.mock(import("~/state/environments"), async (original) => ({
69 + ...(await original()),
70 + useEnvironments: (() => ({ environments })) as never,
71 + usePrimaryEnvironmentId: () => primaryId,
72 +}));
73 +vi.mock(import("~/state/entities"), async (original) => ({
74 + ...(await original()),
75 + useProjects: (() => state.projects) as never,
76 + useThreadShells: () => [],
77 + waitForProjectRemoval: async () => true,
78 +}));
79 +vi.mock(import("~/state/projects"), async (original) => {
80 + const actual = await original();
81 + return {
82 + ...actual,
83 + projectEnvironment: {
84 + ...actual.projectEnvironment,
85 + update: "update",
86 + delete: "delete",
87 + } as unknown as typeof actual.projectEnvironment,
88 + };
89 +});
90 +vi.mock(import("~/state/use-atom-command"), async (original) => ({
91 + ...(await original()),
92 + useAtomCommand: ((command: "update" | "delete") => state[command]) as never,
93 +}));
94 +vi.mock(import("~/hooks/useSettings"), async (original) => ({
95 + ...(await original()),
96 + useClientSettings: ((selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
97 + selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS) as never,
98 +}));
99 +vi.mock(import("~/localApi"), async (original) => ({
100 + ...(await original()),
101 + readLocalApi: (() => ({ dialogs: { confirm: state.confirm } })) as never,
102 +}));
103 +vi.mock(import("~/lib/composerDraftUploads"), async (original) => ({
104 + ...(await original()),
105 + releaseProjectDraftUploads: state.releaseUploads,
106 +}));
107 +// Sections with their own data sources and tests; this file covers project permissions.
108 +vi.mock(import("./ProjectDefaultsSettings"), async (original) => ({
109 + ...(await original()),
110 + ProjectDefaultsSettings: (() => null) as never,
111 +}));
112 +vi.mock(import("./ProjectActionsSettings"), async (original) => ({
113 + ...(await original()),
114 + ProjectActionsSettings: (() => null) as never,
115 +}));
116 +
117 +import { useComposerDraftStore } from "../../composerDraftStore";
118 +import { appAtomRegistry } from "../../rpc/atomRegistry";
119 +import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";
120 +import { ProjectSettingsPanel } from "./ProjectSettingsPanel";
121 +
122 +const primaryId = EnvironmentId.make("primary");
123 +const remoteId = EnvironmentId.make("remote");
124 +const instanceId = ProviderInstanceId.make("codex");
125 +const environments = [primaryId, remoteId].map((environmentId) => ({
126 + environmentId,
127 + label: environmentId,
128 + connection: { phase: "connected" },
129 + serverConfig: { keybindings: DEFAULT_RESOLVED_KEYBINDINGS },
130 +}));
131 +const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({
132 + authenticated: true,
133 + scopes,
134 + auth: {
135 + policy: "remote-reachable",
136 + bootstrapMethods: ["one-time-token"],
137 + sessionMethods: ["bearer-access-token"],
138 + sessionCookieName: "t3_session",
139 + },
140 +});
141 +const writable = () => AsyncResult.success(session([AuthOrchestrationOperateScope]));
142 +
143 +function deferred<T>() {
144 + let resolve!: (value: T) => void;
145 + const promise = new Promise<T>((complete) => {
146 + resolve = complete;
147 + });
148 + return { promise, resolve };
149 +}
150 +
151 +let root: Root;
152 +let container: HTMLDivElement;
153 +
154 +beforeEach(() => {
155 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
156 + vi.clearAllMocks();
157 + container = document.createElement("div");
158 + document.body.append(container);
159 + root = createRoot(container);
160 + state.sessions.clear();
161 + for (const id of [primaryId, remoteId])
162 + state.sessions.set(id, Atom.make<SessionResult>(writable()).pipe(Atom.keepAlive));
163 + state.projects = [primaryId, remoteId].map((environmentId) => ({
164 + id: ProjectId.make(`project-${environmentId}`),
165 + environmentId,
166 + title: "Shared repo",
167 + workspaceRoot: `/work/${environmentId}`,
168 + repositoryIdentity: {
169 + canonicalKey: "github.com/example/shared-repo",
170 + locator: {
171 + source: "git-remote",
172 + remoteName: "origin",
173 + remoteUrl: "https://github.com/example/shared-repo.git",
174 + },
175 + },
176 + defaultModelSelection: { instanceId, model: "gpt-5-codex" },
177 + createdAt: "2026-01-01T00:00:00.000Z",
178 + updatedAt: "2026-01-01T00:00:00.000Z",
179 + scripts: [],
180 + }));
181 + state.update.mockImplementation(async ({ environmentId, input }) => {
182 + const { projectId, ...updates } = input;
183 + const patch = Object.fromEntries(
184 + Object.entries(updates).filter(([, value]) => value !== undefined),
185 + ) as Partial<Project>;
186 + state.projects = state.projects.map((project) =>
187 + project.environmentId === environmentId && project.id === projectId
188 + ? { ...project, ...patch }
189 + : project,
190 + );
191 + return AsyncResult.success(undefined);
192 + });
193 + state.delete.mockResolvedValue(AsyncResult.success(undefined));
194 + state.confirm.mockResolvedValue(true);
195 + useComposerDraftStore.setState({ clearProjectDraftThreadId: state.clearDraft });
196 +});
197 +
198 +afterEach(async () => {
199 + await act(async () => root.unmount());
200 + container.remove();
201 + vi.unstubAllGlobals();
202 +});
203 +
204 +function projectKey() {
205 + return buildSidebarProjectSnapshots({
206 + projects: state.projects,
207 + settings: DEFAULT_CLIENT_SETTINGS,
208 + primaryEnvironmentId: primaryId,
209 + resolveEnvironmentLabel: (id) => id,
210 + })[0]!.projectKey;
211 +}
212 +
213 +async function mountPanel() {
214 + const key = projectKey();
215 + const router = createRouter({
216 + routeTree: createRootRoute({ component: () => <ProjectSettingsPanel projectKey={key} /> }),
217 + history: createMemoryHistory({ initialEntries: ["/settings/projects"] }),
218 + });
219 + await router.load();
220 + await act(async () =>
221 + root.render(
222 + <RegistryContext.Provider value={appAtomRegistry}>
223 + <RouterProvider router={router} />
224 + </RegistryContext.Provider>,
225 + ),
226 + );
227 + await vi.waitFor(() => expect(nameInput()).not.toBeNull());
228 +}
229 +
230 +const nameInput = () => container.querySelector<HTMLInputElement>('[aria-label="Project name"]')!;
231 +const removeCheckout = (root: string) =>
232 + container.querySelector<HTMLButtonElement>(`[aria-label="Remove checkout ${root}"]`)!;
233 +const removeAll = () =>
234 + [...container.querySelectorAll("button")].find((button) =>
235 + button.textContent?.includes("Remove all entries"),
236 + )!;
237 +
238 +async function grant(id: EnvironmentId, result: SessionResult) {
239 + await act(async () => appAtomRegistry.set(state.sessions.get(id)!, result));
240 +}
241 +
242 +async function rename(title: string) {
243 + await userEvent.fill(nameInput(), title);
244 + await userEvent.keyboard("{Enter}");
245 +}
246 +
247 +describe("project settings permissions", () => {
248 + it("disables shared edits when any member lacks project access", async () => {
249 + await grant(remoteId, AsyncResult.success(session([AuthSettingsWriteScope])));
250 + await mountPanel();
251 +
252 + expect(nameInput().disabled).toBe(true);
253 + expect(removeAll().disabled).toBe(true);
254 + expect(container.textContent).toContain(
255 + "Shared settings require permission to change every checkout in this group.",
256 + );
257 + expect(state.update).not.toHaveBeenCalled();
258 + });
259 +
260 + it("renames every member when all have project access without settings access", async () => {
261 + await mountPanel();
262 + await rename("Renamed");
263 + expect(state.update.mock.calls.map(([request]) => request.environmentId)).toEqual([
264 + primaryId,
265 + remoteId,
266 + ]);
267 + expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);
268 + });
269 +
270 + it("stops before the next member if its grant is revoked during an earlier update", async () => {
271 + const firstUpdate = deferred<AsyncResult.Success<void>>();
272 + state.update.mockReturnValueOnce(firstUpdate.promise);
273 + await mountPanel();
274 + await rename("Renamed");
275 + expect(state.update).toHaveBeenCalledOnce();
276 +
277 + await grant(remoteId, AsyncResult.success(session([])));
278 + await act(async () => {
279 + firstUpdate.resolve(AsyncResult.success(undefined));
280 + await firstUpdate.promise;
281 + });
282 + expect(state.update).toHaveBeenCalledOnce();
283 + expect(state.update.mock.calls[0]![0].environmentId).toBe(primaryId);
284 + });
285 +
286 + it("disables removal for a checkout whose project grant is missing", async () => {
287 + await grant(remoteId, AsyncResult.success(session([])));
288 + await mountPanel();
289 + expect(removeCheckout("/work/remote").disabled).toBe(true);
290 + expect(removeCheckout("/work/primary").disabled).toBe(false);
291 + });
292 +
293 + it("removes a writable checkout while removal of the mixed group stays denied", async () => {
294 + await grant(remoteId, AsyncResult.success(session([])));
295 + await mountPanel();
296 + expect(removeAll().disabled).toBe(true);
297 +
298 + await userEvent.click(removeCheckout("/work/primary"));
299 + await vi.waitFor(() => expect(state.delete).toHaveBeenCalledOnce());
300 + expect(state.delete).toHaveBeenCalledWith({
301 + environmentId: primaryId,
302 + input: { projectId: state.projects[0]!.id, force: true },
303 + });
304 + await vi.waitFor(() => expect(state.releaseUploads).toHaveBeenCalledOnce());
305 + expect(state.clearDraft).toHaveBeenCalledOnce();
306 + });
307 +
308 + it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => {
309 + const confirmed = deferred<boolean>();
310 + state.confirm.mockReturnValueOnce(confirmed.promise);
311 + await mountPanel();
312 + await userEvent.click(removeAll());
313 + expect(state.confirm).toHaveBeenCalledOnce();
314 +
315 + await grant(remoteId, AsyncResult.success(session([])));
316 + await act(async () => {
317 + confirmed.resolve(true);
318 + await confirmed.promise;
319 + });
320 + expect(state.delete).not.toHaveBeenCalled();
321 + expect(state.releaseUploads).not.toHaveBeenCalled();
322 + expect(state.clearDraft).not.toHaveBeenCalled();
323 + });
324 +
325 + it("does not save an edit whose grant was revoked mid-edit, and recovers when restored", async () => {
326 + await mountPanel();
327 + await userEvent.fill(nameInput(), "Renamed");
328 + await grant(remoteId, AsyncResult.success(session([])));
329 + await act(async () => nameInput().blur());
330 + expect(state.update).not.toHaveBeenCalled();
331 + expect(nameInput().disabled).toBe(true);
332 +
333 + await grant(remoteId, writable());
334 + expect(nameInput().disabled).toBe(false);
335 + await rename("Renamed");
336 + expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);
337 + });
338 +
339 + it.each([
340 + ["loading", () => AsyncResult.initial<AuthSessionState, Error>(), false],
341 + [
342 + "failed",
343 + () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("Disconnected"))),
344 + false,
345 + ],
346 + ["refreshing", () => AsyncResult.waiting(writable()), true],
347 + ] as const)(
348 + "uses the current grant while a member's session is %s",
349 + async (_state, result, allowed) => {
350 + await grant(remoteId, result());
351 + await mountPanel();
352 + expect(nameInput().disabled).toBe(!allowed);
353 + if (!allowed) return;
354 + await rename("Renamed");
355 + expect(state.update).toHaveBeenCalledTimes(2);
356 + },
357 + );
358 +});
apps/web/src/components/settings/ProjectSettingsPanel.test.tsx deleted
-477
@@ -1,477 +0,0 @@
1 -import { RegistryContext } from "@effect/atom-react";
2 -import type {
3 - DeleteProjectInput,
4 - UpdateProjectInput,
5 -} from "@t3tools/client-runtime/state/projects";
6 -import {
7 - AuthOrchestrationOperateScope,
8 - AuthSettingsWriteScope,
9 - DEFAULT_SERVER_SETTINGS,
10 - EnvironmentId,
11 - ProjectId,
12 - ProviderDriverKind,
13 - ProviderInstanceId,
14 - type AuthEnvironmentScope,
15 - type AuthSessionState,
16 - type ResolvedKeybindingsConfig,
17 - type ServerProvider,
18 -} from "@t3tools/contracts";
19 -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
20 -import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
21 -import * as Cause from "effect/Cause";
22 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
23 -import { cloneElement, type ReactElement, type ReactNode } from "react";
24 -import { act, create, type ReactTestRenderer } from "react-test-renderer";
25 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
26 -
27 -import type { Project } from "../../types";
28 -
29 -type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
30 -const state = vi.hoisted(() => ({
31 - registry: null as AtomRegistry.AtomRegistry | null,
32 - sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
33 - providers: null as Atom.Atom<ReadonlyArray<ServerProvider>> | null,
34 - config: null as Atom.Atom<{ keybindings: ResolvedKeybindingsConfig }> | null,
35 - projects: [] as Project[],
36 - update:
37 - vi.fn<
38 - (request: {
39 - environmentId: EnvironmentId;
40 - input: UpdateProjectInput;
41 - }) => Promise<AsyncResult.Success<void>>
42 - >(),
43 - delete:
44 - vi.fn<
45 - (request: {
46 - environmentId: EnvironmentId;
47 - input: DeleteProjectInput;
48 - }) => Promise<AsyncResult.Success<void>>
49 - >(),
50 - confirm: vi.fn<() => Promise<boolean>>(),
51 - updateSettings: vi.fn(),
52 - upsertKeybinding: vi.fn(),
53 - removeKeybinding: vi.fn(),
54 - updateClientSettings: vi.fn(),
55 - releaseUploads: vi.fn(),
56 - clearDraft: vi.fn(),
57 - copy: vi.fn(),
58 - navigate: vi.fn(),
59 -}));
60 -
61 -vi.mock("~/connection/runtime", () => ({ connectionAtomRuntime: undefined }));
62 -vi.mock("@t3tools/client-runtime/state/session", () => ({
63 - createEnvironmentSessionAtoms: () => ({
64 - sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
65 - }),
66 -}));
67 -vi.mock("~/rpc/atomRegistry", () => ({
68 - get appAtomRegistry() {
69 - return state.registry;
70 - },
71 -}));
72 -vi.mock("~/state/environments", () => ({
73 - useEnvironments: () => ({ environments }),
74 - usePrimaryEnvironmentId: () => primaryId,
75 -}));
76 -vi.mock("~/state/entities", () => ({
77 - useProjects: () => state.projects,
78 - useThreadShells: () => [],
79 - waitForProjectRemoval: async () => true,
80 -}));
81 -vi.mock("~/state/projects", () => ({
82 - projectEnvironment: { update: "update", delete: "delete" },
83 -}));
84 -vi.mock("~/state/server", () => ({
85 - EMPTY_SERVER_PROVIDERS: [],
86 - serverEnvironment: {
87 - providersValueAtom: () => state.providers!,
88 - configValueAtom: () => state.config!,
89 - updateSettings: "updateSettings",
90 - upsertKeybinding: "upsertKeybinding",
91 - removeKeybinding: "removeKeybinding",
92 - },
93 -}));
94 -vi.mock("~/state/use-atom-command", () => ({
95 - useAtomCommand: (
96 - command: "update" | "delete" | "updateSettings" | "upsertKeybinding" | "removeKeybinding",
97 - ) => state[command],
98 -}));
99 -vi.mock("~/hooks/useSettings", () => ({
100 - useClientSettings: () => DEFAULT_CLIENT_SETTINGS,
101 - useUpdateClientSettings: () => state.updateClientSettings,
102 - usePrimarySettings: () => DEFAULT_SERVER_SETTINGS,
103 - useEnvironmentSettings: () => DEFAULT_SERVER_SETTINGS,
104 -}));
105 -vi.mock("~/hooks/useT3ProjectFileScripts", () => ({
106 - useT3ProjectFileState: () => ({
107 - status: "valid",
108 - file: null,
109 - scripts: [{ name: "Imported", command: "vp test" }],
110 - }),
111 -}));
112 -vi.mock("~/hooks/useCopyToClipboard", () => ({
113 - useCopyToClipboard: () => ({ copyToClipboard: state.copy }),
114 -}));
115 -vi.mock("~/localApi", () => ({ readLocalApi: () => ({ dialogs: { confirm: state.confirm } }) }));
116 -vi.mock("~/composerDraftStore", () => ({
117 - useComposerDraftStore: {
118 - getState: () => ({
119 - getDraftThreadByProjectRef: () => null,
120 - clearProjectDraftThreadId: state.clearDraft,
121 - }),
122 - },
123 -}));
124 -vi.mock("~/lib/composerDraftUploads", () => ({ releaseProjectDraftUploads: state.releaseUploads }));
125 -vi.mock("~/env", () => ({ isElectron: true }));
126 -vi.mock("@tanstack/react-router", () => ({
127 - useNavigate: () => state.navigate,
128 - useLocation: () => "/settings/projects",
129 -}));
130 -vi.mock("../ui/toast", () => ({
131 - toastManager: { add: vi.fn() },
132 - stackedThreadToast: (value: unknown) => value,
133 -}));
134 -vi.mock("../ui/button", () => ({ Button: "button" }));
135 -vi.mock("../ui/input", () => ({ Input: "input" }));
136 -vi.mock("../ui/switch", () => ({ Switch: "input" }));
137 -vi.mock("../ui/select", () => ({
138 - Select: "select",
139 - SelectItem: "option",
140 - SelectPopup: "div",
141 - SelectTrigger: "button",
142 - SelectValue: "span",
143 -}));
144 -vi.mock("../ui/menu", () => ({
145 - Menu: "div",
146 - MenuGroup: "div",
147 - MenuGroupLabel: "div",
148 - MenuItem: "button",
149 - MenuPopup: "div",
150 - MenuSeparator: "hr",
151 - MenuTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>
152 - cloneElement(render, {}, children),
153 -}));
154 -vi.mock("../ui/tooltip", () => ({
155 - Tooltip: "div",
156 - TooltipPopup: "span",
157 - TooltipTrigger: ({ render }: { render: ReactNode }) => render,
158 -}));
159 -vi.mock("./settingsLayout", () => ({
160 - SETTINGS_PICKER_TRIGGER_CLASSNAME: "",
161 - SettingsPageContainer: "div",
162 - SettingsSection: ({
163 - children,
164 - headerAction,
165 - }: {
166 - children: ReactNode;
167 - headerAction?: ReactNode;
168 - }) => (
169 - <section>
170 - {headerAction}
171 - {children}
172 - </section>
173 - ),
174 - SettingsRow: ({ control, resetAction }: { control?: ReactNode; resetAction?: ReactNode }) => (
175 - <div>
176 - {resetAction}
177 - {control}
178 - </div>
179 - ),
180 - SettingResetButton: ({
181 - label,
182 - ...props
183 - }: {
184 - label: string;
185 - disabled?: boolean;
186 - onClick: () => void;
187 - }) => <button {...props} aria-label={`Reset ${label} to default`} />,
188 -}));
189 -vi.mock("./ProjectDefaultsSettings", () => ({ ProjectDefaultsSettings: () => null }));
190 -vi.mock("./ProjectActionsSettings", () => ({ ProjectActionsSettings: () => null }));
191 -vi.mock("../ProjectFavicon", () => ({ ProjectFavicon: () => null }));
192 -vi.mock("../chat/ProviderModelPicker", () => ({ ProviderModelPicker: "model-picker" }));
193 -vi.mock("../chat/TraitsPicker", () => ({ TraitsPicker: "traits-picker" }));
194 -vi.mock("./ProjectFaviconPickerDialog", () => ({
195 - canPickExternalProjectFavicon: () => false,
196 - ProjectFaviconPickerDialog: "favicon-picker",
197 -}));
198 -vi.mock("./ProjectIconPickerDialog", () => ({ ProjectIconPickerDialog: "icon-picker" }));
199 -vi.mock("../projectScriptEditor", async (importOriginal) => ({
200 - ...(await importOriginal<typeof import("../projectScriptEditor")>()),
201 - ProjectScriptEditorDialog: "script-editor",
202 -}));
203 -
204 -import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";
205 -import { ProjectFaviconPickerDialog } from "./ProjectFaviconPickerDialog";
206 -import { ProjectSettingsPanel } from "./ProjectSettingsPanel";
207 -
208 -const primaryId = EnvironmentId.make("primary");
209 -const remoteId = EnvironmentId.make("remote");
210 -const instanceId = ProviderInstanceId.make("codex");
211 -const environments = [primaryId, remoteId].map((environmentId) => ({
212 - environmentId,
213 - label: environmentId,
214 - connection: { phase: "connected" },
215 - serverConfig: { keybindings: DEFAULT_RESOLVED_KEYBINDINGS },
216 -}));
217 -const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({
218 - authenticated: true,
219 - scopes,
220 - auth: {
221 - policy: "remote-reachable",
222 - bootstrapMethods: ["one-time-token"],
223 - sessionMethods: ["bearer-access-token"],
224 - sessionCookieName: "t3_session",
225 - },
226 -});
227 -const writable = () => AsyncResult.success(session([AuthOrchestrationOperateScope]));
228 -
229 -function deferred<T>() {
230 - let resolve!: (value: T) => void;
231 - const promise = new Promise<T>((complete) => {
232 - resolve = complete;
233 - });
234 - return { promise, resolve };
235 -}
236 -
237 -let renderer: ReactTestRenderer | undefined;
238 -
239 -beforeEach(() => {
240 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
241 - vi.clearAllMocks();
242 - state.registry = AtomRegistry.make();
243 - state.sessions.clear();
244 - for (const id of [primaryId, remoteId])
245 - state.sessions.set(id, Atom.make<SessionResult>(writable()).pipe(Atom.keepAlive));
246 - state.projects = [primaryId, remoteId].map((environmentId) => ({
247 - id: ProjectId.make(`project-${environmentId}`),
248 - environmentId,
249 - title: "Shared repo",
250 - workspaceRoot: `/work/${environmentId}`,
251 - repositoryIdentity: {
252 - canonicalKey: "github.com/example/shared-repo",
253 - locator: {
254 - source: "git-remote",
255 - remoteName: "origin",
256 - remoteUrl: "https://github.com/example/shared-repo.git",
257 - },
258 - },
259 - defaultModelSelection: { instanceId, model: "gpt-5-codex" },
260 - createdAt: "2026-01-01T00:00:00.000Z",
261 - updatedAt: "2026-01-01T00:00:00.000Z",
262 - scripts: [],
263 - }));
264 - state.providers = Atom.make<ReadonlyArray<ServerProvider>>([
265 - {
266 - instanceId,
267 - driver: ProviderDriverKind.make("codex"),
268 - enabled: true,
269 - installed: true,
270 - version: null,
271 - status: "ready",
272 - auth: { status: "authenticated" },
273 - checkedAt: "2026-01-01T00:00:00.000Z",
274 - models: [],
275 - slashCommands: [],
276 - skills: [],
277 - },
278 - ]);
279 - state.config = Atom.make({ keybindings: DEFAULT_RESOLVED_KEYBINDINGS });
280 - state.update.mockImplementation(async ({ environmentId, input }) => {
281 - const { projectId, ...updates } = input;
282 - const patch = Object.fromEntries(
283 - Object.entries(updates).filter(([, value]) => value !== undefined),
284 - ) as Partial<Project>;
285 - state.projects = state.projects.map((project) =>
286 - project.environmentId === environmentId && project.id === projectId
287 - ? { ...project, ...patch }
288 - : project,
289 - );
290 - return AsyncResult.success(undefined);
291 - });
292 - state.delete.mockResolvedValue(AsyncResult.success(undefined));
293 - state.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
294 - state.confirm.mockResolvedValue(true);
295 -});
296 -
297 -afterEach(async () => {
298 - await act(() => renderer?.unmount());
299 - renderer = undefined;
300 - state.registry?.dispose();
301 - vi.unstubAllGlobals();
302 -});
303 -
304 -function group() {
305 - return buildSidebarProjectSnapshots({
306 - projects: state.projects,
307 - settings: DEFAULT_CLIENT_SETTINGS,
308 - primaryEnvironmentId: primaryId,
309 - resolveEnvironmentLabel: (id) => id,
310 - })[0]!;
311 -}
312 -
313 -async function mountPanel() {
314 - await act(() => {
315 - renderer = create(
316 - <RegistryContext.Provider value={state.registry!}>
317 - <ProjectSettingsPanel projectKey={group().projectKey} />
318 - </RegistryContext.Provider>,
319 - );
320 - });
321 - return renderer!.root;
322 -}
323 -
324 -function button(label: string) {
325 - return renderer!.root.findAllByType("button").find((node) => node.children.includes(label))!;
326 -}
327 -
328 -async function grant(id: EnvironmentId, result: SessionResult) {
329 - await act(() => state.registry!.set(state.sessions.get(id)!, result));
330 -}
331 -
332 -describe("project settings permissions", () => {
333 - it("preflights every member before any shared field update", async () => {
334 - await grant(remoteId, AsyncResult.success(session([AuthSettingsWriteScope])));
335 - const root = await mountPanel();
336 - const name = root.findByProps({ "aria-label": "Project name" });
337 -
338 - await act(async () => {
339 - name.props.onChange();
340 - name.props.onBlur({ currentTarget: { value: "Renamed" } });
341 - root.findByType(ProjectFaviconPickerDialog).props.onSelect("/work/icon.png");
342 - });
343 -
344 - expect(state.update).not.toHaveBeenCalled();
345 - expect(state.projects.every((project) => project.title === "Shared repo")).toBe(true);
346 - expect(name.props.disabled).toBe(true);
347 - expect(button("Remove all entries").props.disabled).toBe(true);
348 - });
349 -
350 - it("updates every member when all have project access without settings access", async () => {
351 - const root = await mountPanel();
352 - await act(async () => {
353 - const name = root.findByProps({ "aria-label": "Project name" });
354 - name.props.onChange();
355 - name.props.onBlur({ currentTarget: { value: "Renamed" } });
356 - });
357 - expect(state.update.mock.calls.map(([request]) => request.environmentId)).toEqual([
358 - primaryId,
359 - remoteId,
360 - ]);
361 - expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);
362 - });
363 -
364 - it("stops before the next member if its grant is revoked during an earlier update", async () => {
365 - const firstUpdate = deferred<AsyncResult.Success<void>>();
366 - state.update.mockReturnValueOnce(firstUpdate.promise);
367 - const root = await mountPanel();
368 - await act(async () => {
369 - const name = root.findByProps({ "aria-label": "Project name" });
370 - name.props.onChange();
371 - name.props.onBlur({ currentTarget: { value: "Renamed" } });
372 - });
373 - expect(state.update).toHaveBeenCalledOnce();
374 -
375 - await grant(remoteId, AsyncResult.success(session([])));
376 - await act(async () => {
377 - firstUpdate.resolve(AsyncResult.success(undefined));
378 - await firstUpdate.promise;
379 - });
380 - expect(state.update).toHaveBeenCalledOnce();
381 - expect(state.update.mock.calls[0]![0].environmentId).toBe(primaryId);
382 - });
383 -
384 - it("disables removal for a checkout whose project grant is missing", async () => {
385 - await grant(remoteId, AsyncResult.success(session([])));
386 - const root = await mountPanel();
387 - const denied = root.findByProps({ "aria-label": "Remove checkout /work/remote" });
388 - expect(denied.props.disabled).toBe(true);
389 - await act(async () => denied.props.onClick());
390 - expect(state.confirm).not.toHaveBeenCalled();
391 - expect(state.delete).not.toHaveBeenCalled();
392 - expect(root.findByProps({ "aria-label": "Remove checkout /work/primary" }).props.disabled).toBe(
393 - false,
394 - );
395 - });
396 -
397 - it("allows removing a writable checkout while denying removal of the mixed group", async () => {
398 - await grant(remoteId, AsyncResult.success(session([])));
399 - await mountPanel();
400 - await act(async () => button("Remove all entries").props.onClick());
401 - expect(state.confirm).not.toHaveBeenCalled();
402 - expect(state.delete).not.toHaveBeenCalled();
403 - await act(async () =>
404 - renderer!.root.findByProps({ "aria-label": "Remove checkout /work/primary" }).props.onClick(),
405 - );
406 - expect(state.delete).toHaveBeenCalledExactlyOnceWith({
407 - environmentId: primaryId,
408 - input: { projectId: state.projects[0]!.id, force: true },
409 - });
410 - expect(state.releaseUploads).toHaveBeenCalledOnce();
411 - expect(state.clearDraft).toHaveBeenCalledOnce();
412 - });
413 -
414 - it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => {
415 - const confirmed = deferred<boolean>();
416 - state.confirm.mockReturnValueOnce(confirmed.promise);
417 - await mountPanel();
418 - await act(async () => button("Remove all entries").props.onClick());
419 - expect(state.confirm).toHaveBeenCalledOnce();
420 - await grant(remoteId, AsyncResult.success(session([])));
421 - await act(async () => {
422 - confirmed.resolve(true);
423 - await confirmed.promise;
424 - });
425 - expect(state.delete).not.toHaveBeenCalled();
426 - expect(state.releaseUploads).not.toHaveBeenCalled();
427 - expect(state.clearDraft).not.toHaveBeenCalled();
428 - });
429 -
430 - it("reacts to another member's revoked and restored grant and guards a stale handler", async () => {
431 - await grant(
432 - primaryId,
433 - AsyncResult.success(session([AuthOrchestrationOperateScope, AuthSettingsWriteScope])),
434 - );
435 - const root = await mountPanel();
436 - const name = () => root.findByProps({ "aria-label": "Project name" });
437 - const staleSave = name().props.onBlur;
438 - await act(async () => {
439 - state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));
440 - name().props.onChange();
441 - staleSave({ currentTarget: { value: "Renamed" } });
442 - });
443 - expect(state.update).not.toHaveBeenCalled();
444 - expect(name().props.disabled).toBe(true);
445 -
446 - await grant(remoteId, writable());
447 - expect(name().props.disabled).toBe(false);
448 - await act(async () => {
449 - name().props.onChange();
450 - name().props.onBlur({ currentTarget: { value: "Renamed" } });
451 - });
452 - expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);
453 - });
454 -
455 - it.each([
456 - ["loading", () => AsyncResult.initial<AuthSessionState, Error>(), false],
457 - [
458 - "failed",
459 - () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("Disconnected"))),
460 - false,
461 - ],
462 - ["refreshing", () => AsyncResult.waiting(writable()), true],
463 - ] as const)(
464 - "uses the current grant while a member's session is %s",
465 - async (_state, result, allowed) => {
466 - await grant(remoteId, result());
467 - const root = await mountPanel();
468 - const name = root.findByProps({ "aria-label": "Project name" });
469 - expect(name.props.disabled).toBe(!allowed);
470 - await act(async () => {
471 - name.props.onChange();
472 - name.props.onBlur({ currentTarget: { value: "Renamed" } });
473 - });
474 - expect(state.update).toHaveBeenCalledTimes(allowed ? 2 : 0);
475 - },
476 - );
477 -});
apps/web/src/components/settings/ProviderInstanceCard.browser.test.tsx new
+105
@@ -0,0 +1,105 @@
1 +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
2 +import { act, type ComponentProps } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { userEvent } from "vite-plus/test/browser";
6 +
7 +import { ProviderInstanceCard } from "./ProviderInstanceCard";
8 +
9 +let root: Root;
10 +let container: HTMLDivElement;
11 +
12 +beforeEach(() => {
13 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14 + container = document.createElement("div");
15 + document.body.append(container);
16 + root = createRoot(container);
17 +});
18 +
19 +afterEach(async () => {
20 + await act(async () => root.unmount());
21 + container.remove();
22 + vi.unstubAllGlobals();
23 +});
24 +
25 +const driver = ProviderDriverKind.make("codex");
26 +
27 +function provider(overrides: Partial<ServerProvider>): ServerProvider {
28 + return {
29 + instanceId: ProviderInstanceId.make("codex"),
30 + driver,
31 + enabled: true,
32 + installed: true,
33 + version: "1.0.0",
34 + status: "ready",
35 + auth: { status: "authenticated" },
36 + checkedAt: "2026-08-27T12:00:00.000Z",
37 + models: [],
38 + slashCommands: [],
39 + skills: [],
40 + ...overrides,
41 + };
42 +}
43 +
44 +async function renderCard(
45 + liveProvider: ServerProvider,
46 + mode: ComponentProps<typeof ProviderInstanceCard>["mode"],
47 +) {
48 + await act(async () =>
49 + root.render(
50 + <ProviderInstanceCard
51 + instanceId={liveProvider.instanceId}
52 + instance={{ driver }}
53 + driverOption={undefined}
54 + liveProvider={liveProvider}
55 + mode={mode}
56 + onUpdate={() => undefined}
57 + hiddenModels={[]}
58 + favoriteModels={[]}
59 + modelOrder={[]}
60 + onHiddenModelsChange={() => undefined}
61 + onFavoriteModelsChange={() => undefined}
62 + onToggleFavorite={() => undefined}
63 + onModelOrderChange={() => undefined}
64 + />,
65 + ),
66 + );
67 +}
68 +
69 +describe("ProviderInstanceCard", () => {
70 + it("hides the account email until the user reveals it, and hides it again", async () => {
71 + await renderCard(
72 + provider({ auth: { status: "authenticated", email: "developer@example.com" } }),
73 + "editor",
74 + );
75 + expect(container.textContent).toContain("Authenticated as");
76 + expect(container.textContent).not.toContain("developer@example.com");
77 +
78 + const toggle = container.querySelector<HTMLButtonElement>(
79 + 'button[aria-label="Toggle account email visibility"]',
80 + )!;
81 + await userEvent.click(toggle);
82 + expect(toggle.textContent).toBe("developer@example.com");
83 +
84 + await userEvent.click(toggle);
85 + expect(container.textContent).not.toContain("developer@example.com");
86 + });
87 +
88 + it.each(["list", "editor"] as const)(
89 + "surfaces a failed probe message in the %s",
90 + async (mode) => {
91 + await renderCard(
92 + provider({
93 + version: null,
94 + status: "error",
95 + auth: { status: "unknown" },
96 + message:
97 + "Codex app-server provider probe failed: Cannot create Codex shadow home entry 'auth.json' because '/home/me/.codex-t3/work/auth.json' already exists and is not a symlink.",
98 + }),
99 + mode,
100 + );
101 + expect(container.textContent).toContain("Unavailable");
102 + expect(container.textContent).toContain("is not a symlink");
103 + },
104 + );
105 +});
apps/web/src/components/settings/ProviderInstanceCard.test.ts
+1 -90
@@ -1,18 +1,10 @@
1 -import { createElement } from "react";
2 -import { renderToStaticMarkup } from "react-dom/server";
1 import { describe, expect, it } from "vite-plus/test";
4 -import {
5 - ProviderDriverKind,
6 - ProviderInstanceId,
7 - type ServerProvider,
8 - type ServerProviderModel,
9 -} from "@t3tools/contracts";
2 +import type { ServerProviderModel } from "@t3tools/contracts";
3
4 import {
5 deriveProviderModelsForDisplay,
6 nextProviderEnvironmentWithFieldValue,
7 providerEnvironmentWithoutNames,
15 - ProviderInstanceCard,
8 readProviderEnvironmentVariable,
9 } from "./ProviderInstanceCard";
10
@@ -86,87 +78,6 @@ describe("deriveProviderModelsForDisplay", () => {
78 capabilities: customCapabilities,
79 });
80 });
89 -
90 - it("shows a redacted provider email in the editor header status line", () => {
91 - const instanceId = ProviderInstanceId.make("codex");
92 - const driver = ProviderDriverKind.make("codex");
93 - const liveProvider: ServerProvider = {
94 - instanceId,
95 - driver,
96 - enabled: true,
97 - installed: true,
98 - version: "1.0.0",
99 - status: "ready",
100 - auth: { status: "authenticated", email: "developer@example.com" },
101 - checkedAt: "2026-08-27T12:00:00.000Z",
102 - models: [],
103 - slashCommands: [],
104 - skills: [],
105 - };
106 -
107 - const markup = renderToStaticMarkup(
108 - createElement(ProviderInstanceCard, {
109 - instanceId,
110 - instance: { driver },
111 - driverOption: undefined,
112 - liveProvider,
113 - mode: "editor",
114 - onUpdate: () => undefined,
115 - hiddenModels: [],
116 - favoriteModels: [],
117 - modelOrder: [],
118 - onHiddenModelsChange: () => undefined,
119 - onFavoriteModelsChange: () => undefined,
120 - onToggleFavorite: () => undefined,
121 - onModelOrderChange: () => undefined,
122 - }),
123 - );
124 -
125 - expect(markup).toContain("Authenticated as");
126 - expect(markup).toContain('aria-label="Toggle account email visibility"');
127 - expect(markup).toContain("blur-xs");
128 - expect(markup).not.toContain("developer@example.com");
129 - });
130 - it("surfaces a failed probe message in both the list row and the editor", () => {
131 - const instanceId = ProviderInstanceId.make("codex_work");
132 - const driver = ProviderDriverKind.make("codex");
133 - const message =
134 - "Codex app-server provider probe failed: Cannot create Codex shadow home entry 'auth.json' because '/home/me/.codex-t3/work/auth.json' already exists and is not a symlink.";
135 - const liveProvider: ServerProvider = {
136 - instanceId,
137 - driver,
138 - enabled: true,
139 - installed: true,
140 - version: null,
141 - status: "error",
142 - auth: { status: "unknown" },
143 - checkedAt: "2026-08-28T12:00:00.000Z",
144 - models: [],
145 - slashCommands: [],
146 - skills: [],
147 - message,
148 - };
149 - const props = {
150 - instanceId,
151 - instance: { driver },
152 - driverOption: undefined,
153 - liveProvider,
154 - onUpdate: () => undefined,
155 - hiddenModels: [],
156 - favoriteModels: [],
157 - modelOrder: [],
158 - onHiddenModelsChange: () => undefined,
159 - onFavoriteModelsChange: () => undefined,
160 - onToggleFavorite: () => undefined,
161 - onModelOrderChange: () => undefined,
162 - } as const;
163 -
164 - for (const mode of ["list", "editor"] as const) {
165 - const markup = renderToStaticMarkup(createElement(ProviderInstanceCard, { ...props, mode }));
166 - expect(markup).toContain("Unavailable");
167 - expect(markup).toContain("is not a symlink");
168 - }
169 - });
81 });
82
83 describe("provider environment helpers", () => {
apps/web/src/components/settings/SecretInput.browser.test.tsx new
+66
@@ -0,0 +1,66 @@
1 +import { act } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { userEvent } from "vite-plus/test/browser";
5 +
6 +import { SecretInput } from "./SecretInput";
7 +
8 +let root: Root;
9 +let container: HTMLDivElement;
10 +
11 +beforeEach(() => {
12 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
13 + container = document.createElement("div");
14 + document.body.append(container);
15 + root = createRoot(container);
16 +});
17 +
18 +afterEach(async () => {
19 + await act(async () => root.unmount());
20 + container.remove();
21 + vi.unstubAllGlobals();
22 +});
23 +
24 +const input = () => container.querySelector("input")!;
25 +
26 +async function edit(value: string) {
27 + await userEvent.clear(input());
28 + if (value) await userEvent.type(input(), value);
29 + await userEvent.click(document.body);
30 +}
31 +
32 +describe("SecretInput", () => {
33 + it("preserves a configured secret on empty edits and commits a replacement", async () => {
34 + const onCommit = vi.fn();
35 + await act(async () => root.render(<SecretInput configured value="" onCommit={onCommit} />));
36 + expect(input().type).toBe("password");
37 +
38 + await userEvent.click(input());
39 + await userEvent.click(document.body);
40 + expect(onCommit).not.toHaveBeenCalled();
41 +
42 + await edit("replacement");
43 + expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
44 + expect(input().value).toBe("");
45 + });
46 +
47 + it("allows clearing an unsaved draft", async () => {
48 + const onCommit = vi.fn();
49 + await act(async () => root.render(<SecretInput value="draft" onCommit={onCommit} />));
50 + await edit("");
51 + expect(onCommit).toHaveBeenCalledExactlyOnceWith("");
52 + });
53 +
54 + it("keeps an in-progress replacement when settings refresh", async () => {
55 + const onCommit = vi.fn();
56 + const render = () => root.render(<SecretInput configured value="" onCommit={onCommit} />);
57 + await act(async () => render());
58 +
59 + await userEvent.type(input(), "replacement");
60 + await act(async () => render());
61 + expect(input().value).toBe("replacement");
62 +
63 + await userEvent.keyboard("{Enter}");
64 + expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
65 + });
66 +});
apps/web/src/components/settings/SecretInput.test.tsx deleted
-63
@@ -1,63 +0,0 @@
1 -import { act } from "react";
2 -import { create, type ReactTestRenderer } from "react-test-renderer";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 -
5 -import { SecretInput } from "./SecretInput";
6 -
7 -vi.mock("../ui/input", () => ({
8 - Input: (props: Record<string, unknown>) => <input {...props} />,
9 -}));
10 -
11 -let renderer: ReactTestRenderer;
12 -
13 -beforeEach(() => vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true));
14 -afterEach(async () => {
15 - await act(() => renderer?.unmount());
16 - vi.unstubAllGlobals();
17 -});
18 -
19 -async function edit(value: string) {
20 - await act(() => renderer.root.findByType("input").props.onFocus());
21 - await act(() => renderer.root.findByType("input").props.onChange({ target: { value } }));
22 - await act(() => renderer.root.findByType("input").props.onBlur());
23 -}
24 -
25 -describe("SecretInput", () => {
26 - it("preserves a configured secret on empty edits and commits a replacement", async () => {
27 - const onCommit = vi.fn();
28 - await act(() => {
29 - renderer = create(<SecretInput configured value="" onCommit={onCommit} />);
30 - });
31 - await edit("");
32 - expect(onCommit).not.toHaveBeenCalled();
33 - await edit("replacement");
34 - expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
35 - expect(renderer.root.findByType("input").props.value).toBe("");
36 - });
37 -
38 - it("allows clearing an unsaved draft", async () => {
39 - const onCommit = vi.fn();
40 - await act(() => {
41 - renderer = create(<SecretInput value="draft" onCommit={onCommit} />);
42 - });
43 - await edit("");
44 - expect(onCommit).toHaveBeenCalledExactlyOnceWith("");
45 - });
46 -
47 - it("keeps an in-progress replacement when settings refresh", async () => {
48 - const onCommit = vi.fn();
49 - await act(() => {
50 - renderer = create(<SecretInput configured value="" onCommit={onCommit} />);
51 - });
52 - await act(() => renderer.root.findByType("input").props.onFocus());
53 - await act(() =>
54 - renderer.root.findByType("input").props.onChange({ target: { value: "replacement" } }),
55 - );
56 - await act(() => {
57 - renderer.update(<SecretInput configured value="" onCommit={onCommit} />);
58 - });
59 - expect(renderer.root.findByType("input").props.value).toBe("replacement");
60 - await act(() => renderer.root.findByType("input").props.onBlur());
61 - expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");
62 - });
63 -});
apps/web/src/components/settings/TelemetryExportSettings.browser.test.tsx new
+95
@@ -0,0 +1,95 @@
1 +import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
2 +import { act } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +import { userEvent } from "vite-plus/test/browser";
6 +
7 +const { state, updateSettings } = vi.hoisted(() => ({
8 + state: { observability: {} as typeof DEFAULT_SERVER_SETTINGS.observability },
9 + updateSettings: vi.fn(async () => ({ _tag: "Success" as const, value: undefined })),
10 +}));
11 +
12 +vi.mock(import("@effect/atom-react"), async (original) => ({
13 + ...(await original()),
14 + useAtomValue: (() => true) as never,
15 +}));
16 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
17 + ...(await original()),
18 + useAtomCommand: ((command: unknown) =>
19 + command === "updateSettings" ? updateSettings : vi.fn()) as never,
20 +}));
21 +vi.mock(import("../../state/server"), async (original) => {
22 + const actual = await original();
23 + return {
24 + ...actual,
25 + serverEnvironment: {
26 + ...actual.serverEnvironment,
27 + updateSettings: "updateSettings",
28 + } as unknown as typeof actual.serverEnvironment,
29 + };
30 +});
31 +vi.mock(import("./SettingsScopeContext"), async (original) => ({
32 + ...(await original()),
33 + useSettingsScope: (() => ({
34 + scope: { kind: "environment" },
35 + environment: {
36 + environmentId: "env",
37 + label: "MAC1",
38 + serverConfig: { environment: { capabilities: {} } },
39 + },
40 + })) as never,
41 +}));
42 +vi.mock(import("./useScopedSettings"), async (original) => ({
43 + ...(await original()),
44 + useScopedSettings: ((select: (settings: typeof state) => unknown) => select(state)) as never,
45 +}));
46 +
47 +import { TelemetryExportSettings } from "./TelemetryExportSettings";
48 +
49 +let root: Root;
50 +let container: HTMLDivElement;
51 +beforeEach(() => {
52 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
53 + container = document.createElement("div");
54 + document.body.append(container);
55 + root = createRoot(container);
56 +});
57 +
58 +afterEach(async () => {
59 + await act(async () => root.unmount());
60 + container.remove();
61 + updateSettings.mockClear();
62 + vi.unstubAllGlobals();
63 +});
64 +
65 +const field = (id: string) => container.querySelector<HTMLInputElement>(`#${id}`)!;
66 +async function replace(id: string, value: string) {
67 + await userEvent.clear(field(id));
68 + await userEvent.type(field(id), value);
69 +}
70 +
71 +describe("TelemetryExportSettings", () => {
72 + it("does not resend a field the user restored after another client changed it", async () => {
73 + state.observability = {
74 + ...DEFAULT_SERVER_SETTINGS.observability,
75 + otlpTracesUrl: "http://old/v1/traces",
76 + };
77 + await act(async () => root.render(<TelemetryExportSettings />));
78 +
79 + await replace("otlpTracesUrl", "http://draft/v1/traces");
80 + await replace("otlpTracesUrl", "http://old/v1/traces");
81 + state.observability = { ...state.observability, otlpTracesUrl: "http://other/v1/traces" };
82 + await act(async () => root.render(<TelemetryExportSettings />));
83 + await replace("otlpMetricsUrl", "http://new/v1/metrics");
84 + const save = [...container.querySelectorAll("button")].find(
85 + (button) => button.textContent === "Save",
86 + )!;
87 + await userEvent.click(save);
88 +
89 + expect(updateSettings).toHaveBeenCalledExactlyOnceWith({
90 + environmentId: "env",
91 + input: { patch: { observability: { otlpMetricsUrl: "http://new/v1/metrics" } } },
92 + });
93 + expect(container.textContent).toContain("Saved. Restart the server to apply.");
94 + });
95 +});
apps/web/src/components/settings/TelemetryExportSettings.test.tsx deleted
-72
@@ -1,72 +0,0 @@
1 -import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
2 -import { act, type ReactNode } from "react";
3 -import { create, type ReactTestRenderer } from "react-test-renderer";
4 -import { afterEach, describe, expect, it, vi } from "vite-plus/test";
5 -
6 -const { state, updateSettings } = vi.hoisted(() => ({
7 - state: { observability: {} as typeof DEFAULT_SERVER_SETTINGS.observability },
8 - updateSettings: vi.fn(async () => ({ _tag: "Success" as const, value: undefined })),
9 -}));
10 -
11 -vi.mock("@effect/atom-react", () => ({ useAtomValue: () => true }));
12 -vi.mock("../../state/server", () => ({
13 - serverEnvironment: {
14 - updateSettings: "updateSettings",
15 - checkOtlpEndpoint: { permissionAtom: () => null },
16 - },
17 -}));
18 -vi.mock("../../state/use-atom-command", () => ({
19 - useAtomCommand: (command: unknown) => (command === "updateSettings" ? updateSettings : vi.fn()),
20 -}));
21 -vi.mock("./SettingsScopeContext", () => ({
22 - useSettingsScope: () => ({
23 - scope: { kind: "environment" },
24 - environment: {
25 - environmentId: "env",
26 - label: "MAC1",
27 - serverConfig: { environment: { capabilities: {} } },
28 - },
29 - }),
30 -}));
31 -vi.mock("./useScopedSettings", () => ({
32 - useScopedSettings: (select: (settings: typeof state) => unknown) => select(state),
33 -}));
34 -vi.mock("./settingsLayout", () => ({
35 - SettingsSection: ({ children }: { children: ReactNode }) => <section>{children}</section>,
36 -}));
37 -
38 -import { TelemetryExportSettings } from "./TelemetryExportSettings";
39 -
40 -let renderer: ReactTestRenderer | null = null;
41 -afterEach(async () => {
42 - await act(() => renderer?.unmount());
43 - renderer = null;
44 - updateSettings.mockClear();
45 -});
46 -
47 -const type = (id: string, value: string) =>
48 - act(() => renderer!.root.findByProps({ id }).props.onChange({ target: { value } }));
49 -
50 -describe("TelemetryExportSettings", () => {
51 - it("does not resend a field the user restored after another client changed it", async () => {
52 - state.observability = {
53 - ...DEFAULT_SERVER_SETTINGS.observability,
54 - otlpTracesUrl: "http://old/v1/traces",
55 - };
56 - await act(() => {
57 - renderer = create(<TelemetryExportSettings />);
58 - });
59 -
60 - await type("otlpTracesUrl", "http://draft/v1/traces");
61 - await type("otlpTracesUrl", "http://old/v1/traces");
62 - state.observability = { ...state.observability, otlpTracesUrl: "http://other/v1/traces" };
63 - await act(() => renderer!.update(<TelemetryExportSettings />));
64 - await type("otlpMetricsUrl", "http://new/v1/metrics");
65 - await act(() => renderer!.root.findByType("form").props.onSubmit({ preventDefault() {} }));
66 -
67 - expect(updateSettings).toHaveBeenCalledWith({
68 - environmentId: "env",
69 - input: { patch: { observability: { otlpMetricsUrl: "http://new/v1/metrics" } } },
70 - });
71 - });
72 -});
apps/web/src/components/settings/colorPickers.browser.test.tsx new
+262
@@ -0,0 +1,262 @@
1 +import { act } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +import { userEvent } from "vite-plus/test/browser";
5 +
6 +import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
7 +import { ThemeColorField } from "./ThemeColorPicker";
8 +
9 +const HUE = "Accent color hue";
10 +const SATURATION = "Accent color saturation";
11 +const BRIGHTNESS = "Accent color brightness";
12 +const PLANE = "Accent color saturation and brightness";
13 +
14 +let root: Root;
15 +let container: HTMLDivElement;
16 +
17 +beforeEach(() => {
18 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
19 + // Synthetic pointer ids are not active pointers, so the browser would reject capture.
20 + vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {});
21 + container = document.createElement("div");
22 + document.body.append(container);
23 + root = createRoot(container);
24 +});
25 +
26 +afterEach(async () => {
27 + await act(async () => root.unmount());
28 + container.remove();
29 + vi.useRealTimers();
30 + vi.restoreAllMocks();
31 + vi.unstubAllGlobals();
32 +});
33 +
34 +function byLabel<T extends HTMLElement = HTMLElement>(label: string) {
35 + const element = document.querySelector<T>(`[aria-label="${label}"]`);
36 + if (!element) throw new Error(`No element labelled ${label}`);
37 + return element;
38 +}
39 +
40 +const slider = (label: string) => byLabel<HTMLInputElement>(label);
41 +const sliderValue = (label: string) => Number(slider(label).value);
42 +
43 +async function open(triggerLabel: string) {
44 + await userEvent.click(byLabel(triggerLabel));
45 + await vi.waitFor(() => byLabel(HUE));
46 +}
47 +
48 +async function press(label: string, key: string, shift = false) {
49 + const target = slider(label);
50 + await act(async () => target.focus());
51 + await userEvent.keyboard(shift ? `{Shift>}{${key}}{/Shift}` : `{${key}}`);
52 +}
53 +
54 +function setRange(label: string, value: number) {
55 + const input = slider(label);
56 + const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
57 + setValue.call(input, String(value));
58 + input.dispatchEvent(new Event("input", { bubbles: true }));
59 +}
60 +
61 +function pointer(label: string, type: string, xFraction: number, yFraction = 0.5, pointerId = 1) {
62 + const target = byLabel(label);
63 + const bounds = target.getBoundingClientRect();
64 + target.dispatchEvent(
65 + new PointerEvent(type, {
66 + bubbles: true,
67 + button: 0,
68 + pointerId,
69 + clientX: bounds.left + bounds.width * xFraction,
70 + clientY: bounds.top + bounds.height * yFraction,
71 + }),
72 + );
73 +}
74 +
75 +const nextFrame = () =>
76 + act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
77 +
78 +async function renderAccent(value: string | undefined, commitDelayMs?: number) {
79 + const onCommit = vi.fn();
80 + await act(async () =>
81 + root.render(
82 + <ProviderAccentColorPicker
83 + displayName="Codex"
84 + value={value}
85 + onCommit={onCommit}
86 + {...(commitDelayMs === undefined ? {} : { commitDelayMs })}
87 + />,
88 + ),
89 + );
90 + await open(`${value ? "Change" : "Add"} accent color for Codex`);
91 + return onCommit;
92 +}
93 +
94 +async function renderThemeField(value: string) {
95 + const onChange = vi.fn();
96 + const render = (current: string) =>
97 + root.render(<ThemeColorField role="accent" value={current} onChange={onChange} />);
98 + await act(async () => render(value));
99 + await open("Choose Accent color color");
100 + return { onChange, echo: (next: string) => act(async () => render(next)) };
101 +}
102 +
103 +describe("provider accent color picker", () => {
104 + it("adjusts each color axis independently from the keyboard", async () => {
105 + const onCommit = await renderAccent("#ff0000");
106 +
107 + await press(HUE, "ArrowLeft");
108 + expect(slider(HUE).getAttribute("aria-valuenow")).toBe("359");
109 + await press(HUE, "ArrowRight");
110 + expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
111 +
112 + await press(SATURATION, "ArrowRight", true);
113 + await press(BRIGHTNESS, "ArrowUp", true);
114 + expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
115 + await press(BRIGHTNESS, "ArrowDown", true);
116 + expect(onCommit).toHaveBeenLastCalledWith("#e60000");
117 + expect(sliderValue(BRIGHTNESS)).toBe(90);
118 + expect(slider(BRIGHTNESS).getAttribute("aria-valuetext")).toBe("90%");
119 + expect(sliderValue(SATURATION)).toBe(100);
120 +
121 + await press(SATURATION, "ArrowDown", true);
122 + expect(onCommit).toHaveBeenLastCalledWith("#e61717");
123 + expect(sliderValue(SATURATION)).toBe(90);
124 + await press(SATURATION, "ArrowUp", true);
125 + expect(onCommit).toHaveBeenLastCalledWith("#e60000");
126 + await press(BRIGHTNESS, "ArrowLeft", true);
127 + expect(onCommit).toHaveBeenLastCalledWith("#cc0000");
128 + await press(BRIGHTNESS, "ArrowRight", true);
129 + expect(onCommit).toHaveBeenLastCalledWith("#e60000");
130 +
131 + onCommit.mockClear();
132 + await press(SATURATION, "Tab");
133 + expect(onCommit).not.toHaveBeenCalled();
134 + });
135 +
136 + it("supports Home/End and clamps each axis without changing the other", async () => {
137 + const onCommit = await renderAccent("#ff0000");
138 +
139 + await press(SATURATION, "Home");
140 + await press(SATURATION, "ArrowLeft");
141 + expect(sliderValue(SATURATION)).toBe(0);
142 + expect(onCommit).toHaveBeenLastCalledWith("#ffffff");
143 + await press(BRIGHTNESS, "Home");
144 + await press(BRIGHTNESS, "ArrowDown");
145 + expect(sliderValue(BRIGHTNESS)).toBe(0);
146 + expect(onCommit).toHaveBeenLastCalledWith("#000000");
147 + await press(SATURATION, "End");
148 + expect(sliderValue(SATURATION)).toBe(100);
149 + expect(sliderValue(BRIGHTNESS)).toBe(0);
150 + await press(BRIGHTNESS, "End");
151 + await press(BRIGHTNESS, "ArrowUp");
152 + expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
153 + await press(SATURATION, "ArrowLeft");
154 + expect(sliderValue(SATURATION)).toBe(98);
155 + expect(onCommit).toHaveBeenLastCalledWith("#ff0505");
156 + });
157 +
158 + it("adds an accent only after choosing one and clears it back to no accent", async () => {
159 + const onCommit = await renderAccent(undefined);
160 + const clearButton = () =>
161 + [...document.querySelectorAll("button")].find((button) =>
162 + button.textContent?.includes("Clear color"),
163 + );
164 + expect(onCommit).not.toHaveBeenCalled();
165 + expect(clearButton()).toBeUndefined();
166 +
167 + await press(HUE, "ArrowRight", true);
168 + expect(onCommit).toHaveBeenCalledOnce();
169 + await vi.waitFor(() => expect(clearButton()).toBeDefined());
170 +
171 + await userEvent.click(clearButton()!);
172 + expect(onCommit).toHaveBeenLastCalledWith("");
173 + expect(clearButton()).toBeUndefined();
174 + });
175 +
176 + it("debounces commits and commits the pending color on unmount", async () => {
177 + const onCommit = await renderAccent("#ff0000", 250);
178 + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
179 +
180 + await press(HUE, "ArrowRight", true);
181 + await press(HUE, "ArrowRight", true);
182 + expect(onCommit).not.toHaveBeenCalled();
183 + await act(async () => vi.advanceTimersByTime(250));
184 + expect(onCommit).toHaveBeenCalledExactlyOnceWith("#ff5500");
185 +
186 + await press(HUE, "ArrowRight", true);
187 + await act(async () => root.unmount());
188 + expect(onCommit).toHaveBeenLastCalledWith("#ff8000");
189 + await act(async () => vi.advanceTimersByTime(250));
190 + expect(onCommit).toHaveBeenCalledTimes(2);
191 + root = createRoot(container);
192 + });
193 +});
194 +
195 +describe("theme color field", () => {
196 + it("batches native range changes into one commit per frame and keeps alpha", async () => {
197 + const { onChange } = await renderThemeField("#ff000080");
198 +
199 + // Both changes land in one task, so no animation frame can run between them.
200 + await act(async () => {
201 + setRange(SATURATION, 50);
202 + setRange(BRIGHTNESS, 50);
203 + expect(onChange).not.toHaveBeenCalled();
204 + });
205 + await nextFrame();
206 + expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#80404080");
207 +
208 + await press(BRIGHTNESS, "ArrowDown", true);
209 + await nextFrame();
210 + expect(onChange).toHaveBeenLastCalledWith("accent", "#66333380");
211 + expect(sliderValue(SATURATION)).toBe(50);
212 + });
213 +
214 + it("flushes the final drag color on release of the dragging pointer only", async () => {
215 + const { onChange } = await renderThemeField("#ff000080");
216 +
217 + // The drag runs in one task, so no animation frame can commit mid-drag.
218 + await act(async () => {
219 + pointer(HUE, "pointerdown", 0.25);
220 + pointer(HUE, "pointermove", 0.5);
221 + pointer(HUE, "pointermove", 0.75, 0.5, 2);
222 + pointer(HUE, "pointerup", 0.75, 0.5, 2);
223 + expect(onChange).not.toHaveBeenCalled();
224 + pointer(HUE, "pointerup", 0.5);
225 + });
226 + expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#00ffff80");
227 + await act(async () => pointer(HUE, "lostpointercapture", 0.5));
228 + await nextFrame();
229 + expect(onChange).toHaveBeenCalledOnce();
230 + });
231 +
232 + it("clamps out-of-bounds drags and flushes on cancellation and unmount", async () => {
233 + const { onChange } = await renderThemeField("#ff000080");
234 +
235 + await act(async () => {
236 + pointer(PLANE, "pointerdown", -0.5, -0.5);
237 + pointer(PLANE, "pointercancel", -0.5, -0.5);
238 + });
239 + expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff80");
240 +
241 + await act(async () => {
242 + pointer(PLANE, "pointerdown", 1.5, 1.5);
243 + root.unmount();
244 + });
245 + expect(onChange).toHaveBeenLastCalledWith("accent", "#00000080");
246 + root = createRoot(container);
247 + });
248 +
249 + it("keeps the selected hue when a grey color is echoed back from theme settings", async () => {
250 + const { onChange, echo } = await renderThemeField("#ff0000");
251 +
252 + await press(HUE, "ArrowRight", true);
253 + await act(async () => {
254 + pointer(PLANE, "pointerdown", 0, 0);
255 + pointer(PLANE, "pointerup", 0, 0);
256 + });
257 + expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff");
258 +
259 + await echo("#ffffff");
260 + expect(slider(HUE).getAttribute("aria-valuenow")).toBe("10");
261 + });
262 +});
apps/web/src/components/settings/colorPickers.test.tsx deleted
-275
@@ -1,275 +0,0 @@
1 -import { act, type ReactNode, type ReactElement } from "react";
2 -import { create, type ReactTestRenderer } from "react-test-renderer";
3 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 -
5 -vi.mock("../ui/popover", () => ({
6 - Popover: ({ children }: { children: ReactNode }) => children,
7 - PopoverPopup: ({ children }: { children: ReactNode }) => children,
8 - PopoverTrigger: () => null,
9 - PopoverClose: ({ render }: { render: ReactElement }) => render,
10 -}));
11 -vi.mock("../ui/tooltip", () => ({
12 - Tooltip: ({ children }: { children: ReactNode }) => children,
13 - TooltipTrigger: ({ render }: { render: ReactElement }) => render,
14 - TooltipPopup: () => null,
15 -}));
16 -
17 -import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
18 -import { ThemeColorField } from "./ThemeColorPicker";
19 -
20 -let renderer: ReactTestRenderer | undefined;
21 -let nextFrameId = 0;
22 -const frames = new Map<number, FrameRequestCallback>();
23 -
24 -beforeEach(() => {
25 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
26 - vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
27 - frames.set(++nextFrameId, callback);
28 - return nextFrameId;
29 - });
30 - vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
31 -});
32 -
33 -afterEach(async () => {
34 - await act(async () => renderer?.unmount());
35 - renderer = undefined;
36 - frames.clear();
37 - vi.useRealTimers();
38 - vi.unstubAllGlobals();
39 -});
40 -
41 -function slider(label: string) {
42 - return renderer!.root.find(
43 - (node) =>
44 - (node.props.role === "slider" || node.props.type === "range") &&
45 - node.props["aria-label"] === label,
46 - );
47 -}
48 -
49 -function plane(label: string) {
50 - return renderer!.root.findByProps({ role: "group", "aria-label": label });
51 -}
52 -
53 -async function key(label: string, key: string, shiftKey = false) {
54 - const preventDefault = vi.fn();
55 - await act(async () => slider(label).props.onKeyDown({ key, shiftKey, preventDefault }));
56 - return preventDefault;
57 -}
58 -
59 -function pointer(clientX: number, clientY = 0, pointerId = 1) {
60 - return {
61 - button: 0,
62 - clientX,
63 - clientY,
64 - pointerId,
65 - currentTarget: {
66 - focus: vi.fn(),
67 - setPointerCapture: vi.fn(),
68 - getBoundingClientRect: () => ({ left: 0, top: 0, width: 100, height: 100 }),
69 - },
70 - };
71 -}
72 -
73 -async function frame() {
74 - await act(async () => {
75 - const pending = [...frames.values()];
76 - frames.clear();
77 - for (const callback of pending) callback(0);
78 - });
79 -}
80 -
81 -describe("shared color controls in settings", () => {
82 - it("adjusts each provider color axis independently and reports the value being changed", async () => {
83 - const onCommit = vi.fn();
84 - await act(async () => {
85 - renderer = create(
86 - <ProviderAccentColorPicker displayName="Codex" value="#ff0000" onCommit={onCommit} />,
87 - );
88 - });
89 - const hue = "Accent color hue";
90 - const saturation = "Accent color saturation";
91 - const brightness = "Accent color brightness";
92 - expect(await key(hue, "ArrowLeft")).toHaveBeenCalledOnce();
93 - expect(slider(hue).props["aria-valuenow"]).toBe(359);
94 - await key(hue, "ArrowRight");
95 - expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
96 - await key(saturation, "ArrowRight", true);
97 - await key(brightness, "ArrowUp", true);
98 - expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
99 - await key(brightness, "ArrowDown", true);
100 - expect(onCommit).toHaveBeenLastCalledWith("#e60000");
101 - expect(slider(brightness).props.value).toBe(90);
102 - expect(slider(brightness).props["aria-valuetext"]).toBe("90%");
103 - expect(slider(saturation).props.value).toBe(100);
104 - await key(saturation, "ArrowDown", true);
105 - expect(onCommit).toHaveBeenLastCalledWith("#e61717");
106 - expect(slider(saturation).props.value).toBe(90);
107 - expect(slider(saturation).props["aria-valuetext"]).toBe("90%");
108 - await key(saturation, "ArrowUp", true);
109 - expect(onCommit).toHaveBeenLastCalledWith("#e60000");
110 - await key(brightness, "ArrowLeft", true);
111 - expect(onCommit).toHaveBeenLastCalledWith("#cc0000");
112 - await key(brightness, "ArrowRight", true);
113 - expect(onCommit).toHaveBeenLastCalledWith("#e60000");
114 - onCommit.mockClear();
115 - expect(await key(saturation, "Tab")).not.toHaveBeenCalled();
116 - expect(await key(brightness, "Tab")).not.toHaveBeenCalled();
117 - expect(onCommit).not.toHaveBeenCalled();
118 - });
119 -
120 - it("supports Home/End and clamps each axis without changing the other", async () => {
121 - const onCommit = vi.fn();
122 - await act(async () => {
123 - renderer = create(
124 - <ProviderAccentColorPicker displayName="Codex" value="#ff0000" onCommit={onCommit} />,
125 - );
126 - });
127 - const saturation = "Accent color saturation";
128 - const brightness = "Accent color brightness";
129 - await key(saturation, "Home");
130 - await key(saturation, "ArrowLeft");
131 - expect(slider(saturation).props.value).toBe(0);
132 - expect(onCommit).toHaveBeenLastCalledWith("#ffffff");
133 - await key(brightness, "Home");
134 - await key(brightness, "ArrowDown");
135 - expect(slider(brightness).props.value).toBe(0);
136 - expect(onCommit).toHaveBeenLastCalledWith("#000000");
137 - await key(saturation, "End");
138 - expect(slider(saturation).props.value).toBe(100);
139 - expect(slider(brightness).props.value).toBe(0);
140 - await key(brightness, "End");
141 - await key(brightness, "ArrowUp");
142 - expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
143 - await key(saturation, "ArrowLeft");
144 - expect(slider(saturation).props.value).toBe(98);
145 - expect(onCommit).toHaveBeenLastCalledWith("#ff0505");
146 - });
147 -
148 - it("persists independent native range changes through theme batching with alpha", async () => {
149 - const onChange = vi.fn();
150 - await act(async () => {
151 - renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);
152 - });
153 - const saturation = "Accent color saturation";
154 - const brightness = "Accent color brightness";
155 - await act(async () =>
156 - slider(saturation).props.onChange({ currentTarget: { valueAsNumber: 50 } }),
157 - );
158 - await act(async () =>
159 - slider(brightness).props.onChange({ currentTarget: { valueAsNumber: 50 } }),
160 - );
161 - expect(onChange).not.toHaveBeenCalled();
162 - expect(frames.size).toBe(1);
163 - await frame();
164 - expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#80404080");
165 - await key(brightness, "ArrowDown", true);
166 - await frame();
167 - expect(onChange).toHaveBeenLastCalledWith("accent", "#66333380");
168 - expect(slider(saturation).props.value).toBe(50);
169 - });
170 -
171 - it("batches theme drag updates and flushes the final color with alpha on pointer release", async () => {
172 - const onChange = vi.fn();
173 - await act(async () => {
174 - renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);
175 - });
176 - const hue = "Accent color hue";
177 - await act(async () => slider(hue).props.onPointerDown(pointer(25)));
178 - await act(async () => slider(hue).props.onPointerMove(pointer(50)));
179 - expect(onChange).not.toHaveBeenCalled();
180 - expect(frames.size).toBe(1);
181 - await act(async () => slider(hue).props.onPointerMove(pointer(75, 0, 2)));
182 - await act(async () => slider(hue).props.onPointerUp(pointer(75, 0, 2)));
183 - expect(onChange).not.toHaveBeenCalled();
184 - await act(async () => slider(hue).props.onPointerUp(pointer(50)));
185 - expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#00ffff80");
186 - await act(async () => slider(hue).props.onLostPointerCapture(pointer(50)));
187 - await frame();
188 - expect(onChange).toHaveBeenCalledTimes(1);
189 - });
190 -
191 - it("clamps out-of-bounds drags and flushes theme changes on cancellation and unmount", async () => {
192 - const onChange = vi.fn();
193 - await act(async () => {
194 - renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);
195 - });
196 - const planeLabel = "Accent color saturation and brightness";
197 - await act(async () => plane(planeLabel).props.onPointerDown(pointer(-50, -50)));
198 - await act(async () => plane(planeLabel).props.onPointerCancel(pointer(-50, -50)));
199 - expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff80");
200 - await act(async () => plane(planeLabel).props.onPointerDown(pointer(150, 150)));
201 - await act(async () => renderer!.unmount());
202 - renderer = undefined;
203 - expect(onChange).toHaveBeenLastCalledWith("accent", "#00000080");
204 - expect(frames.size).toBe(0);
205 - });
206 -
207 - it("preserves the selected hue when a grey color is echoed back from theme settings", async () => {
208 - const onChange = vi.fn();
209 - const render = (value: string) => (
210 - <ThemeColorField role="accent" value={value} onChange={onChange} />
211 - );
212 - await act(async () => {
213 - renderer = create(render("#ff0000"));
214 - });
215 - const hue = "Accent color hue";
216 - const planeLabel = "Accent color saturation and brightness";
217 - await key(hue, "ArrowRight", true);
218 - await act(async () => plane(planeLabel).props.onPointerDown(pointer(0, 0)));
219 - await frame();
220 - expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff");
221 - await act(async () => renderer!.update(render("#ffffff")));
222 - expect(slider(hue).props["aria-valuenow"]).toBe(10);
223 - });
224 -
225 - it("adds an accent only after choosing one and clears it back to no accent", async () => {
226 - const onCommit = vi.fn();
227 - await act(async () => {
228 - renderer = create(
229 - <ProviderAccentColorPicker displayName="Codex" value={undefined} onCommit={onCommit} />,
230 - );
231 - });
232 - const clearButtons = () =>
233 - renderer!.root.findAll(
234 - (node) =>
235 - node.type === "button" &&
236 - Array.isArray(node.props.children) &&
237 - node.props.children.includes("Clear color"),
238 - );
239 - expect(onCommit).not.toHaveBeenCalled();
240 - expect(clearButtons()).toHaveLength(0);
241 - await key("Accent color hue", "ArrowRight", true);
242 - expect(onCommit).toHaveBeenCalledOnce();
243 - expect(clearButtons()).toHaveLength(1);
244 - await act(async () => clearButtons()[0]!.props.onClick());
245 - expect(onCommit).toHaveBeenLastCalledWith("");
246 - expect(clearButtons()).toHaveLength(0);
247 - });
248 -
249 - it("keeps provider debounce at the consumer and commits pending color on unmount", async () => {
250 - vi.useFakeTimers();
251 - const onCommit = vi.fn();
252 - await act(async () => {
253 - renderer = create(
254 - <ProviderAccentColorPicker
255 - displayName="Codex"
256 - value="#ff0000"
257 - onCommit={onCommit}
258 - commitDelayMs={250}
259 - />,
260 - );
261 - });
262 - const hue = "Accent color hue";
263 - await key(hue, "ArrowRight", true);
264 - await key(hue, "ArrowRight", true);
265 - expect(onCommit).not.toHaveBeenCalled();
266 - await act(async () => vi.advanceTimersByTime(250));
267 - expect(onCommit).toHaveBeenCalledExactlyOnceWith("#ff5500");
268 - await key(hue, "ArrowRight", true);
269 - await act(async () => renderer!.unmount());
270 - renderer = undefined;
271 - expect(onCommit).toHaveBeenLastCalledWith("#ff8000");
272 - await act(async () => vi.advanceTimersByTime(250));
273 - expect(onCommit).toHaveBeenCalledTimes(2);
274 - });
275 -});
apps/web/src/components/settings/settingsLayout.browser.test.tsx new
+68
@@ -0,0 +1,68 @@
1 +import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { scrollToSettingsTarget } from "./settingsLayout";
4 +
5 +const PULSE = "settings-search-target-pulse";
6 +
7 +afterEach(() => {
8 + document.body.replaceChildren();
9 + vi.restoreAllMocks();
10 +});
11 +
12 +function mount(html: string) {
13 + document.body.innerHTML = html;
14 + return vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
15 +}
16 +
17 +function reduceMotion(matches: boolean) {
18 + vi.spyOn(window, "matchMedia").mockReturnValue({ matches } as MediaQueryList);
19 +}
20 +
21 +describe("settings search targets", () => {
22 + it("scrolls a section's header into view, focuses the section, and pulses until blur", () => {
23 + reduceMotion(false);
24 + const scrollIntoView = mount(
25 + `<section id="providers" tabindex="-1"><h2>Providers</h2><p>Body</p></section>`,
26 + );
27 + const section = document.getElementById("providers")!;
28 +
29 + expect(scrollToSettingsTarget("providers")).toBe(true);
30 + expect(scrollIntoView).toHaveBeenCalledOnce();
31 + expect(scrollIntoView.mock.contexts[0]).toBe(section.querySelector("h2"));
32 + expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" });
33 + expect(document.activeElement).toBe(section);
34 + expect(section.classList.contains(PULSE)).toBe(true);
35 +
36 + section.blur();
37 + expect(section.classList.contains(PULSE)).toBe(false);
38 + });
39 +
40 + it("restarts the pulse when the same destination is chosen again", () => {
41 + reduceMotion(false);
42 + mount(`<div id="word-wrap" tabindex="-1" class="${PULSE}"></div>`);
43 + const target = document.getElementById("word-wrap")!;
44 + const observer = new MutationObserver(() => {});
45 + observer.observe(target, { attributeFilter: ["class"], attributeOldValue: true });
46 +
47 + scrollToSettingsTarget("word-wrap");
48 + const previousClasses = observer.takeRecords().map((record) => record.oldValue);
49 + expect(previousClasses).toEqual([PULSE, ""]);
50 + expect(target.classList.contains(PULSE)).toBe(true);
51 + });
52 +
53 + it("does not animate the destination when reduced motion is requested", () => {
54 + reduceMotion(true);
55 + const scrollIntoView = mount(`<div id="word-wrap" tabindex="-1"></div>`);
56 + const target = document.getElementById("word-wrap")!;
57 +
58 + expect(scrollToSettingsTarget("word-wrap")).toBe(true);
59 + expect(scrollIntoView.mock.contexts[0]).toBe(target);
60 + expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "auto", block: "center" });
61 + expect(document.activeElement).toBe(target);
62 + expect(target.classList.contains(PULSE)).toBe(false);
63 + });
64 +
65 + it("leaves not-yet-mounted destinations to their mount lifecycle", () => {
66 + expect(scrollToSettingsTarget("archive")).toBe(false);
67 + });
68 +});
apps/web/src/components/settings/settingsLayout.test.tsx deleted
-97
@@ -1,97 +0,0 @@
1 -import { renderToStaticMarkup } from "react-dom/server";
2 -import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import { scrollToSettingsTarget, SettingsRow, SettingsUnavailableGroup } from "./settingsLayout";
5 -
6 -afterEach(() => {
7 - vi.unstubAllGlobals();
8 -});
9 -
10 -describe("unavailable settings", () => {
11 - it("groups disabled controls under one reason", () => {
12 - const markup = renderToStaticMarkup(
13 - <SettingsUnavailableGroup message="Only available in the desktop app.">
14 - <SettingsRow title="Window capture" description="Capture a window." />
15 - </SettingsUnavailableGroup>,
16 - );
17 -
18 - expect(markup).toContain("Only available in the desktop app.");
19 - expect(markup).toContain("border-border/60");
20 - expect(markup).toContain("[&amp;_h3]:opacity-64");
21 - });
22 -});
23 -
24 -describe("settings search targets", () => {
25 - it("scrolls directly to a section header and restarts the destination pulse", () => {
26 - const sectionScrollIntoView = vi.fn();
27 - const headerScrollIntoView = vi.fn();
28 - const focus = vi.fn();
29 - const remove = vi.fn();
30 - const add = vi.fn();
31 - const addEventListener = vi.fn();
32 - const target = {
33 - tagName: "SECTION",
34 - firstElementChild: { scrollIntoView: headerScrollIntoView },
35 - scrollIntoView: sectionScrollIntoView,
36 - focus,
37 - classList: { remove, add },
38 - addEventListener,
39 - offsetWidth: 100,
40 - } as unknown as HTMLElement;
41 - vi.stubGlobal("document", {
42 - getElementById: vi.fn(() => target),
43 - });
44 - vi.stubGlobal("window", {
45 - matchMedia: vi.fn(() => ({ matches: false })),
46 - });
47 -
48 - expect(scrollToSettingsTarget("providers")).toBe(true);
49 - expect(headerScrollIntoView).toHaveBeenCalledWith({
50 - behavior: "smooth",
51 - block: "center",
52 - });
53 - expect(sectionScrollIntoView).not.toHaveBeenCalled();
54 - expect(focus).toHaveBeenCalledWith({ preventScroll: true });
55 - expect(remove).toHaveBeenCalledWith("settings-search-target-pulse");
56 - expect(add).toHaveBeenCalledWith("settings-search-target-pulse");
57 - expect(addEventListener).toHaveBeenCalledWith("blur", expect.any(Function), { once: true });
58 - });
59 -
60 - it("does not animate the destination when reduced motion is requested", () => {
61 - const scrollIntoView = vi.fn();
62 - const focus = vi.fn();
63 - const remove = vi.fn();
64 - const add = vi.fn();
65 - const target = {
66 - tagName: "DIV",
67 - firstElementChild: null,
68 - scrollIntoView,
69 - focus,
70 - classList: { remove, add },
71 - offsetWidth: 100,
72 - } as unknown as HTMLElement;
73 - vi.stubGlobal("document", {
74 - getElementById: vi.fn(() => target),
75 - });
76 - vi.stubGlobal("window", {
77 - matchMedia: vi.fn(() => ({ matches: true })),
78 - });
79 -
80 - expect(scrollToSettingsTarget("word-wrap")).toBe(true);
81 - expect(scrollIntoView).toHaveBeenCalledWith({
82 - behavior: "auto",
83 - block: "center",
84 - });
85 - expect(focus).toHaveBeenCalledWith({ preventScroll: true });
86 - expect(remove).toHaveBeenCalledWith("settings-search-target-pulse");
87 - expect(add).not.toHaveBeenCalled();
88 - });
89 -
90 - it("leaves not-yet-mounted destinations to their mount lifecycle", () => {
91 - vi.stubGlobal("document", {
92 - getElementById: vi.fn(() => null),
93 - });
94 -
95 - expect(scrollToSettingsTarget("archive")).toBe(false);
96 - });
97 -});
apps/web/src/components/settings/useProjectScriptSettings.browser.test.tsx renamed
+39 -24
@@ -6,7 +6,8 @@ import {
6 type ResolvedKeybindingsConfig,
7 } from "@t3tools/contracts";
8 import { AsyncResult } from "effect/reactivity";
9 -import { act, create, type ReactTestRenderer } from "react-test-renderer";
9 +import { act } from "react";
10 +import { createRoot, type Root } from "react-dom/client";
11 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12
13 import type { NewProjectScriptInput } from "../projectScriptEditor";
@@ -17,20 +18,30 @@ const commands = vi.hoisted(() => ({
18 removeKeybinding: vi.fn(),
19 }));
20
20 -vi.mock("../../env", () => ({ isElectron: false }));
21 -vi.mock("../../state/session", () => ({ readEnvironmentScope: () => true }));
22 -vi.mock("../../state/entities", () => ({ useProjects: () => [] }));
23 -vi.mock("../../state/server", () => ({
24 - serverEnvironment: {
25 - updateSettings: "updateSettings",
26 - upsertKeybinding: "upsertKeybinding",
27 - removeKeybinding: "removeKeybinding",
28 - },
21 +vi.mock(import("../../state/session"), async (original) => ({
22 + ...(await original()),
23 + readEnvironmentScope: () => true,
24 +}));
25 +vi.mock(import("../../state/entities"), async (original) => ({
26 + ...(await original()),
27 + useProjects: () => [],
28 }));
30 -vi.mock("../../state/use-atom-command", () => ({
31 - useAtomCommand: (command: keyof typeof commands) => commands[command],
29 +vi.mock(import("../../state/server"), async (original) => {
30 + const actual = await original();
31 + return {
32 + ...actual,
33 + serverEnvironment: {
34 + ...actual.serverEnvironment,
35 + updateSettings: "updateSettings",
36 + upsertKeybinding: "upsertKeybinding",
37 + removeKeybinding: "removeKeybinding",
38 + } as unknown as typeof actual.serverEnvironment,
39 + };
40 +});
41 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
42 + ...(await original()),
43 + useAtomCommand: ((command: keyof typeof commands) => commands[command]) as never,
44 }));
33 -vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
45
46 import { useProjectScriptSettings } from "./useProjectScriptSettings";
47
@@ -86,13 +97,14 @@ function Probe(props: {
97 return null;
98 }
99
89 -let renderer: ReactTestRenderer | undefined;
100 +let root: Root;
101 +let container: HTMLDivElement;
102
91 -function renderSettings(keybindings: ResolvedKeybindingsConfig) {
103 +async function renderSettings(keybindings: ResolvedKeybindingsConfig) {
104 let settings: ProjectScriptSettings | undefined;
93 - act(() => {
94 - renderer = create(<Probe keybindings={keybindings} onResult={(next) => (settings = next)} />);
95 - });
105 + await act(async () =>
106 + root.render(<Probe keybindings={keybindings} onResult={(next) => (settings = next)} />),
107 + );
108 return settings!;
109 }
110
@@ -110,17 +122,20 @@ beforeEach(() => {
122 for (const command of Object.values(commands)) {
123 command.mockResolvedValue(AsyncResult.success(undefined));
124 }
125 + container = document.createElement("div");
126 + document.body.append(container);
127 + root = createRoot(container);
128 });
129
115 -afterEach(() => {
116 - act(() => renderer?.unmount());
117 - renderer = undefined;
130 +afterEach(async () => {
131 + await act(async () => root.unmount());
132 + container.remove();
133 vi.unstubAllGlobals();
134 });
135
121 -describe("useProjectScriptSettings in a browser client", () => {
136 +describe("useProjectScriptSettings", () => {
137 it("saves a recorded action shortcut", async () => {
123 - const { submit } = renderSettings([]);
138 + const { submit } = await renderSettings([]);
139
140 const result = await submitInAct(submit, "mod+shift+k");
141
@@ -132,7 +147,7 @@ describe("useProjectScriptSettings in a browser client", () => {
147 });
148
149 it("removes a cleared action shortcut", async () => {
135 - const { submit } = renderSettings(lintBinding);
150 + const { submit } = await renderSettings(lintBinding);
151
152 const result = await submitInAct(submit, null);
153