TypeScript
test(web): settings tests run in a real browser (#20872)
Julius Marminge476a010fdc0b
diff --git a/apps/web/src/components/device/DeviceSetup.test.ts b/apps/web/src/components/device/DeviceSetup.test.tsnew file mode 100644index 00000000000..3a17528e7ce--- /dev/null+++ b/apps/web/src/components/device/DeviceSetup.test.ts@@ -0,0 +1,95 @@+import type { DeviceServiceState } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { deviceHubReadiness, platformSetupStatus } from "./DeviceSetup";++const deviceState = (overrides: Partial<DeviceServiceState> = {}): DeviceServiceState => ({+ hosts: [+ {+ id: "local",+ kind: "local",+ label: "This machine",+ hubInstalled: false,+ agentDeviceInstalled: false,+ platforms: [+ { platform: "ios", available: true },+ { platform: "android", available: true },+ ],+ },+ ],+ hostStatus: "ready",+ hostStatuses: {},+ devices: [],+ sessions: [],+ onboardingCompleted: false,+ agentAccessEnabled: false,+ hubBasePath: "/api/device-hub",+ revision: 0,+ ...overrides,+});++describe("device setup guidance", () => {+ it("directs users to install an iOS runtime and create an Android virtual device", () => {+ expect(platformSetupStatus(deviceState(), "ios").message).toContain("Xcode Settings");+ expect(platformSetupStatus(deviceState(), "android").message).toContain("Device Manager");+ });++ it("preserves a specific missing-tool explanation from the server", () => {+ const state = deviceState({+ hosts: [+ {+ ...deviceState().hosts[0]!,+ platforms: [+ { platform: "ios", available: true },+ { platform: "android", available: false, reason: "Android Emulator is missing." },+ ],+ },+ ],+ });+ expect(platformSetupStatus(state, "android").message).toBe("Android Emulator is missing.");+ });++ it("counts a remote device host when this machine has no simulator tooling", () => {+ const state = deviceState({+ hostStatus: "idle",+ hostStatuses: { macmini: { status: "ready" } },+ hosts: [+ {+ ...deviceState().hosts[0]!,+ platforms: [+ { platform: "ios", available: false, reason: "Xcode was not found." },+ { platform: "android", available: false, reason: "Android SDK was not found." },+ ],+ },+ {+ id: "macmini",+ kind: "ssh",+ label: "Mac Mini",+ hubInstalled: true,+ agentDeviceInstalled: true,+ platforms: [+ { platform: "ios", available: true },+ { platform: "android", available: false, reason: "Android SDK was not found." },+ ],+ },+ ],+ devices: [+ {+ hostId: "macmini",+ id: "iphone",+ platform: "ios",+ name: "iPhone 16 Pro",+ version: "iOS 27.0",+ booted: true,+ physical: false,+ },+ ],+ });+ expect(deviceHubReadiness(state).ready).toBe(true);+ expect(platformSetupStatus(state, "ios")).toEqual({+ ready: true,+ message: "Xcode and iOS Simulator are available on Mac Mini.",+ });+ expect(platformSetupStatus(state, "android").ready).toBe(false);+ });+});diff --git a/apps/web/src/components/settings/IntegrationsSettings.browser.test.tsx b/apps/web/src/components/settings/IntegrationsSettings.browser.test.tsxnew file mode 100644index 00000000000..eda958c161f--- /dev/null+++ b/apps/web/src/components/settings/IntegrationsSettings.browser.test.tsx@@ -0,0 +1,102 @@+import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { act, StrictMode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const { listBrowserImportSources } = vi.hoisted(() => ({+ listBrowserImportSources: vi.fn().mockResolvedValue([]),+}));++vi.mock(import("../preview/previewBridge"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ previewBridge: { ...actual.previewBridge, listBrowserImportSources } as never,+ };+});+vi.mock(import("../../env"), async (original) => ({ ...(await original()), isElectron: true }));+vi.mock(import("../../state/environments"), async (original) => ({+ ...(await original()),+ useEnvironments: (() => ({ environments: [], isReady: true })) as never,+ usePrimaryEnvironment: () => null,+ usePrimaryEnvironmentId: () => null,+}));+vi.mock(import("../../hooks/useSettings"), async (original) => ({+ ...(await original()),+ useClientSettings: ((selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>+ selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS) as never,+ useClientSettingsHydrated: () => true,+ usePrimarySettingsAvailable: () => true,+ usePrimarySettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,+ useUpdatePrimarySettings: (() => vi.fn()) as never,+}));+vi.mock(import("./ProjectDefaultsSettings"), async (original) => ({+ ...(await original()),+ ProjectDefaultsSettings: (() => null) as never,+}));+vi.mock(import("./SettingsScopeContext"), async (original) => ({+ ...(await original()),+ useSettingsScope: (() => ({+ scope: { kind: "all", environmentIds: [] },+ search: {},+ environment: null,+ environments: [],+ target: null,+ connectedEnvironments: [],+ targets: [],+ })) as never,+ useOptionalSettingsScope: () => null,+}));++import { IntegrationsSettingsPanel } from "./IntegrationsSettings";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ listBrowserImportSources.mockClear();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++async function openSettings() {+ const router = createRouter({+ routeTree: createRootRoute({ component: IntegrationsSettingsPanel }),+ history: createMemoryHistory(),+ });+ await router.load();+ await act(async () =>+ root.render(+ <StrictMode>+ <RouterProvider router={router} />+ </StrictMode>,+ ),+ );+ await vi.waitFor(() => expect(container.querySelector("section#browser")).not.toBeNull());+}++describe("Integrations browser discovery", () => {+ it("does not scan browser files when entering or revisiting settings", async () => {+ await openSettings();+ expect(listBrowserImportSources).not.toHaveBeenCalled();++ await act(async () => root.unmount());+ root = createRoot(container);+ await openSettings();+ expect(listBrowserImportSources).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/components/settings/IntegrationsSettings.test.tsx b/apps/web/src/components/settings/IntegrationsSettings.test.tsxdeleted file mode 100644index 198c2cf3f3c..00000000000--- a/apps/web/src/components/settings/IntegrationsSettings.test.tsx+++ /dev/null@@ -1,207 +0,0 @@-import {- DEFAULT_CLIENT_SETTINGS,- DEFAULT_UNIFIED_SETTINGS,- type DeviceServiceState,-} from "@t3tools/contracts";-import {- createMemoryHistory,- createRootRoute,- createRouter,- RouterProvider,-} from "@tanstack/react-router";-import { act, StrictMode, type ReactNode } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";--const { listBrowserImportSources } = vi.hoisted(() => ({- listBrowserImportSources: vi.fn().mockResolvedValue([]),-}));--vi.mock("../ui/tooltip", () => ({- Tooltip: ({ children }: { children: ReactNode }) => children,- TooltipTrigger: ({ render, children }: { render: ReactNode; children: ReactNode }) => (- <>- {render}- {children}- </>- ),- TooltipPopup: () => null,-}));-vi.mock("../preview/previewBridge", () => ({- previewBridge: { listBrowserImportSources },-}));-vi.mock("../../env", () => ({ isElectron: true }));-vi.mock("../../state/environments", () => ({- useEnvironments: () => ({ environments: [], isReady: true }),- usePrimaryEnvironment: () => null,- usePrimaryEnvironmentId: () => null,-}));-vi.mock("../../hooks/useSettings", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../hooks/useSettings")>()),- PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE: "Connect to an environment",- useClientSettings: (selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>- selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS,- useClientSettingsHydrated: () => true,- usePrimarySettingsAvailable: () => true,- usePrimarySettings: () => DEFAULT_UNIFIED_SETTINGS,- useUpdatePrimarySettings: () => vi.fn(),-}));-vi.mock("./settingsLayout", async (importOriginal) => ({- ...(await importOriginal<typeof import("./settingsLayout")>()),- SettingsPageContainer: ({ children }: { children: ReactNode }) => children,-}));-vi.mock("./ProjectDefaultsSettings", () => ({ ProjectDefaultsSettings: () => null }));-vi.mock("./SettingsScopeContext", () => ({- useSettingsScope: () => ({- scope: { kind: "all", environmentIds: [] },- search: {},- environment: null,- environments: [],- target: null,- connectedEnvironments: [],- targets: [],- }),- useOptionalSettingsScope: () => null,-}));--import { IntegrationsSettingsPanel } from "./IntegrationsSettings";-import { deviceHubReadiness, platformSetupStatus } from "../device/DeviceSetup";--let renderer: ReactTestRenderer | undefined;--beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- listBrowserImportSources.mockClear();-});--afterEach(async () => {- await act(() => renderer?.unmount());- vi.unstubAllGlobals();-});--async function openSettings() {- const router = createRouter({- routeTree: createRootRoute({ component: IntegrationsSettingsPanel }),- history: createMemoryHistory(),- });- await router.load();- await act(() => {- renderer = create(- <StrictMode>- <RouterProvider router={router} />- </StrictMode>,- );- });- expect(renderer!.root.findByType(IntegrationsSettingsPanel)).toBeDefined();-}--describe("Integrations browser discovery", () => {- it("does not scan browser files when entering or revisiting settings", async () => {- await openSettings();- expect(listBrowserImportSources).not.toHaveBeenCalled();-- await act(() => renderer?.unmount());- await openSettings();- expect(listBrowserImportSources).not.toHaveBeenCalled();- });-- it("places device settings directly after browser settings", async () => {- await openSettings();- const sections = renderer!.root- .findAll((node) => node.type === "section")- .map((node) => node.props.id)- .filter(Boolean);- expect(sections.indexOf("devices")).toBeGreaterThan(sections.indexOf("browser"));- });-});--const deviceState = (overrides: Partial<DeviceServiceState> = {}): DeviceServiceState => ({- hosts: [- {- id: "local",- kind: "local",- label: "This machine",- hubInstalled: false,- agentDeviceInstalled: false,- platforms: [- { platform: "ios", available: true },- { platform: "android", available: true },- ],- },- ],- hostStatus: "ready",- hostStatuses: {},- devices: [],- sessions: [],- onboardingCompleted: false,- agentAccessEnabled: false,- hubBasePath: "/api/device-hub",- revision: 0,- ...overrides,-});--describe("device setup guidance", () => {- it("directs users to install an iOS runtime and create an Android virtual device", () => {- expect(platformSetupStatus(deviceState(), "ios").message).toContain("Xcode Settings");- expect(platformSetupStatus(deviceState(), "android").message).toContain("Device Manager");- });-- it("preserves a specific missing-tool explanation from the server", () => {- const state = deviceState({- hosts: [- {- ...deviceState().hosts[0]!,- platforms: [- { platform: "ios", available: true },- { platform: "android", available: false, reason: "Android Emulator is missing." },- ],- },- ],- });- expect(platformSetupStatus(state, "android").message).toBe("Android Emulator is missing.");- });-- it("counts a remote device host when this machine has no simulator tooling", () => {- const state = deviceState({- hostStatus: "idle",- hostStatuses: { macmini: { status: "ready" } },- hosts: [- {- ...deviceState().hosts[0]!,- platforms: [- { platform: "ios", available: false, reason: "Xcode was not found." },- { platform: "android", available: false, reason: "Android SDK was not found." },- ],- },- {- id: "macmini",- kind: "ssh",- label: "Mac Mini",- hubInstalled: true,- agentDeviceInstalled: true,- platforms: [- { platform: "ios", available: true },- { platform: "android", available: false, reason: "Android SDK was not found." },- ],- },- ],- devices: [- {- hostId: "macmini",- id: "iphone",- platform: "ios",- name: "iPhone 16 Pro",- version: "iOS 27.0",- booted: true,- physical: false,- },- ],- });- expect(deviceHubReadiness(state).ready).toBe(true);- expect(platformSetupStatus(state, "ios")).toEqual({- ready: true,- message: "Xcode and iOS Simulator are available on Mac Mini.",- });- expect(platformSetupStatus(state, "android").ready).toBe(false);- });-});diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsxnew file mode 100644index 00000000000..eab8eb3bd88--- /dev/null+++ b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx@@ -0,0 +1,100 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import { deriveProjectIdentity } from "../../projectIdentity";+import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++function button(name: string) {+ return vi.waitFor(() => {+ const match = [...document.querySelectorAll<HTMLElement>("button, [role='radio']")].find(+ (element) => element.getAttribute("aria-label") === name || element.textContent === name,+ );+ if (!match) throw new Error(`No button ${name}`);+ return match;+ });+}++// The modal's inert backdrop covers the unstyled popup, so Playwright pointer clicks land on it.+async function click(name: string) {+ const target = await button(name);+ await act(async () => target.click());+}++async function openPicker() {+ const onSelect = vi.fn();+ const onOpenChange = vi.fn();+ await act(async () =>+ root.render(+ <ProjectIconPickerDialog+ current={null}+ projectName="Test"+ open+ onOpenChange={onOpenChange}+ onSelect={onSelect}+ />,+ ),+ );+ return { onSelect, onOpenChange };+}++describe("ProjectIconPickerDialog", () => {+ it("starts an automatic project on icons in its derived color and saves the picked icon", async () => {+ const { onSelect, onOpenChange } = await openPicker();+ const { color } = deriveProjectIdentity("Test");+ expect((await button("Icons")).getAttribute("aria-pressed")).toBe("true");+ expect(+ document.querySelector('[aria-label="Icon color"] [aria-pressed="true"]'),+ ).not.toBeNull();++ await userEvent.fill(searchBox(), "rocket");+ await click("Rocket");+ await click("Save icon");++ expect(onSelect).toHaveBeenCalledExactlyOnceWith({ kind: "lucide", name: "rocket", color });+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it("saves a monogram only once the letters are letters or numbers", async () => {+ const { onSelect } = await openPicker();+ await click("Monogram");+ const letters = await vi.waitFor(() => {+ const input = document.querySelector<HTMLInputElement>("#project-monogram");+ if (!input) throw new Error("No monogram input");+ return input;+ });++ await userEvent.fill(letters, "t-3");+ await click("Save icon");+ expect(onSelect).not.toHaveBeenCalled();++ await userEvent.fill(letters, "t3");+ await click("Save icon");+ expect(onSelect).toHaveBeenCalledExactlyOnceWith({+ kind: "monogram",+ text: "T3",+ color: deriveProjectIdentity("Test").color,+ });+ });+});++function searchBox() {+ return document.querySelector<HTMLInputElement>('input[aria-label="Search Lucide icons"]')!;+}diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.test.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.test.tsxdeleted file mode 100644index e1c08dfbabb..00000000000--- a/apps/web/src/components/settings/ProjectIconPickerDialog.test.tsx+++ /dev/null@@ -1,57 +0,0 @@-import type { ReactNode } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it, vi } from "vite-plus/test";--vi.mock("../ui/button", () => ({- Button: ({ children }: { readonly children?: ReactNode }) => <button>{children}</button>,-}));--vi.mock("../ui/dialog", () => {- const Container = ({ children }: { readonly children?: ReactNode }) => <div>{children}</div>;- return {- Dialog: Container,- DialogDescription: Container,- DialogFooter: Container,- DialogHeader: Container,- DialogPanel: Container,- DialogPopup: Container,- DialogTitle: Container,- };-});--vi.mock("../ui/input", () => ({ Input: () => <input /> }));-vi.mock("../ui/scroll-area", () => ({- ScrollArea: ({ children }: { readonly children?: ReactNode }) => <div>{children}</div>,-}));-vi.mock("../ui/toggle-group", () => ({- Toggle: ({ children, value }: { readonly children?: ReactNode; readonly value: string }) => (- <button data-value={value}>{children}</button>- ),- ToggleGroup: ({- children,- value,- }: {- readonly children?: ReactNode;- readonly value: readonly string[];- }) => <div data-current={value.join(",")}>{children}</div>,-}));--import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog";--describe("ProjectIconPickerDialog", () => {- it("shows icons first and selects them for an automatic project", () => {- const markup = renderToStaticMarkup(- <ProjectIconPickerDialog- current={null}- projectName="Test"- open- onOpenChange={() => {}}- onSelect={() => {}}- />,- );-- expect(markup).toContain('data-current="lucide"');- expect(markup.indexOf(">Icons<")).toBeLessThan(markup.indexOf(">Emoji<"));- expect(markup).toContain('aria-label="Icon color"');- });-});diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsxnew file mode 100644index 00000000000..cf7f4f2fc98--- /dev/null+++ b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx@@ -0,0 +1,358 @@+import { RegistryContext } from "@effect/atom-react";+import type {+ DeleteProjectInput,+ UpdateProjectInput,+} from "@t3tools/client-runtime/state/projects";+import {+ AuthOrchestrationOperateScope,+ AuthSettingsWriteScope,+ EnvironmentId,+ ProjectId,+ ProviderInstanceId,+ type AuthEnvironmentScope,+ type AuthSessionState,+} from "@t3tools/contracts";+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import * as Cause from "effect/Cause";+import { AsyncResult, Atom } from "effect/reactivity";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import type { Project } from "../../types";++type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;+const state = vi.hoisted(() => ({+ sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),+ projects: [] as Project[],+ update:+ vi.fn<+ (request: {+ environmentId: EnvironmentId;+ input: UpdateProjectInput;+ }) => Promise<AsyncResult.Success<void>>+ >(),+ delete:+ vi.fn<+ (request: {+ environmentId: EnvironmentId;+ input: DeleteProjectInput;+ }) => Promise<AsyncResult.Success<void>>+ >(),+ confirm: vi.fn<() => Promise<boolean>>(),+ releaseUploads: vi.fn(),+ clearDraft: vi.fn(),+}));++// Session grants come from the server; each test drives them through these atoms.+vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ createEnvironmentSessionAtoms: ((+ ...args: Parameters<typeof actual.createEnvironmentSessionAtoms>+ ) => ({+ ...actual.createEnvironmentSessionAtoms(...args),+ sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,+ })) as typeof actual.createEnvironmentSessionAtoms,+ };+});+vi.mock(import("~/state/environments"), async (original) => ({+ ...(await original()),+ useEnvironments: (() => ({ environments })) as never,+ usePrimaryEnvironmentId: () => primaryId,+}));+vi.mock(import("~/state/entities"), async (original) => ({+ ...(await original()),+ useProjects: (() => state.projects) as never,+ useThreadShells: () => [],+ waitForProjectRemoval: async () => true,+}));+vi.mock(import("~/state/projects"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ projectEnvironment: {+ ...actual.projectEnvironment,+ update: "update",+ delete: "delete",+ } as unknown as typeof actual.projectEnvironment,+ };+});+vi.mock(import("~/state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: ((command: "update" | "delete") => state[command]) as never,+}));+vi.mock(import("~/hooks/useSettings"), async (original) => ({+ ...(await original()),+ useClientSettings: ((selector?: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>+ selector ? selector(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS) as never,+}));+vi.mock(import("~/localApi"), async (original) => ({+ ...(await original()),+ readLocalApi: (() => ({ dialogs: { confirm: state.confirm } })) as never,+}));+vi.mock(import("~/lib/composerDraftUploads"), async (original) => ({+ ...(await original()),+ releaseProjectDraftUploads: state.releaseUploads,+}));+// Sections with their own data sources and tests; this file covers project permissions.+vi.mock(import("./ProjectDefaultsSettings"), async (original) => ({+ ...(await original()),+ ProjectDefaultsSettings: (() => null) as never,+}));+vi.mock(import("./ProjectActionsSettings"), async (original) => ({+ ...(await original()),+ ProjectActionsSettings: (() => null) as never,+}));++import { useComposerDraftStore } from "../../composerDraftStore";+import { appAtomRegistry } from "../../rpc/atomRegistry";+import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";+import { ProjectSettingsPanel } from "./ProjectSettingsPanel";++const primaryId = EnvironmentId.make("primary");+const remoteId = EnvironmentId.make("remote");+const instanceId = ProviderInstanceId.make("codex");+const environments = [primaryId, remoteId].map((environmentId) => ({+ environmentId,+ label: environmentId,+ connection: { phase: "connected" },+ serverConfig: { keybindings: DEFAULT_RESOLVED_KEYBINDINGS },+}));+const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({+ authenticated: true,+ scopes,+ auth: {+ policy: "remote-reachable",+ bootstrapMethods: ["one-time-token"],+ sessionMethods: ["bearer-access-token"],+ sessionCookieName: "t3_session",+ },+});+const writable = () => AsyncResult.success(session([AuthOrchestrationOperateScope]));++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((complete) => {+ resolve = complete;+ });+ return { promise, resolve };+}++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.clearAllMocks();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ state.sessions.clear();+ for (const id of [primaryId, remoteId])+ state.sessions.set(id, Atom.make<SessionResult>(writable()).pipe(Atom.keepAlive));+ state.projects = [primaryId, remoteId].map((environmentId) => ({+ id: ProjectId.make(`project-${environmentId}`),+ environmentId,+ title: "Shared repo",+ workspaceRoot: `/work/${environmentId}`,+ repositoryIdentity: {+ canonicalKey: "github.com/example/shared-repo",+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: "https://github.com/example/shared-repo.git",+ },+ },+ defaultModelSelection: { instanceId, model: "gpt-5-codex" },+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ scripts: [],+ }));+ state.update.mockImplementation(async ({ environmentId, input }) => {+ const { projectId, ...updates } = input;+ const patch = Object.fromEntries(+ Object.entries(updates).filter(([, value]) => value !== undefined),+ ) as Partial<Project>;+ state.projects = state.projects.map((project) =>+ project.environmentId === environmentId && project.id === projectId+ ? { ...project, ...patch }+ : project,+ );+ return AsyncResult.success(undefined);+ });+ state.delete.mockResolvedValue(AsyncResult.success(undefined));+ state.confirm.mockResolvedValue(true);+ useComposerDraftStore.setState({ clearProjectDraftThreadId: state.clearDraft });+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++function projectKey() {+ return buildSidebarProjectSnapshots({+ projects: state.projects,+ settings: DEFAULT_CLIENT_SETTINGS,+ primaryEnvironmentId: primaryId,+ resolveEnvironmentLabel: (id) => id,+ })[0]!.projectKey;+}++async function mountPanel() {+ const key = projectKey();+ const router = createRouter({+ routeTree: createRootRoute({ component: () => <ProjectSettingsPanel projectKey={key} /> }),+ history: createMemoryHistory({ initialEntries: ["/settings/projects"] }),+ });+ await router.load();+ await act(async () =>+ root.render(+ <RegistryContext.Provider value={appAtomRegistry}>+ <RouterProvider router={router} />+ </RegistryContext.Provider>,+ ),+ );+ await vi.waitFor(() => expect(nameInput()).not.toBeNull());+}++const nameInput = () => container.querySelector<HTMLInputElement>('[aria-label="Project name"]')!;+const removeCheckout = (root: string) =>+ container.querySelector<HTMLButtonElement>(`[aria-label="Remove checkout ${root}"]`)!;+const removeAll = () =>+ [...container.querySelectorAll("button")].find((button) =>+ button.textContent?.includes("Remove all entries"),+ )!;++async function grant(id: EnvironmentId, result: SessionResult) {+ await act(async () => appAtomRegistry.set(state.sessions.get(id)!, result));+}++async function rename(title: string) {+ await userEvent.fill(nameInput(), title);+ await userEvent.keyboard("{Enter}");+}++describe("project settings permissions", () => {+ it("disables shared edits when any member lacks project access", async () => {+ await grant(remoteId, AsyncResult.success(session([AuthSettingsWriteScope])));+ await mountPanel();++ expect(nameInput().disabled).toBe(true);+ expect(removeAll().disabled).toBe(true);+ expect(container.textContent).toContain(+ "Shared settings require permission to change every checkout in this group.",+ );+ expect(state.update).not.toHaveBeenCalled();+ });++ it("renames every member when all have project access without settings access", async () => {+ await mountPanel();+ await rename("Renamed");+ expect(state.update.mock.calls.map(([request]) => request.environmentId)).toEqual([+ primaryId,+ remoteId,+ ]);+ expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);+ });++ it("stops before the next member if its grant is revoked during an earlier update", async () => {+ const firstUpdate = deferred<AsyncResult.Success<void>>();+ state.update.mockReturnValueOnce(firstUpdate.promise);+ await mountPanel();+ await rename("Renamed");+ expect(state.update).toHaveBeenCalledOnce();++ await grant(remoteId, AsyncResult.success(session([])));+ await act(async () => {+ firstUpdate.resolve(AsyncResult.success(undefined));+ await firstUpdate.promise;+ });+ expect(state.update).toHaveBeenCalledOnce();+ expect(state.update.mock.calls[0]![0].environmentId).toBe(primaryId);+ });++ it("disables removal for a checkout whose project grant is missing", async () => {+ await grant(remoteId, AsyncResult.success(session([])));+ await mountPanel();+ expect(removeCheckout("/work/remote").disabled).toBe(true);+ expect(removeCheckout("/work/primary").disabled).toBe(false);+ });++ it("removes a writable checkout while removal of the mixed group stays denied", async () => {+ await grant(remoteId, AsyncResult.success(session([])));+ await mountPanel();+ expect(removeAll().disabled).toBe(true);++ await userEvent.click(removeCheckout("/work/primary"));+ await vi.waitFor(() => expect(state.delete).toHaveBeenCalledOnce());+ expect(state.delete).toHaveBeenCalledWith({+ environmentId: primaryId,+ input: { projectId: state.projects[0]!.id, force: true },+ });+ await vi.waitFor(() => expect(state.releaseUploads).toHaveBeenCalledOnce());+ expect(state.clearDraft).toHaveBeenCalledOnce();+ });++ it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => {+ const confirmed = deferred<boolean>();+ state.confirm.mockReturnValueOnce(confirmed.promise);+ await mountPanel();+ await userEvent.click(removeAll());+ expect(state.confirm).toHaveBeenCalledOnce();++ await grant(remoteId, AsyncResult.success(session([])));+ await act(async () => {+ confirmed.resolve(true);+ await confirmed.promise;+ });+ expect(state.delete).not.toHaveBeenCalled();+ expect(state.releaseUploads).not.toHaveBeenCalled();+ expect(state.clearDraft).not.toHaveBeenCalled();+ });++ it("does not save an edit whose grant was revoked mid-edit, and recovers when restored", async () => {+ await mountPanel();+ await userEvent.fill(nameInput(), "Renamed");+ await grant(remoteId, AsyncResult.success(session([])));+ await act(async () => nameInput().blur());+ expect(state.update).not.toHaveBeenCalled();+ expect(nameInput().disabled).toBe(true);++ await grant(remoteId, writable());+ expect(nameInput().disabled).toBe(false);+ await rename("Renamed");+ expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);+ });++ it.each([+ ["loading", () => AsyncResult.initial<AuthSessionState, Error>(), false],+ [+ "failed",+ () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("Disconnected"))),+ false,+ ],+ ["refreshing", () => AsyncResult.waiting(writable()), true],+ ] as const)(+ "uses the current grant while a member's session is %s",+ async (_state, result, allowed) => {+ await grant(remoteId, result());+ await mountPanel();+ expect(nameInput().disabled).toBe(!allowed);+ if (!allowed) return;+ await rename("Renamed");+ expect(state.update).toHaveBeenCalledTimes(2);+ },+ );+});diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.test.tsxdeleted file mode 100644index 79f6a35a8d2..00000000000--- a/apps/web/src/components/settings/ProjectSettingsPanel.test.tsx+++ /dev/null@@ -1,477 +0,0 @@-import { RegistryContext } from "@effect/atom-react";-import type {- DeleteProjectInput,- UpdateProjectInput,-} from "@t3tools/client-runtime/state/projects";-import {- AuthOrchestrationOperateScope,- AuthSettingsWriteScope,- DEFAULT_SERVER_SETTINGS,- EnvironmentId,- ProjectId,- ProviderDriverKind,- ProviderInstanceId,- type AuthEnvironmentScope,- type AuthSessionState,- type ResolvedKeybindingsConfig,- type ServerProvider,-} from "@t3tools/contracts";-import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";-import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";-import * as Cause from "effect/Cause";-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";-import { cloneElement, type ReactElement, type ReactNode } from "react";-import { act, create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";--import type { Project } from "../../types";--type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;-const state = vi.hoisted(() => ({- registry: null as AtomRegistry.AtomRegistry | null,- sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),- providers: null as Atom.Atom<ReadonlyArray<ServerProvider>> | null,- config: null as Atom.Atom<{ keybindings: ResolvedKeybindingsConfig }> | null,- projects: [] as Project[],- update:- vi.fn<- (request: {- environmentId: EnvironmentId;- input: UpdateProjectInput;- }) => Promise<AsyncResult.Success<void>>- >(),- delete:- vi.fn<- (request: {- environmentId: EnvironmentId;- input: DeleteProjectInput;- }) => Promise<AsyncResult.Success<void>>- >(),- confirm: vi.fn<() => Promise<boolean>>(),- updateSettings: vi.fn(),- upsertKeybinding: vi.fn(),- removeKeybinding: vi.fn(),- updateClientSettings: vi.fn(),- releaseUploads: vi.fn(),- clearDraft: vi.fn(),- copy: vi.fn(),- navigate: vi.fn(),-}));--vi.mock("~/connection/runtime", () => ({ connectionAtomRuntime: undefined }));-vi.mock("@t3tools/client-runtime/state/session", () => ({- createEnvironmentSessionAtoms: () => ({- sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,- }),-}));-vi.mock("~/rpc/atomRegistry", () => ({- get appAtomRegistry() {- return state.registry;- },-}));-vi.mock("~/state/environments", () => ({- useEnvironments: () => ({ environments }),- usePrimaryEnvironmentId: () => primaryId,-}));-vi.mock("~/state/entities", () => ({- useProjects: () => state.projects,- useThreadShells: () => [],- waitForProjectRemoval: async () => true,-}));-vi.mock("~/state/projects", () => ({- projectEnvironment: { update: "update", delete: "delete" },-}));-vi.mock("~/state/server", () => ({- EMPTY_SERVER_PROVIDERS: [],- serverEnvironment: {- providersValueAtom: () => state.providers!,- configValueAtom: () => state.config!,- updateSettings: "updateSettings",- upsertKeybinding: "upsertKeybinding",- removeKeybinding: "removeKeybinding",- },-}));-vi.mock("~/state/use-atom-command", () => ({- useAtomCommand: (- command: "update" | "delete" | "updateSettings" | "upsertKeybinding" | "removeKeybinding",- ) => state[command],-}));-vi.mock("~/hooks/useSettings", () => ({- useClientSettings: () => DEFAULT_CLIENT_SETTINGS,- useUpdateClientSettings: () => state.updateClientSettings,- usePrimarySettings: () => DEFAULT_SERVER_SETTINGS,- useEnvironmentSettings: () => DEFAULT_SERVER_SETTINGS,-}));-vi.mock("~/hooks/useT3ProjectFileScripts", () => ({- useT3ProjectFileState: () => ({- status: "valid",- file: null,- scripts: [{ name: "Imported", command: "vp test" }],- }),-}));-vi.mock("~/hooks/useCopyToClipboard", () => ({- useCopyToClipboard: () => ({ copyToClipboard: state.copy }),-}));-vi.mock("~/localApi", () => ({ readLocalApi: () => ({ dialogs: { confirm: state.confirm } }) }));-vi.mock("~/composerDraftStore", () => ({- useComposerDraftStore: {- getState: () => ({- getDraftThreadByProjectRef: () => null,- clearProjectDraftThreadId: state.clearDraft,- }),- },-}));-vi.mock("~/lib/composerDraftUploads", () => ({ releaseProjectDraftUploads: state.releaseUploads }));-vi.mock("~/env", () => ({ isElectron: true }));-vi.mock("@tanstack/react-router", () => ({- useNavigate: () => state.navigate,- useLocation: () => "/settings/projects",-}));-vi.mock("../ui/toast", () => ({- toastManager: { add: vi.fn() },- stackedThreadToast: (value: unknown) => value,-}));-vi.mock("../ui/button", () => ({ Button: "button" }));-vi.mock("../ui/input", () => ({ Input: "input" }));-vi.mock("../ui/switch", () => ({ Switch: "input" }));-vi.mock("../ui/select", () => ({- Select: "select",- SelectItem: "option",- SelectPopup: "div",- SelectTrigger: "button",- SelectValue: "span",-}));-vi.mock("../ui/menu", () => ({- Menu: "div",- MenuGroup: "div",- MenuGroupLabel: "div",- MenuItem: "button",- MenuPopup: "div",- MenuSeparator: "hr",- MenuTrigger: ({ render, children }: { render: ReactElement; children: ReactNode }) =>- cloneElement(render, {}, children),-}));-vi.mock("../ui/tooltip", () => ({- Tooltip: "div",- TooltipPopup: "span",- TooltipTrigger: ({ render }: { render: ReactNode }) => render,-}));-vi.mock("./settingsLayout", () => ({- SETTINGS_PICKER_TRIGGER_CLASSNAME: "",- SettingsPageContainer: "div",- SettingsSection: ({- children,- headerAction,- }: {- children: ReactNode;- headerAction?: ReactNode;- }) => (- <section>- {headerAction}- {children}- </section>- ),- SettingsRow: ({ control, resetAction }: { control?: ReactNode; resetAction?: ReactNode }) => (- <div>- {resetAction}- {control}- </div>- ),- SettingResetButton: ({- label,- ...props- }: {- label: string;- disabled?: boolean;- onClick: () => void;- }) => <button {...props} aria-label={`Reset ${label} to default`} />,-}));-vi.mock("./ProjectDefaultsSettings", () => ({ ProjectDefaultsSettings: () => null }));-vi.mock("./ProjectActionsSettings", () => ({ ProjectActionsSettings: () => null }));-vi.mock("../ProjectFavicon", () => ({ ProjectFavicon: () => null }));-vi.mock("../chat/ProviderModelPicker", () => ({ ProviderModelPicker: "model-picker" }));-vi.mock("../chat/TraitsPicker", () => ({ TraitsPicker: "traits-picker" }));-vi.mock("./ProjectFaviconPickerDialog", () => ({- canPickExternalProjectFavicon: () => false,- ProjectFaviconPickerDialog: "favicon-picker",-}));-vi.mock("./ProjectIconPickerDialog", () => ({ ProjectIconPickerDialog: "icon-picker" }));-vi.mock("../projectScriptEditor", async (importOriginal) => ({- ...(await importOriginal<typeof import("../projectScriptEditor")>()),- ProjectScriptEditorDialog: "script-editor",-}));--import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";-import { ProjectFaviconPickerDialog } from "./ProjectFaviconPickerDialog";-import { ProjectSettingsPanel } from "./ProjectSettingsPanel";--const primaryId = EnvironmentId.make("primary");-const remoteId = EnvironmentId.make("remote");-const instanceId = ProviderInstanceId.make("codex");-const environments = [primaryId, remoteId].map((environmentId) => ({- environmentId,- label: environmentId,- connection: { phase: "connected" },- serverConfig: { keybindings: DEFAULT_RESOLVED_KEYBINDINGS },-}));-const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({- authenticated: true,- scopes,- auth: {- policy: "remote-reachable",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["bearer-access-token"],- sessionCookieName: "t3_session",- },-});-const writable = () => AsyncResult.success(session([AuthOrchestrationOperateScope]));--function deferred<T>() {- let resolve!: (value: T) => void;- const promise = new Promise<T>((complete) => {- resolve = complete;- });- return { promise, resolve };-}--let renderer: ReactTestRenderer | undefined;--beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.clearAllMocks();- state.registry = AtomRegistry.make();- state.sessions.clear();- for (const id of [primaryId, remoteId])- state.sessions.set(id, Atom.make<SessionResult>(writable()).pipe(Atom.keepAlive));- state.projects = [primaryId, remoteId].map((environmentId) => ({- id: ProjectId.make(`project-${environmentId}`),- environmentId,- title: "Shared repo",- workspaceRoot: `/work/${environmentId}`,- repositoryIdentity: {- canonicalKey: "github.com/example/shared-repo",- locator: {- source: "git-remote",- remoteName: "origin",- remoteUrl: "https://github.com/example/shared-repo.git",- },- },- defaultModelSelection: { instanceId, model: "gpt-5-codex" },- createdAt: "2026-01-01T00:00:00.000Z",- updatedAt: "2026-01-01T00:00:00.000Z",- scripts: [],- }));- state.providers = Atom.make<ReadonlyArray<ServerProvider>>([- {- instanceId,- driver: ProviderDriverKind.make("codex"),- enabled: true,- installed: true,- version: null,- status: "ready",- auth: { status: "authenticated" },- checkedAt: "2026-01-01T00:00:00.000Z",- models: [],- slashCommands: [],- skills: [],- },- ]);- state.config = Atom.make({ keybindings: DEFAULT_RESOLVED_KEYBINDINGS });- state.update.mockImplementation(async ({ environmentId, input }) => {- const { projectId, ...updates } = input;- const patch = Object.fromEntries(- Object.entries(updates).filter(([, value]) => value !== undefined),- ) as Partial<Project>;- state.projects = state.projects.map((project) =>- project.environmentId === environmentId && project.id === projectId- ? { ...project, ...patch }- : project,- );- return AsyncResult.success(undefined);- });- state.delete.mockResolvedValue(AsyncResult.success(undefined));- state.updateSettings.mockResolvedValue(AsyncResult.success(undefined));- state.confirm.mockResolvedValue(true);-});--afterEach(async () => {- await act(() => renderer?.unmount());- renderer = undefined;- state.registry?.dispose();- vi.unstubAllGlobals();-});--function group() {- return buildSidebarProjectSnapshots({- projects: state.projects,- settings: DEFAULT_CLIENT_SETTINGS,- primaryEnvironmentId: primaryId,- resolveEnvironmentLabel: (id) => id,- })[0]!;-}--async function mountPanel() {- await act(() => {- renderer = create(- <RegistryContext.Provider value={state.registry!}>- <ProjectSettingsPanel projectKey={group().projectKey} />- </RegistryContext.Provider>,- );- });- return renderer!.root;-}--function button(label: string) {- return renderer!.root.findAllByType("button").find((node) => node.children.includes(label))!;-}--async function grant(id: EnvironmentId, result: SessionResult) {- await act(() => state.registry!.set(state.sessions.get(id)!, result));-}--describe("project settings permissions", () => {- it("preflights every member before any shared field update", async () => {- await grant(remoteId, AsyncResult.success(session([AuthSettingsWriteScope])));- const root = await mountPanel();- const name = root.findByProps({ "aria-label": "Project name" });-- await act(async () => {- name.props.onChange();- name.props.onBlur({ currentTarget: { value: "Renamed" } });- root.findByType(ProjectFaviconPickerDialog).props.onSelect("/work/icon.png");- });-- expect(state.update).not.toHaveBeenCalled();- expect(state.projects.every((project) => project.title === "Shared repo")).toBe(true);- expect(name.props.disabled).toBe(true);- expect(button("Remove all entries").props.disabled).toBe(true);- });-- it("updates every member when all have project access without settings access", async () => {- const root = await mountPanel();- await act(async () => {- const name = root.findByProps({ "aria-label": "Project name" });- name.props.onChange();- name.props.onBlur({ currentTarget: { value: "Renamed" } });- });- expect(state.update.mock.calls.map(([request]) => request.environmentId)).toEqual([- primaryId,- remoteId,- ]);- expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);- });-- it("stops before the next member if its grant is revoked during an earlier update", async () => {- const firstUpdate = deferred<AsyncResult.Success<void>>();- state.update.mockReturnValueOnce(firstUpdate.promise);- const root = await mountPanel();- await act(async () => {- const name = root.findByProps({ "aria-label": "Project name" });- name.props.onChange();- name.props.onBlur({ currentTarget: { value: "Renamed" } });- });- expect(state.update).toHaveBeenCalledOnce();-- await grant(remoteId, AsyncResult.success(session([])));- await act(async () => {- firstUpdate.resolve(AsyncResult.success(undefined));- await firstUpdate.promise;- });- expect(state.update).toHaveBeenCalledOnce();- expect(state.update.mock.calls[0]![0].environmentId).toBe(primaryId);- });-- it("disables removal for a checkout whose project grant is missing", async () => {- await grant(remoteId, AsyncResult.success(session([])));- const root = await mountPanel();- const denied = root.findByProps({ "aria-label": "Remove checkout /work/remote" });- expect(denied.props.disabled).toBe(true);- await act(async () => denied.props.onClick());- expect(state.confirm).not.toHaveBeenCalled();- expect(state.delete).not.toHaveBeenCalled();- expect(root.findByProps({ "aria-label": "Remove checkout /work/primary" }).props.disabled).toBe(- false,- );- });-- it("allows removing a writable checkout while denying removal of the mixed group", async () => {- await grant(remoteId, AsyncResult.success(session([])));- await mountPanel();- await act(async () => button("Remove all entries").props.onClick());- expect(state.confirm).not.toHaveBeenCalled();- expect(state.delete).not.toHaveBeenCalled();- await act(async () =>- renderer!.root.findByProps({ "aria-label": "Remove checkout /work/primary" }).props.onClick(),- );- expect(state.delete).toHaveBeenCalledExactlyOnceWith({- environmentId: primaryId,- input: { projectId: state.projects[0]!.id, force: true },- });- expect(state.releaseUploads).toHaveBeenCalledOnce();- expect(state.clearDraft).toHaveBeenCalledOnce();- });-- it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => {- const confirmed = deferred<boolean>();- state.confirm.mockReturnValueOnce(confirmed.promise);- await mountPanel();- await act(async () => button("Remove all entries").props.onClick());- expect(state.confirm).toHaveBeenCalledOnce();- await grant(remoteId, AsyncResult.success(session([])));- await act(async () => {- confirmed.resolve(true);- await confirmed.promise;- });- expect(state.delete).not.toHaveBeenCalled();- expect(state.releaseUploads).not.toHaveBeenCalled();- expect(state.clearDraft).not.toHaveBeenCalled();- });-- it("reacts to another member's revoked and restored grant and guards a stale handler", async () => {- await grant(- primaryId,- AsyncResult.success(session([AuthOrchestrationOperateScope, AuthSettingsWriteScope])),- );- const root = await mountPanel();- const name = () => root.findByProps({ "aria-label": "Project name" });- const staleSave = name().props.onBlur;- await act(async () => {- state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));- name().props.onChange();- staleSave({ currentTarget: { value: "Renamed" } });- });- expect(state.update).not.toHaveBeenCalled();- expect(name().props.disabled).toBe(true);-- await grant(remoteId, writable());- expect(name().props.disabled).toBe(false);- await act(async () => {- name().props.onChange();- name().props.onBlur({ currentTarget: { value: "Renamed" } });- });- expect(state.projects.map((project) => project.title)).toEqual(["Renamed", "Renamed"]);- });-- it.each([- ["loading", () => AsyncResult.initial<AuthSessionState, Error>(), false],- [- "failed",- () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("Disconnected"))),- false,- ],- ["refreshing", () => AsyncResult.waiting(writable()), true],- ] as const)(- "uses the current grant while a member's session is %s",- async (_state, result, allowed) => {- await grant(remoteId, result());- const root = await mountPanel();- const name = root.findByProps({ "aria-label": "Project name" });- expect(name.props.disabled).toBe(!allowed);- await act(async () => {- name.props.onChange();- name.props.onBlur({ currentTarget: { value: "Renamed" } });- });- expect(state.update).toHaveBeenCalledTimes(allowed ? 2 : 0);- },- );-});diff --git a/apps/web/src/components/settings/ProviderInstanceCard.browser.test.tsx b/apps/web/src/components/settings/ProviderInstanceCard.browser.test.tsxnew file mode 100644index 00000000000..d0ca84fb88c--- /dev/null+++ b/apps/web/src/components/settings/ProviderInstanceCard.browser.test.tsx@@ -0,0 +1,105 @@+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";+import { act, type ComponentProps } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import { ProviderInstanceCard } from "./ProviderInstanceCard";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++const driver = ProviderDriverKind.make("codex");++function provider(overrides: Partial<ServerProvider>): ServerProvider {+ return {+ instanceId: ProviderInstanceId.make("codex"),+ driver,+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-08-27T12:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+ ...overrides,+ };+}++async function renderCard(+ liveProvider: ServerProvider,+ mode: ComponentProps<typeof ProviderInstanceCard>["mode"],+) {+ await act(async () =>+ root.render(+ <ProviderInstanceCard+ instanceId={liveProvider.instanceId}+ instance={{ driver }}+ driverOption={undefined}+ liveProvider={liveProvider}+ mode={mode}+ onUpdate={() => undefined}+ hiddenModels={[]}+ favoriteModels={[]}+ modelOrder={[]}+ onHiddenModelsChange={() => undefined}+ onFavoriteModelsChange={() => undefined}+ onToggleFavorite={() => undefined}+ onModelOrderChange={() => undefined}+ />,+ ),+ );+}++describe("ProviderInstanceCard", () => {+ it("hides the account email until the user reveals it, and hides it again", async () => {+ await renderCard(+ provider({ auth: { status: "authenticated", email: "[email protected]" } }),+ "editor",+ );+ expect(container.textContent).toContain("Authenticated as");+ expect(container.textContent).not.toContain("[email protected]");++ const toggle = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Toggle account email visibility"]',+ )!;+ await userEvent.click(toggle);+ expect(toggle.textContent).toBe("[email protected]");++ await userEvent.click(toggle);+ expect(container.textContent).not.toContain("[email protected]");+ });++ it.each(["list", "editor"] as const)(+ "surfaces a failed probe message in the %s",+ async (mode) => {+ await renderCard(+ provider({+ version: null,+ status: "error",+ auth: { status: "unknown" },+ message:+ "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.",+ }),+ mode,+ );+ expect(container.textContent).toContain("Unavailable");+ expect(container.textContent).toContain("is not a symlink");+ },+ );+});diff --git a/apps/web/src/components/settings/ProviderInstanceCard.test.ts b/apps/web/src/components/settings/ProviderInstanceCard.test.tsindex 45cf17aeacf..e7a0826f790 100644--- a/apps/web/src/components/settings/ProviderInstanceCard.test.ts+++ b/apps/web/src/components/settings/ProviderInstanceCard.test.ts@@ -1,18 +1,10 @@-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vite-plus/test";-import {- ProviderDriverKind,- ProviderInstanceId,- type ServerProvider,- type ServerProviderModel,-} from "@t3tools/contracts";+import type { ServerProviderModel } from "@t3tools/contracts";import {deriveProviderModelsForDisplay,nextProviderEnvironmentWithFieldValue,providerEnvironmentWithoutNames,- ProviderInstanceCard,readProviderEnvironmentVariable,} from "./ProviderInstanceCard";@@ -86,87 +78,6 @@ describe("deriveProviderModelsForDisplay", () => {capabilities: customCapabilities,});});-- it("shows a redacted provider email in the editor header status line", () => {- const instanceId = ProviderInstanceId.make("codex");- const driver = ProviderDriverKind.make("codex");- const liveProvider: ServerProvider = {- instanceId,- driver,- enabled: true,- installed: true,- version: "1.0.0",- status: "ready",- auth: { status: "authenticated", email: "[email protected]" },- checkedAt: "2026-08-27T12:00:00.000Z",- models: [],- slashCommands: [],- skills: [],- };-- const markup = renderToStaticMarkup(- createElement(ProviderInstanceCard, {- instanceId,- instance: { driver },- driverOption: undefined,- liveProvider,- mode: "editor",- onUpdate: () => undefined,- hiddenModels: [],- favoriteModels: [],- modelOrder: [],- onHiddenModelsChange: () => undefined,- onFavoriteModelsChange: () => undefined,- onToggleFavorite: () => undefined,- onModelOrderChange: () => undefined,- }),- );-- expect(markup).toContain("Authenticated as");- expect(markup).toContain('aria-label="Toggle account email visibility"');- expect(markup).toContain("blur-xs");- expect(markup).not.toContain("[email protected]");- });- it("surfaces a failed probe message in both the list row and the editor", () => {- const instanceId = ProviderInstanceId.make("codex_work");- const driver = ProviderDriverKind.make("codex");- const message =- "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.";- const liveProvider: ServerProvider = {- instanceId,- driver,- enabled: true,- installed: true,- version: null,- status: "error",- auth: { status: "unknown" },- checkedAt: "2026-08-28T12:00:00.000Z",- models: [],- slashCommands: [],- skills: [],- message,- };- const props = {- instanceId,- instance: { driver },- driverOption: undefined,- liveProvider,- onUpdate: () => undefined,- hiddenModels: [],- favoriteModels: [],- modelOrder: [],- onHiddenModelsChange: () => undefined,- onFavoriteModelsChange: () => undefined,- onToggleFavorite: () => undefined,- onModelOrderChange: () => undefined,- } as const;-- for (const mode of ["list", "editor"] as const) {- const markup = renderToStaticMarkup(createElement(ProviderInstanceCard, { ...props, mode }));- expect(markup).toContain("Unavailable");- expect(markup).toContain("is not a symlink");- }- });});describe("provider environment helpers", () => {diff --git a/apps/web/src/components/settings/SecretInput.browser.test.tsx b/apps/web/src/components/settings/SecretInput.browser.test.tsxnew file mode 100644index 00000000000..960214b5ca5--- /dev/null+++ b/apps/web/src/components/settings/SecretInput.browser.test.tsx@@ -0,0 +1,66 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import { SecretInput } from "./SecretInput";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++const input = () => container.querySelector("input")!;++async function edit(value: string) {+ await userEvent.clear(input());+ if (value) await userEvent.type(input(), value);+ await userEvent.click(document.body);+}++describe("SecretInput", () => {+ it("preserves a configured secret on empty edits and commits a replacement", async () => {+ const onCommit = vi.fn();+ await act(async () => root.render(<SecretInput configured value="" onCommit={onCommit} />));+ expect(input().type).toBe("password");++ await userEvent.click(input());+ await userEvent.click(document.body);+ expect(onCommit).not.toHaveBeenCalled();++ await edit("replacement");+ expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");+ expect(input().value).toBe("");+ });++ it("allows clearing an unsaved draft", async () => {+ const onCommit = vi.fn();+ await act(async () => root.render(<SecretInput value="draft" onCommit={onCommit} />));+ await edit("");+ expect(onCommit).toHaveBeenCalledExactlyOnceWith("");+ });++ it("keeps an in-progress replacement when settings refresh", async () => {+ const onCommit = vi.fn();+ const render = () => root.render(<SecretInput configured value="" onCommit={onCommit} />);+ await act(async () => render());++ await userEvent.type(input(), "replacement");+ await act(async () => render());+ expect(input().value).toBe("replacement");++ await userEvent.keyboard("{Enter}");+ expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");+ });+});diff --git a/apps/web/src/components/settings/SecretInput.test.tsx b/apps/web/src/components/settings/SecretInput.test.tsxdeleted file mode 100644index 8b7f7928a88..00000000000--- a/apps/web/src/components/settings/SecretInput.test.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { act } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { SecretInput } from "./SecretInput";--vi.mock("../ui/input", () => ({- Input: (props: Record<string, unknown>) => <input {...props} />,-}));--let renderer: ReactTestRenderer;--beforeEach(() => vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true));-afterEach(async () => {- await act(() => renderer?.unmount());- vi.unstubAllGlobals();-});--async function edit(value: string) {- await act(() => renderer.root.findByType("input").props.onFocus());- await act(() => renderer.root.findByType("input").props.onChange({ target: { value } }));- await act(() => renderer.root.findByType("input").props.onBlur());-}--describe("SecretInput", () => {- it("preserves a configured secret on empty edits and commits a replacement", async () => {- const onCommit = vi.fn();- await act(() => {- renderer = create(<SecretInput configured value="" onCommit={onCommit} />);- });- await edit("");- expect(onCommit).not.toHaveBeenCalled();- await edit("replacement");- expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");- expect(renderer.root.findByType("input").props.value).toBe("");- });-- it("allows clearing an unsaved draft", async () => {- const onCommit = vi.fn();- await act(() => {- renderer = create(<SecretInput value="draft" onCommit={onCommit} />);- });- await edit("");- expect(onCommit).toHaveBeenCalledExactlyOnceWith("");- });-- it("keeps an in-progress replacement when settings refresh", async () => {- const onCommit = vi.fn();- await act(() => {- renderer = create(<SecretInput configured value="" onCommit={onCommit} />);- });- await act(() => renderer.root.findByType("input").props.onFocus());- await act(() =>- renderer.root.findByType("input").props.onChange({ target: { value: "replacement" } }),- );- await act(() => {- renderer.update(<SecretInput configured value="" onCommit={onCommit} />);- });- expect(renderer.root.findByType("input").props.value).toBe("replacement");- await act(() => renderer.root.findByType("input").props.onBlur());- expect(onCommit).toHaveBeenCalledExactlyOnceWith("replacement");- });-});diff --git a/apps/web/src/components/settings/TelemetryExportSettings.browser.test.tsx b/apps/web/src/components/settings/TelemetryExportSettings.browser.test.tsxnew file mode 100644index 00000000000..278442ed468--- /dev/null+++ b/apps/web/src/components/settings/TelemetryExportSettings.browser.test.tsx@@ -0,0 +1,95 @@+import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++const { state, updateSettings } = vi.hoisted(() => ({+ state: { observability: {} as typeof DEFAULT_SERVER_SETTINGS.observability },+ updateSettings: vi.fn(async () => ({ _tag: "Success" as const, value: undefined })),+}));++vi.mock(import("@effect/atom-react"), async (original) => ({+ ...(await original()),+ useAtomValue: (() => true) as never,+}));+vi.mock(import("../../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: ((command: unknown) =>+ command === "updateSettings" ? updateSettings : vi.fn()) as never,+}));+vi.mock(import("../../state/server"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ serverEnvironment: {+ ...actual.serverEnvironment,+ updateSettings: "updateSettings",+ } as unknown as typeof actual.serverEnvironment,+ };+});+vi.mock(import("./SettingsScopeContext"), async (original) => ({+ ...(await original()),+ useSettingsScope: (() => ({+ scope: { kind: "environment" },+ environment: {+ environmentId: "env",+ label: "MAC1",+ serverConfig: { environment: { capabilities: {} } },+ },+ })) as never,+}));+vi.mock(import("./useScopedSettings"), async (original) => ({+ ...(await original()),+ useScopedSettings: ((select: (settings: typeof state) => unknown) => select(state)) as never,+}));++import { TelemetryExportSettings } from "./TelemetryExportSettings";++let root: Root;+let container: HTMLDivElement;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ updateSettings.mockClear();+ vi.unstubAllGlobals();+});++const field = (id: string) => container.querySelector<HTMLInputElement>(`#${id}`)!;+async function replace(id: string, value: string) {+ await userEvent.clear(field(id));+ await userEvent.type(field(id), value);+}++describe("TelemetryExportSettings", () => {+ it("does not resend a field the user restored after another client changed it", async () => {+ state.observability = {+ ...DEFAULT_SERVER_SETTINGS.observability,+ otlpTracesUrl: "http://old/v1/traces",+ };+ await act(async () => root.render(<TelemetryExportSettings />));++ await replace("otlpTracesUrl", "http://draft/v1/traces");+ await replace("otlpTracesUrl", "http://old/v1/traces");+ state.observability = { ...state.observability, otlpTracesUrl: "http://other/v1/traces" };+ await act(async () => root.render(<TelemetryExportSettings />));+ await replace("otlpMetricsUrl", "http://new/v1/metrics");+ const save = [...container.querySelectorAll("button")].find(+ (button) => button.textContent === "Save",+ )!;+ await userEvent.click(save);++ expect(updateSettings).toHaveBeenCalledExactlyOnceWith({+ environmentId: "env",+ input: { patch: { observability: { otlpMetricsUrl: "http://new/v1/metrics" } } },+ });+ expect(container.textContent).toContain("Saved. Restart the server to apply.");+ });+});diff --git a/apps/web/src/components/settings/TelemetryExportSettings.test.tsx b/apps/web/src/components/settings/TelemetryExportSettings.test.tsxdeleted file mode 100644index 50e3c64fcb9..00000000000--- a/apps/web/src/components/settings/TelemetryExportSettings.test.tsx+++ /dev/null@@ -1,72 +0,0 @@-import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";-import { act, type ReactNode } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--const { state, updateSettings } = vi.hoisted(() => ({- state: { observability: {} as typeof DEFAULT_SERVER_SETTINGS.observability },- updateSettings: vi.fn(async () => ({ _tag: "Success" as const, value: undefined })),-}));--vi.mock("@effect/atom-react", () => ({ useAtomValue: () => true }));-vi.mock("../../state/server", () => ({- serverEnvironment: {- updateSettings: "updateSettings",- checkOtlpEndpoint: { permissionAtom: () => null },- },-}));-vi.mock("../../state/use-atom-command", () => ({- useAtomCommand: (command: unknown) => (command === "updateSettings" ? updateSettings : vi.fn()),-}));-vi.mock("./SettingsScopeContext", () => ({- useSettingsScope: () => ({- scope: { kind: "environment" },- environment: {- environmentId: "env",- label: "MAC1",- serverConfig: { environment: { capabilities: {} } },- },- }),-}));-vi.mock("./useScopedSettings", () => ({- useScopedSettings: (select: (settings: typeof state) => unknown) => select(state),-}));-vi.mock("./settingsLayout", () => ({- SettingsSection: ({ children }: { children: ReactNode }) => <section>{children}</section>,-}));--import { TelemetryExportSettings } from "./TelemetryExportSettings";--let renderer: ReactTestRenderer | null = null;-afterEach(async () => {- await act(() => renderer?.unmount());- renderer = null;- updateSettings.mockClear();-});--const type = (id: string, value: string) =>- act(() => renderer!.root.findByProps({ id }).props.onChange({ target: { value } }));--describe("TelemetryExportSettings", () => {- it("does not resend a field the user restored after another client changed it", async () => {- state.observability = {- ...DEFAULT_SERVER_SETTINGS.observability,- otlpTracesUrl: "http://old/v1/traces",- };- await act(() => {- renderer = create(<TelemetryExportSettings />);- });-- await type("otlpTracesUrl", "http://draft/v1/traces");- await type("otlpTracesUrl", "http://old/v1/traces");- state.observability = { ...state.observability, otlpTracesUrl: "http://other/v1/traces" };- await act(() => renderer!.update(<TelemetryExportSettings />));- await type("otlpMetricsUrl", "http://new/v1/metrics");- await act(() => renderer!.root.findByType("form").props.onSubmit({ preventDefault() {} }));-- expect(updateSettings).toHaveBeenCalledWith({- environmentId: "env",- input: { patch: { observability: { otlpMetricsUrl: "http://new/v1/metrics" } } },- });- });-});diff --git a/apps/web/src/components/settings/colorPickers.browser.test.tsx b/apps/web/src/components/settings/colorPickers.browser.test.tsxnew file mode 100644index 00000000000..69998c90ab0--- /dev/null+++ b/apps/web/src/components/settings/colorPickers.browser.test.tsx@@ -0,0 +1,262 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { userEvent } from "vite-plus/test/browser";++import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";+import { ThemeColorField } from "./ThemeColorPicker";++const HUE = "Accent color hue";+const SATURATION = "Accent color saturation";+const BRIGHTNESS = "Accent color brightness";+const PLANE = "Accent color saturation and brightness";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ // Synthetic pointer ids are not active pointers, so the browser would reject capture.+ vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {});+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function byLabel<T extends HTMLElement = HTMLElement>(label: string) {+ const element = document.querySelector<T>(`[aria-label="${label}"]`);+ if (!element) throw new Error(`No element labelled ${label}`);+ return element;+}++const slider = (label: string) => byLabel<HTMLInputElement>(label);+const sliderValue = (label: string) => Number(slider(label).value);++async function open(triggerLabel: string) {+ await userEvent.click(byLabel(triggerLabel));+ await vi.waitFor(() => byLabel(HUE));+}++async function press(label: string, key: string, shift = false) {+ const target = slider(label);+ await act(async () => target.focus());+ await userEvent.keyboard(shift ? `{Shift>}{${key}}{/Shift}` : `{${key}}`);+}++function setRange(label: string, value: number) {+ const input = slider(label);+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;+ setValue.call(input, String(value));+ input.dispatchEvent(new Event("input", { bubbles: true }));+}++function pointer(label: string, type: string, xFraction: number, yFraction = 0.5, pointerId = 1) {+ const target = byLabel(label);+ const bounds = target.getBoundingClientRect();+ target.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ button: 0,+ pointerId,+ clientX: bounds.left + bounds.width * xFraction,+ clientY: bounds.top + bounds.height * yFraction,+ }),+ );+}++const nextFrame = () =>+ act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));++async function renderAccent(value: string | undefined, commitDelayMs?: number) {+ const onCommit = vi.fn();+ await act(async () =>+ root.render(+ <ProviderAccentColorPicker+ displayName="Codex"+ value={value}+ onCommit={onCommit}+ {...(commitDelayMs === undefined ? {} : { commitDelayMs })}+ />,+ ),+ );+ await open(`${value ? "Change" : "Add"} accent color for Codex`);+ return onCommit;+}++async function renderThemeField(value: string) {+ const onChange = vi.fn();+ const render = (current: string) =>+ root.render(<ThemeColorField role="accent" value={current} onChange={onChange} />);+ await act(async () => render(value));+ await open("Choose Accent color color");+ return { onChange, echo: (next: string) => act(async () => render(next)) };+}++describe("provider accent color picker", () => {+ it("adjusts each color axis independently from the keyboard", async () => {+ const onCommit = await renderAccent("#ff0000");++ await press(HUE, "ArrowLeft");+ expect(slider(HUE).getAttribute("aria-valuenow")).toBe("359");+ await press(HUE, "ArrowRight");+ expect(onCommit).toHaveBeenLastCalledWith("#ff0000");++ await press(SATURATION, "ArrowRight", true);+ await press(BRIGHTNESS, "ArrowUp", true);+ expect(onCommit).toHaveBeenLastCalledWith("#ff0000");+ await press(BRIGHTNESS, "ArrowDown", true);+ expect(onCommit).toHaveBeenLastCalledWith("#e60000");+ expect(sliderValue(BRIGHTNESS)).toBe(90);+ expect(slider(BRIGHTNESS).getAttribute("aria-valuetext")).toBe("90%");+ expect(sliderValue(SATURATION)).toBe(100);++ await press(SATURATION, "ArrowDown", true);+ expect(onCommit).toHaveBeenLastCalledWith("#e61717");+ expect(sliderValue(SATURATION)).toBe(90);+ await press(SATURATION, "ArrowUp", true);+ expect(onCommit).toHaveBeenLastCalledWith("#e60000");+ await press(BRIGHTNESS, "ArrowLeft", true);+ expect(onCommit).toHaveBeenLastCalledWith("#cc0000");+ await press(BRIGHTNESS, "ArrowRight", true);+ expect(onCommit).toHaveBeenLastCalledWith("#e60000");++ onCommit.mockClear();+ await press(SATURATION, "Tab");+ expect(onCommit).not.toHaveBeenCalled();+ });++ it("supports Home/End and clamps each axis without changing the other", async () => {+ const onCommit = await renderAccent("#ff0000");++ await press(SATURATION, "Home");+ await press(SATURATION, "ArrowLeft");+ expect(sliderValue(SATURATION)).toBe(0);+ expect(onCommit).toHaveBeenLastCalledWith("#ffffff");+ await press(BRIGHTNESS, "Home");+ await press(BRIGHTNESS, "ArrowDown");+ expect(sliderValue(BRIGHTNESS)).toBe(0);+ expect(onCommit).toHaveBeenLastCalledWith("#000000");+ await press(SATURATION, "End");+ expect(sliderValue(SATURATION)).toBe(100);+ expect(sliderValue(BRIGHTNESS)).toBe(0);+ await press(BRIGHTNESS, "End");+ await press(BRIGHTNESS, "ArrowUp");+ expect(onCommit).toHaveBeenLastCalledWith("#ff0000");+ await press(SATURATION, "ArrowLeft");+ expect(sliderValue(SATURATION)).toBe(98);+ expect(onCommit).toHaveBeenLastCalledWith("#ff0505");+ });++ it("adds an accent only after choosing one and clears it back to no accent", async () => {+ const onCommit = await renderAccent(undefined);+ const clearButton = () =>+ [...document.querySelectorAll("button")].find((button) =>+ button.textContent?.includes("Clear color"),+ );+ expect(onCommit).not.toHaveBeenCalled();+ expect(clearButton()).toBeUndefined();++ await press(HUE, "ArrowRight", true);+ expect(onCommit).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(clearButton()).toBeDefined());++ await userEvent.click(clearButton()!);+ expect(onCommit).toHaveBeenLastCalledWith("");+ expect(clearButton()).toBeUndefined();+ });++ it("debounces commits and commits the pending color on unmount", async () => {+ const onCommit = await renderAccent("#ff0000", 250);+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });++ await press(HUE, "ArrowRight", true);+ await press(HUE, "ArrowRight", true);+ expect(onCommit).not.toHaveBeenCalled();+ await act(async () => vi.advanceTimersByTime(250));+ expect(onCommit).toHaveBeenCalledExactlyOnceWith("#ff5500");++ await press(HUE, "ArrowRight", true);+ await act(async () => root.unmount());+ expect(onCommit).toHaveBeenLastCalledWith("#ff8000");+ await act(async () => vi.advanceTimersByTime(250));+ expect(onCommit).toHaveBeenCalledTimes(2);+ root = createRoot(container);+ });+});++describe("theme color field", () => {+ it("batches native range changes into one commit per frame and keeps alpha", async () => {+ const { onChange } = await renderThemeField("#ff000080");++ // Both changes land in one task, so no animation frame can run between them.+ await act(async () => {+ setRange(SATURATION, 50);+ setRange(BRIGHTNESS, 50);+ expect(onChange).not.toHaveBeenCalled();+ });+ await nextFrame();+ expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#80404080");++ await press(BRIGHTNESS, "ArrowDown", true);+ await nextFrame();+ expect(onChange).toHaveBeenLastCalledWith("accent", "#66333380");+ expect(sliderValue(SATURATION)).toBe(50);+ });++ it("flushes the final drag color on release of the dragging pointer only", async () => {+ const { onChange } = await renderThemeField("#ff000080");++ // The drag runs in one task, so no animation frame can commit mid-drag.+ await act(async () => {+ pointer(HUE, "pointerdown", 0.25);+ pointer(HUE, "pointermove", 0.5);+ pointer(HUE, "pointermove", 0.75, 0.5, 2);+ pointer(HUE, "pointerup", 0.75, 0.5, 2);+ expect(onChange).not.toHaveBeenCalled();+ pointer(HUE, "pointerup", 0.5);+ });+ expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#00ffff80");+ await act(async () => pointer(HUE, "lostpointercapture", 0.5));+ await nextFrame();+ expect(onChange).toHaveBeenCalledOnce();+ });++ it("clamps out-of-bounds drags and flushes on cancellation and unmount", async () => {+ const { onChange } = await renderThemeField("#ff000080");++ await act(async () => {+ pointer(PLANE, "pointerdown", -0.5, -0.5);+ pointer(PLANE, "pointercancel", -0.5, -0.5);+ });+ expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff80");++ await act(async () => {+ pointer(PLANE, "pointerdown", 1.5, 1.5);+ root.unmount();+ });+ expect(onChange).toHaveBeenLastCalledWith("accent", "#00000080");+ root = createRoot(container);+ });++ it("keeps the selected hue when a grey color is echoed back from theme settings", async () => {+ const { onChange, echo } = await renderThemeField("#ff0000");++ await press(HUE, "ArrowRight", true);+ await act(async () => {+ pointer(PLANE, "pointerdown", 0, 0);+ pointer(PLANE, "pointerup", 0, 0);+ });+ expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff");++ await echo("#ffffff");+ expect(slider(HUE).getAttribute("aria-valuenow")).toBe("10");+ });+});diff --git a/apps/web/src/components/settings/colorPickers.test.tsx b/apps/web/src/components/settings/colorPickers.test.tsxdeleted file mode 100644index 7d4eae739c4..00000000000--- a/apps/web/src/components/settings/colorPickers.test.tsx+++ /dev/null@@ -1,275 +0,0 @@-import { act, type ReactNode, type ReactElement } from "react";-import { create, type ReactTestRenderer } from "react-test-renderer";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";--vi.mock("../ui/popover", () => ({- Popover: ({ children }: { children: ReactNode }) => children,- PopoverPopup: ({ children }: { children: ReactNode }) => children,- PopoverTrigger: () => null,- PopoverClose: ({ render }: { render: ReactElement }) => render,-}));-vi.mock("../ui/tooltip", () => ({- Tooltip: ({ children }: { children: ReactNode }) => children,- TooltipTrigger: ({ render }: { render: ReactElement }) => render,- TooltipPopup: () => null,-}));--import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";-import { ThemeColorField } from "./ThemeColorPicker";--let renderer: ReactTestRenderer | undefined;-let nextFrameId = 0;-const frames = new Map<number, FrameRequestCallback>();--beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {- frames.set(++nextFrameId, callback);- return nextFrameId;- });- vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));-});--afterEach(async () => {- await act(async () => renderer?.unmount());- renderer = undefined;- frames.clear();- vi.useRealTimers();- vi.unstubAllGlobals();-});--function slider(label: string) {- return renderer!.root.find(- (node) =>- (node.props.role === "slider" || node.props.type === "range") &&- node.props["aria-label"] === label,- );-}--function plane(label: string) {- return renderer!.root.findByProps({ role: "group", "aria-label": label });-}--async function key(label: string, key: string, shiftKey = false) {- const preventDefault = vi.fn();- await act(async () => slider(label).props.onKeyDown({ key, shiftKey, preventDefault }));- return preventDefault;-}--function pointer(clientX: number, clientY = 0, pointerId = 1) {- return {- button: 0,- clientX,- clientY,- pointerId,- currentTarget: {- focus: vi.fn(),- setPointerCapture: vi.fn(),- getBoundingClientRect: () => ({ left: 0, top: 0, width: 100, height: 100 }),- },- };-}--async function frame() {- await act(async () => {- const pending = [...frames.values()];- frames.clear();- for (const callback of pending) callback(0);- });-}--describe("shared color controls in settings", () => {- it("adjusts each provider color axis independently and reports the value being changed", async () => {- const onCommit = vi.fn();- await act(async () => {- renderer = create(- <ProviderAccentColorPicker displayName="Codex" value="#ff0000" onCommit={onCommit} />,- );- });- const hue = "Accent color hue";- const saturation = "Accent color saturation";- const brightness = "Accent color brightness";- expect(await key(hue, "ArrowLeft")).toHaveBeenCalledOnce();- expect(slider(hue).props["aria-valuenow"]).toBe(359);- await key(hue, "ArrowRight");- expect(onCommit).toHaveBeenLastCalledWith("#ff0000");- await key(saturation, "ArrowRight", true);- await key(brightness, "ArrowUp", true);- expect(onCommit).toHaveBeenLastCalledWith("#ff0000");- await key(brightness, "ArrowDown", true);- expect(onCommit).toHaveBeenLastCalledWith("#e60000");- expect(slider(brightness).props.value).toBe(90);- expect(slider(brightness).props["aria-valuetext"]).toBe("90%");- expect(slider(saturation).props.value).toBe(100);- await key(saturation, "ArrowDown", true);- expect(onCommit).toHaveBeenLastCalledWith("#e61717");- expect(slider(saturation).props.value).toBe(90);- expect(slider(saturation).props["aria-valuetext"]).toBe("90%");- await key(saturation, "ArrowUp", true);- expect(onCommit).toHaveBeenLastCalledWith("#e60000");- await key(brightness, "ArrowLeft", true);- expect(onCommit).toHaveBeenLastCalledWith("#cc0000");- await key(brightness, "ArrowRight", true);- expect(onCommit).toHaveBeenLastCalledWith("#e60000");- onCommit.mockClear();- expect(await key(saturation, "Tab")).not.toHaveBeenCalled();- expect(await key(brightness, "Tab")).not.toHaveBeenCalled();- expect(onCommit).not.toHaveBeenCalled();- });-- it("supports Home/End and clamps each axis without changing the other", async () => {- const onCommit = vi.fn();- await act(async () => {- renderer = create(- <ProviderAccentColorPicker displayName="Codex" value="#ff0000" onCommit={onCommit} />,- );- });- const saturation = "Accent color saturation";- const brightness = "Accent color brightness";- await key(saturation, "Home");- await key(saturation, "ArrowLeft");- expect(slider(saturation).props.value).toBe(0);- expect(onCommit).toHaveBeenLastCalledWith("#ffffff");- await key(brightness, "Home");- await key(brightness, "ArrowDown");- expect(slider(brightness).props.value).toBe(0);- expect(onCommit).toHaveBeenLastCalledWith("#000000");- await key(saturation, "End");- expect(slider(saturation).props.value).toBe(100);- expect(slider(brightness).props.value).toBe(0);- await key(brightness, "End");- await key(brightness, "ArrowUp");- expect(onCommit).toHaveBeenLastCalledWith("#ff0000");- await key(saturation, "ArrowLeft");- expect(slider(saturation).props.value).toBe(98);- expect(onCommit).toHaveBeenLastCalledWith("#ff0505");- });-- it("persists independent native range changes through theme batching with alpha", async () => {- const onChange = vi.fn();- await act(async () => {- renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);- });- const saturation = "Accent color saturation";- const brightness = "Accent color brightness";- await act(async () =>- slider(saturation).props.onChange({ currentTarget: { valueAsNumber: 50 } }),- );- await act(async () =>- slider(brightness).props.onChange({ currentTarget: { valueAsNumber: 50 } }),- );- expect(onChange).not.toHaveBeenCalled();- expect(frames.size).toBe(1);- await frame();- expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#80404080");- await key(brightness, "ArrowDown", true);- await frame();- expect(onChange).toHaveBeenLastCalledWith("accent", "#66333380");- expect(slider(saturation).props.value).toBe(50);- });-- it("batches theme drag updates and flushes the final color with alpha on pointer release", async () => {- const onChange = vi.fn();- await act(async () => {- renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);- });- const hue = "Accent color hue";- await act(async () => slider(hue).props.onPointerDown(pointer(25)));- await act(async () => slider(hue).props.onPointerMove(pointer(50)));- expect(onChange).not.toHaveBeenCalled();- expect(frames.size).toBe(1);- await act(async () => slider(hue).props.onPointerMove(pointer(75, 0, 2)));- await act(async () => slider(hue).props.onPointerUp(pointer(75, 0, 2)));- expect(onChange).not.toHaveBeenCalled();- await act(async () => slider(hue).props.onPointerUp(pointer(50)));- expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#00ffff80");- await act(async () => slider(hue).props.onLostPointerCapture(pointer(50)));- await frame();- expect(onChange).toHaveBeenCalledTimes(1);- });-- it("clamps out-of-bounds drags and flushes theme changes on cancellation and unmount", async () => {- const onChange = vi.fn();- await act(async () => {- renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);- });- const planeLabel = "Accent color saturation and brightness";- await act(async () => plane(planeLabel).props.onPointerDown(pointer(-50, -50)));- await act(async () => plane(planeLabel).props.onPointerCancel(pointer(-50, -50)));- expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff80");- await act(async () => plane(planeLabel).props.onPointerDown(pointer(150, 150)));- await act(async () => renderer!.unmount());- renderer = undefined;- expect(onChange).toHaveBeenLastCalledWith("accent", "#00000080");- expect(frames.size).toBe(0);- });-- it("preserves the selected hue when a grey color is echoed back from theme settings", async () => {- const onChange = vi.fn();- const render = (value: string) => (- <ThemeColorField role="accent" value={value} onChange={onChange} />- );- await act(async () => {- renderer = create(render("#ff0000"));- });- const hue = "Accent color hue";- const planeLabel = "Accent color saturation and brightness";- await key(hue, "ArrowRight", true);- await act(async () => plane(planeLabel).props.onPointerDown(pointer(0, 0)));- await frame();- expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff");- await act(async () => renderer!.update(render("#ffffff")));- expect(slider(hue).props["aria-valuenow"]).toBe(10);- });-- it("adds an accent only after choosing one and clears it back to no accent", async () => {- const onCommit = vi.fn();- await act(async () => {- renderer = create(- <ProviderAccentColorPicker displayName="Codex" value={undefined} onCommit={onCommit} />,- );- });- const clearButtons = () =>- renderer!.root.findAll(- (node) =>- node.type === "button" &&- Array.isArray(node.props.children) &&- node.props.children.includes("Clear color"),- );- expect(onCommit).not.toHaveBeenCalled();- expect(clearButtons()).toHaveLength(0);- await key("Accent color hue", "ArrowRight", true);- expect(onCommit).toHaveBeenCalledOnce();- expect(clearButtons()).toHaveLength(1);- await act(async () => clearButtons()[0]!.props.onClick());- expect(onCommit).toHaveBeenLastCalledWith("");- expect(clearButtons()).toHaveLength(0);- });-- it("keeps provider debounce at the consumer and commits pending color on unmount", async () => {- vi.useFakeTimers();- const onCommit = vi.fn();- await act(async () => {- renderer = create(- <ProviderAccentColorPicker- displayName="Codex"- value="#ff0000"- onCommit={onCommit}- commitDelayMs={250}- />,- );- });- const hue = "Accent color hue";- await key(hue, "ArrowRight", true);- await key(hue, "ArrowRight", true);- expect(onCommit).not.toHaveBeenCalled();- await act(async () => vi.advanceTimersByTime(250));- expect(onCommit).toHaveBeenCalledExactlyOnceWith("#ff5500");- await key(hue, "ArrowRight", true);- await act(async () => renderer!.unmount());- renderer = undefined;- expect(onCommit).toHaveBeenLastCalledWith("#ff8000");- await act(async () => vi.advanceTimersByTime(250));- expect(onCommit).toHaveBeenCalledTimes(2);- });-});diff --git a/apps/web/src/components/settings/settingsLayout.browser.test.tsx b/apps/web/src/components/settings/settingsLayout.browser.test.tsxnew file mode 100644index 00000000000..565fcb278c0--- /dev/null+++ b/apps/web/src/components/settings/settingsLayout.browser.test.tsx@@ -0,0 +1,68 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import { scrollToSettingsTarget } from "./settingsLayout";++const PULSE = "settings-search-target-pulse";++afterEach(() => {+ document.body.replaceChildren();+ vi.restoreAllMocks();+});++function mount(html: string) {+ document.body.innerHTML = html;+ return vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});+}++function reduceMotion(matches: boolean) {+ vi.spyOn(window, "matchMedia").mockReturnValue({ matches } as MediaQueryList);+}++describe("settings search targets", () => {+ it("scrolls a section's header into view, focuses the section, and pulses until blur", () => {+ reduceMotion(false);+ const scrollIntoView = mount(+ `<section id="providers" tabindex="-1"><h2>Providers</h2><p>Body</p></section>`,+ );+ const section = document.getElementById("providers")!;++ expect(scrollToSettingsTarget("providers")).toBe(true);+ expect(scrollIntoView).toHaveBeenCalledOnce();+ expect(scrollIntoView.mock.contexts[0]).toBe(section.querySelector("h2"));+ expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" });+ expect(document.activeElement).toBe(section);+ expect(section.classList.contains(PULSE)).toBe(true);++ section.blur();+ expect(section.classList.contains(PULSE)).toBe(false);+ });++ it("restarts the pulse when the same destination is chosen again", () => {+ reduceMotion(false);+ mount(`<div id="word-wrap" tabindex="-1" class="${PULSE}"></div>`);+ const target = document.getElementById("word-wrap")!;+ const observer = new MutationObserver(() => {});+ observer.observe(target, { attributeFilter: ["class"], attributeOldValue: true });++ scrollToSettingsTarget("word-wrap");+ const previousClasses = observer.takeRecords().map((record) => record.oldValue);+ expect(previousClasses).toEqual([PULSE, ""]);+ expect(target.classList.contains(PULSE)).toBe(true);+ });++ it("does not animate the destination when reduced motion is requested", () => {+ reduceMotion(true);+ const scrollIntoView = mount(`<div id="word-wrap" tabindex="-1"></div>`);+ const target = document.getElementById("word-wrap")!;++ expect(scrollToSettingsTarget("word-wrap")).toBe(true);+ expect(scrollIntoView.mock.contexts[0]).toBe(target);+ expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "auto", block: "center" });+ expect(document.activeElement).toBe(target);+ expect(target.classList.contains(PULSE)).toBe(false);+ });++ it("leaves not-yet-mounted destinations to their mount lifecycle", () => {+ expect(scrollToSettingsTarget("archive")).toBe(false);+ });+});diff --git a/apps/web/src/components/settings/settingsLayout.test.tsx b/apps/web/src/components/settings/settingsLayout.test.tsxdeleted file mode 100644index 4195a359d1b..00000000000--- a/apps/web/src/components/settings/settingsLayout.test.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { renderToStaticMarkup } from "react-dom/server";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--import { scrollToSettingsTarget, SettingsRow, SettingsUnavailableGroup } from "./settingsLayout";--afterEach(() => {- vi.unstubAllGlobals();-});--describe("unavailable settings", () => {- it("groups disabled controls under one reason", () => {- const markup = renderToStaticMarkup(- <SettingsUnavailableGroup message="Only available in the desktop app.">- <SettingsRow title="Window capture" description="Capture a window." />- </SettingsUnavailableGroup>,- );-- expect(markup).toContain("Only available in the desktop app.");- expect(markup).toContain("border-border/60");- expect(markup).toContain("[&_h3]:opacity-64");- });-});--describe("settings search targets", () => {- it("scrolls directly to a section header and restarts the destination pulse", () => {- const sectionScrollIntoView = vi.fn();- const headerScrollIntoView = vi.fn();- const focus = vi.fn();- const remove = vi.fn();- const add = vi.fn();- const addEventListener = vi.fn();- const target = {- tagName: "SECTION",- firstElementChild: { scrollIntoView: headerScrollIntoView },- scrollIntoView: sectionScrollIntoView,- focus,- classList: { remove, add },- addEventListener,- offsetWidth: 100,- } as unknown as HTMLElement;- vi.stubGlobal("document", {- getElementById: vi.fn(() => target),- });- vi.stubGlobal("window", {- matchMedia: vi.fn(() => ({ matches: false })),- });-- expect(scrollToSettingsTarget("providers")).toBe(true);- expect(headerScrollIntoView).toHaveBeenCalledWith({- behavior: "smooth",- block: "center",- });- expect(sectionScrollIntoView).not.toHaveBeenCalled();- expect(focus).toHaveBeenCalledWith({ preventScroll: true });- expect(remove).toHaveBeenCalledWith("settings-search-target-pulse");- expect(add).toHaveBeenCalledWith("settings-search-target-pulse");- expect(addEventListener).toHaveBeenCalledWith("blur", expect.any(Function), { once: true });- });-- it("does not animate the destination when reduced motion is requested", () => {- const scrollIntoView = vi.fn();- const focus = vi.fn();- const remove = vi.fn();- const add = vi.fn();- const target = {- tagName: "DIV",- firstElementChild: null,- scrollIntoView,- focus,- classList: { remove, add },- offsetWidth: 100,- } as unknown as HTMLElement;- vi.stubGlobal("document", {- getElementById: vi.fn(() => target),- });- vi.stubGlobal("window", {- matchMedia: vi.fn(() => ({ matches: true })),- });-- expect(scrollToSettingsTarget("word-wrap")).toBe(true);- expect(scrollIntoView).toHaveBeenCalledWith({- behavior: "auto",- block: "center",- });- expect(focus).toHaveBeenCalledWith({ preventScroll: true });- expect(remove).toHaveBeenCalledWith("settings-search-target-pulse");- expect(add).not.toHaveBeenCalled();- });-- it("leaves not-yet-mounted destinations to their mount lifecycle", () => {- vi.stubGlobal("document", {- getElementById: vi.fn(() => null),- });-- expect(scrollToSettingsTarget("archive")).toBe(false);- });-});diff --git a/apps/web/src/components/settings/useProjectScriptSettings.test.tsx b/apps/web/src/components/settings/useProjectScriptSettings.browser.test.tsxsimilarity index 67%rename from apps/web/src/components/settings/useProjectScriptSettings.test.tsxrename to apps/web/src/components/settings/useProjectScriptSettings.browser.test.tsxindex efca3bb8640..46b07ef317d 100644--- a/apps/web/src/components/settings/useProjectScriptSettings.test.tsx+++ b/apps/web/src/components/settings/useProjectScriptSettings.browser.test.tsx@@ -6,7 +6,8 @@ import {type ResolvedKeybindingsConfig,} from "@t3tools/contracts";import { AsyncResult } from "effect/reactivity";-import { act, create, type ReactTestRenderer } from "react-test-renderer";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import type { NewProjectScriptInput } from "../projectScriptEditor";@@ -17,20 +18,30 @@ const commands = vi.hoisted(() => ({removeKeybinding: vi.fn(),}));-vi.mock("../../env", () => ({ isElectron: false }));-vi.mock("../../state/session", () => ({ readEnvironmentScope: () => true }));-vi.mock("../../state/entities", () => ({ useProjects: () => [] }));-vi.mock("../../state/server", () => ({- serverEnvironment: {- updateSettings: "updateSettings",- upsertKeybinding: "upsertKeybinding",- removeKeybinding: "removeKeybinding",- },+vi.mock(import("../../state/session"), async (original) => ({+ ...(await original()),+ readEnvironmentScope: () => true,+}));+vi.mock(import("../../state/entities"), async (original) => ({+ ...(await original()),+ useProjects: () => [],}));-vi.mock("../../state/use-atom-command", () => ({- useAtomCommand: (command: keyof typeof commands) => commands[command],+vi.mock(import("../../state/server"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ serverEnvironment: {+ ...actual.serverEnvironment,+ updateSettings: "updateSettings",+ upsertKeybinding: "upsertKeybinding",+ removeKeybinding: "removeKeybinding",+ } as unknown as typeof actual.serverEnvironment,+ };+});+vi.mock(import("../../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: ((command: keyof typeof commands) => commands[command]) as never,}));-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));import { useProjectScriptSettings } from "./useProjectScriptSettings";@@ -86,13 +97,14 @@ function Probe(props: {return null;}-let renderer: ReactTestRenderer | undefined;+let root: Root;+let container: HTMLDivElement;-function renderSettings(keybindings: ResolvedKeybindingsConfig) {+async function renderSettings(keybindings: ResolvedKeybindingsConfig) {let settings: ProjectScriptSettings | undefined;- act(() => {- renderer = create(<Probe keybindings={keybindings} onResult={(next) => (settings = next)} />);- });+ await act(async () =>+ root.render(<Probe keybindings={keybindings} onResult={(next) => (settings = next)} />),+ );return settings!;}@@ -110,17 +122,20 @@ beforeEach(() => {for (const command of Object.values(commands)) {command.mockResolvedValue(AsyncResult.success(undefined));}+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);});-afterEach(() => {- act(() => renderer?.unmount());- renderer = undefined;+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();vi.unstubAllGlobals();});-describe("useProjectScriptSettings in a browser client", () => {+describe("useProjectScriptSettings", () => {it("saves a recorded action shortcut", async () => {- const { submit } = renderSettings([]);+ const { submit } = await renderSettings([]);const result = await submitInAct(submit, "mod+shift+k");@@ -132,7 +147,7 @@ describe("useProjectScriptSettings in a browser client", () => {});it("removes a cleared action shortcut", async () => {- const { submit } = renderSettings(lintBinding);+ const { submit } = await renderSettings(lintBinding);const result = await submitInAct(submit, null);