From c09f491b37793fabf15a39ad0e10dddde276a08b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 18 Jun 2026 00:00:47 -0700 Subject: [PATCH] nuke browser tests cause codex just gets caught up in them --- .github/workflows/ci.yml | 44 - apps/web/package.json | 8 +- .../src/components/ChatMarkdown.browser.tsx | 918 --- apps/web/src/components/ChatView.browser.tsx | 7142 ----------------- .../src/components/DiffPanelShell.browser.tsx | 22 - .../components/Sidebar.dblclick.browser.tsx | 266 - .../ThreadTerminalDrawer.browser.tsx | 408 - .../CompactComposerControlsMenu.browser.tsx | 326 - .../ComposerPendingReviewComments.browser.tsx | 41 - .../chat/MessagesTimeline.browser.tsx | 481 -- .../chat/ProviderModelPicker.browser.tsx | 1258 --- .../clerk/DesktopClerkSignIn.browser.tsx | 71 - .../RelayClientInstallDialog.browser.tsx | 47 - .../diffs/AnnotatableFileDiff.browser.tsx | 122 - .../files/FilePreviewPanel.browser.tsx | 168 - .../preview/PreviewChromeRow.browser.tsx | 85 - .../settings/SettingsPanels.browser.tsx | 2027 ----- apps/web/test/authHttpHandlers.ts | 103 - apps/web/test/environmentHttpTest.ts | 136 - apps/web/test/wsRpcHarness.ts | 188 - apps/web/vite.config.ts | 27 +- pnpm-lock.yaml | 238 - 22 files changed, 3 insertions(+), 14123 deletions(-) delete mode 100644 apps/web/src/components/ChatMarkdown.browser.tsx delete mode 100644 apps/web/src/components/ChatView.browser.tsx delete mode 100644 apps/web/src/components/DiffPanelShell.browser.tsx delete mode 100644 apps/web/src/components/Sidebar.dblclick.browser.tsx delete mode 100644 apps/web/src/components/ThreadTerminalDrawer.browser.tsx delete mode 100644 apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx delete mode 100644 apps/web/src/components/chat/ComposerPendingReviewComments.browser.tsx delete mode 100644 apps/web/src/components/chat/MessagesTimeline.browser.tsx delete mode 100644 apps/web/src/components/chat/ProviderModelPicker.browser.tsx delete mode 100644 apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx delete mode 100644 apps/web/src/components/cloud/RelayClientInstallDialog.browser.tsx delete mode 100644 apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx delete mode 100644 apps/web/src/components/files/FilePreviewPanel.browser.tsx delete mode 100644 apps/web/src/components/preview/PreviewChromeRow.browser.tsx delete mode 100644 apps/web/src/components/settings/SettingsPanels.browser.tsx delete mode 100644 apps/web/test/authHttpHandlers.ts delete mode 100644 apps/web/test/environmentHttpTest.ts delete mode 100644 apps/web/test/wsRpcHarness.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94a130c25f..eaf8fc367c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,50 +60,6 @@ jobs: - name: Test run: vp run test - test_browser: - name: Test Browser - runs-on: blacksmith-8vcpu-ubuntu-2404 - timeout-minutes: 10 - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 - with: - node-version-file: package.json - cache: true - run-install: true - - - name: Cache Playwright browsers - uses: actions/cache@v5 - with: - path: ~/.cache/ms-playwright - key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }} - restore-keys: | - ${{ runner.os }}-playwright- - - - name: Install browser test runtime - run: vp run --filter @t3tools/web test:browser:install - - - name: Browser test / Chat view - working-directory: apps/web - run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx - - - name: Browser test / Chat markdown - working-directory: apps/web - run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx - - - name: Browser test / Components - working-directory: apps/web - run: | - vp test run --mode browser --browser=chromium \ - src/components/ThreadTerminalDrawer.browser.tsx \ - src/components/chat/MessagesTimeline.browser.tsx \ - src/components/chat/ProviderModelPicker.browser.tsx \ - src/components/chat/CompactComposerControlsMenu.browser.tsx \ - src/components/settings/SettingsPanels.browser.tsx - mobile_native_static_analysis: name: Mobile Native Static Analysis runs-on: blacksmith-12vcpu-macos-26 diff --git a/apps/web/package.json b/apps/web/package.json index d6751c7348..f72926e542 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,9 +8,7 @@ "build": "vp build", "preview": "vp preview", "typecheck": "tsgo --noEmit", - "test": "vp test run --passWithNoTests --project unit", - "test:browser": "vp test run --project browser", - "test:browser:install": "playwright install --with-deps chromium" + "test": "vp test run --passWithNoTests --project unit" }, "dependencies": { "@base-ui/react": "^1.4.1", @@ -64,10 +62,8 @@ "@vitejs/plugin-react": "^6.0.0", "babel-plugin-react-compiler": "1.0.0", "msw": "2.12.11", - "playwright": "^1.58.2", "tailwindcss": "^4.0.0", "vite": "catalog:", - "vite-plus": "catalog:", - "vitest-browser-react": "^2.0.5" + "vite-plus": "catalog:" } } diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx deleted file mode 100644 index d2c4e75286..0000000000 --- a/apps/web/src/components/ChatMarkdown.browser.tsx +++ /dev/null @@ -1,918 +0,0 @@ -import "../index.css"; - -import { AsyncResult } from "effect/unstable/reactivity"; -import { page } from "vite-plus/test/browser"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -const { - contextMenuShowMock, - openFileInPreviewMock, - openInPreferredEditorMock, - openUrlInPreviewMock, - readLocalApiMock, -} = vi.hoisted(() => ({ - contextMenuShowMock: vi.fn(), - openFileInPreviewMock: vi.fn(), - openInPreferredEditorMock: vi.fn(), - openUrlInPreviewMock: vi.fn(), - readLocalApiMock: vi.fn(() => ({ - contextMenu: { show: contextMenuShowMock }, - server: { getConfig: vi.fn(async () => ({ availableEditors: ["vscode"] })) }, - shell: { - openExternal: vi.fn(async () => undefined), - openInEditor: vi.fn(async () => undefined), - }, - })), -})); - -vi.mock("../editorPreferences", () => ({ - useOpenInPreferredEditor: () => openInPreferredEditorMock, -})); - -vi.mock("../localApi", () => ({ - ensureLocalApi: vi.fn(() => { - throw new Error("ensureLocalApi not implemented in browser test"); - }), - readLocalApi: readLocalApiMock, -})); - -vi.mock("../previewStateStore", async (importOriginal) => ({ - ...(await importOriginal()), - isPreviewSupportedInRuntime: () => true, -})); - -vi.mock("../state/session", async (importOriginal) => ({ - ...(await importOriginal()), - usePreparedConnection: () => ({ - _tag: "Some", - value: { httpBaseUrl: "http://localhost:3000" }, - }), -})); - -vi.mock("../browser/openFileInPreview", async (importOriginal) => ({ - ...(await importOriginal()), - openFileInPreview: openFileInPreviewMock, - openUrlInPreview: openUrlInPreviewMock, -})); - -import ChatMarkdown from "./ChatMarkdown"; -import { serializeTableElementToCsv, serializeTableElementToMarkdown } from "../markdown-clipboard"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; - -const threadRef = { - environmentId: EnvironmentId.make("environment-test"), - threadId: ThreadId.make("thread-test"), -}; - -describe("ChatMarkdown", () => { - beforeEach(() => { - openInPreferredEditorMock.mockResolvedValue(AsyncResult.success("vscode")); - openFileInPreviewMock.mockResolvedValue(AsyncResult.success(undefined)); - openUrlInPreviewMock.mockResolvedValue(AsyncResult.success(undefined)); - }); - - afterEach(() => { - openInPreferredEditorMock.mockClear(); - openFileInPreviewMock.mockClear(); - openUrlInPreviewMock.mockClear(); - contextMenuShowMock.mockReset(); - readLocalApiMock.mockClear(); - useRightPanelStore.setState({ byThreadKey: {} }); - localStorage.clear(); - document.body.innerHTML = ""; - }); - - it("makes task-list checkboxes interactive when a change handler is provided", async () => { - const onTaskListChange = vi.fn(); - const screen = await render( - , - ); - - try { - const checkbox = page.getByRole("checkbox", { name: "Toggle task" }); - await expect.element(checkbox).not.toBeDisabled(); - await checkbox.click(); - expect(onTaskListChange).toHaveBeenCalledWith({ markerOffset: 2, checked: true }); - } finally { - await screen.unmount(); - } - }); - - it("rewrites file uri hrefs into direct paths before rendering", async () => { - const filePath = - "/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts"; - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "PermissionRule.ts" }); - await expect.element(link).toBeInTheDocument(); - await expect.element(link).toHaveAttribute("href", filePath); - - await link.click(); - - await vi.waitFor(() => { - expect(openInPreferredEditorMock).toHaveBeenCalledWith(filePath); - }); - } finally { - await screen.unmount(); - } - }); - - it("keeps line anchors working after rewriting file uri hrefs", async () => { - const filePath = - "/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts"; - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "PermissionRule.ts · L1" }); - await expect.element(link).toBeInTheDocument(); - await expect.element(link).toHaveAttribute("href", `${filePath}:1`); - - await link.click(); - - await vi.waitFor(() => { - expect(openInPreferredEditorMock).toHaveBeenCalledWith(`${filePath}:1`); - }); - } finally { - await screen.unmount(); - } - }); - - it("shows column information inline when present", async () => { - const filePath = - "/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts"; - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "PermissionRule.ts · L1:C7" }); - await expect.element(link).toBeInTheDocument(); - await expect.element(link).toHaveAttribute("href", `${filePath}:1:7`); - - await link.click(); - - await vi.waitFor(() => { - expect(openInPreferredEditorMock).toHaveBeenCalledWith(`${filePath}:1:7`); - }); - } finally { - await screen.unmount(); - } - }); - - it("disambiguates duplicate file basenames inline", async () => { - const firstPath = "/Users/yashsingh/p/t3code/apps/web/src/components/chat/MessagesTimeline.tsx"; - const secondPath = "/Users/yashsingh/p/t3code/apps/web/src/components/MessagesTimeline.tsx"; - const screen = await render( - , - ); - - try { - await expect - .element(page.getByRole("link", { name: "MessagesTimeline.tsx · components/chat" })) - .toBeInTheDocument(); - await expect - .element(page.getByRole("link", { name: "MessagesTimeline.tsx · src/components" })) - .toBeInTheDocument(); - } finally { - await screen.unmount(); - } - }); - - it("keeps normal web links unchanged", async () => { - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "OpenAI" }); - await expect.element(link).toBeInTheDocument(); - await expect.element(link).toHaveAttribute("href", "https://openai.com/docs"); - await expect.element(link).toHaveAttribute("target", "_blank"); - const favicon = link.element().querySelector(".chat-markdown-link-favicon"); - const leading = link.element().querySelector(".chat-markdown-link-leading"); - expect(favicon).not.toBeNull(); - expect(leading).not.toBeNull(); - expect(leading?.contains(favicon)).toBe(true); - expect(getComputedStyle(leading!).display).toBe("inline"); - expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap"); - expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline"); - expect(leading?.textContent).toBe("O"); - expect(link.element().textContent).toBe("OpenAI"); - expect(getComputedStyle(link.element()).textDecorationLine).toBe("none"); - expect(link.element().querySelector("img, svg")?.getBoundingClientRect().width).toBe(14); - await link.hover(); - expect(getComputedStyle(link.element()).backgroundImage).not.toBe("none"); - await expect.element(page.getByText("https://openai.com/docs")).toBeVisible(); - } finally { - await screen.unmount(); - } - }); - - it("opens web links in the integrated browser from the context menu", async () => { - contextMenuShowMock.mockResolvedValue("open-in-browser"); - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "OpenAI" }).element(); - link.dispatchEvent( - new MouseEvent("contextmenu", { - bubbles: true, - cancelable: true, - clientX: 12, - clientY: 24, - }), - ); - - await vi.waitFor(() => { - expect(contextMenuShowMock).toHaveBeenCalled(); - expect(openUrlInPreviewMock).toHaveBeenCalledWith({ - threadRef, - url: "https://openai.com/docs", - openPreview: expect.any(Function), - }); - }); - } finally { - await screen.unmount(); - } - }); - - it("offers integrated browser opening for HTML file links", async () => { - contextMenuShowMock.mockResolvedValue("open-in-browser"); - const filePath = "/repo/project/report.html"; - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "report.html" }).element(); - link.dispatchEvent( - new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 4, clientY: 8 }), - ); - - await vi.waitFor(() => { - expect(contextMenuShowMock).toHaveBeenCalledWith( - expect.arrayContaining([ - expect.objectContaining({ - id: "open-in-browser", - label: "Open in integrated browser", - }), - ]), - { x: 4, y: 8 }, - ); - expect(openFileInPreviewMock).toHaveBeenCalledWith({ - threadRef, - filePath, - httpBaseUrl: "http://localhost:3000", - createAssetUrl: expect.any(Function), - openPreview: expect.any(Function), - }); - }); - } finally { - await screen.unmount(); - } - }); - - it("opens code file links in the right-panel file preview", async () => { - const screen = await render( - , - ); - - try { - await page.getByRole("link", { name: "ChatMarkdown.tsx · L978" }).click(); - - await vi.waitFor(() => { - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef), - ).toMatchObject({ - isOpen: true, - activeSurfaceId: "file:apps/web/src/components/ChatMarkdown.tsx", - surfaces: [ - expect.objectContaining({ - relativePath: "apps/web/src/components/ChatMarkdown.tsx", - revealLine: 978, - revealRequestId: 1, - }), - ], - }); - expect(openInPreferredEditorMock).not.toHaveBeenCalled(); - expect(openFileInPreviewMock).not.toHaveBeenCalled(); - }); - } finally { - await screen.unmount(); - } - }); - - it("opens HTML and PDF file links in the integrated browser preview", async () => { - const screen = await render( - , - ); - - try { - await page.getByRole("link", { name: "report.html" }).click(); - await page.getByRole("link", { name: "report.pdf" }).click(); - - await vi.waitFor(() => { - expect(openFileInPreviewMock).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ - threadRef, - filePath: "/repo/project/report.html", - }), - ); - expect(openFileInPreviewMock).toHaveBeenNthCalledWith( - 2, - expect.objectContaining({ - threadRef, - filePath: "/repo/project/report.pdf", - }), - ); - expect(openInPreferredEditorMock).not.toHaveBeenCalled(); - }); - } finally { - await screen.unmount(); - } - }); - - it("keeps opening file links in the editor from the context menu", async () => { - contextMenuShowMock.mockResolvedValue("open"); - const filePath = "/repo/project/src/index.ts"; - const screen = await render( - , - ); - - try { - page - .getByRole("link", { name: "index.ts" }) - .element() - .dispatchEvent( - new MouseEvent("contextmenu", { - bubbles: true, - cancelable: true, - clientX: 4, - clientY: 8, - }), - ); - - await vi.waitFor(() => { - expect(openInPreferredEditorMock).toHaveBeenCalledWith(filePath); - }); - } finally { - await screen.unmount(); - } - }); - - it("keeps a favicon with the leading segment of a wrapping URL", async () => { - const url = "https://github.com/pingdotgg/t3code/pull/3017/changes"; - const screen = await render( -
- -
, - ); - - try { - const link = page.getByRole("link", { name: url }); - const leading = link.element().querySelector(".chat-markdown-link-leading"); - const favicon = link.element().querySelector(".chat-markdown-link-favicon"); - expect(leading).not.toBeNull(); - expect(favicon).not.toBeNull(); - expect(leading?.contains(favicon)).toBe(true); - expect(leading?.textContent).toBe("https://"); - expect(getComputedStyle(leading!).display).toBe("inline"); - expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap"); - expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline"); - expect(link.element().textContent).toBe(url); - expect(link.element().querySelectorAll("wbr").length).toBeGreaterThan(0); - const markdownRoot = link.element().closest(".chat-markdown"); - expect(markdownRoot).not.toBeNull(); - expect(markdownRoot!.scrollWidth).toBeLessThanOrEqual(markdownRoot!.clientWidth); - } finally { - await screen.unmount(); - } - }); - - it("renders file links with the shared file tag chip treatment", async () => { - const screen = await render( - , - ); - - try { - const link = page.getByRole("link", { name: "package.json" }); - await expect.element(link).toHaveClass(/chat-markdown-file-link/); - const element = document.querySelector(".chat-markdown-file-link"); - expect(element?.querySelector("img, svg")).not.toBeNull(); - expect(getComputedStyle(element!).display).toBe("inline-flex"); - expect(getComputedStyle(element!).textDecorationLine).toBe("none"); - expect(getComputedStyle(element!).borderStyle).toBe("solid"); - expect(getComputedStyle(element!).userSelect).not.toBe("none"); - } finally { - await screen.unmount(); - } - }); - - it("renders sanitized details with the design-system collapsible", async () => { - const source = [ - "
", - "Expandable details section", - "", - "This content includes **formatted text**.", - "", - 'Safe inline HTML', - "", - "
", - ].join("\n"); - const screen = await render(); - - try { - const details = document.querySelector("[data-markdown-details]"); - const trigger = page.getByRole("button", { name: "Expandable details section" }); - expect(details).not.toBeNull(); - expect(details?.tagName).toBe("DIV"); - await expect.element(trigger).toHaveAttribute("aria-expanded", "true"); - expect(details?.querySelector("strong")?.textContent).toBe("formatted text"); - expect(details?.querySelector("script")).toBeNull(); - expect(details?.querySelector("[title]")).toBeNull(); - - await trigger.click(); - await expect.element(trigger).toHaveAttribute("aria-expanded", "false"); - await trigger.click(); - await expect.element(trigger).toHaveAttribute("aria-expanded", "true"); - } finally { - await screen.unmount(); - } - }); - - it("renders footnotes as same-document references", async () => { - const source = [ - "A claim with supporting context.[^context]", - "", - "[^context]: Supporting **footnote text**.", - ].join("\n"); - const screen = await render(); - - try { - const reference = document.querySelector( - '.chat-markdown a[data-footnote-ref=""]', - ); - const footnotes = document.querySelector( - ".chat-markdown section[data-footnotes]", - ); - expect(reference).not.toBeNull(); - expect(reference?.getAttribute("href")).toMatch(/^#user-content-fn-/); - expect(reference?.hasAttribute("target")).toBe(false); - expect(footnotes).not.toBeNull(); - expect(footnotes?.querySelector("strong")?.textContent).toBe("footnote text"); - expect(footnotes?.querySelector("a[data-footnote-backref]")?.target).toBe( - "", - ); - } finally { - await screen.unmount(); - } - }); - - it("navigates hash links within the clicked markdown message", async () => { - const source = [ - "A claim with supporting context.[^context]", - "", - "[^context]: Supporting footnote text.", - ].join("\n"); - const originalUrl = window.location.href; - const scrollIntoView = vi - .spyOn(HTMLElement.prototype, "scrollIntoView") - .mockImplementation(() => undefined); - const screen = await render( -
- - -
, - ); - - try { - const markdownRoots = document.querySelectorAll(".chat-markdown"); - const secondRoot = markdownRoots[1]; - const secondReference = - secondRoot?.querySelector('a[data-footnote-ref=""]'); - const secondFootnote = secondRoot?.querySelector( - "section[data-footnotes] li[id]", - ); - expect(secondReference).not.toBeNull(); - expect(secondFootnote).not.toBeNull(); - - secondReference?.click(); - - expect(scrollIntoView).toHaveBeenCalledTimes(1); - expect(scrollIntoView.mock.instances[0]).toBe(secondFootnote); - expect(window.location.hash).toBe(secondReference?.hash); - - const secondBackref = secondRoot?.querySelector( - "a[data-footnote-backref]", - ); - expect(secondBackref).not.toBeNull(); - secondBackref?.click(); - - const secondReferenceTarget = secondReference?.closest("[id]"); - expect(scrollIntoView).toHaveBeenCalledTimes(2); - expect(scrollIntoView.mock.instances[1]).toBe(secondReferenceTarget); - } finally { - scrollIntoView.mockRestore(); - window.history.replaceState(window.history.state, "", originalUrl); - await screen.unmount(); - } - }); - - describe("code block chrome", () => { - it("shows icon-only language titles, text fallbacks, and filename overrides", async () => { - const source = [ - "```ts", - "const a = 1;", - "```", - "", - '```ts title="src/main.ts"', - "const b = 2;", - "```", - "", - "```text", - "plain", - "```", - ].join("\n"); - const screen = await render(); - - try { - const titles = [...document.querySelectorAll(".chat-markdown-codeblock-title")]; - expect(titles).toHaveLength(3); - - // Language with a known icon: icon XOR text — never the redundant pair. - const languageOnly = titles[0]!; - const hasIcon = languageOnly.querySelector("svg[data-pierre-icon]") != null; - const hasText = (languageOnly.textContent ?? "").includes("ts"); - expect(hasIcon || hasText).toBe(true); - expect(hasIcon && hasText).toBe(false); - if (hasIcon) { - const languageTrigger = page.getByLabelText("Language: ts").first(); - await languageTrigger.hover(); - await vi.waitFor(() => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip?.textContent).toContain("ts"); - }); - } - - // Explicit filename: text always shown. - expect(titles[1]!.textContent).toBe("src/main.ts"); - - // Unknown language: no icon attempt, text label. - expect(titles[2]!.querySelector("svg[data-pierre-icon]")).toBeNull(); - expect(titles[2]!.textContent).toBe("text"); - } finally { - await screen.unmount(); - } - }); - - it("toggles line wrapping per block", async () => { - const screen = await render( - , - ); - - try { - const block = document.querySelector(".chat-markdown-codeblock"); - expect(block?.getAttribute("data-wrap")).toBe("false"); - - const toggle = page.getByRole("button", { name: "Wrap lines" }); - await expect.element(toggle).not.toHaveAttribute("title"); - await toggle.hover(); - await vi.waitFor(() => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip?.textContent).toContain("Wrap lines"); - }); - await toggle.click(); - expect(block?.getAttribute("data-wrap")).toBe("true"); - - await page.getByRole("button", { name: "Disable line wrap" }).click(); - expect(block?.getAttribute("data-wrap")).toBe("false"); - } finally { - await screen.unmount(); - } - }); - }); - - it("scrolls wide tables horizontally instead of letter-wrapping cells", async () => { - const header = `| ${Array.from({ length: 8 }, (_, i) => `ColumnHeading${i}`).join(" | ")} |`; - const separator = `| ${Array.from({ length: 8 }, () => "---").join(" | ")} |`; - const row = `| ${Array.from({ length: 8 }, () => "averylongunbrokencellvalue@example-domain.com").join(" | ")} |`; - const screen = await render( - , - ); - - try { - const viewport = document.querySelector( - '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', - ); - expect(viewport).not.toBeNull(); - expect(viewport!.querySelector("table")).not.toBeNull(); - // Content exceeds the container — the scroll-fade viewport scrolls - // horizontally rather than squishing columns. - expect(viewport!.scrollWidth).toBeGreaterThan(viewport!.clientWidth); - // And cells keep their longest word intact instead of breaking mid-word. - const cell = viewport!.querySelector("td"); - expect(cell!.getBoundingClientRect().width).toBeGreaterThan(100); - } finally { - await screen.unmount(); - } - }); - - describe("table chrome", () => { - const longCell = - "This service has been experiencing intermittent latency spikes during peak traffic hours and the on-call team is investigating."; - - it("truncates cells by default and expands them from the footer toggle", async () => { - const source = ["| Name | Notes |", "| --- | --- |", `| api | ${longCell} |`].join("\n"); - const screen = await render(); - - try { - const container = document.querySelector(".chat-markdown-table-container"); - expect(container?.getAttribute("data-expanded")).toBe("false"); - - const noteCell = [...document.querySelectorAll(".chat-markdown td")].at(-1)!; - expect(getComputedStyle(noteCell).whiteSpace).toBe("nowrap"); - expect(noteCell.scrollWidth).toBeGreaterThan(noteCell.clientWidth); - - const expandButton = page.getByRole("button", { name: "Expand table cells" }); - await expect.element(expandButton).not.toHaveAttribute("title"); - await expandButton.hover(); - await vi.waitFor(() => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip?.textContent).toContain("Expand table cells"); - }); - await expandButton.click(); - expect(container?.getAttribute("data-expanded")).toBe("true"); - expect(getComputedStyle(noteCell).whiteSpace).not.toBe("nowrap"); - - await page.getByRole("button", { name: "Collapse table cells" }).click(); - expect(container?.getAttribute("data-expanded")).toBe("false"); - - const copyButton = page.getByRole("button", { name: "Copy table" }); - await expect.element(copyButton).not.toHaveAttribute("title"); - await copyButton.hover(); - await vi.waitFor(() => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip?.textContent).toContain("Copy table"); - }); - expect(document.querySelector(".chat-markdown [title]")).toBeNull(); - } finally { - await screen.unmount(); - } - }); - - it("retains column widths when cells expand", async () => { - const source = [ - "| ID | Owner | Status | Priority | Region | Summary | Long Description | Metrics | Payload | Notes |", - "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |", - '| 1001 | Ada Lovelace | Active | High | us-west-2 | Payment workflow migration | This cell has enough text to wrap across several lines when expanded without shrinking its column. | Requests: 128,440; Error rate: 0.04%; P95: 212ms | `{ "feature": "billing", "version": 3 }` | Needs post-release monitoring for 24 hours. |', - ].join("\n"); - const screen = await render(); - - try { - const viewport = document.querySelector( - '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', - )!; - const table = viewport.querySelector("table")!; - const collapsedWidths = [...table.querySelectorAll("thead th")].map( - (cell) => cell.getBoundingClientRect().width, - ); - expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth); - - await page.getByRole("button", { name: "Expand table cells" }).click(); - - const expandedWidths = [...table.querySelectorAll("thead th")].map( - (cell) => cell.getBoundingClientRect().width, - ); - expect(expandedWidths).toHaveLength(collapsedWidths.length); - expandedWidths.forEach((width, index) => { - expect(width).toBeGreaterThanOrEqual(collapsedWidths[index]! - 1); - }); - expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth); - } finally { - await screen.unmount(); - } - }); - - it("exports tables as markdown and csv", async () => { - const source = [ - "| Name | Count |", - "| --- | ---: |", - '| widget, "deluxe" | 2 |', - "| plain | 1 |", - ].join("\n"); - const screen = await render(); - - try { - const table = document.querySelector(".chat-markdown table")!; - expect(serializeTableElementToMarkdown(table)).toBe( - ["| Name | Count |", "| --- | ---: |", '| widget, "deluxe" | 2 |', "| plain | 1 |"].join( - "\n", - ), - ); - expect(serializeTableElementToCsv(table)).toBe( - ["Name,Count", '"widget, ""deluxe""",2', "plain,1"].join("\n"), - ); - } finally { - await screen.unmount(); - } - }); - }); - - describe("copying rendered markdown", () => { - function copySelectedMarkdown(): { text: string; html: string } { - const root = document.querySelector(".chat-markdown"); - if (!root) throw new Error("chat-markdown root not rendered"); - const selection = window.getSelection(); - if (!selection) throw new Error("selection unavailable"); - selection.removeAllRanges(); - const range = document.createRange(); - range.selectNodeContents(root); - selection.addRange(range); - - const clipboardData = new DataTransfer(); - root.dispatchEvent( - new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true }), - ); - selection.removeAllRanges(); - return { - text: clipboardData.getData("text/plain"), - html: clipboardData.getData("text/html"), - }; - } - - it("round-trips links, emphasis, and inline code", async () => { - const screen = await render( - , - ); - - try { - const { text, html } = copySelectedMarkdown(); - expect(text).toBe( - "Check out [Anthropic](https://anthropic.com), **bold**, *italic*, and `code`.", - ); - expect(html).toContain('href="https://anthropic.com"'); - } finally { - await screen.unmount(); - } - }); - - it("round-trips block structure: headings, lists, quotes, and fences", async () => { - const source = [ - "## Heading", - "", - "- first", - "- second", - " - nested", - "", - "1. one", - "2. two", - "", - "- [x] done", - "- [ ] todo", - "", - "> quoted", - "", - "```ts", - "const x = 1;", - "", - "const y = 2;", - "```", - ].join("\n"); - const screen = await render(); - - try { - const { text } = copySelectedMarkdown(); - expect(text).toBe(source); - } finally { - await screen.unmount(); - } - }); - - it("round-trips tables with alignment", async () => { - const source = ["| Name | Count |", "| --- | ---: |", "| a | 1 |", "| b | 2 |"].join("\n"); - const screen = await render(); - - try { - const { text } = copySelectedMarkdown(); - expect(text).toBe(source); - } finally { - await screen.unmount(); - } - }); - - it("round-trips details rendered through the collapsible", async () => { - const source = [ - "
", - "Expandable details section", - "", - "This content includes **formatted text**.", - "
", - ].join("\n"); - const screen = await render(); - - try { - const { text } = copySelectedMarkdown(); - expect(text).toBe(source); - } finally { - await screen.unmount(); - } - }); - - it("excludes the code block header chrome from copied markdown", async () => { - const source = ["```ts", "const x = 1;", "```"].join("\n"); - const screen = await render(); - - try { - const { text } = copySelectedMarkdown(); - expect(text).toBe(source); - } finally { - await screen.unmount(); - } - }); - - it("copies file links as markdown and skips UI affordances", async () => { - const filePath = "/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts"; - const screen = await render( - , - ); - - try { - const { text, html } = copySelectedMarkdown(); - expect(text).toBe( - `See [PermissionRule.ts](/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts) for details.`, - ); - expect(html).toContain("PermissionRule.ts"); - expect(html).not.toContain(" { - const source = - "Use $agent-browser with [package.json](path/to/package.json) before continuing."; - const screen = await render( - , - ); - - try { - const root = document.querySelector(".chat-markdown")!; - const selection = window.getSelection()!; - selection.removeAllRanges(); - const range = document.createRange(); - range.selectNodeContents(root); - selection.addRange(range); - expect(selection.toString()).toContain("Agent Browser"); - expect(selection.toString()).toContain("package.json"); - selection.removeAllRanges(); - - const { text, html } = copySelectedMarkdown(); - expect(text).toBe(source); - expect(html).toContain("Agent Browser"); - expect(html).toContain("package.json"); - expect(html).not.toContain("; -} - -let fixture: TestFixture; -const rpcHarness = new BrowserWsRpcHarness(); -const wsRequests = rpcHarness.requests; -let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null; -const wsLink = ws.link(/ws(s)?:\/\/.*/); -const encodeServerConfig = Schema.encodeSync(ServerConfigSchema); - -interface ViewportSpec { - name: string; - width: number; - height: number; - textTolerancePx: number; - attachmentTolerancePx: number; -} - -const DEFAULT_VIEWPORT: ViewportSpec = { - name: "desktop", - width: 960, - height: 1_100, - textTolerancePx: 44, - attachmentTolerancePx: 56, -}; -const WIDE_FOOTER_VIEWPORT: ViewportSpec = { - name: "wide-footer", - width: 1_400, - height: 1_100, - textTolerancePx: 44, - attachmentTolerancePx: 56, -}; -const COMPACT_FOOTER_VIEWPORT: ViewportSpec = { - name: "compact-footer", - width: 430, - height: 932, - textTolerancePx: 56, - attachmentTolerancePx: 56, -}; - -interface MountedChatView { - [Symbol.asyncDispose]: () => Promise; - cleanup: () => Promise; - setViewport: (viewport: ViewportSpec) => Promise; - setContainerSize: (viewport: Pick) => Promise; - router: ReturnType; -} - -function isoAt(offsetSeconds: number): string { - return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString(); -} - -function createBaseServerConfig(): ServerConfig { - return { - environment: { - environmentId: EnvironmentId.make("environment-local"), - label: "Local environment", - platform: { os: "darwin" as const, arch: "arm64" as const }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }, - auth: { - policy: "loopback-browser", - bootstrapMethods: ["one-time-token"], - sessionMethods: ["browser-session-cookie", "bearer-access-token"], - sessionCookieName: "t3_session", - }, - cwd: "/repo/project", - keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", - keybindings: [], - issues: [], - providers: [ - { - driver: ProviderDriverKind.make("codex"), - instanceId: ProviderInstanceId.make("codex"), - enabled: true, - installed: true, - version: "0.116.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: NOW_ISO, - models: [], - slashCommands: [], - skills: [], - }, - ], - availableEditors: [], - observability: { - logsDirectoryPath: "/repo/project/.t3/logs", - localTracingEnabled: true, - otlpTracesEnabled: false, - otlpMetricsEnabled: false, - }, - settings: { - ...DEFAULT_SERVER_SETTINGS, - ...DEFAULT_CLIENT_SETTINGS, - }, - }; -} - -function createUserMessage(options: { - id: MessageId; - text: string; - offsetSeconds: number; - attachments?: Array<{ - type: "image"; - id: string; - name: string; - mimeType: string; - sizeBytes: number; - }>; -}) { - return { - id: options.id, - role: "user" as const, - text: options.text, - ...(options.attachments ? { attachments: options.attachments } : {}), - turnId: null, - streaming: false, - createdAt: isoAt(options.offsetSeconds), - updatedAt: isoAt(options.offsetSeconds + 1), - }; -} - -function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) { - return { - id: options.id, - role: "assistant" as const, - text: options.text, - turnId: null, - streaming: false, - createdAt: isoAt(options.offsetSeconds), - updatedAt: isoAt(options.offsetSeconds + 1), - }; -} - -function createTerminalContext(input: { - id: string; - terminalLabel: string; - lineStart: number; - lineEnd: number; - text: string; -}): TerminalContextDraft { - return { - id: input.id, - threadId: THREAD_ID, - terminalId: `terminal-${input.id}`, - terminalLabel: input.terminalLabel, - lineStart: input.lineStart, - lineEnd: input.lineEnd, - text: input.text, - createdAt: NOW_ISO, - }; -} - -function createSnapshotForTargetUser(options: { - targetMessageId: MessageId; - targetText: string; - targetAttachmentCount?: number; - targetIndex?: number; - sessionStatus?: OrchestrationSessionStatus; -}): OrchestrationReadModel { - const messages: Array = []; - - for (let index = 0; index < 22; index += 1) { - const isTarget = index === (options.targetIndex ?? 3); - const userId = `msg-user-${index}` as MessageId; - const assistantId = `msg-assistant-${index}` as MessageId; - const attachments = - isTarget && (options.targetAttachmentCount ?? 0) > 0 - ? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({ - type: "image" as const, - id: `attachment-${attachmentIndex + 1}`, - name: `attachment-${attachmentIndex + 1}.png`, - mimeType: "image/png", - sizeBytes: 128, - })) - : undefined; - - messages.push( - createUserMessage({ - id: isTarget ? options.targetMessageId : userId, - text: isTarget ? options.targetText : `filler user message ${index}`, - offsetSeconds: messages.length * 3, - ...(attachments ? { attachments } : {}), - }), - ); - messages.push( - createAssistantMessage({ - id: assistantId, - text: `assistant filler ${index}`, - offsetSeconds: messages.length * 3, - }), - ); - } - - return { - snapshotSequence: 1, - projects: [ - { - id: PROJECT_ID, - title: "Project", - workspaceRoot: "/repo/project", - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5", - }, - scripts: [], - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - deletedAt: null, - }, - ], - threads: [ - { - id: THREAD_ID, - projectId: PROJECT_ID, - title: THREAD_TITLE, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5", - }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "main", - worktreePath: null, - latestTurn: null, - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - archivedAt: null, - deletedAt: null, - messages, - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId: THREAD_ID, - status: options.sessionStatus ?? "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: NOW_ISO, - }, - }, - ], - updatedAt: NOW_ISO, - }; -} - -function buildFixture(snapshot: OrchestrationReadModel): TestFixture { - return { - snapshot, - serverConfig: createBaseServerConfig(), - welcome: { - environment: { - environmentId: EnvironmentId.make("environment-local"), - label: "Local environment", - platform: { os: "darwin" as const, arch: "arm64" as const }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }, - cwd: "/repo/project", - projectName: "Project", - bootstrapProjectId: PROJECT_ID, - bootstrapThreadId: THREAD_ID, - }, - terminalMetadataEvents: [], - }; -} - -function addThreadToSnapshot( - snapshot: OrchestrationReadModel, - threadId: ThreadId, -): OrchestrationReadModel { - return { - ...snapshot, - snapshotSequence: snapshot.snapshotSequence + 1, - threads: [ - ...snapshot.threads, - { - id: threadId, - projectId: PROJECT_ID, - title: "New thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5", - }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "main", - worktreePath: null, - latestTurn: null, - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - archivedAt: null, - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: NOW_ISO, - }, - }, - ], - }; -} - -function toShellThread(thread: OrchestrationReadModel["threads"][number]) { - return { - id: thread.id, - projectId: thread.projectId, - title: thread.title, - modelSelection: thread.modelSelection, - runtimeMode: thread.runtimeMode, - interactionMode: thread.interactionMode, - branch: thread.branch, - worktreePath: thread.worktreePath, - latestTurn: thread.latestTurn, - createdAt: thread.createdAt, - updatedAt: thread.updatedAt, - archivedAt: thread.archivedAt, - session: thread.session, - latestUserMessageAt: - thread.messages.findLast((message) => message.role === "user")?.createdAt ?? null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - }; -} - -function toShellSnapshot(snapshot: OrchestrationReadModel) { - return { - snapshotSequence: snapshot.snapshotSequence, - projects: snapshot.projects.map((project) => ({ - id: project.id, - title: project.title, - workspaceRoot: project.workspaceRoot, - repositoryIdentity: project.repositoryIdentity ?? null, - defaultModelSelection: project.defaultModelSelection, - scripts: project.scripts, - createdAt: project.createdAt, - updatedAt: project.updatedAt, - })), - threads: snapshot.threads.map(toShellThread), - updatedAt: snapshot.updatedAt, - }; -} - -function updateThreadSessionInSnapshot( - snapshot: OrchestrationReadModel, - threadId: ThreadId, - session: OrchestrationReadModel["threads"][number]["session"], -): OrchestrationReadModel { - return { - ...snapshot, - snapshotSequence: snapshot.snapshotSequence + 1, - threads: snapshot.threads.map((thread) => - thread.id === threadId - ? { - ...thread, - session, - updatedAt: NOW_ISO, - } - : thread, - ), - }; -} - -async function waitForWsClient(router?: ReturnType): Promise { - await vi.waitFor( - () => { - const receivedRequestTags = wsRequests.map((request) => request._tag).join(", "); - const diagnostics = [ - `requests=${receivedRequestTags}`, - `pathname=${router?.state.location.pathname ?? "unknown"}`, - `routerStatus=${router?.state.status ?? "unknown"}`, - `matches=${router?.state.matches.map((match) => match.routeId).join(",") ?? "unknown"}`, - `body=${document.body.textContent?.trim().slice(0, 200) || ""}`, - ].join("; "); - expect( - wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.subscribeShell), - `Expected shell subscription. ${diagnostics}`, - ).toBe(true); - expect( - wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle), - ).toBe(true); - expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe( - true, - ); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -function threadRefFor(threadId: ThreadId) { - return scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); -} - -function threadKeyFor(threadId: ThreadId): string { - return scopedThreadKey(threadRefFor(threadId)); -} - -function composerDraftFor(target: string) { - const { draftsByThreadKey } = useComposerDraftStore.getState(); - return draftsByThreadKey[target] ?? draftsByThreadKey[threadKeyFor(target as ThreadId)]; -} - -function draftIdFromPath(pathname: string) { - const segments = pathname.split("/"); - const draftId = segments[segments.length - 1]; - if (!draftId) { - throw new Error(`Expected thread path, received "${pathname}".`); - } - return DraftId.make(draftId); -} - -function draftThreadIdFor(draftId: ReturnType): ThreadId { - const draftSession = useComposerDraftStore.getState().getDraftSession(draftId); - if (!draftSession) { - throw new Error(`Expected draft session for "${draftId}".`); - } - return draftSession.threadId; -} - -function serverThreadPath(threadId: ThreadId): string { - return `/${LOCAL_ENVIRONMENT_ID}/${threadId}`; -} - -async function waitForAppBootstrap(): Promise { - await vi.waitFor( - () => { - const serverConfig = appAtomRegistry.get(primaryServerConfigAtom); - expect(serverConfig?.keybindings).toEqual(fixture.serverConfig.keybindings); - const snapshot = appAtomRegistry.get(environmentSnapshotAtom(LOCAL_ENVIRONMENT_ID)); - expect(snapshot?.snapshotSequence).toBe(fixture.snapshot.snapshotSequence); - expect(snapshot?.projects.map((project) => project.id)).toEqual( - fixture.snapshot.projects.map((project) => project.id), - ); - expect(snapshot?.threads.map((thread) => thread.id)).toEqual( - fixture.snapshot.threads.map((thread) => thread.id), - ); - expect( - appAtomRegistry.get(environmentProjects.projectsAtom).map((project) => project.id), - ).toEqual(fixture.snapshot.projects.map((project) => project.id)); - for (const thread of fixture.snapshot.threads) { - expect(readThreadDetail(threadRefFor(thread.id))?.worktreePath).toBe(thread.worktreePath); - } - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function materializePromotedDraftThreadViaDomainEvent(threadId: ThreadId): Promise { - await waitForWsClient(); - fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId); - fixture.snapshot = updateThreadSessionInSnapshot(fixture.snapshot, threadId, null); - await waitForLayout(); - rpcHarness.emitStreamValue(ORCHESTRATION_WS_METHODS.subscribeShell, { - kind: "snapshot", - snapshot: toShellSnapshot(fixture.snapshot), - }); - await vi.waitFor( - () => { - expect(readThreadShell(threadRefFor(threadId))?.id).toBe(threadId); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function startPromotedServerThreadViaDomainEvent(threadId: ThreadId): Promise { - fixture.snapshot = updateThreadSessionInSnapshot(fixture.snapshot, threadId, { - threadId, - status: "running", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: `turn-${threadId}` as TurnId, - lastError: null, - updatedAt: NOW_ISO, - }); - await waitForLayout(); - rpcHarness.emitStreamValue(ORCHESTRATION_WS_METHODS.subscribeShell, { - kind: "snapshot", - snapshot: toShellSnapshot(fixture.snapshot), - }); - const thread = fixture.snapshot.threads.find((entry) => entry.id === threadId); - if (!thread) { - throw new Error(`Expected promoted thread ${threadId} in snapshot.`); - } - await waitForLayout(); - rpcHarness.emitStreamValue(ORCHESTRATION_WS_METHODS.subscribeThread, { - kind: "snapshot", - snapshot: { - snapshotSequence: fixture.snapshot.snapshotSequence, - thread, - }, - }); -} - -async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise { - await materializePromotedDraftThreadViaDomainEvent(threadId); - await startPromotedServerThreadViaDomainEvent(threadId); - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftThreadsByThreadKey[threadKeyFor(threadId)]).toBe( - undefined, - ); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -function createDraftOnlySnapshot(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-draft-target" as MessageId, - targetText: "draft thread", - }); - return { - ...snapshot, - threads: [], - }; -} - -function createProjectlessSnapshot(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-projectless-target" as MessageId, - targetText: "projectless", - }); - return { - ...snapshot, - projects: [], - threads: [], - }; -} - -function withProjectScripts( - snapshot: OrchestrationReadModel, - scripts: OrchestrationReadModel["projects"][number]["scripts"], -): OrchestrationReadModel { - return { - ...snapshot, - projects: snapshot.projects.map((project) => - project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project, - ), - }; -} - -function setDraftThreadWithoutWorktree(): void { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); -} - -function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-plan-target" as MessageId, - targetText: "plan thread", - }); - const planMarkdown = [ - "# Ship plan mode follow-up", - "", - "- Step 1: capture the thread-open trace", - "- Step 2: identify the main-thread bottleneck", - "- Step 3: keep collapsed cards cheap", - "- Step 4: render the full markdown only on demand", - "- Step 5: preserve export and save actions", - "- Step 6: add regression coverage", - "- Step 7: verify route transitions stay responsive", - "- Step 8: confirm no server-side work changed", - "- Step 9: confirm short plans still render normally", - "- Step 10: confirm long plans stay collapsed by default", - "- Step 11: confirm preview text is still useful", - "- Step 12: confirm plan follow-up flow still works", - "- Step 13: confirm timeline virtualization still behaves", - "- Step 14: confirm theme styling still looks correct", - "- Step 15: confirm save dialog behavior is unchanged", - "- Step 16: confirm download behavior is unchanged", - "- Step 17: confirm code fences do not parse until expand", - "- Step 18: confirm preview truncation ends cleanly", - "- Step 19: confirm markdown links still open in editor after expand", - "- Step 20: confirm deep hidden detail only appears after expand", - "", - "```ts", - "export const hiddenPlanImplementationDetail = 'deep hidden detail only after expand';", - "```", - ].join("\n"); - - return { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - proposedPlans: [ - { - id: "plan-browser-test", - turnId: null, - planMarkdown, - implementedAt: null, - implementationThreadId: null, - createdAt: isoAt(1_000), - updatedAt: isoAt(1_001), - }, - ], - updatedAt: isoAt(1_001), - }) - : thread, - ), - }; -} - -function createSnapshotWithSecondaryProject(options?: { - includeSecondaryThread?: boolean; - includeArchivedSecondaryThread?: boolean; -}): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-secondary-project-target" as MessageId, - targetText: "secondary project", - }); - const includeSecondaryThread = options?.includeSecondaryThread ?? true; - const includeArchivedSecondaryThread = options?.includeArchivedSecondaryThread ?? true; - const secondaryThreads: OrchestrationReadModel["threads"] = includeSecondaryThread - ? [ - { - id: "thread-secondary-project" as ThreadId, - projectId: SECOND_PROJECT_ID, - title: "Release checklist", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "release/docs-portal", - worktreePath: null, - latestTurn: null, - createdAt: isoAt(30), - updatedAt: isoAt(31), - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId: "thread-secondary-project" as ThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: isoAt(31), - }, - archivedAt: null, - }, - ] - : []; - const archivedSecondaryThreads: OrchestrationReadModel["threads"] = includeArchivedSecondaryThread - ? [ - { - id: ARCHIVED_SECONDARY_THREAD_ID, - projectId: SECOND_PROJECT_ID, - title: "Archived Docs Notes", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, - interactionMode: "default", - runtimeMode: "full-access", - branch: "release/docs-archive", - worktreePath: null, - latestTurn: null, - createdAt: isoAt(24), - updatedAt: isoAt(25), - deletedAt: null, - messages: [], - activities: [], - proposedPlans: [], - checkpoints: [], - session: { - threadId: ARCHIVED_SECONDARY_THREAD_ID, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: isoAt(25), - }, - archivedAt: isoAt(26), - }, - ] - : []; - - return { - ...snapshot, - projects: [ - ...snapshot.projects, - { - id: SECOND_PROJECT_ID, - title: "Docs Portal", - workspaceRoot: "/repo/clients/docs-portal", - defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, - scripts: [], - createdAt: NOW_ISO, - updatedAt: NOW_ISO, - deletedAt: null, - }, - ], - threads: [...snapshot.threads, ...secondaryThreads, ...archivedSecondaryThreads], - }; -} - -function createSnapshotWithPendingUserInput(): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-pending-input-target" as MessageId, - targetText: "question thread", - }); - - return { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - interactionMode: "plan", - activities: [ - { - id: EventId.make("activity-user-input-requested"), - tone: "info", - kind: "user-input.requested", - summary: "User input requested", - payload: { - requestId: "req-browser-user-input", - questions: [ - { - id: "scope", - header: "Scope", - question: "What should this change cover?", - options: [ - { - label: "Tight", - description: "Touch only the footer layout logic.", - }, - { - label: "Broad", - description: "Also adjust the related composer controls.", - }, - ], - }, - { - id: "risk", - header: "Risk", - question: "How aggressive should the imaginary plan be?", - options: [ - { - label: "Conservative", - description: "Favor reliability and low-risk changes.", - }, - { - label: "Balanced", - description: "Mix quick wins with one structural improvement.", - }, - ], - }, - ], - }, - turnId: null, - sequence: 1, - createdAt: isoAt(1_000), - }, - ], - updatedAt: isoAt(1_000), - }) - : thread, - ), - }; -} - -function createSnapshotWithPlanFollowUpPrompt(options?: { - modelSelection?: { instanceId: ProviderInstanceId; model: string }; - planMarkdown?: string; -}): OrchestrationReadModel { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-plan-follow-up-target" as MessageId, - targetText: "plan follow-up thread", - }); - const modelSelection = options?.modelSelection ?? { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5", - }; - const planMarkdown = - options?.planMarkdown ?? "# Follow-up plan\n\n- Keep the composer footer stable on resize."; - - return { - ...snapshot, - projects: snapshot.projects.map((project) => - project.id === PROJECT_ID ? { ...project, defaultModelSelection: modelSelection } : project, - ), - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - modelSelection, - interactionMode: "plan", - latestTurn: { - turnId: "turn-plan-follow-up" as TurnId, - state: "completed", - requestedAt: isoAt(1_000), - startedAt: isoAt(1_001), - completedAt: isoAt(1_010), - assistantMessageId: null, - }, - proposedPlans: [ - { - id: "plan-follow-up-browser-test", - turnId: "turn-plan-follow-up" as TurnId, - planMarkdown, - implementedAt: null, - implementationThreadId: null, - createdAt: isoAt(1_002), - updatedAt: isoAt(1_003), - }, - ], - session: { - ...thread.session, - status: "ready", - updatedAt: isoAt(1_010), - }, - updatedAt: isoAt(1_010), - }) - : thread, - ), - }; -} - -function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown { - const customResult = customWsRpcResolver?.(body); - if (customResult !== undefined) { - return customResult; - } - const tag = body._tag; - if (tag === WS_METHODS.serverGetConfig) { - return encodeServerConfig(fixture.serverConfig); - } - if (tag === WS_METHODS.serverDiscoverSourceControl) { - return { - versionControlSystems: [], - sourceControlProviders: [ - { - kind: "github", - label: "GitHub", - executable: "gh", - status: "available", - version: Option.some("gh version 2.0.0"), - installHint: "Install GitHub CLI.", - detail: Option.none(), - auth: { - status: "authenticated", - account: Option.some("t3-oss"), - host: Option.some("github.com"), - detail: Option.none(), - }, - }, - { - kind: "gitlab", - label: "GitLab", - executable: "glab", - status: "available", - version: Option.some("glab version 1.0.0"), - installHint: "Install GitLab CLI.", - detail: Option.none(), - auth: { - status: "authenticated", - account: Option.some("t3-oss"), - host: Option.some("gitlab.com"), - detail: Option.none(), - }, - }, - { - kind: "bitbucket", - label: "Bitbucket", - executable: "Bitbucket REST API", - status: "available", - version: Option.none(), - installHint: "Set Bitbucket API token environment variables.", - detail: Option.none(), - auth: { - status: "authenticated", - account: Option.some("t3-oss"), - host: Option.some("bitbucket.org"), - detail: Option.none(), - }, - }, - { - kind: "azure-devops", - label: "Azure DevOps", - executable: "az", - status: "available", - version: Option.some("azure-cli 2.0.0"), - installHint: "Install Azure CLI.", - detail: Option.none(), - auth: { - status: "authenticated", - account: Option.some("t3-oss"), - host: Option.some("dev.azure.com"), - detail: Option.none(), - }, - }, - ], - }; - } - if (tag === WS_METHODS.vcsListRefs) { - return { - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 1, - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - ], - }; - } - if (tag === WS_METHODS.projectsSearchEntries) { - return { - entries: [], - truncated: false, - }; - } - if (tag === WS_METHODS.assetsCreateUrl) { - const resource = body.resource as { _tag?: string; attachmentId?: string }; - const fileName = - resource._tag === "attachment" && resource.attachmentId - ? `${resource.attachmentId}.svg` - : "favicon.svg"; - return { - relativeUrl: `/api/assets/test-token/${fileName}`, - expiresAt: Date.now() + 60_000, - }; - } - if (tag === WS_METHODS.shellOpenInEditor) { - return null; - } - if (tag === WS_METHODS.terminalOpen) { - return { - threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID, - terminalId: typeof body.terminalId === "string" ? body.terminalId : "default", - cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project", - worktreePath: - typeof body.worktreePath === "string" - ? body.worktreePath - : body.worktreePath === null - ? null - : null, - status: "running", - pid: 123, - history: "", - exitCode: null, - exitSignal: null, - label: "Terminal 1", - updatedAt: NOW_ISO, - }; - } - if (tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { sequence: fixture.snapshot.snapshotSequence + 1 }; - } - if ( - tag === WS_METHODS.terminalWrite || - tag === WS_METHODS.terminalResize || - tag === WS_METHODS.terminalClear || - tag === WS_METHODS.terminalClose - ) { - return null; - } - return {}; -} - -const worker = setupWorker( - wsLink.addEventListener("connection", ({ client }) => { - void rpcHarness.connect(client); - client.addEventListener("message", (event) => { - const rawData = event.data; - if (typeof rawData !== "string") return; - void rpcHarness.onMessage(rawData); - }); - }), - ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth), - http.get("*/api/assets/test-token/:fileName", () => - HttpResponse.text(ATTACHMENT_SVG, { - headers: { - "Content-Type": "image/svg+xml", - }, - }), - ), - http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })), -); - -async function nextFrame(): Promise { - await new Promise((resolve) => { - window.requestAnimationFrame(() => resolve()); - }); -} - -async function waitForLayout(): Promise { - await nextFrame(); - await nextFrame(); - await nextFrame(); -} - -async function setViewport(viewport: ViewportSpec): Promise { - await page.viewport(viewport.width, viewport.height); - await waitForLayout(); -} - -async function waitForProductionStyles(): Promise { - await vi.waitFor( - () => { - expect( - getComputedStyle(document.documentElement).getPropertyValue("--background").trim(), - ).not.toBe(""); - expect(getComputedStyle(document.body).marginTop).toBe("0px"); - }, - { - timeout: 4_000, - interval: 16, - }, - ); -} - -async function waitForElement( - query: () => T | null, - errorMessage: string, -): Promise { - let element: T | null = null; - await vi.waitFor( - () => { - element = query(); - expect(element, errorMessage).toBeTruthy(); - }, - { - timeout: 8_000, - interval: 16, - }, - ); - if (!element) { - throw new Error(errorMessage); - } - return element; -} - -async function waitForURL( - router: ReturnType, - predicate: (pathname: string) => boolean, - errorMessage: string, -): Promise { - let pathname = ""; - await vi.waitFor( - () => { - pathname = router.state.location.pathname; - expect(predicate(pathname), `${errorMessage} Current path: ${pathname}`).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - return pathname; -} - -async function waitForComposerEditor(): Promise { - return waitForElement( - () => document.querySelector('[contenteditable="true"]'), - "Unable to find composer editor.", - ); -} - -async function pressComposerKey(key: string): Promise { - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - const keydownEvent = new KeyboardEvent("keydown", { - key, - bubbles: true, - cancelable: true, - }); - composerEditor.dispatchEvent(keydownEvent); - if (keydownEvent.defaultPrevented) { - await waitForLayout(); - return; - } - - const beforeInputEvent = new InputEvent("beforeinput", { - data: key, - inputType: "insertText", - bubbles: true, - cancelable: true, - }); - composerEditor.dispatchEvent(beforeInputEvent); - if (beforeInputEvent.defaultPrevented) { - await waitForLayout(); - return; - } - - if ( - typeof document.execCommand === "function" && - document.execCommand("insertText", false, key) - ) { - await waitForLayout(); - return; - } - - const selection = window.getSelection(); - if (!selection || selection.rangeCount === 0) { - throw new Error("Unable to resolve composer selection for text input."); - } - const range = selection.getRangeAt(0); - range.deleteContents(); - const textNode = document.createTextNode(key); - range.insertNode(textNode); - range.setStartAfter(textNode); - range.collapse(true); - selection.removeAllRanges(); - selection.addRange(range); - composerEditor.dispatchEvent( - new InputEvent("input", { - data: key, - inputType: "insertText", - bubbles: true, - }), - ); - await waitForLayout(); -} - -async function pressComposerUndo(): Promise { - const composerEditor = await waitForComposerEditor(); - const useMetaForMod = isMacPlatform(navigator.platform); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "z", - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); -} - -async function waitForComposerText(expectedText: string): Promise { - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe( - expectedText, - ); - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function setComposerSelectionByTextOffsets(options: { - start: number; - end: number; - direction?: "forward" | "backward"; -}): Promise { - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - const resolvePoint = (targetOffset: number) => { - const traversedRef = { value: 0 }; - - const visitNode = (node: Node): { node: Node; offset: number } | null => { - if (node.nodeType === Node.TEXT_NODE) { - const textLength = node.textContent?.length ?? 0; - if (targetOffset <= traversedRef.value + textLength) { - return { - node, - offset: Math.max(0, Math.min(targetOffset - traversedRef.value, textLength)), - }; - } - traversedRef.value += textLength; - return null; - } - - if (node instanceof HTMLBRElement) { - const parent = node.parentNode; - if (!parent) { - return null; - } - const siblingIndex = Array.prototype.indexOf.call(parent.childNodes, node); - if (targetOffset <= traversedRef.value) { - return { node: parent, offset: siblingIndex }; - } - if (targetOffset <= traversedRef.value + 1) { - return { node: parent, offset: siblingIndex + 1 }; - } - traversedRef.value += 1; - return null; - } - - if (node instanceof Element || node instanceof DocumentFragment) { - for (const child of node.childNodes) { - const point = visitNode(child); - if (point) { - return point; - } - } - } - - return null; - }; - - return ( - visitNode(composerEditor) ?? { - node: composerEditor, - offset: composerEditor.childNodes.length, - } - ); - }; - - const startPoint = resolvePoint(options.start); - const endPoint = resolvePoint(options.end); - const selection = window.getSelection(); - if (!selection) { - throw new Error("Unable to resolve window selection."); - } - selection.removeAllRanges(); - - if (options.direction === "backward" && "setBaseAndExtent" in selection) { - selection.setBaseAndExtent(endPoint.node, endPoint.offset, startPoint.node, startPoint.offset); - await waitForLayout(); - return; - } - - const range = document.createRange(); - range.setStart(startPoint.node, startPoint.offset); - range.setEnd(endPoint.node, endPoint.offset); - selection.addRange(range); - await waitForLayout(); -} - -async function selectAllComposerContent(): Promise { - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - const selection = window.getSelection(); - if (!selection) { - throw new Error("Unable to resolve window selection."); - } - selection.removeAllRanges(); - const range = document.createRange(); - range.selectNodeContents(composerEditor); - selection.addRange(range); - await waitForLayout(); -} - -async function waitForComposerMenuItem(itemId: string): Promise { - return waitForElement( - () => document.querySelector(`[data-composer-item-id="${itemId}"]`), - `Unable to find composer menu item "${itemId}".`, - ); -} -async function waitForSendButton(): Promise { - return waitForElement( - () => document.querySelector('button[aria-label="Send message"]'), - "Unable to find send button.", - ); -} - -function findComposerProviderModelPicker(): HTMLButtonElement | null { - return document.querySelector('[data-chat-provider-model-picker="true"]'); -} - -function findButtonByText(text: string): HTMLButtonElement | null { - return (Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === text, - ) ?? null) as HTMLButtonElement | null; -} - -async function waitForButtonByText(text: string): Promise { - return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`); -} - -function findButtonContainingText(text: string): HTMLElement | null { - return ( - Array.from(document.querySelectorAll('button, [role="button"]')).find((button) => - button.textContent?.includes(text), - ) ?? null - ); -} - -async function waitForButtonContainingText(text: string): Promise { - return waitForElement( - () => findButtonContainingText(text), - `Unable to find button containing "${text}".`, - ); -} - -async function waitForSelectItemContainingText(text: string): Promise { - return waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="select-item"]')).find((item) => - item.textContent?.includes(text), - ) ?? null, - `Unable to find select item containing "${text}".`, - ); -} - -async function expectComposerActionsContained(): Promise { - const footer = await waitForElement( - () => document.querySelector('[data-chat-composer-footer="true"]'), - "Unable to find composer footer.", - ); - const actions = await waitForElement( - () => document.querySelector('[data-chat-composer-actions="right"]'), - "Unable to find composer actions container.", - ); - - await vi.waitFor( - () => { - const footerRect = footer.getBoundingClientRect(); - const actionButtons = Array.from(actions.querySelectorAll("button")); - expect(actionButtons.length).toBeGreaterThanOrEqual(1); - - const buttonRects = actionButtons.map((button) => button.getBoundingClientRect()); - const firstTop = buttonRects[0]?.top ?? 0; - - for (const rect of buttonRects) { - expect(rect.right).toBeLessThanOrEqual(footerRect.right + 0.5); - expect(rect.bottom).toBeLessThanOrEqual(footerRect.bottom + 0.5); - expect(Math.abs(rect.top - firstTop)).toBeLessThanOrEqual(1.5); - } - }, - { timeout: 8_000, interval: 16 }, - ); -} - -async function waitForInteractionModeButton( - expectedLabel: "Build" | "Plan", -): Promise { - return waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === expectedLabel, - ) as HTMLButtonElement | null, - `Unable to find ${expectedLabel} interaction mode button.`, - ); -} - -async function waitForServerConfigToApply(): Promise { - await vi.waitFor( - () => { - expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe( - true, - ); - expect(appAtomRegistry.get(primaryServerConfigAtom)?.keybindings).toEqual( - fixture.serverConfig.keybindings, - ); - }, - { timeout: 8_000, interval: 16 }, - ); - await waitForLayout(); -} - -function dispatchChatNewShortcut(): void { - const useMetaForMod = isMacPlatform(navigator.platform); - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "o", - shiftKey: true, - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); -} - -function releaseModShortcut(key?: string): void { - window.dispatchEvent( - new KeyboardEvent("keyup", { - key: key ?? (isMacPlatform(navigator.platform) ? "Meta" : "Control"), - metaKey: false, - ctrlKey: false, - bubbles: true, - cancelable: true, - }), - ); -} - -async function triggerChatNewShortcutUntilPath( - router: ReturnType, - predicate: (pathname: string) => boolean, - errorMessage: string, -): Promise { - let pathname = router.state.location.pathname; - const deadline = Date.now() + 8_000; - while (Date.now() < deadline) { - dispatchChatNewShortcut(); - await waitForLayout(); - pathname = router.state.location.pathname; - if (predicate(pathname)) { - return pathname; - } - } - throw new Error(`${errorMessage} Last path: ${pathname}`); -} - -async function openCommandPaletteFromTrigger(): Promise { - const trigger = page.getByTestId("command-palette-trigger"); - await expect.element(trigger).toBeInTheDocument(); - await trigger.click(); - await waitForElement( - () => document.querySelector('[data-testid="command-palette"]'), - "Command palette should have opened from the sidebar trigger.", - ); -} - -async function waitForCommandPaletteShortcutLabel(): Promise { - await waitForElement( - () => document.querySelector('[data-testid="command-palette-trigger"] kbd'), - "Command palette shortcut label did not render.", - ); -} - -async function waitForCommandPaletteInput(placeholder: string): Promise { - return waitForElement( - () => document.querySelector(`input[placeholder="${placeholder}"]`) as HTMLInputElement | null, - `Command palette input with placeholder "${placeholder}" did not render.`, - ); -} - -function getCommandPaletteLegendEntries(): string[] { - const footer = document.querySelector('[data-slot="command-footer"]'); - if (!footer) { - return []; - } - - return Array.from(footer.querySelectorAll('[data-slot="kbd-group"]')) - .map((group) => - Array.from(group.children) - .map((child) => child.textContent?.trim() ?? "") - .filter((value) => value.length > 0) - .join(" "), - ) - .filter((value) => value.length > 0); -} - -async function dispatchInputKey( - input: HTMLInputElement, - init: Pick, -): Promise { - input.focus(); - input.dispatchEvent( - new KeyboardEvent("keydown", { - bubbles: true, - cancelable: true, - ...init, - }), - ); - await waitForLayout(); -} - -async function mountChatView(options: { - viewport: ViewportSpec; - snapshot: OrchestrationReadModel; - configureFixture?: (fixture: TestFixture) => void; - resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined; - initialPath?: string; -}): Promise { - fixture = buildFixture(options.snapshot); - options.configureFixture?.(fixture); - customWsRpcResolver = options.resolveRpc ?? null; - await setViewport(options.viewport); - await waitForProductionStyles(); - - const host = document.createElement("div"); - host.style.position = "fixed"; - host.style.top = "0"; - host.style.left = "0"; - host.style.width = "100vw"; - host.style.height = "100vh"; - host.style.display = "grid"; - host.style.overflow = "hidden"; - document.body.append(host); - - const defaultInitialPath = (() => { - if (options.snapshot.threads.some((thread) => thread.id === THREAD_ID)) { - return `/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`; - } - const draftEntry = Object.entries( - useComposerDraftStore.getState().draftThreadsByThreadKey, - ).find( - ([, draftSession]) => - draftSession.environmentId === LOCAL_ENVIRONMENT_ID && draftSession.threadId === THREAD_ID, - ); - return draftEntry ? `/draft/${draftEntry[0]}` : `/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`; - })(); - const router = getRouter( - createMemoryHistory({ - initialEntries: [options.initialPath ?? defaultInitialPath], - }), - ); - - const screen = await render(, { - container: host, - }); - - await waitForWsClient(router); - await waitForAppBootstrap(); - await waitForLayout(); - - const cleanup = async () => { - customWsRpcResolver = null; - await screen.unmount(); - host.remove(); - await waitForLayout(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - setViewport: async (viewport: ViewportSpec) => { - await setViewport(viewport); - await waitForProductionStyles(); - }, - setContainerSize: async (viewport) => { - host.style.width = `${viewport.width}px`; - host.style.height = `${viewport.height}px`; - await waitForLayout(); - }, - router, - }; -} - -describe("ChatView timeline estimator parity (full app)", () => { - beforeAll(async () => { - fixture = buildFixture( - createSnapshotForTargetUser({ - targetMessageId: "msg-user-bootstrap" as MessageId, - targetText: "bootstrap", - }), - ); - await worker.start({ - onUnhandledRequest: "bypass", - quiet: true, - serviceWorker: { - url: "/mockServiceWorker.js", - }, - }); - }); - - afterAll(async () => { - await rpcHarness.disconnect(); - await worker.stop(); - }); - - beforeEach(async () => { - resetAppAtomRegistryForTests(); - await rpcHarness.reset({ - resolveUnary: resolveWsRpc, - getInitialStreamValues: (request) => { - if (request._tag === WS_METHODS.subscribeServerLifecycle) { - return [ - { - version: 1, - sequence: 1, - type: "welcome", - payload: fixture.welcome, - }, - ]; - } - if (request._tag === WS_METHODS.subscribeServerConfig) { - return [ - { - version: 1, - type: "snapshot", - config: encodeServerConfig(fixture.serverConfig), - }, - ]; - } - if (request._tag === ORCHESTRATION_WS_METHODS.subscribeShell) { - return [ - { - kind: "snapshot", - snapshot: toShellSnapshot(fixture.snapshot), - }, - ]; - } - if (request._tag === ORCHESTRATION_WS_METHODS.subscribeThread) { - const thread = fixture.snapshot.threads.find((entry) => entry.id === request.threadId); - return thread - ? [ - { - kind: "snapshot", - snapshot: { - snapshotSequence: fixture.snapshot.snapshotSequence, - thread, - }, - }, - ] - : []; - } - if (request._tag === WS_METHODS.subscribeTerminalMetadata) { - return fixture.terminalMetadataEvents; - } - if (request._tag === WS_METHODS.subscribeVcsStatus) { - return [INITIAL_VCS_STATUS_EVENT]; - } - return []; - }, - }); - await __resetLocalApiForTests(); - await setViewport(DEFAULT_VIEWPORT); - __resetClientSettingsPersistenceForTests(); - useComposerDraftStore.persist.clearStorage(); - localStorage.clear(); - document.body.innerHTML = ""; - wsRequests.length = 0; - customWsRpcResolver = null; - Reflect.deleteProperty(window, "desktopBridge"); - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - stickyActiveProvider: null, - }); - useCommandPaletteStore.setState({ - open: false, - openIntent: null, - }); - useUiStateStore.setState({ - projectExpandedById: {}, - projectOrder: [], - threadLastVisitedAtById: {}, - }); - useTerminalUiStateStore.persist.clearStorage(); - useTerminalUiStateStore.setState({ - terminalUiStateByThreadKey: {}, - suppressedTerminalIdsByThreadKey: {}, - }); - useRightPanelStore.persist.clearStorage(); - useRightPanelStore.setState({ byThreadKey: {} }); - }); - - afterEach(() => { - customWsRpcResolver = null; - document.body.innerHTML = ""; - resetAppAtomRegistryForTests(); - }); - - it("renders locked single-environment mobile run context as a static workspace label", async () => { - const mounted = await mountChatView({ - viewport: COMPACT_FOOTER_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-mobile-locked-workspace" as MessageId, - targetText: "locked mobile workspace", - }), - }); - - try { - await waitForElement( - () => - Array.from(document.querySelectorAll("span")).find( - (element) => element.textContent?.trim() === "Local checkout", - ) ?? null, - "Unable to find static mobile workspace label.", - ); - - expect(findButtonByText("Local checkout")).toBeNull(); - } finally { - await mounted.cleanup(); - } - }); - - it("loads historical message images through signed asset URLs", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-signed-attachment" as MessageId, - targetText: "signed attachment", - targetAttachmentCount: 2, - targetIndex: 21, - }), - }); - - try { - const firstImage = await waitForElement( - () => document.querySelector('img[alt="attachment-1.png"]'), - "Unable to find signed attachment image.", - ); - const secondImage = await waitForElement( - () => document.querySelector('img[alt="attachment-2.png"]'), - "Unable to find second signed attachment image.", - ); - - expect(firstImage.src).toContain("/api/assets/test-token/attachment-1.svg"); - expect(secondImage.src).toContain("/api/assets/test-token/attachment-2.svg"); - expect(firstImage.src).not.toBe(secondImage.src); - await vi.waitFor(() => { - const attachmentRequests = wsRequests.filter( - (request) => - request._tag === WS_METHODS.assetsCreateUrl && - (request.resource as { _tag?: string })._tag === "attachment", - ); - expect(attachmentRequests).toHaveLength(2); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps dismiss-only composer banners aligned on mobile", async () => { - const mounted = await mountChatView({ - viewport: COMPACT_FOOTER_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-mobile-version-banner" as MessageId, - targetText: "mobile version banner", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - environment: { - ...nextFixture.serverConfig.environment, - serverVersion: "9.9.9", - }, - }; - }, - }); - - try { - const banner = await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="alert"]')).find( - (element) => element.textContent?.includes("Client and server versions differ"), - ) ?? null, - "Unable to find version mismatch banner.", - ); - const title = banner.querySelector('[data-slot="alert-title"]'); - const description = banner.querySelector('[data-slot="alert-description"]'); - const dismissButton = banner.querySelector( - 'button[aria-label="Dismiss version mismatch warning"]', - ); - - expect(title).toBeTruthy(); - expect(description).toBeTruthy(); - expect(dismissButton).toBeTruthy(); - expect(dismissButton!.getBoundingClientRect().top).toBeLessThan( - description!.getBoundingClientRect().top, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("re-expands the bootstrap project using its logical key", async () => { - useUiStateStore.setState({ - projectExpandedById: { - [PROJECT_LOGICAL_KEY]: false, - }, - projectOrder: [PROJECT_LOGICAL_KEY], - threadLastVisitedAtById: {}, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-bootstrap-project-expand" as MessageId, - targetText: "bootstrap project expand", - }), - }); - - try { - await vi.waitFor( - () => { - expect(useUiStateStore.getState().projectExpandedById[PROJECT_LOGICAL_KEY]).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows an explicit empty state for projects without threads in the sidebar", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - }); - - try { - await expect.element(page.getByText("No threads yet")).toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the project cwd for draft threads without a worktree path", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscode", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not leak a server worktree path into drawer runtime env when launch context clears it", async () => { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-launch-context-target" as MessageId, - targetText: "launch context worktree override", - }); - const targetThread = snapshot.threads.find((thread) => thread.id === THREAD_ID); - if (targetThread) { - Object.assign(targetThread, { - branch: "feature/branch", - worktreePath: "/repo/worktrees/feature-branch", - }); - } - - useTerminalUiStateStore.setState({ - terminalUiStateByThreadKey: { - [THREAD_KEY]: { - terminalOpen: true, - terminalHeight: 280, - terminalIds: ["default"], - activeTerminalId: "default", - terminalGroups: [{ id: "group-default", terminalIds: ["default"] }], - activeTerminalGroupId: "group-default", - }, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot, - configureFixture: (nextFixture) => { - nextFixture.terminalMetadataEvents = [ - { - type: "upsert", - terminal: { - threadId: THREAD_ID, - terminalId: DEFAULT_TERMINAL_ID, - cwd: "/repo/project", - worktreePath: null, - status: "running", - pid: 123, - exitCode: null, - exitSignal: null, - hasRunningSubprocess: false, - label: "Terminal 1", - updatedAt: isoAt(0), - }, - }, - ]; - }, - }); - - try { - await vi.waitFor( - () => { - const attachRequest = wsRequests - .toReversed() - .find((request) => request._tag === WS_METHODS.terminalAttach) as - | { - _tag: string; - cwd?: string; - worktreePath?: string | null; - env?: Record; - } - | undefined; - expect(attachRequest).toMatchObject({ - _tag: WS_METHODS.terminalAttach, - cwd: "/repo/project", - worktreePath: null, - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - }, - }); - expect(attachRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("attaches the default terminal when opening an empty terminal drawer", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-open-empty-terminal-drawer" as MessageId, - targetText: "open empty terminal drawer", - }), - }); - - try { - const toggle = await waitForElement( - () => - document.querySelector('button[aria-label="Toggle terminal drawer"]'), - "Unable to find terminal drawer toggle.", - ); - toggle.click(); - - await vi.waitFor( - () => { - const attachRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.terminalAttach, - ); - expect(attachRequest).toMatchObject({ - _tag: WS_METHODS.terminalAttach, - threadId: THREAD_ID, - terminalId: DEFAULT_TERMINAL_ID, - cwd: "/repo/project", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("recreates the final terminal when reopening the drawer after closing it", async () => { - useTerminalUiStateStore.setState({ - terminalUiStateByThreadKey: { - [THREAD_KEY]: { - terminalOpen: true, - terminalHeight: 280, - terminalIds: [DEFAULT_TERMINAL_ID], - activeTerminalId: DEFAULT_TERMINAL_ID, - terminalGroups: [ - { id: `group-${DEFAULT_TERMINAL_ID}`, terminalIds: [DEFAULT_TERMINAL_ID] }, - ], - activeTerminalGroupId: `group-${DEFAULT_TERMINAL_ID}`, - }, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-reopen-terminal-drawer" as MessageId, - targetText: "reopen terminal drawer", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "terminal.toggle", - shortcut: { - key: "j", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - }, - { - command: "terminal.close", - shortcut: { - key: "w", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { type: "identifier", name: "terminalFocus" }, - }, - ], - }; - nextFixture.terminalMetadataEvents = [ - { - type: "upsert", - terminal: { - threadId: THREAD_ID, - terminalId: DEFAULT_TERMINAL_ID, - cwd: "/repo/project", - worktreePath: null, - status: "running", - pid: 123, - exitCode: null, - exitSignal: null, - hasRunningSubprocess: false, - label: "Terminal 1", - updatedAt: NOW_ISO, - }, - }, - ]; - }, - }); - - try { - await waitForServerConfigToApply(); - const terminalInput = await waitForElement( - () => - document.querySelector( - '[data-terminal-owner="drawer"] .xterm-helper-textarea', - ), - "Unable to find terminal drawer input.", - ); - const useMetaForMod = isMacPlatform(navigator.platform); - terminalInput.focus(); - terminalInput.dispatchEvent( - new KeyboardEvent("keydown", { - key: "w", - code: "KeyW", - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor(() => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalClose && - request.terminalId === DEFAULT_TERMINAL_ID, - ), - ).toBe(true); - expect(wsRequests.some((request) => request._tag === WS_METHODS.terminalClear)).toBe(false); - expect( - selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - THREAD_REF, - ).terminalOpen, - ).toBe(false); - }); - - rpcHarness.emitStreamValue(WS_METHODS.subscribeTerminalMetadata, { - type: "remove", - threadId: THREAD_ID, - terminalId: DEFAULT_TERMINAL_ID, - }); - await waitForLayout(); - - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "j", - code: "KeyJ", - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor(() => { - const terminalState = selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - THREAD_REF, - ); - expect(terminalState.terminalOpen).toBe(true); - expect(terminalState.terminalIds).toEqual([DEFAULT_TERMINAL_ID]); - - const closeRequestIndex = wsRequests.findIndex( - (request) => request._tag === WS_METHODS.terminalClose, - ); - const reopenRequestIndex = wsRequests.findIndex( - (request) => - request._tag === WS_METHODS.terminalOpen && request.terminalId === DEFAULT_TERMINAL_ID, - ); - expect(reopenRequestIndex).toBeGreaterThan(closeRequestIndex); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("does not remount a closed terminal while server metadata is stale", async () => { - useTerminalUiStateStore.setState({ - terminalUiStateByThreadKey: { - [THREAD_KEY]: { - terminalOpen: true, - terminalHeight: 280, - terminalIds: ["term-2"], - activeTerminalId: "term-2", - terminalGroups: [{ id: "group-term-2", terminalIds: ["term-2"] }], - activeTerminalGroupId: "group-term-2", - }, - }, - }); - useRightPanelStore.setState({ - byThreadKey: { - [THREAD_KEY]: { - isOpen: true, - activeSurfaceId: "terminal:term-1", - surfaces: [ - { - id: "terminal:term-1", - kind: "terminal", - resourceId: "term-1", - terminalIds: ["term-1"], - activeTerminalId: "term-1", - }, - ], - }, - }, - }); - - const terminalSummary = (terminalId: string, pid: number) => ({ - threadId: THREAD_ID, - terminalId, - cwd: "/repo/project", - worktreePath: null, - status: "running" as const, - pid, - exitCode: null, - exitSignal: null, - hasRunningSubprocess: false, - label: terminalId === "term-1" ? "Terminal One" : "Terminal Two", - updatedAt: isoAt(pid), - }); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-close-terminal" as MessageId, - targetText: "close terminal", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "terminal.close", - shortcut: { - key: "w", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { type: "identifier", name: "terminalFocus" }, - }, - ], - }; - nextFixture.terminalMetadataEvents = [ - { type: "upsert", terminal: terminalSummary("term-1", 101) }, - { type: "upsert", terminal: terminalSummary("term-2", 102) }, - ]; - }, - }); - - try { - const terminalInput = await waitForElement( - () => - document.querySelector( - '[data-terminal-owner="right-panel"] .xterm-helper-textarea', - ), - "Unable to find right-panel terminal input.", - ); - terminalInput.focus(); - terminalInput.dispatchEvent( - new KeyboardEvent("keydown", { - key: "w", - code: "KeyW", - metaKey: isMacPlatform(navigator.platform), - ctrlKey: !isMacPlatform(navigator.platform), - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor(() => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalClose && request.terminalId === "term-1", - ), - ).toBe(true); - }); - - rpcHarness.emitStreamValue(WS_METHODS.subscribeTerminalMetadata, { - type: "upsert", - terminal: terminalSummary("term-1", 103), - }); - - await vi.waitFor(() => { - expect( - selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - THREAD_REF, - ).terminalIds, - ).toEqual(["term-2"]); - expect(document.querySelectorAll(".xterm-helper-textarea")).toHaveLength(1); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("preserves vertical panel splits, routes split actions to the panel, and attaches each pane at its own launch location", async () => { - useRightPanelStore.setState({ - byThreadKey: { - [THREAD_KEY]: { - isOpen: true, - activeSurfaceId: "terminal:term-1", - surfaces: [ - { - id: "terminal:term-1", - kind: "terminal", - resourceId: "term-1", - terminalIds: ["term-1", "term-2"], - activeTerminalId: "term-1", - splitDirection: "vertical", - }, - ], - }, - }, - }); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-vertical-terminal-panel" as MessageId, - targetText: "vertical terminal panel", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "terminal.splitVertical", - shortcut: { - key: "d", - metaKey: false, - ctrlKey: true, - shiftKey: true, - altKey: false, - modKey: false, - }, - whenAst: { type: "identifier", name: "terminalFocus" }, - }, - ], - }; - nextFixture.terminalMetadataEvents = [ - { - type: "upsert", - terminal: { - threadId: THREAD_ID, - terminalId: "term-1", - cwd: "/repo/worktrees/one", - worktreePath: "/repo/worktrees/one", - status: "running", - pid: 101, - exitCode: null, - exitSignal: null, - hasRunningSubprocess: false, - label: "Terminal One", - updatedAt: isoAt(0), - }, - }, - { - type: "upsert", - terminal: { - threadId: THREAD_ID, - terminalId: "term-2", - cwd: "/repo/worktrees/two", - worktreePath: "/repo/worktrees/two", - status: "running", - pid: 102, - exitCode: null, - exitSignal: null, - hasRunningSubprocess: false, - label: "Terminal Two", - updatedAt: isoAt(1), - }, - }, - ]; - }, - }); - - try { - const panel = await waitForElement( - () => document.querySelector('[data-terminal-owner="right-panel"]'), - "Unable to find right-panel terminal.", - ); - - await vi.waitFor( - () => { - const splitGrid = panel.querySelector(".grid"); - expect(splitGrid?.style.gridTemplateRows).toContain("repeat(2"); - expect(splitGrid?.style.gridTemplateColumns).toBe(""); - - const attachRequests = wsRequests.filter( - (request) => request._tag === WS_METHODS.terminalAttach, - ); - expect(attachRequests).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - terminalId: "term-1", - cwd: "/repo/worktrees/one", - worktreePath: "/repo/worktrees/one", - env: expect.objectContaining({ - T3CODE_WORKTREE_PATH: "/repo/worktrees/one", - }), - }), - expect.objectContaining({ - terminalId: "term-2", - cwd: "/repo/worktrees/two", - worktreePath: "/repo/worktrees/two", - env: expect.objectContaining({ - T3CODE_WORKTREE_PATH: "/repo/worktrees/two", - }), - }), - ]), - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - const verticalSplitButton = await waitForElement( - () => - Array.from(panel.querySelectorAll("button")).find((button) => - button.getAttribute("aria-label")?.startsWith("Split Terminal Vertically"), - ) ?? null, - "Unable to find vertical split action.", - ); - verticalSplitButton.click(); - - await vi.waitFor(() => { - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF) - .surfaces[0], - ).toMatchObject({ - terminalIds: ["term-1", "term-2", "term-3"], - activeTerminalId: "term-3", - splitDirection: "vertical", - }); - }); - - const terminalInput = await waitForElement( - () => - Array.from(panel.querySelectorAll(".xterm-helper-textarea")).at( - -1, - ) ?? null, - "Unable to find terminal input.", - ); - terminalInput.focus(); - terminalInput.dispatchEvent( - new KeyboardEvent("keydown", { - key: "d", - code: "KeyD", - ctrlKey: true, - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor(() => { - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF) - .surfaces[0], - ).toMatchObject({ - terminalIds: ["term-1", "term-2", "term-3", "term-4"], - activeTerminalId: "term-4", - splitDirection: "vertical", - }); - expect( - selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - THREAD_REF, - ).terminalOpen, - ).toBe(false); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps multiple terminal panel surfaces separate from the bottom drawer", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-open-inline-terminal-panel" as MessageId, - targetText: "open inline terminal panel", - }), - }); - - try { - const rightPanelToggle = await waitForElement( - () => document.querySelector('button[aria-label="Toggle right panel"]'), - "Unable to find right panel toggle.", - ); - rightPanelToggle.click(); - - await vi.waitFor(() => { - expect(document.body.textContent).toContain("Open a surface"); - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF), - ).toEqual({ - isOpen: true, - activeSurfaceId: null, - surfaces: [], - }); - }); - expect(wsRequests.some((request) => request._tag === WS_METHODS.terminalOpen)).toBe(false); - - const emptyStateTerminalButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find((button) => - button.textContent?.includes("Start a shell in this workspace."), - ) ?? null, - "Unable to find the empty-state Terminal button.", - ); - emptyStateTerminalButton.click(); - - await vi.waitFor(() => { - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF) - .surfaces.filter((surface) => surface.kind === "terminal") - .map((surface) => surface.resourceId), - ).toEqual(["term-1"]); - }); - - const addSurface = await waitForElement( - () => document.querySelector('button[aria-label="Add panel surface"]'), - "Unable to find add panel surface button beside the tabs.", - ); - addSurface.click(); - const secondTerminalItem = await waitForElement( - () => - Array.from(document.querySelectorAll('[role="menuitem"]')).find( - (item) => item.textContent?.trim() === "Terminal", - ) ?? null, - "Unable to find Terminal panel menu item.", - ); - secondTerminalItem.click(); - - await vi.waitFor( - () => { - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF) - .surfaces.filter((surface) => surface.kind === "terminal") - .map((surface) => surface.resourceId), - ).toEqual(["term-1", "term-2"]); - expect(document.querySelector('[data-terminal-owner="right-panel"]')).not.toBeNull(); - expect( - wsRequests - .filter((request) => request._tag === WS_METHODS.terminalOpen) - .map((request) => ("terminalId" in request ? request.terminalId : null)), - ).toEqual(expect.arrayContaining(["term-1", "term-2"])); - const attachRequest = wsRequests.find( - (request) => - request._tag === WS_METHODS.terminalAttach && - "terminalId" in request && - request.terminalId === "term-2", - ); - expect(attachRequest).toMatchObject({ - _tag: WS_METHODS.terminalAttach, - threadId: THREAD_ID, - terminalId: "term-2", - cwd: "/repo/project", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - const drawerToggle = await waitForElement( - () => - document.querySelector('button[aria-label="Toggle terminal drawer"]'), - "Unable to find terminal drawer toggle.", - ); - drawerToggle.click(); - - await vi.waitFor(() => { - expect( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey[THREAD_KEY], - ).toMatchObject({ - terminalOpen: true, - terminalIds: ["term-3"], - }); - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalAttach && - "terminalId" in request && - request.terminalId === "term-3", - ), - ).toBe(true); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("mounts one diff viewer through the right panel across responsive layouts", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-single-diff-panel" as MessageId, - targetText: "single diff panel", - }), - initialPath: `/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}?diff=1`, - }); - - try { - await waitForElement( - () => document.querySelector('button[aria-label="Stacked diff view"]'), - "Unable to find diff viewer.", - ); - for (const viewport of [WIDE_FOOTER_VIEWPORT, COMPACT_FOOTER_VIEWPORT]) { - await mounted.setViewport(viewport); - expect( - document.querySelectorAll('button[aria-label="Stacked diff view"]'), - ).toHaveLength(1); - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF), - ).toMatchObject({ - isOpen: true, - activeSurfaceId: "diff", - surfaces: [{ id: "diff", kind: "diff" }], - }); - } - } finally { - await mounted.cleanup(); - } - }); - - it("renders a persisted plan surface across responsive layouts", async () => { - useRightPanelStore.getState().open(THREAD_REF, "plan"); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithLongProposedPlan(), - }); - - try { - await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (element) => element.textContent?.trim() === "Ship plan mode follow-up", - ) ?? null, - "Unable to find persisted plan surface content.", - ); - for (const viewport of [WIDE_FOOTER_VIEWPORT, COMPACT_FOOTER_VIEWPORT]) { - await mounted.setViewport(viewport); - await vi.waitFor(() => { - expect(document.body.textContent).toContain("Ship plan mode follow-up"); - expect( - document.querySelector("[data-right-panel-tabbar]")?.textContent, - ).toContain("Plan"); - }); - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF), - ).toMatchObject({ - isOpen: true, - activeSurfaceId: "plan", - surfaces: [{ id: "plan", kind: "plan" }], - }); - } - } finally { - await mounted.cleanup(); - } - }); - - it("shows configured terminal and right-panel shortcuts in header tooltips", async () => { - const keybindings = [ - { - command: "terminal.toggle" as const, - shortcut: { - key: "u", - metaKey: false, - ctrlKey: true, - shiftKey: true, - altKey: false, - modKey: false, - }, - }, - { - command: "rightPanel.toggle" as const, - shortcut: { - key: "i", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: true, - modKey: false, - }, - }, - ]; - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-header-shortcut-labels" as MessageId, - targetText: "header shortcut labels", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings, - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const terminalLabel = shortcutLabelForCommand(keybindings, "terminal.toggle"); - const rightPanelLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle"); - - const terminalToggle = page.getByRole("button", { name: "Toggle terminal drawer" }).first(); - await terminalToggle.hover(); - await expect - .element(page.getByText(`Toggle terminal drawer (${terminalLabel})`, { exact: true })) - .toBeInTheDocument(); - - const rightPanelToggle = page.getByRole("button", { name: "Toggle right panel" }).first(); - await rightPanelToggle.hover(); - await expect - .element(page.getByText(`Toggle right panel (${rightPanelLabel})`, { exact: true })) - .toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode-insiders"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscode-insiders", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the project cwd with Trae when it is the only available editor", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["trae"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "trae", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows Kiro in the open picker menu and opens the project cwd with it", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["kiro"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const menuButton = await waitForElement( - () => document.querySelector('button[aria-label="Copy options"]'), - "Unable to find Open picker button.", - ); - (menuButton as HTMLButtonElement).click(); - - const kiroItem = await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => - item.textContent?.includes("Kiro"), - ) ?? null, - "Unable to find Kiro menu item.", - ); - (kiroItem as HTMLElement).click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "kiro", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("filters the open picker menu and opens VSCodium from the menu", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode-insiders", "vscodium"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const menuButton = await waitForElement( - () => document.querySelector('button[aria-label="Copy options"]'), - "Unable to find Open picker button.", - ); - (menuButton as HTMLButtonElement).click(); - - await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => - item.textContent?.includes("VS Code Insiders"), - ) ?? null, - "Unable to find VS Code Insiders menu item.", - ); - - expect( - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) => - item.textContent?.includes("Zed"), - ), - ).toBe(false); - - const vscodiumItem = await waitForElement( - () => - Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => - item.textContent?.includes("VSCodium"), - ) ?? null, - "Unable to find VSCodium menu item.", - ); - (vscodiumItem as HTMLElement).click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscodium", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to the first installed editor when the stored favorite is unavailable", async () => { - localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium")); - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - availableEditors: ["vscode-insiders"], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const openButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Open", - ) as HTMLButtonElement | null, - "Unable to find Open button.", - ); - await vi.waitFor(() => { - expect(openButton.disabled).toBe(false); - }); - openButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.shellOpenInEditor, - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/repo/project", - editor: "vscode-insiders", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("runs project scripts from local draft threads at the project cwd", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "lint", - name: "Lint", - command: "bun run lint", - icon: "lint", - runOnWorktreeCreate: false, - }, - ]), - }); - - try { - const runButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.getAttribute("aria-label") === "Run Lint", - ) as HTMLButtonElement | null, - "Unable to find Run Lint button.", - ); - runButton.click(); - - await vi.waitFor( - () => { - const openRequest = wsRequests.find( - (request) => - request._tag === WS_METHODS.terminalOpen && - request.threadId === THREAD_ID && - request.cwd === "/repo/project", - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.terminalOpen, - threadId: THREAD_ID, - cwd: "/repo/project", - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await vi.waitFor( - () => { - const writeRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.terminalWrite, - ); - expect(writeRequest).toMatchObject({ - _tag: WS_METHODS.terminalWrite, - threadId: THREAD_ID, - data: "bun run lint\r", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("runs project scripts from worktree draft threads at the worktree cwd", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "feature/draft", - worktreePath: "/repo/worktrees/feature-draft", - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "test", - name: "Test", - command: "bun run test", - icon: "test", - runOnWorktreeCreate: false, - }, - ]), - }); - - try { - const runButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.getAttribute("aria-label") === "Run Test", - ) as HTMLButtonElement | null, - "Unable to find Run Test button.", - ); - runButton.click(); - - await vi.waitFor( - () => { - const openRequests = wsRequests.filter( - (request) => request._tag === WS_METHODS.terminalOpen, - ); - expect(openRequests).toContainEqual( - expect.objectContaining({ - _tag: WS_METHODS.terminalOpen, - threadId: THREAD_ID, - cwd: "/repo/worktrees/feature-draft", - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft", - }, - }), - ); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("lets the server own setup after preparing a pull request worktree thread", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.gitResolvePullRequest) { - return { - pullRequest: { - number: 1359, - title: "Add thread archiving and settings navigation", - url: "https://github.com/pingdotgg/t3code/pull/1359", - baseBranch: "main", - headBranch: "archive-settings-overhaul", - state: "open", - }, - }; - } - if (body._tag === WS_METHODS.gitPreparePullRequestThread) { - return { - pullRequest: { - number: 1359, - title: "Add thread archiving and settings navigation", - url: "https://github.com/pingdotgg/t3code/pull/1359", - baseBranch: "main", - headBranch: "archive-settings-overhaul", - state: "open", - }, - branch: "archive-settings-overhaul", - worktreePath: "/repo/worktrees/pr-1359", - }; - } - return undefined; - }, - }); - - try { - const branchButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "main", - ) as HTMLButtonElement | null, - "Unable to find branch selector button.", - ); - branchButton.click(); - - const branchInput = await waitForElement( - () => document.querySelector('input[placeholder="Search refs..."]'), - "Unable to find ref search input.", - ); - branchInput.focus(); - await page.getByPlaceholder("Search refs...").fill("1359"); - - const checkoutItem = await waitForElement( - () => - Array.from(document.querySelectorAll("span")).find( - (element) => element.textContent?.trim() === "Checkout pull request", - ) as HTMLSpanElement | null, - "Unable to find checkout pull request option.", - ); - checkoutItem.click(); - - const worktreeButton = await waitForElement(() => { - const dialog = Array.from(document.querySelectorAll('[role="dialog"]')).find( - (candidate) => candidate.textContent?.includes("Checkout pull request"), - ); - return ( - Array.from(dialog?.querySelectorAll("button") ?? []).find( - (button) => button.textContent?.trim() === "Worktree" && !button.disabled, - ) ?? null - ); - }, "Unable to find Worktree button."); - worktreeButton.click(); - - await vi.waitFor( - () => { - const prepareRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.gitPreparePullRequestThread, - ); - expect(prepareRequest).toMatchObject({ - _tag: WS_METHODS.gitPreparePullRequestThread, - cwd: "/repo/project", - reference: "1359", - mode: "worktree", - threadId: THREAD_ID, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r", - ), - ).toBe(false); - } finally { - await mounted.cleanup(); - } - }); - - it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => { - useTerminalUiStateStore.setState({ - terminalUiStateByThreadKey: {}, - }); - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [THREAD_KEY]: { - threadId: THREAD_ID, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: THREAD_KEY, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]), - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand, - ) as - | { - _tag: string; - type?: string; - bootstrap?: { - createThread?: { projectId?: string }; - prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string }; - runSetupScript?: boolean; - }; - } - | undefined; - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "thread.turn.start", - bootstrap: { - createThread: { - projectId: PROJECT_ID, - }, - prepareWorktree: { - projectCwd: "/repo/project", - baseBranch: "main", - branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/), - }, - runSetupScript: true, - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - expect(wsRequests.some((request) => request._tag === WS_METHODS.vcsCreateWorktree)).toBe( - false, - ); - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.terminalWrite && - request.threadId === THREAD_ID && - request.data === "bun install\r", - ), - ).toBe(false); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps custom provider instance ids when bootstrapping a local draft thread", async () => { - setDraftThreadWithoutWorktree(); - const openRouterInstanceId = ProviderInstanceId.make("claude_openrouter"); - const openRouterSelection = createModelSelection(openRouterInstanceId, "openai/gpt-5.5"); - useComposerDraftStore.getState().setModelSelection(THREAD_REF, openRouterSelection); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - providers: [ - ...nextFixture.serverConfig.providers, - { - driver: ProviderDriverKind.make("claudeAgent"), - instanceId: ProviderInstanceId.make("claudeAgent"), - enabled: true, - installed: true, - version: "2.1.117", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: NOW_ISO, - models: [ - { - slug: "claude-opus-4-7", - name: "Claude Opus 4.7", - isCustom: false, - capabilities: createModelCapabilities({ optionDescriptors: [] }), - }, - ], - slashCommands: [], - skills: [], - }, - { - driver: ProviderDriverKind.make("claudeAgent"), - instanceId: openRouterInstanceId, - displayName: "Claude OpenRouter", - enabled: true, - installed: true, - version: "2.1.117", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: NOW_ISO, - models: [ - { - slug: "claude-opus-4-7", - name: "Claude Opus 4.7", - isCustom: false, - capabilities: createModelCapabilities({ optionDescriptors: [] }), - }, - ], - slashCommands: [], - skills: [], - }, - ], - settings: { - ...nextFixture.serverConfig.settings, - providerInstances: { - ...nextFixture.serverConfig.settings.providerInstances, - [openRouterInstanceId]: { - driver: ProviderDriverKind.make("claudeAgent"), - displayName: "Claude OpenRouter", - config: { customModels: ["openai/gpt-5.5"] }, - }, - }, - }, - }; - }, - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Hello there"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const turnStartRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.turn.start", - ) as - | { - modelSelection?: { instanceId?: string; model?: string }; - bootstrap?: { - createThread?: { - modelSelection?: { instanceId?: string; model?: string }; - }; - }; - } - | undefined; - - expect(turnStartRequest?.modelSelection).toMatchObject({ - instanceId: openRouterInstanceId, - model: "openai/gpt-5.5", - }); - expect(turnStartRequest?.bootstrap?.createThread?.modelSelection).toMatchObject({ - instanceId: openRouterInstanceId, - model: "openai/gpt-5.5", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps new-worktree mode on empty server threads and bootstraps the first send", async () => { - const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, - ), - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.vcsListRefs) { - return { - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 1, - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - ], - }; - } - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("New worktree")).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const turnStartRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.turn.start", - ) as - | { - _tag: string; - type?: string; - bootstrap?: { - createThread?: { projectId?: string }; - prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string }; - runSetupScript?: boolean; - }; - } - | undefined; - - expect(turnStartRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "thread.turn.start", - bootstrap: { - prepareWorktree: { - projectCwd: "/repo/project", - baseBranch: "main", - branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/), - }, - runSetupScript: true, - }, - }); - expect(turnStartRequest?.bootstrap?.createThread).toBeUndefined(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("updates the selected worktree base branch on empty server threads", async () => { - const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, - ), - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.vcsListRefs) { - return { - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 2, - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - { - name: "release/next", - current: false, - isDefault: false, - worktreePath: null, - }, - ], - }; - } - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - await page.getByText("From main", { exact: true }).click(); - await page.getByText("release/next", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("From release/next")).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - - useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - const turnStartRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.turn.start", - ) as - | { - _tag: string; - type?: string; - bootstrap?: { - prepareWorktree?: { baseBranch?: string }; - }; - } - | undefined; - - expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("release/next"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("clears pending worktree overrides when switching empty server threads", async () => { - const secondThreadId = "thread-browser-test-second" as ThreadId; - const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); - const snapshotWithSecondThread = addThreadToSnapshot(snapshot, secondThreadId); - const snapshotWithTwoThreads = { - ...snapshotWithSecondThread, - threads: snapshotWithSecondThread.threads.map((thread) => { - if (thread.id === THREAD_ID) { - return Object.assign({}, thread, { session: null, title: "Thread alpha" }); - } - if (thread.id === secondThreadId) { - return Object.assign({}, thread, { session: null, title: "Thread beta" }); - } - return thread; - }), - }; - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: snapshotWithTwoThreads, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.vcsListRefs) { - return { - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 2, - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - { - name: "release/next", - current: false, - isDefault: false, - worktreePath: null, - }, - ], - }; - } - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - await page.getByText("From main", { exact: true }).click(); - await page.getByText("release/next", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("From release/next")).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - - await mounted.router.navigate({ - to: "/$environmentId/$threadId", - params: { - environmentId: LOCAL_ENVIRONMENT_ID, - threadId: secondThreadId, - }, - }); - - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(secondThreadId), - "Route should switch to the second empty server thread.", - ); - - await vi.waitFor( - () => { - expect(findButtonByText("Current checkout")).toBeTruthy(); - expect(findButtonByText("From release/next")).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - - (await waitForButtonByText("Current checkout")).click(); - await page.getByText("New worktree", { exact: true }).click(); - - await vi.waitFor( - () => { - expect(findButtonByText("From main")).toBeTruthy(); - expect(findButtonByText("From release/next")).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows the send state once bootstrap dispatch is in flight", async () => { - const sendStateThreadId = "thread-send-state-bootstrap" as ThreadId; - const sendStateThreadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, sendStateThreadId); - const sendStateThreadKey = scopedThreadKey(sendStateThreadRef); - useTerminalUiStateStore.setState({ - terminalUiStateByThreadKey: {}, - }); - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [sendStateThreadKey]: { - threadId: sendStateThreadId, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: sendStateThreadKey, - }, - }); - - let resolveDispatch!: (value: { sequence: number }) => void; - const dispatchPromise = new Promise<{ sequence: number }>((resolve) => { - resolveDispatch = resolve; - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: withProjectScripts(createDraftOnlySnapshot(), [ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]), - initialPath: `/draft/${sendStateThreadKey}`, - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return dispatchPromise; - } - return undefined; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(sendStateThreadRef, "Ship it"); - await waitForLayout(); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - expect( - wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand), - ).toBe(true); - expect(document.querySelector('button[aria-label="Sending"]')).toBeTruthy(); - expect(document.querySelector('button[aria-label="Preparing worktree"]')).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 }); - await mounted.cleanup(); - } - }); - - it("toggles plan mode with Shift+Tab only while the composer is focused", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-target-hotkey" as MessageId, - targetText: "hotkey target", - }), - }); - - try { - const initialModeButton = await waitForInteractionModeButton("Build"); - expect(initialModeButton.getAttribute("aria-label")).toContain("enter plan mode"); - expect(initialModeButton.hasAttribute("title")).toBe(false); - - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Tab", - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); - - expect((await waitForInteractionModeButton("Build")).getAttribute("aria-label")).toContain( - "enter plan mode", - ); - - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Tab", - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor( - async () => { - expect((await waitForInteractionModeButton("Plan")).getAttribute("aria-label")).toContain( - "return to normal build mode", - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Tab", - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor( - async () => { - expect( - (await waitForInteractionModeButton("Build")).getAttribute("aria-label"), - ).toContain("enter plan mode"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("focuses the composer and inserts printable text typed from the page background", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-target-type-to-focus" as MessageId, - targetText: "type-to-focus target", - }), - }); - - const backgroundTarget = document.createElement("div"); - backgroundTarget.tabIndex = -1; - document.body.append(backgroundTarget); - - try { - const composerEditor = await waitForComposerEditor(); - backgroundTarget.focus(); - expect(document.activeElement).not.toBe(composerEditor); - - const event = new KeyboardEvent("keydown", { - key: "h", - bubbles: true, - cancelable: true, - }); - backgroundTarget.dispatchEvent(event); - - await waitForComposerText("h"); - expect(event.defaultPrevented).toBe(true); - expect(document.activeElement).toBe(composerEditor); - - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "i", - bubbles: true, - cancelable: true, - }), - ); - - await waitForComposerText("hi"); - } finally { - backgroundTarget.remove(); - await mounted.cleanup(); - } - }); - - it("does not steal printable keys from editable targets or shortcut modifiers", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-target-type-to-focus-guards" as MessageId, - targetText: "type-to-focus guards target", - }), - }); - const input = document.createElement("input"); - document.body.append(input); - - try { - input.focus(); - input.dispatchEvent( - new KeyboardEvent("keydown", { - key: "x", - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); - expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe(""); - - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "k", - metaKey: true, - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); - expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe(""); - } finally { - input.remove(); - await mounted.cleanup(); - } - }); - - it("uses the active draft route session when changing the base branch", async () => { - const staleDraftId = draftIdFromPath("/draft/draft-stale-branch-session"); - const activeDraftId = draftIdFromPath("/draft/draft-active-branch-session"); - const staleThreadId = "thread-stale-branch-session" as ThreadId; - const activeThreadId = "thread-active-branch-session" as ThreadId; - - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [staleDraftId]: { - threadId: staleThreadId, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: `${PROJECT_DRAFT_KEY}:stale`, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - [activeDraftId]: { - threadId: activeThreadId, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [`${PROJECT_DRAFT_KEY}:stale`]: staleDraftId, - [PROJECT_DRAFT_KEY]: activeDraftId, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - initialPath: `/draft/${activeDraftId}`, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.vcsListRefs) { - return { - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 2, - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - { - name: "release/next", - current: false, - isDefault: false, - worktreePath: null, - }, - ], - }; - } - return undefined; - }, - }); - - try { - const branchButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "From main", - ) as HTMLButtonElement | null, - 'Unable to find branch selector button with "From main".', - ); - branchButton.click(); - - const branchOption = await waitForElement( - () => - Array.from(document.querySelectorAll("span")).find( - (element) => element.textContent?.trim() === "release/next", - ) as HTMLSpanElement | null, - 'Unable to find the "release/next" branch option.', - ); - branchOption.click(); - - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().getDraftSession(activeDraftId)?.branch).toBe( - "release/next", - ); - expect(useComposerDraftStore.getState().getDraftSession(staleDraftId)?.branch).toBe( - "main", - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - await vi.waitFor( - () => { - const updatedButton = Array.from(document.querySelectorAll("button")).find((button) => - button.textContent?.trim().includes("From release/next"), - ); - expect(updatedButton).toBeTruthy(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the new worktree branch picker anchored at the top when opening with a preselected branch", async () => { - const draftId = DraftId.make("draft-branch-picker-scroll-regression"); - const draftThreadId = "thread-branch-picker-scroll-regression" as ThreadId; - const branches = [ - { - name: "feature/current", - current: true, - isDefault: false, - worktreePath: null, - }, - { - name: "main", - current: false, - isDefault: true, - worktreePath: null, - }, - ...Array.from({ length: 48 }, (_, index) => ({ - name: `feature/${String(index).padStart(2, "0")}`, - current: false, - isDefault: false, - worktreePath: null, - })), - { - name: "feature/selected", - current: false, - isDefault: false, - worktreePath: null, - }, - ]; - - useComposerDraftStore.setState({ - draftThreadsByThreadKey: { - [draftId]: { - threadId: draftThreadId, - environmentId: LOCAL_ENVIRONMENT_ID, - projectId: PROJECT_ID, - logicalProjectKey: PROJECT_DRAFT_KEY, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: "feature/selected", - worktreePath: null, - envMode: "worktree", - }, - }, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - [PROJECT_DRAFT_KEY]: draftId, - }, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - initialPath: `/draft/${draftId}`, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.vcsListRefs) { - return { - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: branches.length, - refs: branches, - }; - } - return undefined; - }, - }); - - try { - const branchButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "From feature/selected", - ) as HTMLButtonElement | null, - 'Unable to find branch selector button with "From feature/selected".', - ); - branchButton.click(); - - await waitForElement( - () => document.querySelector('input[placeholder="Search refs..."]'), - "Unable to find ref search input.", - ); - - const popup = await waitForElement( - () => document.querySelector('[data-slot="combobox-popup"]'), - "Unable to find the branch picker popup.", - ); - - await vi.waitFor( - () => { - const popupSpans = Array.from(popup.querySelectorAll("span")); - expect( - popupSpans.some((element) => element.textContent?.trim() === "feature/current"), - ).toBe(true); - expect(popupSpans.some((element) => element.textContent?.trim() === "main")).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("surrounds selected plain text and preserves the inner selection for repeated wrapping", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-basic" as MessageId, - targetText: "surround basic", - }), - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "selected"); - await waitForComposerText("selected"); - await setComposerSelectionByTextOffsets({ start: 0, end: "selected".length }); - await pressComposerKey("("); - await waitForComposerText("(selected)"); - - await pressComposerKey("["); - await waitForComposerText("([selected])"); - } finally { - await mounted.cleanup(); - } - }); - - it("leaves collapsed-caret typing unchanged for surround symbols", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "selected"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-collapsed" as MessageId, - targetText: "surround collapsed", - }), - }); - - try { - await waitForComposerText("selected"); - await setComposerSelectionByTextOffsets({ - start: "selected".length, - end: "selected".length, - }); - await pressComposerKey("("); - await waitForComposerText("selected("); - } finally { - await mounted.cleanup(); - } - }); - - it("supports symmetric and backward-selection surrounds", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "backward"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-backward" as MessageId, - targetText: "surround backward", - }), - }); - - try { - await waitForComposerText("backward"); - await setComposerSelectionByTextOffsets({ - start: 0, - end: "backward".length, - direction: "backward", - }); - await pressComposerKey("*"); - await waitForComposerText("*backward*"); - } finally { - await mounted.cleanup(); - } - }); - - it("supports option-produced surround symbols like guillemets", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "quoted"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-guillemet" as MessageId, - targetText: "surround guillemet", - }), - }); - - try { - await waitForComposerText("quoted"); - await setComposerSelectionByTextOffsets({ start: 0, end: "quoted".length }); - await pressComposerKey("«"); - await waitForComposerText("«quoted»"); - } finally { - await mounted.cleanup(); - } - }); - - it("supports dead-key composition that resolves to another surround symbol without an extra undo step", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "quoted"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-dead-quote" as MessageId, - targetText: "surround dead quote", - }), - }); - - try { - await waitForComposerText("quoted"); - await setComposerSelectionByTextOffsets({ start: 0, end: "quoted".length }); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - composerEditor.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Dead", - bubbles: true, - cancelable: true, - }), - ); - composerEditor.dispatchEvent( - new InputEvent("beforeinput", { - data: "'", - inputType: "insertCompositionText", - bubbles: true, - cancelable: true, - }), - ); - const resolvedInputEvent = new InputEvent("beforeinput", { - data: "'", - inputType: "insertText", - bubbles: true, - cancelable: true, - }); - composerEditor.dispatchEvent(resolvedInputEvent); - expect(resolvedInputEvent.defaultPrevented).toBe(true); - await waitForComposerText("'quoted'"); - await pressComposerUndo(); - await waitForComposerText("quoted"); - } finally { - await mounted.cleanup(); - } - }); - - it("surrounds text after a mention using the correct expanded offsets", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "hi @package.json there"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-after-mention" as MessageId, - targetText: "surround after mention", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain("package.json"); - }, - { timeout: 8_000, interval: 16 }, - ); - await waitForComposerText("hi [package.json](package.json) there"); - await setComposerSelectionByTextOffsets({ - start: "hi package.json ".length, - end: "hi package.json there".length, - }); - await pressComposerKey("("); - await waitForComposerText("hi [package.json](package.json) (there)"); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to normal replacement when the selection includes a mention token", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "hi @package.json there "); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-surround-token" as MessageId, - targetText: "surround token", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain("package.json"); - }, - { timeout: 8_000, interval: 16 }, - ); - await selectAllComposerContent(); - await pressComposerKey("("); - await waitForComposerText("("); - } finally { - await mounted.cleanup(); - } - }); - - it("stores selected file tags as markdown links while keeping the composer chip", async () => { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "@pack"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-file-tag-encoding" as MessageId, - targetText: "file tag encoding", - }), - resolveRpc: (body) => { - if (body._tag !== WS_METHODS.projectsSearchEntries) { - return undefined; - } - return { - entries: [ - { - path: "path/to/package.json", - kind: "file", - }, - ], - truncated: false, - }; - }, - }); - - try { - const item = await waitForComposerMenuItem("path:file:path/to/package.json"); - item.click(); - - await waitForComposerText("[package.json](path/to/package.json) "); - const chip = await waitForElement( - () => document.querySelector('[data-composer-mention-chip="true"]'), - "Unable to find rendered composer file chip.", - ); - expect(chip.textContent).toContain("package.json"); - } finally { - await mounted.cleanup(); - } - }); - - it("shows runtime mode descriptions in the desktop composer access select", async () => { - setDraftThreadWithoutWorktree(); - - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createDraftOnlySnapshot(), - }); - - try { - const runtimeModeSelect = await waitForButtonByText("Full access"); - runtimeModeSelect.click(); - - expect((await waitForSelectItemContainingText("Supervised")).textContent).toContain( - "Ask before commands and file changes", - ); - - const autoAcceptItem = await waitForSelectItemContainingText("Auto-accept edits"); - expect(autoAcceptItem.textContent).toContain("Auto-approve edits"); - expect((await waitForSelectItemContainingText("Full access")).textContent).toContain( - "Allow commands and edits without prompts", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps removed terminal context pills removed when a new one is added", async () => { - const removedLabel = "Terminal 1 lines 1-2"; - const addedLabel = "Terminal 2 lines 9-10"; - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-removed", - terminalLabel: "Terminal 1", - lineStart: 1, - lineEnd: 2, - text: "bun i\nno changes", - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-terminal-pill-backspace" as MessageId, - targetText: "terminal pill backspace target", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain(removedLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - const store = useComposerDraftStore.getState(); - const currentPrompt = store.draftsByThreadKey[THREAD_KEY]?.prompt ?? ""; - const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0); - store.setPrompt(THREAD_REF, nextPrompt.prompt); - store.removeTerminalContext(THREAD_REF, "ctx-removed"); - - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]).toBeUndefined(); - expect(document.body.textContent).not.toContain(removedLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-added", - terminalLabel: "Terminal 2", - lineStart: 9, - lineEnd: 10, - text: "git status\nOn branch main", - }), - ); - - await vi.waitFor( - () => { - const draft = useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]; - expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]); - expect(document.body.textContent).toContain(addedLabel); - expect(document.body.textContent).not.toContain(removedLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("disables send when the composer only contains an expired terminal pill", async () => { - const expiredLabel = "Terminal 1 line 4"; - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-expired-only", - terminalLabel: "Terminal 1", - lineStart: 4, - lineEnd: 4, - text: "", - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-expired-pill-disabled" as MessageId, - targetText: "expired pill disabled target", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain(expiredLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(true); - } finally { - await mounted.cleanup(); - } - }); - - it("warns when sending text while omitting expired terminal pills", async () => { - const expiredLabel = "Terminal 1 line 4"; - useComposerDraftStore.getState().addTerminalContext( - THREAD_REF, - createTerminalContext({ - id: "ctx-expired-send-warning", - terminalLabel: "Terminal 1", - lineStart: 4, - lineEnd: 4, - text: "", - }), - ); - useComposerDraftStore - .getState() - .setPrompt(THREAD_REF, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-expired-pill-warning" as MessageId, - targetText: "expired pill warning target", - }), - }); - - try { - await vi.waitFor( - () => { - expect(document.body.textContent).toContain(expiredLabel); - }, - { timeout: 8_000, interval: 16 }, - ); - - const sendButton = await waitForSendButton(); - expect(sendButton.disabled).toBe(false); - sendButton.click(); - - await vi.waitFor( - () => { - expect(document.body.textContent).toContain( - "Expired terminal context omitted from message", - ); - expect(document.body.textContent).not.toContain(expiredLabel); - expect(document.body.textContent).toContain("yoowaddup"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows a pointer cursor for the running stop button", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-stop-button-cursor" as MessageId, - targetText: "stop button cursor target", - sessionStatus: "running", - }), - }); - - try { - const stopButton = await waitForElement( - () => document.querySelector('button[aria-label="Stop generation"]'), - "Unable to find stop generation button.", - ); - - expect(getComputedStyle(stopButton).cursor).toBe("pointer"); - } finally { - await mounted.cleanup(); - } - }); - - it("hides the archive action when the pointer leaves a thread row", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-archive-hover-test" as MessageId, - targetText: "archive hover target", - }), - }); - - try { - const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); - - await expect.element(threadRow).toBeInTheDocument(); - const archiveButton = await waitForElement( - () => - document.querySelector(`[data-testid="thread-archive-${THREAD_ID}"]`), - "Unable to find archive button.", - ); - const archiveAction = archiveButton.parentElement; - expect( - archiveAction, - "Archive button should render inside a visibility wrapper.", - ).not.toBeNull(); - expect(getComputedStyle(archiveAction!).opacity).toBe("0"); - - await threadRow.hover(); - await vi.waitFor( - () => { - expect(getComputedStyle(archiveAction!).opacity).toBe("1"); - }, - { timeout: 4_000, interval: 16 }, - ); - - await page.getByTestId("composer-editor").hover(); - await vi.waitFor( - () => { - expect(getComputedStyle(archiveAction!).opacity).toBe("0"); - }, - { timeout: 4_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("exposes the full thread title on the sidebar row tooltip", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-thread-tooltip-target" as MessageId, - targetText: "thread tooltip target", - }), - }); - - try { - const threadTitle = page.getByTestId(`thread-title-${THREAD_ID}`); - - await expect.element(threadTitle).toBeInTheDocument(); - await threadTitle.hover(); - - await vi.waitFor( - () => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip).not.toBeNull(); - expect(tooltip?.textContent).toContain(THREAD_TITLE); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows the sidebar terminal indicator from terminal metadata activity", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-terminal-metadata-indicator" as MessageId, - targetText: "terminal metadata indicator target", - }), - configureFixture: (nextFixture) => { - nextFixture.terminalMetadataEvents = [ - { - type: "upsert", - terminal: { - threadId: THREAD_ID, - terminalId: DEFAULT_TERMINAL_ID, - cwd: "/repo/project", - worktreePath: null, - status: "running", - pid: 123, - exitCode: null, - exitSignal: null, - hasRunningSubprocess: true, - label: "Terminal 1", - updatedAt: isoAt(1_200), - }, - }, - ]; - }, - }); - - try { - await vi.waitFor( - () => { - const terminalIndicator = document.querySelector( - '[aria-label="Terminal process running"]', - ); - expect(terminalIndicator).not.toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows the confirm archive action after clicking the archive button", async () => { - localStorage.setItem( - "t3code:client-settings:v1", - JSON.stringify({ - ...DEFAULT_CLIENT_SETTINGS, - confirmThreadArchive: true, - }), - ); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-archive-confirm-test" as MessageId, - targetText: "archive confirm target", - }), - }); - - try { - const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); - - await expect.element(threadRow).toBeInTheDocument(); - await threadRow.hover(); - - const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`); - await expect.element(archiveButton).toBeInTheDocument(); - await archiveButton.click(); - - const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`); - await expect.element(confirmButton).toBeInTheDocument(); - await expect.element(confirmButton).toBeVisible(); - } finally { - localStorage.removeItem("t3code:client-settings:v1"); - await mounted.cleanup(); - } - }); - - it("canonicalizes promoted draft threads to the server thread route", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-new-thread-test" as MessageId, - targetText: "new thread selection test", - }), - }); - - try { - // Wait for the sidebar to render with the project. - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - // The route should change to a new draft thread ID. - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - const newThreadId = draftThreadIdFor(newDraftId); - - // The composer editor should be present for the new draft thread. - await waitForComposerEditor(); - - // `thread.created` should only mark the draft as promoting; it should - // not navigate away until the server thread has actual runtime state. - await materializePromotedDraftThreadViaDomainEvent(newThreadId); - expect(mounted.router.state.location.pathname).toBe(newThreadPath); - await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); - - // Once the server thread starts, the route should canonicalize. - await startPromotedServerThreadViaDomainEvent(newThreadId); - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().draftThreadsByThreadKey[newDraftId]).toBe( - undefined, - ); - }, - { timeout: 8_000, interval: 16 }, - ); - - // The route should switch to the canonical server thread path. - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(newThreadId), - "Promoted drafts should canonicalize to the server thread route.", - ); - - // The composer should remain usable after canonicalization, regardless of - // whether the promoted thread is still visibly empty or has already - // entered the running state. - await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("canonicalizes stale promoted draft routes to the server thread route", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-draft-hydration-race-test" as MessageId, - targetText: "draft hydration race test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - const newThreadId = draftThreadIdFor(newDraftId); - - await promoteDraftThreadViaDomainEvent(newThreadId); - - await mounted.router.navigate({ - to: "/draft/$draftId", - params: { draftId: newDraftId }, - }); - - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(newThreadId), - "Stale promoted draft routes should canonicalize to the server thread path.", - ); - - await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a fresh worktree draft from an existing worktree thread when the default mode is worktree", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...createSnapshotForTargetUser({ - targetMessageId: "msg-user-new-thread-worktree-default-test" as MessageId, - targetText: "new thread worktree default test", - }), - threads: createSnapshotForTargetUser({ - targetMessageId: "msg-user-new-thread-worktree-default-test" as MessageId, - targetText: "new thread worktree default test", - }).threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - branch: "feature/existing", - worktreePath: "/repo/.t3/worktrees/existing", - }) - : thread, - ), - }, - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - defaultThreadEnvMode: "worktree", - }, - }; - }, - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should change to a new draft thread.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(useComposerDraftStore.getState().getDraftSession(newDraftId)).toMatchObject({ - envMode: "worktree", - worktreePath: null, - }); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a new draft instead of reusing a promoting draft thread", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-promoting-draft-new-thread-test" as MessageId, - targetText: "promoting draft new thread test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const firstDraftPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should change to the first draft thread.", - ); - const firstDraftId = draftIdFromPath(firstDraftPath); - const firstThreadId = draftThreadIdFor(firstDraftId); - - await materializePromotedDraftThreadViaDomainEvent(firstThreadId); - expect(mounted.router.state.location.pathname).toBe(firstDraftPath); - - await newThreadButton.click(); - - const secondDraftPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path) && path !== firstDraftPath, - "Route should change to a second draft thread instead of reusing the promoting draft.", - ); - expect(draftIdFromPath(secondDraftPath)).not.toBe(firstDraftId); - } finally { - await mounted.cleanup(); - } - }); - - it("snapshots sticky codex settings into a new draft thread", async () => { - useComposerDraftStore.setState({ - stickyModelSelectionByProvider: { - [ProviderInstanceId.make("codex")]: createModelSelection( - ProviderInstanceId.make("codex"), - "gpt-5.3-codex", - [ - { id: "reasoningEffort", value: "medium" }, - { id: "fastMode", value: true }, - ], - ), - }, - stickyActiveProvider: ProviderInstanceId.make("codex"), - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sticky-codex-traits-test" as MessageId, - targetText: "sticky codex traits test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - // `toMatchObject` matches objects loosely (extras ignored) but compares - // arrays strictly, so wrap `options` in `arrayContaining` to keep the - // assertion focused on sticky `fastMode` carrying over without asserting - // on exactly which other options are preserved. - expect(composerDraftFor(newDraftId)).toMatchObject({ - modelSelectionByProvider: { - codex: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.3-codex", - options: expect.arrayContaining([{ id: "fastMode", value: true }]), - }, - }, - activeProvider: "codex", - }); - } finally { - await mounted.cleanup(); - } - }); - - it("hydrates the provider alongside a sticky claude model", async () => { - useComposerDraftStore.setState({ - stickyModelSelectionByProvider: { - [ProviderInstanceId.make("claudeAgent")]: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - [ - { id: "effort", value: "max" }, - { id: "fastMode", value: true }, - ], - ), - }, - stickyActiveProvider: ProviderInstanceId.make("claudeAgent"), - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sticky-claude-model-test" as MessageId, - targetText: "sticky claude model test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new sticky claude draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(composerDraftFor(newDraftId)).toMatchObject({ - modelSelectionByProvider: { - claudeAgent: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - [ - { id: "effort", value: "max" }, - { id: "fastMode", value: true }, - ], - ), - }, - activeProvider: "claudeAgent", - }); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to defaults when no sticky composer settings exist", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-default-codex-traits-test" as MessageId, - targetText: "default codex traits test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const newThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID.", - ); - const newDraftId = draftIdFromPath(newThreadPath); - - expect(composerDraftFor(newDraftId)).toBe(undefined); - } finally { - await mounted.cleanup(); - } - }); - - it("prefers draft state over sticky composer settings and defaults", async () => { - useComposerDraftStore.setState({ - stickyModelSelectionByProvider: { - [ProviderInstanceId.make("codex")]: createModelSelection( - ProviderInstanceId.make("codex"), - "gpt-5.3-codex", - [ - { id: "reasoningEffort", value: "medium" }, - { id: "fastMode", value: true }, - ], - ), - }, - stickyActiveProvider: ProviderInstanceId.make("codex"), - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-draft-codex-traits-precedence-test" as MessageId, - targetText: "draft codex traits precedence test", - }), - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - - await newThreadButton.click(); - - const threadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a sticky draft thread UUID.", - ); - const draftId = draftIdFromPath(threadPath); - - // See the note on the sibling sticky-codex test: arrays match strictly - // under `toMatchObject`, so use `arrayContaining` to keep the assertion - // scoped to the sticky trait (`fastMode`) that must carry over. - expect(composerDraftFor(draftId)).toMatchObject({ - modelSelectionByProvider: { - codex: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.3-codex", - options: expect.arrayContaining([{ id: "fastMode", value: true }]), - }, - }, - activeProvider: "codex", - }); - - useComposerDraftStore.getState().setModelSelection( - draftId, - createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ - { id: "reasoningEffort", value: "low" }, - { id: "fastMode", value: true }, - ]), - ); - - await newThreadButton.click(); - - await waitForURL( - mounted.router, - (path) => path === threadPath, - "New-thread should reuse the existing project draft thread.", - ); - expect(composerDraftFor(draftId)).toMatchObject({ - modelSelectionByProvider: { - codex: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ - { id: "reasoningEffort", value: "low" }, - { id: "fastMode", value: true }, - ]), - }, - activeProvider: "codex", - }); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a new thread from the global chat.new shortcut", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-chat-shortcut-test" as MessageId, - targetText: "chat shortcut test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "chat.new", - shortcut: { - key: "o", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - { - command: "thread.jump.1", - shortcut: { - key: "1", - metaKey: true, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: false, - }, - }, - { - command: "modelPicker.jump.1", - shortcut: { - key: "1", - metaKey: true, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: false, - }, - whenAst: { type: "identifier", name: "modelPickerOpen" }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - await waitForLayout(); - await triggerChatNewShortcutUntilPath( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID from the shortcut.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not consume chat.new when there is no project context", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createProjectlessSnapshot(), - initialPath: "/", - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "chat.new", - shortcut: { - key: "p", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await mounted.router.navigate({ to: "/" }); - await waitForURL( - mounted.router, - (path) => path === "/", - "Projectless fixture should settle on the no-active-thread route.", - ); - const pathBeforeShortcut = mounted.router.state.location.pathname; - const useMetaForMod = isMacPlatform(navigator.platform); - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "p", - code: "KeyP", - metaKey: useMetaForMod, - ctrlKey: !useMetaForMod, - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - await waitForLayout(); - - expect(mounted.router.state.location.pathname).toBe(pathBeforeShortcut); - expect(Object.keys(useComposerDraftStore.getState().draftThreadsByThreadKey)).toHaveLength(0); - } finally { - await mounted.cleanup(); - } - }); - - it("renders the configurable shortcut and runs a command from the sidebar trigger", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-shortcut-test" as MessageId, - targetText: "command palette shortcut test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await expect - .element(palette.getByText("New thread in Project", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("New thread in Project", { exact: true }).click(); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID from the command palette.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("filters command palette results as the user types", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-search-test" as MessageId, - targetText: "command palette search test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("settings"); - await expect.element(palette.getByText("Open settings", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("New thread in Project", { exact: true })) - .not.toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("adds a project from browse mode with Enter when no directory is highlighted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-enter" as MessageId, - targetText: "command palette add project enter", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [ - { name: "alpha", fullPath: "~/Development/alpha" }, - { name: "beta", fullPath: "~/Development/beta" }, - ], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await palette.getByText("Local folder", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); - await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument(); - - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development", - title: "Development", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project with Enter.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows clone destination controls after resolving an add project repository", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-remote" as MessageId, - targetText: "command palette add project remote", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === WS_METHODS.sourceControlLookupRepository) { - return { - provider: "github", - nameWithOwner: "t3-oss/t3-env", - url: "https://github.com/t3-oss/t3-env", - sshUrl: "git@github.com:t3-oss/t3-env.git", - }; - } - - if (body._tag === WS_METHODS.sourceControlCloneRepository) { - return { - cwd: body.destinationPath, - remoteUrl: body.remoteUrl, - repository: null, - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await palette.getByText("GitHub repository", { exact: true }).click(); - - const repositoryInput = await waitForCommandPaletteInput( - "Enter GitHub repository (owner/repo)", - ); - await page.getByPlaceholder("Enter GitHub repository (owner/repo)").fill("t3-oss/t3-env"); - await dispatchInputKey(repositoryInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const clonePathInput = document.querySelector( - 'input[placeholder="Enter path (e.g. ~/projects/my-app)"]', - ); - expect(clonePathInput?.value).toBe("~/"); - expect(document.body.textContent).toContain("Repository"); - expect(document.body.textContent).toContain("t3-oss/t3-env"); - expect(document.body.textContent).toContain("https://github.com/t3-oss/t3-env"); - expect(document.body.textContent).toContain("Select where to clone"); - expect(document.body.textContent).toContain("Development"); - expect(document.body.textContent).toContain("Clone"); - }, - { timeout: 8_000, interval: 16 }, - ); - - await page - .getByPlaceholder("Enter path (e.g. ~/projects/my-app)") - .fill("~/Development/t3env"); - const clonePathInput = await waitForCommandPaletteInput( - "Enter path (e.g. ~/projects/my-app)", - ); - await dispatchInputKey(clonePathInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const cloneRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.sourceControlCloneRepository, - ) as { destinationPath?: string; remoteUrl?: string } | undefined; - expect(cloneRequest).toMatchObject({ - remoteUrl: "git@github.com:t3-oss/t3-env.git", - destinationPath: "~/Development/t3env", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("opens add project browse mode from the sidebar add button", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sidebar-add-project-trigger" as MessageId, - targetText: "sidebar add project trigger", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - - await page.getByTestId("sidebar-add-project-trigger").click(); - - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Local folder", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await expect.element(browseInput).toHaveValue("~/"); - - await vi.waitFor( - () => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.filesystemBrowse && request.partialPath === "~/", - ), - ).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("starts add project browse mode from the configured base directory", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-sidebar-add-project-custom-base-dir" as MessageId, - targetText: "sidebar add project custom base directory", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - addProjectBaseDirectory: "~/Development", - }, - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [{ name: "codething", fullPath: "~/Development/codething" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - - await page.getByTestId("sidebar-add-project-trigger").click(); - - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Local folder", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await expect.element(browseInput).toHaveValue("~/Development/"); - - await vi.waitFor( - () => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.filesystemBrowse && - request.partialPath === "~/Development/", - ), - ).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows create-folder affordances for missing project paths", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-create-missing-project" as MessageId, - targetText: "command palette create missing project", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Desktop/") { - return { - parentPath: "~/Desktop/", - entries: [{ name: "existing", fullPath: "~/Desktop/existing" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Desktop", fullPath: "~/Desktop" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - const palette = page.getByTestId("command-palette"); - await page.getByTestId("sidebar-add-project-trigger").click(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Local folder", { exact: true }).click(); - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Desktop/fresh-project"); - - await expect - .element(palette.getByRole("button", { name: "Create & Add (Enter)" })) - .toBeInTheDocument(); - await expect.element(palette.getByText("Will create this folder")).not.toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - createWorkspaceRootIfMissing?: boolean; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Desktop/fresh-project", - title: "fresh-project", - createWorkspaceRootIfMissing: true, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not show create affordances for an existing directory with a trailing slash", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-existing-trailing-directory" as MessageId, - targetText: "command palette existing trailing directory", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/codex/") { - return { - parentPath: "~/Development/codex/", - entries: [{ name: "Codex.app", fullPath: "~/Development/codex/Codex.app" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - const palette = page.getByTestId("command-palette"); - await page.getByTestId("sidebar-add-project-trigger").click(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Local folder", { exact: true }).click(); - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/codex/"); - - await vi.waitFor( - () => { - expect( - wsRequests.some( - (request) => - request._tag === WS_METHODS.filesystemBrowse && - request.partialPath === "~/Development/codex/", - ), - ).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - await expect - .element(palette.getByRole("button", { name: "Create & Add (Enter)" })) - .not.toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development/codex", - title: "codex", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("picks a local project from the native file manager", async () => { - const pickFolder = vi.fn().mockResolvedValue("/Users/julius/Projects/finder-picked"); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-file-manager" as MessageId, - targetText: "command palette add project file manager", - }), - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Applications/") { - return { - parentPath: "~/Applications/", - entries: [{ name: "Utilities", fullPath: "~/Applications/Utilities" }], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Applications", fullPath: "~/Applications" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - window.desktopBridge = { - pickFolder, - setTheme: vi.fn().mockResolvedValue(undefined), - } as unknown as NonNullable; - - await page.getByTestId("sidebar-add-project-trigger").click(); - - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Local folder", { exact: true }).click(); - const browseInput = palette.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await browseInput.fill("~/Applications/access"); - - const fileManagerLabel = isMacPlatform(navigator.platform) - ? "Open in Finder" - : navigator.platform.toLowerCase().startsWith("win") - ? "Open in Explorer" - : "Open in Files"; - await palette.getByRole("button", { name: fileManagerLabel }).click(); - - await vi.waitFor( - () => { - expect(pickFolder).toHaveBeenCalledWith({ initialPath: "~/Applications" }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "/Users/julius/Projects/finder-picked", - title: "finder-picked", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project from the native file manager.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("adds a project from browse mode with Mod+Enter when a directory is highlighted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-mod-enter" as MessageId, - targetText: "command palette add project mod enter", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [ - { name: "alpha", fullPath: "~/Development/alpha" }, - { name: "beta", fullPath: "~/Development/beta" }, - ], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await palette.getByText("Local folder", { exact: true }).click(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); - await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "ArrowDown" }); - - const addButtonLabel = isMacPlatform(navigator.platform) - ? "Add (\u2318 Enter)" - : "Add (Ctrl Enter)"; - await vi.waitFor( - () => { - const legendEntries = getCommandPaletteLegendEntries(); - expect(legendEntries).toContain("Enter Select"); - }, - { timeout: 8_000, interval: 16 }, - ); - await expect - .element(palette.getByRole("button", { name: addButtonLabel })) - .toBeInTheDocument(); - - await dispatchInputKey(browseInput, { - key: "Enter", - metaKey: isMacPlatform(navigator.platform), - ctrlKey: !isMacPlatform(navigator.platform), - }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development", - title: "Development", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project with Mod+Enter.", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps project-context thread matches available when searching by project name", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("Release checklist", { exact: true })) - .toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("searches projects by path and opens the latest thread for that project", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - defaultThreadEnvMode: "worktree", - }, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("/repo/clients/docs-portal", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("Docs Portal", { exact: true }).click(); - - const nextPath = await waitForURL( - mounted.router, - (path) => path === serverThreadPath("thread-secondary-project" as ThreadId), - "Route should have changed to the latest thread for the selected project.", - ); - expect(nextPath).toBe(serverThreadPath("thread-secondary-project" as ThreadId)); - expect( - useComposerDraftStore - .getState() - .getDraftThread(threadRefFor("thread-secondary-project" as ThreadId)), - ).toBeNull(); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a new thread from project search when no active project thread exists", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject({ includeSecondaryThread: false }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - settings: { - ...nextFixture.serverConfig.settings, - defaultThreadEnvMode: "worktree", - }, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByText("/repo/clients/docs-portal", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("Docs Portal", { exact: true }).click(); - - const nextPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread UUID from the project search result.", - ); - const nextDraftId = draftIdFromPath(nextPath); - const draftThread = useComposerDraftStore.getState().getDraftSession(nextDraftId); - expect(draftThread?.projectId).toBe(SECOND_PROJECT_ID); - expect(draftThread?.envMode).toBe("worktree"); - } finally { - await mounted.cleanup(); - } - }); - - it("filters archived threads out of command palette search results", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithSecondaryProject(), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("docs-archive"); - await expect - .element(palette.getByText("Archived Docs Notes", { exact: true })) - .not.toBeInTheDocument(); - } finally { - await mounted.cleanup(); - } - }); - - it("creates a fresh draft after the previous draft thread is promoted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-promoted-draft-shortcut-test" as MessageId, - targetText: "promoted draft shortcut test", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "chat.new", - shortcut: { - key: "o", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - }); - - try { - const newThreadButton = page.getByTestId("new-thread-button"); - await expect.element(newThreadButton).toBeInTheDocument(); - await waitForServerConfigToApply(); - await newThreadButton.click(); - - const promotedThreadPath = await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a promoted draft thread UUID.", - ); - const promotedDraftId = draftIdFromPath(promotedThreadPath); - const promotedThreadId = draftThreadIdFor(promotedDraftId); - - await promoteDraftThreadViaDomainEvent(promotedThreadId); - await waitForURL( - mounted.router, - (path) => path === serverThreadPath(promotedThreadId), - "Promoted drafts should canonicalize to the server thread route before a fresh draft is created.", - ); - await vi.waitFor( - () => { - expect(useComposerDraftStore.getState().getDraftThread(promotedDraftId)).toBeNull(); - }, - { timeout: 8_000, interval: 16 }, - ); - const composerEditor = await waitForComposerEditor(); - composerEditor.focus(); - await waitForLayout(); - - const freshThreadPath = await triggerChatNewShortcutUntilPath( - mounted.router, - (path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath, - "Shortcut should create a fresh draft instead of reusing the promoted thread.", - ); - expect(freshThreadPath).not.toBe(promotedThreadPath); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps long proposed plans lightweight until the user expands them", async () => { - __setClientSettingsForTests({ - ...DEFAULT_CLIENT_SETTINGS, - autoOpenPlanSidebar: false, - }); - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithLongProposedPlan(), - }); - - try { - await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Expand plan", - ) as HTMLButtonElement | null, - "Unable to find Expand plan button.", - ); - - expect(document.body.textContent).not.toContain("deep hidden detail only after expand"); - - const expandButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Expand plan", - ) as HTMLButtonElement | null, - "Unable to find Expand plan button.", - ); - expandButton.click(); - - await vi.waitFor( - () => { - expect(document.body.textContent).toContain("deep hidden detail only after expand"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("uses the active worktree path when saving a proposed plan to the workspace", async () => { - __setClientSettingsForTests({ - ...DEFAULT_CLIENT_SETTINGS, - autoOpenPlanSidebar: false, - }); - const snapshot = createSnapshotWithLongProposedPlan(); - const threads = snapshot.threads.slice(); - const targetThreadIndex = threads.findIndex((thread) => thread.id === THREAD_ID); - const targetThread = targetThreadIndex >= 0 ? threads[targetThreadIndex] : undefined; - if (targetThread) { - threads[targetThreadIndex] = { - ...targetThread, - worktreePath: "/repo/worktrees/plan-thread", - }; - } - - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - threads, - }, - }); - - try { - const expandPlanButton = await waitForElement( - () => - Array.from(document.querySelectorAll("button")).find( - (button) => button.textContent?.trim() === "Expand plan", - ) ?? null, - "Unable to find proposed plan card.", - ); - const planActionsButton = await waitForElement(() => { - let ancestor = expandPlanButton.parentElement; - while (ancestor) { - const button = ancestor.querySelector( - 'button[aria-label="Plan actions"]', - ); - if (button) { - return button; - } - ancestor = ancestor.parentElement; - } - return null; - }, "Unable to find proposed plan card actions button."); - planActionsButton.click(); - - const saveToWorkspaceItem = await waitForElement( - () => - (Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find( - (item) => item.textContent?.trim() === "Save to workspace", - ) ?? null) as HTMLElement | null, - 'Unable to find "Save to workspace" menu item.', - ); - saveToWorkspaceItem.click(); - - await vi.waitFor( - () => { - expect(document.body.textContent).toContain( - "Enter a path relative to /repo/worktrees/plan-thread.", - ); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps pending-question footer actions inside the composer after a real resize", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPendingUserInput(), - }); - - try { - const firstOption = await waitForButtonContainingText("Tight"); - firstOption.click(); - - await waitForButtonByText("Previous"); - await waitForButtonByText("Submit answers"); - - await mounted.setContainerSize(COMPACT_FOOTER_VIEWPORT); - await expectComposerActionsContained(); - } finally { - await mounted.cleanup(); - } - }); - - it("submits pending user input after the final option selection resolves the draft answers", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotWithPendingUserInput(), - resolveRpc: (body) => { - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - return undefined; - }, - }); - - try { - const firstOption = await waitForButtonContainingText("Tight"); - firstOption.click(); - - const finalOption = await waitForButtonContainingText("Conservative"); - finalOption.click(); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.user-input.respond", - ) as - | { - _tag: string; - type?: string; - requestId?: string; - answers?: Record; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "thread.user-input.respond", - requestId: "req-browser-user-input", - answers: { - scope: "Tight", - risk: "Conservative", - }, - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPlanFollowUpPrompt(), - }); - - try { - const footer = await waitForElement( - () => document.querySelector('[data-chat-composer-footer="true"]'), - "Unable to find composer footer.", - ); - const initialModelPicker = await waitForElement( - findComposerProviderModelPicker, - "Unable to find provider model picker.", - ); - const initialModelPickerOffset = - initialModelPicker.getBoundingClientRect().left - footer.getBoundingClientRect().left; - const initialImplementButton = await waitForButtonByText("Implement"); - const initialImplementWidth = initialImplementButton.getBoundingClientRect().width; - - await waitForElement( - () => - document.querySelector('button[aria-label="Implementation actions"]'), - "Unable to find implementation actions trigger.", - ); - - await mounted.setContainerSize({ - width: 440, - height: WIDE_FOOTER_VIEWPORT.height, - }); - await expectComposerActionsContained(); - - const implementButton = await waitForButtonByText("Implement"); - const implementActionsButton = await waitForElement( - () => - document.querySelector('button[aria-label="Implementation actions"]'), - "Unable to find implementation actions trigger.", - ); - - await vi.waitFor( - () => { - const implementRect = implementButton.getBoundingClientRect(); - const implementActionsRect = implementActionsButton.getBoundingClientRect(); - const compactModelPicker = findComposerProviderModelPicker(); - expect(compactModelPicker).toBeTruthy(); - - const compactModelPickerOffset = - compactModelPicker!.getBoundingClientRect().left - footer.getBoundingClientRect().left; - - expect(Math.abs(implementRect.right - implementActionsRect.left)).toBeLessThanOrEqual(1); - expect(Math.abs(implementRect.top - implementActionsRect.top)).toBeLessThanOrEqual(1); - expect(Math.abs(implementRect.width - initialImplementWidth)).toBeLessThanOrEqual(1); - expect(Math.abs(compactModelPickerOffset - initialModelPickerOffset)).toBeLessThanOrEqual( - 1, - ); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the wide desktop follow-up layout expanded when the footer still fits", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPlanFollowUpPrompt({ - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.3-codex-spark", - }, - planMarkdown: - "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative", - }), - }); - - try { - await waitForButtonByText("Implement"); - - await vi.waitFor( - () => { - const footer = document.querySelector('[data-chat-composer-footer="true"]'); - const actions = document.querySelector( - '[data-chat-composer-actions="right"]', - ); - - expect(footer?.dataset.chatComposerFooterCompact).toBe("false"); - expect(actions?.dataset.chatComposerPrimaryActionsCompact).toBe("false"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("compacts the footer when a wide desktop follow-up layout starts overflowing", async () => { - const mounted = await mountChatView({ - viewport: WIDE_FOOTER_VIEWPORT, - snapshot: createSnapshotWithPlanFollowUpPrompt({ - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.3-codex-spark", - }, - planMarkdown: - "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative", - }), - }); - - try { - await waitForButtonByText("Implement"); - - await mounted.setContainerSize({ - width: 804, - height: WIDE_FOOTER_VIEWPORT.height, - }); - - await expectComposerActionsContained(); - - await vi.waitFor( - () => { - const footer = document.querySelector('[data-chat-composer-footer="true"]'); - const actions = document.querySelector( - '[data-chat-composer-actions="right"]', - ); - - expect(footer?.dataset.chatComposerFooterCompact).toBe("true"); - expect(actions?.dataset.chatComposerPrimaryActionsCompact).toBe("true"); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the slash-command menu visible above the composer", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-menu-target" as MessageId, - targetText: "command menu thread", - }), - }); - - try { - await waitForComposerEditor(); - await page.getByTestId("composer-editor").fill("/"); - - const menuItem = await waitForComposerMenuItem("slash:model"); - const composerForm = await waitForElement( - () => document.querySelector('[data-chat-composer-form="true"]'), - "Unable to find composer form.", - ); - - await vi.waitFor( - () => { - const menuRect = menuItem.getBoundingClientRect(); - const composerRect = composerForm.getBoundingClientRect(); - const hitTarget = document.elementFromPoint( - menuRect.left + menuRect.width / 2, - menuRect.top + menuRect.height / 2, - ); - - expect(menuRect.width).toBeGreaterThan(0); - expect(menuRect.height).toBeGreaterThan(0); - expect(menuRect.bottom).toBeLessThanOrEqual(composerRect.bottom); - expect(hitTarget instanceof Element && menuItem.contains(hitTarget)).toBe(true); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - - it("opens the model picker when selecting /model", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-model-command-target" as MessageId, - targetText: "model command thread", - }), - }); - - try { - await waitForComposerEditor(); - await page.getByTestId("composer-editor").fill("/mod"); - - const menuItem = await waitForComposerMenuItem("slash:model"); - await menuItem.click(); - - await vi.waitFor(() => { - expect(document.querySelector(".model-picker-list")).not.toBeNull(); - expect(findComposerProviderModelPicker()?.textContent).not.toContain("/model"); - }); - - await new Promise((resolve) => { - requestAnimationFrame(() => { - requestAnimationFrame(() => resolve()); - }); - }); - - await vi.waitFor(() => { - const searchInput = document.querySelector( - 'input[placeholder="Search models..."]', - ); - expect(searchInput).not.toBeNull(); - expect(document.activeElement).toBe(searchInput); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("toggles the model picker and shows jump keys immediately from the shortcut", async () => { - const snapshot = createSnapshotForTargetUser({ - targetMessageId: "msg-user-model-picker-shortcut-target" as MessageId, - targetText: "model picker shortcut thread", - }); - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: { - ...snapshot, - projects: snapshot.projects.map((project) => - project.id === PROJECT_ID - ? Object.assign({}, project, { - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - }) - : project, - ), - threads: snapshot.threads.map((thread) => - thread.id === THREAD_ID - ? Object.assign({}, thread, { - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - }) - : thread, - ), - }, - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "modelPicker.toggle", - shortcut: { - key: "m", - metaKey: false, - ctrlKey: true, - shiftKey: true, - altKey: false, - modKey: false, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - { - command: "thread.jump.1", - shortcut: { - key: "1", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: false, - modKey: false, - }, - }, - { - command: "modelPicker.jump.1", - shortcut: { - key: "1", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: false, - modKey: false, - }, - whenAst: { type: "identifier", name: "modelPickerOpen" }, - }, - ], - providers: [ - { - ...nextFixture.serverConfig.providers[0]!, - models: [ - { - slug: "gpt-5.1-codex-max", - name: "GPT-5.1 Codex Max", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - { id: "fastMode", label: "Fast Mode", type: "boolean" as const }, - ], - }), - }, - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - { id: "fastMode", label: "Fast Mode", type: "boolean" as const }, - ], - }), - }, - { - slug: "gpt-5.4", - name: "GPT-5.4", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - { id: "fastMode", label: "Fast Mode", type: "boolean" as const }, - ], - }), - }, - ], - }, - ], - }; - }, - }); - - try { - await waitForServerConfigToApply(); - await waitForComposerEditor(); - - const initialPath = mounted.router.state.location.pathname; - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "m", - ctrlKey: true, - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor(() => { - expect(document.querySelector(".model-picker-list")).not.toBeNull(); - }); - - const jumpLabel = isMacPlatform(navigator.platform) ? "⌃1" : "Ctrl+1"; - await vi.waitFor(() => { - expect( - Array.from( - document.querySelectorAll('.model-picker-list [data-slot="kbd"]'), - ).some((element) => element.textContent?.trim() === jumpLabel), - ).toBe(true); - }); - expect(mounted.router.state.location.pathname).toBe(initialPath); - - window.dispatchEvent( - new KeyboardEvent("keydown", { - key: "m", - ctrlKey: true, - shiftKey: true, - bubbles: true, - cancelable: true, - }), - ); - - await vi.waitFor(() => { - expect(document.querySelector(".model-picker-list")).toBeNull(); - }); - } finally { - releaseModShortcut("Control"); - await mounted.cleanup(); - } - }); - - it("shows a tooltip with the skill description when hovering a skill pill", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-skill-tooltip-target" as MessageId, - targetText: "skill tooltip thread", - }), - configureFixture: (nextFixture) => { - const provider = nextFixture.serverConfig.providers[0]; - if (!provider) { - throw new Error("Expected default provider in test fixture."); - } - ( - provider as { - skills: ServerConfig["providers"][number]["skills"]; - } - ).skills = [ - { - name: "agent-browser", - displayName: "Agent Browser", - description: "Open pages, click around, and inspect web apps.", - path: "/Users/test/.agents/skills/agent-browser/SKILL.md", - enabled: true, - }, - ]; - }, - }); - - try { - useComposerDraftStore.getState().setPrompt(THREAD_REF, "use the $agent-browser "); - await waitForComposerText("use the $agent-browser "); - - await waitForElement( - () => document.querySelector('[data-composer-skill-chip="true"]'), - "Unable to find rendered composer skill chip.", - ); - await page.getByText("Agent Browser").hover(); - - await vi.waitFor( - () => { - const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); - expect(tooltip).not.toBeNull(); - expect(tooltip?.textContent).toContain("Open pages, click around, and inspect web apps."); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); -}); diff --git a/apps/web/src/components/DiffPanelShell.browser.tsx b/apps/web/src/components/DiffPanelShell.browser.tsx deleted file mode 100644 index d767fdba60..0000000000 --- a/apps/web/src/components/DiffPanelShell.browser.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import "../index.css"; - -import { describe, expect, it } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -import { DiffPanelShell } from "./DiffPanelShell"; - -describe("DiffPanelShell", () => { - it("uses the shared compact surface subheader in embedded mode", async () => { - const screen = await render( - Diff controls}> -
Diff content
-
, - ); - const subheader = screen.container.querySelector("[data-surface-subheader]"); - - expect(subheader).not.toBeNull(); - expect(subheader?.getBoundingClientRect().height).toBe(40); - expect(window.getComputedStyle(subheader!).borderTopWidth).toBe("0px"); - expect(window.getComputedStyle(subheader!).borderBottomWidth).toBe("1px"); - }); -}); diff --git a/apps/web/src/components/Sidebar.dblclick.browser.tsx b/apps/web/src/components/Sidebar.dblclick.browser.tsx deleted file mode 100644 index 798c61e6d7..0000000000 --- a/apps/web/src/components/Sidebar.dblclick.browser.tsx +++ /dev/null @@ -1,266 +0,0 @@ -import "../index.css"; - -import { - DEFAULT_RUNTIME_MODE, - EnvironmentId, - ProjectId, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; -import { useCallback, useRef, useState } from "react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { page, userEvent } from "vite-plus/test/browser"; -import { cleanup, render } from "vitest-browser-react"; - -import { AppAtomRegistryProvider } from "../rpc/atomRegistry"; -import { DEFAULT_INTERACTION_MODE } from "../types"; -import type { SidebarThreadSummary } from "../types"; -import { SidebarThreadRow } from "./Sidebar"; - -// Double-click-to-rename is a desktop affordance; force the non-mobile path so -// the rename input is reachable regardless of the test browser viewport. -vi.mock("~/hooks/useMediaQuery", () => ({ - useIsMobile: () => false, - useMediaQuery: () => false, -})); - -const THREAD_ID = ThreadId.make("thread-1"); -const ENVIRONMENT_ID = EnvironmentId.make("environment-local"); -const PROJECT_ID = ProjectId.make("project-1"); -const INITIAL_TITLE = "Original title"; - -const ROW_TESTID = `thread-row-${THREAD_ID}`; -const TITLE_TESTID = `thread-title-${THREAD_ID}`; - -// Spies live at module scope so their call history survives the row's -// re-renders; reset between tests. -const spies = { - handleThreadClick: vi.fn(), - startThreadRename: vi.fn(), - navigateToThread: vi.fn(), - handleMultiSelectContextMenu: vi.fn(async () => {}), - handleThreadContextMenu: vi.fn(async () => {}), - clearSelection: vi.fn(), - commitRename: vi.fn(), - attemptArchiveThread: vi.fn(async () => {}), - openPrLink: vi.fn(), -}; - -function buildThread(title: string): SidebarThreadSummary { - return { - id: THREAD_ID, - environmentId: ENVIRONMENT_ID, - projectId: PROJECT_ID, - title, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - runtimeMode: DEFAULT_RUNTIME_MODE, - interactionMode: DEFAULT_INTERACTION_MODE, - session: null, - createdAt: "2024-01-01T00:00:00.000Z", - archivedAt: null, - updatedAt: "2024-01-01T00:00:00.000Z", - latestTurn: null, - branch: null, - worktreePath: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - }; -} - -// Mirrors the real parent (`SidebarProjectItem`): holds the rename state, wires -// `startThreadRename`, and commits by clearing the rename state and persisting -// the new title back onto the thread so the row re-renders with it. -function Harness() { - const [title, setTitle] = useState(INITIAL_TITLE); - const [renamingThreadKey, setRenamingThreadKey] = useState(null); - const [renamingTitle, setRenamingTitle] = useState(""); - const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState(null); - const renamingInputRef = useRef(null); - const renamingCommittedRef = useRef(false); - const confirmArchiveButtonRefs = useRef(new Map()); - - const startThreadRename = useCallback((threadKey: string, nextTitle: string) => { - spies.startThreadRename(threadKey, nextTitle); - setRenamingThreadKey(threadKey); - setRenamingTitle(nextTitle); - renamingCommittedRef.current = false; - }, []); - - const commitRename = useCallback( - async (threadRef: unknown, newTitle: string, originalTitle: string) => { - spies.commitRename(threadRef, newTitle, originalTitle); - const trimmed = newTitle.trim(); - if (trimmed.length > 0) { - setTitle(trimmed); - } - setRenamingThreadKey(null); - renamingInputRef.current = null; - }, - [], - ); - - const cancelRename = useCallback(() => { - setRenamingThreadKey(null); - renamingInputRef.current = null; - }, []); - - return ( - -
    - -
-
- ); -} - -describe("SidebarThreadRow double-click rename", () => { - beforeEach(() => { - for (const spy of Object.values(spies)) spy.mockClear(); - }); - - afterEach(() => { - cleanup(); - }); - - it("double-clicking a row starts the inline rename, focused with text selected", async () => { - render(); - - await expect.element(page.getByTestId(TITLE_TESTID)).toBeVisible(); - - await userEvent.dblClick(page.getByTestId(ROW_TESTID)); - - const input = page.getByRole("textbox"); - await expect.element(input).toBeVisible(); - - const element = input.element() as HTMLInputElement; - expect(element.value).toBe(INITIAL_TITLE); - // The existing rename-input ref focuses + selects the whole title. - expect(document.activeElement).toBe(element); - expect(element.selectionStart).toBe(0); - expect(element.selectionEnd).toBe(INITIAL_TITLE.length); - }); - - it("Enter commits the rename and the new title persists on the row", async () => { - render(); - - await userEvent.dblClick(page.getByTestId(ROW_TESTID)); - const input = page.getByRole("textbox"); - await expect.element(input).toBeVisible(); - - await userEvent.fill(input, "Renamed thread"); - await userEvent.keyboard("{Enter}"); - - // commitRename was invoked with (threadRef, newTitle, originalTitle). - expect(spies.commitRename).toHaveBeenCalledTimes(1); - expect(spies.commitRename).toHaveBeenCalledWith( - expect.anything(), - "Renamed thread", - INITIAL_TITLE, - ); - - // Input is gone and the row now shows the persisted title. - const title = page.getByTestId(TITLE_TESTID); - await expect.element(title).toBeVisible(); - await expect.element(title).toHaveTextContent("Renamed thread"); - }); - - it("Escape cancels the rename without committing", async () => { - render(); - - await userEvent.dblClick(page.getByTestId(ROW_TESTID)); - await expect.element(page.getByRole("textbox")).toBeVisible(); - - await userEvent.keyboard("{Escape}"); - - expect(spies.commitRename).not.toHaveBeenCalled(); - const title = page.getByTestId(TITLE_TESTID); - await expect.element(title).toBeVisible(); - await expect.element(title).toHaveTextContent(INITIAL_TITLE); - }); - - it("double-clicking inside the rename input keeps the edit (does not reset to the title)", async () => { - render(); - - await userEvent.dblClick(page.getByTestId(ROW_TESTID)); - const input = page.getByRole("textbox"); - await expect.element(input).toBeVisible(); - - await userEvent.fill(input, "Edited but not committed"); - // Double-clicking inside the input (e.g. to select a word) must not bubble - // to the row and restart the rename, which would wipe the edit. - await userEvent.dblClick(input); - - expect((input.element() as HTMLInputElement).value).toBe("Edited but not committed"); - expect(spies.commitRename).not.toHaveBeenCalled(); - }); - - it("double-clicking the row chrome while already renaming does not restart/reset it", async () => { - render(); - - await userEvent.dblClick(page.getByTestId(ROW_TESTID)); - const input = page.getByRole("textbox"); - await expect.element(input).toBeVisible(); - await userEvent.fill(input, "Edited"); - expect(spies.startThreadRename).toHaveBeenCalledTimes(1); - - // Double-click the row element itself (chrome, not the input). - const rowEl = page.getByTestId(ROW_TESTID).element(); - rowEl.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true, detail: 2 })); - - // Guard short-circuits: rename is not restarted and the edit is preserved. - expect(spies.startThreadRename).toHaveBeenCalledTimes(1); - expect((input.element() as HTMLInputElement).value).toBe("Edited"); - }); - - it("modifier double-click is multi-select intent and does not start a rename", async () => { - render(); - - await userEvent.keyboard("{Shift>}"); - await userEvent.dblClick(page.getByTestId(ROW_TESTID)); - await userEvent.keyboard("{/Shift}"); - - await expect.element(page.getByTestId(TITLE_TESTID)).toBeVisible(); - expect(page.getByRole("textbox").elements()).toHaveLength(0); - }); - - it("single click routes through the navigation handler and does not start a rename", async () => { - render(); - - await userEvent.click(page.getByTestId(ROW_TESTID)); - - expect(spies.handleThreadClick).toHaveBeenCalledTimes(1); - // No rename input: the title span is still shown. - await expect.element(page.getByTestId(TITLE_TESTID)).toBeVisible(); - expect(page.getByRole("textbox").elements()).toHaveLength(0); - }); -}); diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx deleted file mode 100644 index 319e64d18b..0000000000 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx +++ /dev/null @@ -1,408 +0,0 @@ -import "../index.css"; - -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { ThreadId } from "@t3tools/contracts"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -const { - terminalConstructorSpy, - terminalDisposeSpy, - fitAddonFitSpy, - fitAddonLoadSpy, - terminalSessionByEnvironmentId, - useAttachedTerminalSessionMock, - atomCommandInvocationMock, - useAtomCommandMock, - readLocalApiMock, -} = vi.hoisted(() => ({ - terminalConstructorSpy: vi.fn(), - terminalDisposeSpy: vi.fn(), - fitAddonFitSpy: vi.fn(), - fitAddonLoadSpy: vi.fn(), - terminalSessionByEnvironmentId: new Map< - string, - { - summary: null; - buffer: string; - status: "running"; - error: null; - hasRunningSubprocess: false; - updatedAt: null; - version: number; - } - >(), - useAttachedTerminalSessionMock: vi.fn(), - atomCommandInvocationMock: vi.fn(async () => ({ - _tag: "Success" as const, - value: undefined, - waiting: false, - })), - useAtomCommandMock: vi.fn(), - readLocalApiMock: vi.fn< - () => - | { - contextMenu: { show: ReturnType }; - shell: { openExternal: ReturnType }; - } - | undefined - >(() => ({ - contextMenu: { show: vi.fn(async () => null) }, - shell: { openExternal: vi.fn(async () => undefined) }, - })), -})); - -vi.mock("@xterm/addon-fit", () => ({ - FitAddon: class MockFitAddon { - fit = fitAddonFitSpy; - }, -})); - -vi.mock("@xterm/xterm", () => ({ - Terminal: class MockTerminal { - cols = 80; - rows = 24; - options: { theme?: unknown } = {}; - buffer = { - active: { - viewportY: 0, - baseY: 0, - getLine: vi.fn(() => null), - }, - }; - - constructor(options: unknown) { - terminalConstructorSpy(options); - } - - loadAddon(addon: unknown) { - fitAddonLoadSpy(addon); - } - - open() {} - - write() {} - - clear() {} - - clearSelection() {} - - focus() {} - - refresh() {} - - scrollToBottom() {} - - hasSelection() { - return false; - } - - getSelection() { - return ""; - } - - getSelectionPosition() { - return null; - } - - attachCustomKeyEventHandler() { - return true; - } - - registerLinkProvider() { - return { dispose: vi.fn() }; - } - - onData() { - return { dispose: vi.fn() }; - } - - onSelectionChange() { - return { dispose: vi.fn() }; - } - - dispose() { - terminalDisposeSpy(); - } - }, -})); - -vi.mock("../state/terminalSessions", () => ({ - useAttachedTerminalSession: (input: { environmentId: string }) => { - useAttachedTerminalSessionMock(input); - const session = terminalSessionByEnvironmentId.get(input.environmentId); - if (session === undefined) { - throw new Error(`Missing test terminal session for ${input.environmentId}`); - } - return session; - }, -})); - -vi.mock("../state/use-atom-command", () => ({ - useAtomCommand: (...args: ReadonlyArray) => { - useAtomCommandMock(...args); - return atomCommandInvocationMock; - }, -})); - -vi.mock("../state/server", async (importOriginal) => { - const [actual, { Atom }] = await Promise.all([ - importOriginal(), - import("effect/unstable/reactivity"), - ]); - return { - ...actual, - primaryServerAvailableEditorsAtom: Atom.make([]), - }; -}); - -vi.mock("~/localApi", () => ({ - ensureLocalApi: vi.fn(() => { - throw new Error("ensureLocalApi not implemented in browser test"); - }), - readLocalApi: readLocalApiMock, -})); - -import { TerminalViewport } from "./ThreadTerminalDrawer"; - -const THREAD_ID = ThreadId.make("thread-terminal-browser"); - -function createTerminalSession() { - return { - summary: null, - buffer: "", - status: "running" as const, - error: null, - hasRunningSubprocess: false as const, - updatedAt: null, - version: 1, - }; -} - -async function mountTerminalViewport(props: { - threadRef: ReturnType; - drawerBackgroundColor?: string; - drawerTextColor?: string; - runtimeEnv?: Record; -}) { - const drawer = document.createElement("div"); - drawer.className = "thread-terminal-drawer"; - if (props.drawerBackgroundColor) { - drawer.style.backgroundColor = props.drawerBackgroundColor; - } - if (props.drawerTextColor) { - drawer.style.color = props.drawerTextColor; - } - - const host = document.createElement("div"); - host.style.width = "800px"; - host.style.height = "400px"; - drawer.append(host); - document.body.append(drawer); - - const screen = await render( - undefined} - onAddTerminalContext={() => undefined} - focusRequestId={0} - autoFocus={false} - resizeEpoch={0} - drawerHeight={320} - keybindings={[]} - />, - { container: host }, - ); - - return { - rerender: async (nextProps: { - threadRef: ReturnType; - runtimeEnv?: Record; - }) => { - await screen.rerender( - undefined} - onAddTerminalContext={() => undefined} - focusRequestId={0} - autoFocus={false} - resizeEpoch={0} - drawerHeight={320} - keybindings={[]} - />, - ); - }, - cleanup: async () => { - await screen.unmount(); - drawer.remove(); - }, - }; -} - -describe("TerminalViewport", () => { - afterEach(() => { - terminalSessionByEnvironmentId.clear(); - useAttachedTerminalSessionMock.mockClear(); - atomCommandInvocationMock.mockClear(); - useAtomCommandMock.mockClear(); - readLocalApiMock.mockClear(); - terminalConstructorSpy.mockClear(); - terminalDisposeSpy.mockClear(); - fitAddonFitSpy.mockClear(); - fitAddonLoadSpy.mockClear(); - }); - - it("renders the terminal through shared session state without the desktop API", async () => { - terminalSessionByEnvironmentId.set("environment-a", createTerminalSession()); - readLocalApiMock.mockReturnValueOnce(undefined); - - const mounted = await mountTerminalViewport({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - }); - - try { - await vi.waitFor(() => { - expect(useAttachedTerminalSessionMock).toHaveBeenCalledWith( - expect.objectContaining({ environmentId: "environment-a" }), - ); - }); - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the terminal mounted when xterm fit runs before dimensions are ready", async () => { - terminalSessionByEnvironmentId.set("environment-a", createTerminalSession()); - fitAddonFitSpy.mockImplementationOnce(() => { - throw new TypeError("Cannot read properties of undefined (reading 'dimensions')"); - }); - - const mounted = await mountTerminalViewport({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - }); - - try { - await vi.waitFor(() => { - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - }); - expect(fitAddonFitSpy).toHaveBeenCalled(); - } finally { - await mounted.cleanup(); - } - }); - - it("reattaches the terminal when the scoped thread reference changes", async () => { - terminalSessionByEnvironmentId.set("environment-a", createTerminalSession()); - terminalSessionByEnvironmentId.set("environment-b", createTerminalSession()); - - const mounted = await mountTerminalViewport({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - }); - - try { - await vi.waitFor(() => { - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - }); - - await mounted.rerender({ - threadRef: scopeThreadRef("environment-b" as never, THREAD_ID), - }); - - await vi.waitFor(() => { - expect(useAttachedTerminalSessionMock).toHaveBeenCalledWith( - expect.objectContaining({ environmentId: "environment-b" }), - ); - }); - expect(terminalDisposeSpy).toHaveBeenCalledTimes(1); - expect(terminalConstructorSpy).toHaveBeenCalledTimes(2); - } finally { - await mounted.cleanup(); - } - }); - - it("does not reattach the terminal when the scoped thread reference values stay the same", async () => { - terminalSessionByEnvironmentId.set("environment-a", createTerminalSession()); - - const mounted = await mountTerminalViewport({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - }); - - try { - await vi.waitFor(() => { - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - }); - - await mounted.rerender({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - }); - - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - expect(terminalDisposeSpy).not.toHaveBeenCalled(); - } finally { - await mounted.cleanup(); - } - }); - - it("does not reattach when runtime env contents are unchanged but object identity changes", async () => { - terminalSessionByEnvironmentId.set("environment-a", createTerminalSession()); - - const mounted = await mountTerminalViewport({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - runtimeEnv: { PATH: "/usr/bin", T3: "1" }, - }); - - try { - await vi.waitFor(() => { - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - }); - - await mounted.rerender({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - runtimeEnv: { T3: "1", PATH: "/usr/bin" }, - }); - - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - expect(terminalDisposeSpy).not.toHaveBeenCalled(); - } finally { - await mounted.cleanup(); - } - }); - - it("uses the drawer surface colors for the terminal theme", async () => { - terminalSessionByEnvironmentId.set("environment-a", createTerminalSession()); - - const mounted = await mountTerminalViewport({ - threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), - drawerBackgroundColor: "rgb(24, 28, 36)", - drawerTextColor: "rgb(228, 232, 240)", - }); - - try { - await vi.waitFor(() => { - expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); - }); - - expect(terminalConstructorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - theme: expect.objectContaining({ - background: "rgb(24, 28, 36)", - foreground: "rgb(228, 232, 240)", - }), - }), - ); - } finally { - await mounted.cleanup(); - } - }); -}); diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx deleted file mode 100644 index 98893898f8..0000000000 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx +++ /dev/null @@ -1,326 +0,0 @@ -import { - DEFAULT_MODEL, - DEFAULT_MODEL_BY_PROVIDER, - EnvironmentId, - ModelSelection, - ProviderInstanceId, - ProviderDriverKind, - ThreadId, -} from "@t3tools/contracts"; -import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import "../../index.css"; - -import { page } from "vite-plus/test/browser"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; -import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model"; - -import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; -import { TraitsMenuContent } from "./TraitsPicker"; -import { createEmptyThreadDraft, useComposerDraftStore } from "../../composerDraftStore"; - -const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); - -function selectDescriptor( - id: string, - label: string, - options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, - promptInjectedValues?: ReadonlyArray, -) { - return { - id, - label, - type: "select" as const, - options: [...options], - ...(options.find((option) => option.isDefault)?.id - ? { currentValue: options.find((option) => option.isDefault)?.id } - : {}), - ...(promptInjectedValues && promptInjectedValues.length > 0 - ? { promptInjectedValues: [...promptInjectedValues] } - : {}), - }; -} - -function booleanDescriptor(id: string, label: string) { - return { - id, - label, - type: "boolean" as const, - }; -} - -async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) { - const threadId = ThreadId.make("thread-compact-menu"); - const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); - const threadKey = scopedThreadKey(threadRef); - const provider = ProviderDriverKind.make("claudeAgent"); - const instanceId = ProviderInstanceId.make(props?.modelSelection?.instanceId ?? provider); - const model = - props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL; - - useComposerDraftStore.setState({ - draftsByThreadKey: { - // Compose from the canonical empty-draft factory so adding a new - // ComposerThreadDraftState slice (e.g. a future attachment kind) doesn't - // silently break this stub via `Property X is missing in type ...`. - [threadKey]: { - ...createEmptyThreadDraft(), - prompt: props?.prompt ?? "", - modelSelectionByProvider: { - [instanceId]: createModelSelection(instanceId, model, props?.modelSelection?.options), - }, - activeProvider: instanceId, - }, - }, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - }); - const host = document.createElement("div"); - document.body.append(host); - const onPromptChange = vi.fn(); - const providerOptions = props?.modelSelection?.options; - const models = [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor( - "effort", - "Reasoning", - [ - { id: "low", label: "Low" }, - { id: "medium", label: "Medium" }, - { id: "high", label: "High", isDefault: true }, - { id: "max", label: "Max" }, - { id: "ultrathink", label: "Ultrathink" }, - ], - ["ultrathink"], - ), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [booleanDescriptor("thinking", "Thinking")], - }), - }, - { - slug: "claude-sonnet-4-6", - name: "Claude Sonnet 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor( - "effort", - "Reasoning", - [ - { id: "low", label: "Low" }, - { id: "medium", label: "Medium" }, - { id: "high", label: "High", isDefault: true }, - { id: "ultrathink", label: "Ultrathink" }, - ], - ["ultrathink"], - ), - ], - }), - }, - ]; - const screen = await render( - - } - onToggleInteractionMode={vi.fn()} - onTogglePlanSidebar={vi.fn()} - onRuntimeModeChange={vi.fn()} - />, - { container: host }, - ); - - const cleanup = async () => { - await screen.unmount(); - host.remove(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - }; -} - -describe("CompactComposerControlsMenu", () => { - afterEach(() => { - document.body.innerHTML = ""; - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - }); - }); - - it("shows fast mode controls for Opus", async () => { - await using _ = await mountMenu({ - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - ), - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Fast Mode"); - expect(text).toContain("On"); - expect(text).toContain("Off"); - }); - }); - - it("hides fast mode controls for non-Opus Claude models", async () => { - await using _ = await mountMenu({ - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-sonnet-4-6", - ), - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").not.toContain("Fast Mode"); - }); - }); - - it("shows only the provided effort options", async () => { - await using _ = await mountMenu({ - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-sonnet-4-6", - ), - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Low"); - expect(text).toContain("Medium"); - expect(text).toContain("High"); - expect(text).not.toContain("Max"); - expect(text).toContain("Ultrathink"); - }); - }); - - it("shows a Claude thinking on/off section for Haiku", async () => { - await using _ = await mountMenu({ - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-haiku-4-5", - [{ id: "thinking", value: true }], - ), - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Thinking"); - expect(text).toContain("On"); - expect(text).toContain("Off"); - }); - }); - - it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { - await using _ = await mountMenu({ - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - [{ id: "effort", value: "high" }], - ), - prompt: "Ultrathink:\nInvestigate this", - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Reasoning"); - expect(text).not.toContain("ultrathink"); - }); - }); - - it("warns when ultrathink appears in prompt body text", async () => { - await using _ = await mountMenu({ - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - [{ id: "effort", value: "high" }], - ), - prompt: "Ultrathink:\nplease ultrathink about this problem", - }); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain( - 'Your prompt contains "ultrathink" in the text. Remove it to change this option.', - ); - }); - }); - - it("can hide the interaction mode section", async () => { - const host = document.createElement("div"); - document.body.append(host); - const screen = await render( - , - { container: host }, - ); - - await page.getByLabelText("More composer controls").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).not.toContain("Mode"); - expect(text).not.toContain("Chat"); - expect(text).not.toContain("Plan"); - expect(text).toContain("Access"); - expect(text).toContain("Supervised"); - expect(text).toContain("Full access"); - }); - - await screen.unmount(); - host.remove(); - }); -}); diff --git a/apps/web/src/components/chat/ComposerPendingReviewComments.browser.tsx b/apps/web/src/components/chat/ComposerPendingReviewComments.browser.tsx deleted file mode 100644 index a5aa6e224e..0000000000 --- a/apps/web/src/components/chat/ComposerPendingReviewComments.browser.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import "../../index.css"; - -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; -import { render } from "vitest-browser-react"; - -import { ComposerPendingReviewComments } from "./ComposerPendingReviewComments"; - -describe("ComposerPendingReviewComments", () => { - afterEach(() => { - document.body.innerHTML = ""; - }); - - it("renders a removable file comment pill", async () => { - const onRemove = vi.fn(); - const screen = await render( - , - ); - - await expect.element(page.getByText("src/app.ts L2 to L3")).toBeVisible(); - await page.getByRole("button", { name: "Remove comment on src/app.ts L2 to L3" }).click(); - expect(onRemove).toHaveBeenCalledWith("comment-1"); - - await screen.unmount(); - }); -}); diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.tsx deleted file mode 100644 index 66b1cba1bd..0000000000 --- a/apps/web/src/components/chat/MessagesTimeline.browser.tsx +++ /dev/null @@ -1,481 +0,0 @@ -import "../../index.css"; - -import { EnvironmentId } from "@t3tools/contracts"; -import { createRef } from "react"; -import type { LegendListRef } from "@legendapp/list/react"; -import { page } from "vite-plus/test/browser"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -const scrollToEndSpy = vi.fn(); -const getStateSpy = vi.fn(() => ({ isAtEnd: true })); - -vi.mock("@legendapp/list/react", async () => { - const React = await import("react"); - - function LegendList(props: { - data: Array<{ id: string }>; - keyExtractor: (item: { id: string }) => string; - renderItem: (args: { item: { id: string } }) => React.ReactNode; - ListHeaderComponent?: React.ReactNode; - ListFooterComponent?: React.ReactNode; - ref?: React.Ref; - }) { - React.useImperativeHandle( - props.ref, - () => - ({ - scrollToEnd: scrollToEndSpy, - getState: getStateSpy, - }) as unknown as LegendListRef, - ); - - return ( -
- {props.ListHeaderComponent} - {props.data.map((item) => ( -
{props.renderItem({ item })}
- ))} - {props.ListFooterComponent} -
- ); - } - - return { LegendList }; -}); - -import { MessagesTimeline } from "./MessagesTimeline"; - -const MESSAGE_CREATED_AT = "2026-04-13T12:00:00.000Z"; - -function buildProps() { - return { - isWorking: false, - activeTurnInProgress: false, - activeTurnStartedAt: null, - listRef: createRef(), - latestTurn: null, - turnDiffSummaryByAssistantMessageId: new Map(), - routeThreadKey: "environment-local:thread-1", - onOpenTurnDiff: vi.fn(), - revertTurnCountByUserMessageId: new Map(), - onRevertUserMessage: vi.fn(), - isRevertingCheckpoint: false, - onImageExpand: vi.fn(), - activeThreadEnvironmentId: EnvironmentId.make("environment-local"), - markdownCwd: undefined, - resolvedTheme: "dark" as const, - timestampFormat: "24-hour" as const, - workspaceRoot: undefined, - onIsAtEndChange: vi.fn(), - }; -} - -function buildLongUserMessageText(tail = "deep hidden detail only after expand") { - return Array.from({ length: 9 }, (_, index) => - index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`, - ).join("\n"); -} - -function buildUserTimelineEntry(text: string) { - return { - id: "entry-1", - kind: "message" as const, - createdAt: MESSAGE_CREATED_AT, - message: { - id: "message-1" as never, - role: "user" as const, - text, - turnId: null, - createdAt: MESSAGE_CREATED_AT, - updatedAt: MESSAGE_CREATED_AT, - streaming: false, - }, - }; -} - -function buildAssistantTimelineEntry(text: string) { - return { - id: "entry-assistant-1", - kind: "message" as const, - createdAt: MESSAGE_CREATED_AT, - message: { - id: "message-assistant-1" as never, - role: "assistant" as const, - text, - turnId: null, - createdAt: MESSAGE_CREATED_AT, - updatedAt: MESSAGE_CREATED_AT, - streaming: false, - }, - }; -} - -describe("MessagesTimeline", () => { - afterEach(() => { - scrollToEndSpy.mockReset(); - getStateSpy.mockClear(); - vi.restoreAllMocks(); - document.body.innerHTML = ""; - }); - - it("renders activity rows instead of the empty placeholder when a thread has non-message timeline data", async () => { - const screen = await render( - , - ); - - try { - await expect - .element(page.getByText("Send a message to start the conversation.")) - .not.toBeInTheDocument(); - await expect.element(page.getByText("Inspecting repository state")).toBeVisible(); - expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull(); - } finally { - await screen.unmount(); - } - }); - - it("uses accessible expansion instead of native titles or preview tooltips for work entry details", async () => { - const screen = await render( - , - ); - - try { - expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull(); - - const commandTrigger = page.getByLabelText( - "Command - git diff -- apps/web/src/components/ChatMarkdown.tsx", - ); - await commandTrigger.hover(); - expect(document.querySelector('[data-slot="tooltip-popup"]')).toBeNull(); - - await commandTrigger.click(); - await expect - .element(page.getByText("git diff -- apps/web/src/components/ChatMarkdown.tsx --stat")) - .toBeVisible(); - } finally { - await screen.unmount(); - } - }); - - it("snaps to the bottom when timeline rows appear after an initially empty render", async () => { - const requestAnimationFrameSpy = vi - .spyOn(window, "requestAnimationFrame") - .mockImplementation((callback: FrameRequestCallback) => { - callback(0); - return 1; - }); - vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined); - - const props = buildProps(); - const screen = await render(); - - try { - await expect - .element(page.getByText("Send a message to start the conversation.")) - .toBeVisible(); - - await screen.rerender( - , - ); - - await expect.element(page.getByText("Inspecting repository state")).toBeVisible(); - expect(props.onIsAtEndChange).toHaveBeenCalledWith(true); - expect(scrollToEndSpy).toHaveBeenCalledWith({ animated: false }); - expect(requestAnimationFrameSpy).toHaveBeenCalled(); - } finally { - await screen.unmount(); - } - }); - - it("starts long user messages collapsed by default", async () => { - const screen = await render( - , - ); - - try { - const toggle = page.getByRole("button", { name: "Show full message" }); - await expect.element(toggle).toBeVisible(); - await expect.element(toggle).toHaveAttribute("aria-expanded", "false"); - - const messageBody = document.querySelector( - "[data-user-message-body='true']", - ) as HTMLDivElement | null; - expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true"); - expect(messageBody?.className).toContain("max-h-44"); - expect(messageBody?.className).toContain("overflow-hidden"); - expect(messageBody?.getAttribute("data-user-message-fade")).toBe("true"); - expect(messageBody?.style.maskImage).toContain("linear-gradient"); - } finally { - await screen.unmount(); - } - }); - - it("expands and re-collapses long user messages from the toggle", async () => { - const screen = await render( - , - ); - - try { - const expandButton = page.getByRole("button", { name: "Show full message" }); - await expect.element(expandButton).toBeVisible(); - - expect(document.body.textContent ?? "").toContain("deep hidden detail only after expand"); - - await expandButton.click(); - - const collapseButton = page.getByRole("button", { name: "Show less" }); - await expect.element(collapseButton).toBeVisible(); - await expect.element(collapseButton).toHaveAttribute("aria-expanded", "true"); - - let messageBody = document.querySelector("[data-user-message-body='true']"); - expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("false"); - expect(messageBody?.className).not.toContain("max-h-44"); - expect(messageBody?.getAttribute("data-user-message-fade")).toBe("false"); - expect((messageBody as HTMLDivElement | null)?.style.maskImage ?? "").toBe(""); - - await collapseButton.click(); - - await expect.element(page.getByRole("button", { name: "Show full message" })).toBeVisible(); - messageBody = document.querySelector("[data-user-message-body='true']"); - expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true"); - expect(messageBody?.className).toContain("max-h-44"); - expect(messageBody?.getAttribute("data-user-message-fade")).toBe("true"); - expect((messageBody as HTMLDivElement | null)?.style.maskImage).toContain("linear-gradient"); - } finally { - await screen.unmount(); - } - }); - - it("starts the newest long user prompt collapsed", async () => { - const screen = await render( - , - ); - - try { - await expect.element(page.getByRole("button", { name: "Show full message" })).toBeVisible(); - - const messageBody = document.querySelector("[data-user-message-body='true']"); - expect(messageBody?.getAttribute("data-user-message-collapsed")).toBe("true"); - } finally { - await screen.unmount(); - } - }); - - it("renders user messages as markdown with chat-style line breaks", async () => { - const screen = await render( - , - ); - - try { - await expect.element(page.getByRole("heading", { level: 2, name: "Plan" })).toBeVisible(); - await expect - .element(page.getByRole("link", { name: "a link" })) - .toHaveAttribute("href", "https://example.com"); - - const messageBody = document.querySelector("[data-user-message-body='true']"); - expect(messageBody?.querySelector("strong")?.textContent).toBe("bold"); - // remark-breaks: the single newline between the inline runs is a
. - expect(messageBody?.querySelectorAll("p br").length).toBe(1); - } finally { - await screen.unmount(); - } - }); - - it("renders markdown file tags in user and assistant messages", async () => { - const fileLink = "[package.json](path/to/package.json)"; - const screen = await render( - , - ); - - try { - const userFileLink = document.querySelector( - '[data-message-role="user"] .chat-markdown-file-link', - ); - const assistantFileLink = document.querySelector( - '[data-message-role="assistant"] .chat-markdown-file-link', - ); - - expect(userFileLink?.textContent).toContain("package.json"); - expect(userFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json"); - expect(assistantFileLink?.textContent).toContain("package.json"); - expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json"); - } finally { - await screen.unmount(); - } - }); - - it("uses the file path without line suffix for markdown file tag icons", async () => { - const fileLink = "[package.json](path/to/package.json:25)"; - const screen = await render( - , - ); - - try { - const assistantFileLink = document.querySelector( - '[data-message-role="assistant"] .chat-markdown-file-link', - ); - const icon = assistantFileLink?.querySelector("svg[data-pierre-icon]"); - - expect(assistantFileLink?.textContent).toContain("package.json"); - expect(assistantFileLink?.textContent).toContain("L25"); - expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json:25"); - expect(icon?.getAttribute("data-pierre-icon")).toBe("t3-file-icon-package-json"); - } finally { - await screen.unmount(); - } - }); - - it("folds settled-turn work behind a Worked-for row and expands it on click", async () => { - const screen = await render( - , - ); - - try { - const foldButton = page.getByRole("button", { name: "Worked for 30s" }); - await expect.element(foldButton).toBeVisible(); - await expect.element(foldButton).toHaveAttribute("aria-expanded", "false"); - - expect(document.body.textContent).toContain("All done."); - expect(document.body.textContent).not.toContain("Let me look around first."); - expect(document.body.textContent).not.toContain("Inspecting repository state"); - - await foldButton.click(); - - await expect.element(foldButton).toHaveAttribute("aria-expanded", "true"); - expect(document.body.textContent).toContain("Let me look around first."); - expect(document.body.textContent).toContain("Inspecting repository state"); - - await foldButton.click(); - - await expect.element(foldButton).toHaveAttribute("aria-expanded", "false"); - expect(document.body.textContent).not.toContain("Inspecting repository state"); - } finally { - await screen.unmount(); - } - }); -}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx deleted file mode 100644 index 484080013c..0000000000 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ /dev/null @@ -1,1258 +0,0 @@ -import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; -import { createModelCapabilities } from "@t3tools/shared/model"; -import { page, userEvent } from "vite-plus/test/browser"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -import { ProviderModelPicker } from "./ProviderModelPicker"; -import { getCustomModelOptionsByInstance } from "../../modelSelection"; -import { - deriveProviderInstanceEntries, - sortProviderInstanceEntries, -} from "../../providerInstances"; -import type { ModelEsque } from "./providerIconUtils"; -import { - DEFAULT_CLIENT_SETTINGS, - DEFAULT_UNIFIED_SETTINGS, - type UnifiedSettings, -} from "@t3tools/contracts/settings"; -import { __resetLocalApiForTests } from "../../localApi"; - -function selectDescriptor( - id: string, - label: string, - options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, -) { - return { - id, - label, - type: "select" as const, - options: [...options], - ...(options.find((option) => option.isDefault)?.id - ? { currentValue: options.find((option) => option.isDefault)?.id } - : {}), - }; -} - -function booleanDescriptor(id: string, label: string) { - return { - id, - label, - type: "boolean" as const, - }; -} - -const TEST_PROVIDERS: ReadonlyArray = [ - { - driver: ProviderDriverKind.make("codex"), - instanceId: ProviderInstanceId.make("codex"), - displayName: "Codex", - enabled: true, - installed: true, - version: "0.116.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: new Date().toISOString(), - slashCommands: [], - skills: [], - models: [ - { - slug: "gpt-5-codex", - name: "GPT-5 Codex", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - ], - }, - { - driver: ProviderDriverKind.make("claudeAgent"), - instanceId: ProviderInstanceId.make("claudeAgent"), - displayName: "Claude", - enabled: true, - installed: true, - version: "1.0.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: new Date().toISOString(), - slashCommands: [], - skills: [], - models: [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("effort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - { id: "max", label: "max" }, - ]), - booleanDescriptor("thinking", "Thinking"), - ], - }), - }, - { - slug: "claude-sonnet-4-6", - name: "Claude Sonnet 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("effort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - { id: "max", label: "max" }, - ]), - booleanDescriptor("thinking", "Thinking"), - ], - }), - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("effort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("thinking", "Thinking"), - ], - }), - }, - ], - }, -]; - -const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex"); -const CLAUDE_INSTANCE_ID = ProviderInstanceId.make("claudeAgent"); -const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode"); - -function buildCodexProvider(models: ServerProvider["models"]): ServerProvider { - return { - driver: ProviderDriverKind.make("codex"), - instanceId: ProviderInstanceId.make("codex"), - displayName: "Codex", - enabled: true, - installed: true, - version: "0.116.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: new Date().toISOString(), - models, - slashCommands: [], - skills: [], - }; -} - -function buildOpenCodeProvider(models: ServerProvider["models"]): ServerProvider { - return { - driver: ProviderDriverKind.make("opencode"), - instanceId: ProviderInstanceId.make("opencode"), - enabled: true, - installed: true, - version: "1.0.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: new Date().toISOString(), - models, - slashCommands: [], - skills: [], - }; -} - -async function mountPicker(props: { - activeInstanceId?: ProviderInstanceId; - model: string; - lockedProvider: ProviderDriverKind | null; - lockedContinuationGroupKey?: string | null; - providers?: ReadonlyArray; - settings?: UnifiedSettings; - triggerVariant?: "ghost" | "outline"; - getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; -}) { - const host = document.createElement("div"); - document.body.append(host); - const onInstanceModelChange = vi.fn(); - const providers = props.providers ?? TEST_PROVIDERS; - const instanceEntries = sortProviderInstanceEntries(deriveProviderInstanceEntries(providers)); - const activeInstanceId = props.activeInstanceId ?? CODEX_INSTANCE_ID; - const modelOptionsByInstance = getCustomModelOptionsByInstance( - props.settings ?? DEFAULT_UNIFIED_SETTINGS, - providers, - activeInstanceId, - props.model, - ); - const screen = await render( - , - { container: host }, - ); - - return { - onInstanceModelChange, - // Back-compat alias used by callers that still assert on the old callback - // name. Delegates to the instance-aware mock so existing expectations work. - get onProviderModelChange() { - return onInstanceModelChange; - }, - cleanup: async () => { - await screen.unmount(); - host.remove(); - }, - }; -} - -function getModelPickerListElement() { - const modelPickerList = document.querySelector(".model-picker-list"); - expect(modelPickerList).not.toBeNull(); - return modelPickerList!; -} - -function getModelPickerListText() { - return getModelPickerListElement().textContent ?? ""; -} - -function getVisibleModelNames() { - return Array.from(getModelPickerListElement().querySelectorAll("div.font-medium")) - .map((element) => element.textContent?.replace(/New$/u, "").trim() ?? "") - .filter((text) => text.length > 0); -} - -function getSidebarProviderOrder() { - return Array.from(document.querySelectorAll("[data-model-picker-provider]")).map( - (element) => element.dataset.modelPickerProvider ?? "", - ); -} - -describe("ProviderModelPicker", () => { - beforeEach(async () => { - // Reset test environment before each test - await __resetLocalApiForTests(); - }); - - afterEach(async () => { - document.body.innerHTML = ""; - await __resetLocalApiForTests(); - }); - - it("shows provider sidebar in unlocked mode", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).not.toContain("Codex"); - expect(text).toContain("Claude"); - expect(text).toContain("Claude Opus 4.6"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("shows favorites first in the provider sidebar", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(getSidebarProviderOrder().slice(0, 3)).toEqual([ - "favorites", - "codex", - "claudeAgent", - ]); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("filters models by selected provider in sidebar", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - // Start with Claude models visible - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).not.toContain("GPT-5 Codex"); - expect(text).toContain("Claude Opus 4.6"); - }); - - // Click on Codex provider in sidebar - await vi.waitFor(() => { - expect(document.querySelector('[data-model-picker-provider="codex"]')).not.toBeNull(); - }); - await page.getByRole("button", { name: "Codex", exact: true }).click(); - - // Now should only show Codex models - await vi.waitFor(() => { - const listText = getModelPickerListText(); - expect(listText).toContain("GPT-5 Codex"); - expect(listText).not.toContain("Claude Opus 4.6"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("uses client model visibility and ordering preferences", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - settings: { - ...DEFAULT_UNIFIED_SETTINGS, - providerModelPreferences: { - [CLAUDE_INSTANCE_ID]: { - hiddenModels: ["claude-opus-4-6"], - modelOrder: ["claude-haiku-4-5", "claude-sonnet-4-6"], - }, - }, - }, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(getVisibleModelNames()).toEqual(["Claude Haiku 4.5", "Claude Sonnet 4.6"]); - expect(getModelPickerListText()).not.toContain("Claude Opus 4.6"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("focuses the search input after selecting a sidebar provider", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(document.querySelector('[data-model-picker-provider="codex"]')).not.toBeNull(); - }); - await page.getByRole("button", { name: "Codex", exact: true }).click(); - - await vi.waitFor(() => { - const searchInput = document.querySelector( - 'input[placeholder="Search models..."]', - ); - expect(searchInput).not.toBeNull(); - expect(document.activeElement).toBe(searchInput); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("keeps the full provider rail in locked mode and only lists compatible models", async () => { - localStorage.setItem( - "t3code:client-settings:v1", - JSON.stringify({ - ...DEFAULT_CLIENT_SETTINGS, - favorites: [ - { provider: "codex", model: "gpt-5-codex" }, - { provider: "claudeAgent", model: "claude-sonnet-4-6" }, - ], - }), - ); - - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: ProviderDriverKind.make("claudeAgent"), - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude"); - // Locked-compatible instances render first, then disabled ones. - expect(getSidebarProviderOrder().slice(0, 3)).toEqual([ - "favorites", - "claudeAgent", - "codex", - ]); - expect( - document.querySelector('[data-model-picker-provider="codex"]') - ?.disabled, - ).toBe(true); - expect( - document.querySelector('[data-model-picker-provider="claudeAgent"]') - ?.disabled, - ).toBe(false); - expect(getVisibleModelNames()).toEqual([ - "Claude Sonnet 4.6", - "Claude Opus 4.6", - "Claude Haiku 4.5", - ]); - }); - } finally { - localStorage.removeItem("t3code:client-settings:v1"); - await mounted.cleanup(); - } - }); - - it("keeps an instance sidebar in locked mode when that provider has multiple instances", async () => { - const defaultCodexModels: ServerProvider["models"] = [ - { - slug: "gpt-work", - name: "GPT Work", - isCustom: false, - capabilities: createModelCapabilities({ optionDescriptors: [] }), - }, - ]; - const personalCodexModels: ServerProvider["models"] = [ - { - slug: "gpt-personal", - name: "GPT Personal", - isCustom: false, - capabilities: createModelCapabilities({ optionDescriptors: [] }), - }, - ]; - const isolatedCodexModels: ServerProvider["models"] = [ - { - slug: "gpt-isolated", - name: "GPT Isolated", - isCustom: false, - capabilities: createModelCapabilities({ optionDescriptors: [] }), - }, - ]; - const providers: ReadonlyArray = [ - { - ...buildCodexProvider(defaultCodexModels), - instanceId: "codex" as ProviderInstanceId, - displayName: "Codex Work", - accentColor: "#2563eb", - continuation: { groupKey: "codex:home:/Users/julius/.codex" }, - }, - { - ...buildCodexProvider(personalCodexModels), - instanceId: "codex_personal" as ProviderInstanceId, - displayName: "Codex Personal", - accentColor: "#dc2626", - continuation: { groupKey: "codex:home:/Users/julius/.codex" }, - }, - { - ...buildCodexProvider(isolatedCodexModels), - instanceId: "codex_isolated" as ProviderInstanceId, - displayName: "Codex Isolated", - accentColor: "#16a34a", - continuation: { groupKey: "codex:home:/Users/julius/.codex_isolated" }, - }, - TEST_PROVIDERS[1]!, - ]; - const mounted = await mountPicker({ - activeInstanceId: "codex" as ProviderInstanceId, - model: "gpt-work", - lockedProvider: ProviderDriverKind.make("codex"), - lockedContinuationGroupKey: "codex:home:/Users/julius/.codex", - providers, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(getSidebarProviderOrder().slice(0, 5)).toEqual([ - "favorites", - "codex", - "codex_personal", - "codex_isolated", - "claudeAgent", - ]); - expect( - document.querySelector('[data-model-picker-provider="codex_isolated"]') - ?.disabled, - ).toBe(true); - expect( - document.querySelector('[data-model-picker-provider="claudeAgent"]') - ?.disabled, - ).toBe(true); - expect(getModelPickerListText()).not.toContain("Codex Isolated"); - expect( - document.querySelector('[data-model-picker-provider="codex_personal"]') - ?.dataset.providerAccentColor, - ).toBe("#dc2626"); - expect(getModelPickerListText()).toContain("Codex Work"); - expect(getVisibleModelNames()).toEqual(["GPT Work"]); - }); - - await page.getByRole("button", { name: "Codex Personal" }).click(); - - await vi.waitFor(() => { - expect(getModelPickerListText()).toContain("Codex Personal"); - expect(getVisibleModelNames()).toEqual(["GPT Personal"]); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("falls back to the active provider's first model when props.model belongs to another provider (#1982)", async () => { - const host = document.createElement("div"); - document.body.append(host); - const onInstanceModelChange = vi.fn(); - const modelOptionsByInstance = new Map>([ - [ - "claudeAgent" as ProviderInstanceId, - [ - { slug: "claude-opus-4-6", name: "Claude Opus 4.6" }, - { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, - ], - ], - ["codex" as ProviderInstanceId, [{ slug: "gpt-5-codex", name: "GPT-5 Codex" }]], - ["cursor" as ProviderInstanceId, []], - ["opencode" as ProviderInstanceId, []], - ]); - const instanceEntries = sortProviderInstanceEntries( - deriveProviderInstanceEntries(TEST_PROVIDERS), - ); - const screen = await render( - , - { container: host }, - ); - - try { - const trigger = document.querySelector( - '[data-chat-provider-model-picker="true"]', - ); - expect(trigger).not.toBeNull(); - const label = trigger?.textContent ?? ""; - expect(label).not.toContain("gpt-5-codex"); - expect(label).toContain("Claude Opus 4.6"); - } finally { - await screen.unmount(); - host.remove(); - } - }); - - it("shows the plain model name in the trigger and provider details on locked opencode rows", async () => { - const providers: ReadonlyArray = [ - buildOpenCodeProvider([ - { - slug: "github-copilot/claude-opus-4.5", - name: "Claude Opus 4.5", - subProvider: "GitHub Copilot", - shortName: "Opus 4.5", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - ], - }), - }, - ]), - ]; - const mounted = await mountPicker({ - activeInstanceId: OPENCODE_INSTANCE_ID, - model: "github-copilot/claude-opus-4.5", - lockedProvider: ProviderDriverKind.make("opencode"), - providers, - }); - - try { - await vi.waitFor(() => { - const trigger = document.querySelector( - '[data-chat-provider-model-picker="true"]', - ); - expect(trigger?.textContent).toContain("Opus 4.5"); - expect(trigger?.textContent).not.toContain("GitHub Copilot"); - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(getVisibleModelNames()).toEqual(["Claude Opus 4.5"]); - expect(getModelPickerListText()).toContain("OpenCode · GitHub Copilot"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("searches models by name in flat list", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude Opus 4.6"); - expect(text).not.toContain("GPT-5 Codex"); - }); - - // Find and type in search box - const searchInput = page.getByPlaceholder("Search models..."); - await searchInput.fill("claude"); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude Opus 4.6"); - expect(text).not.toContain("GPT-5 Codex"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("supports arrow-key navigation in the model picker", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: ProviderDriverKind.make("claudeAgent"), - }); - - try { - await page.getByRole("button").click(); - - const searchInput = page.getByPlaceholder("Search models..."); - await userEvent.click(searchInput); - await userEvent.keyboard("{ArrowDown}"); - await vi.waitFor(() => { - const highlightedItem = document.querySelector( - '[data-slot="combobox-item"][data-highlighted]', - ); - expect(highlightedItem).not.toBeNull(); - expect(highlightedItem?.textContent).toContain("Claude Opus 4.6"); - }); - await userEvent.keyboard("{ArrowDown}"); - await vi.waitFor(() => { - const highlightedItem = document.querySelector( - '[data-slot="combobox-item"][data-highlighted]', - ); - expect(highlightedItem).not.toBeNull(); - expect(highlightedItem?.textContent).toContain("Claude Sonnet 4.6"); - }); - await userEvent.keyboard("{Enter}"); - - expect(mounted.onProviderModelChange).toHaveBeenCalledWith( - "claudeAgent", - "claude-sonnet-4-6", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("hides the provider sidebar while searching", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(getSidebarProviderOrder().length).toBeGreaterThan(0); - }); - - await page.getByPlaceholder("Search models...").fill("cla"); - - await vi.waitFor(() => { - expect(getSidebarProviderOrder()).toEqual([]); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("closes the picker when escape is pressed in search", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - const searchInput = page.getByPlaceholder("Search models..."); - await searchInput.click(); - const searchInputElement = document.querySelector( - 'input[placeholder="Search models..."]', - ); - expect(searchInputElement).not.toBeNull(); - searchInputElement!.dispatchEvent( - new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), - ); - - await vi.waitFor(() => { - expect(document.querySelector(".model-picker-list")).toBeNull(); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("searches models by provider name", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude Opus 4.6"); - expect(text).not.toContain("GPT-5 Codex"); - }); - - // Search by provider name - const searchInput = page.getByPlaceholder("Search models..."); - await searchInput.fill("codex"); - - await vi.waitFor(() => { - const listText = getModelPickerListText(); - expect(listText).toContain("GPT-5 Codex"); - expect(listText).not.toContain("Claude Opus 4.6"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("matches fuzzy multi-token queries across provider and model text", async () => { - const providers: ReadonlyArray = [ - buildCodexProvider([ - { - slug: "gpt-5-codex", - name: "GPT-5 Codex", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - ]), - buildOpenCodeProvider([ - { - slug: "github-copilot/claude-opus-4.7", - name: "Claude Opus 4.7", - subProvider: "GitHub Copilot", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - ], - }), - }, - ]), - ]; - const mounted = await mountPicker({ - activeInstanceId: OPENCODE_INSTANCE_ID, - model: "github-copilot/claude-opus-4.7", - lockedProvider: null, - providers, - }); - - try { - await page.getByRole("button").click(); - await page.getByPlaceholder("Search models...").fill("coplt op"); - - await vi.waitFor(() => { - const listText = getModelPickerListText(); - expect(listText).toContain("Claude Opus 4.7"); - expect(listText).not.toContain("GPT-5 Codex"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("renders each search result with its own provider branding", async () => { - const providers: ReadonlyArray = [ - buildOpenCodeProvider([ - { - slug: "github-copilot/claude-opus-4.7", - name: "Claude Opus 4.7", - subProvider: "GitHub Copilot", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - ], - }), - }, - ]), - { - ...TEST_PROVIDERS[1]!, - models: [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("effort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - { id: "max", label: "max" }, - ]), - booleanDescriptor("thinking", "Thinking"), - ], - }), - }, - ], - }, - ]; - const mounted = await mountPicker({ - activeInstanceId: OPENCODE_INSTANCE_ID, - model: "github-copilot/claude-opus-4.7", - lockedProvider: null, - providers, - }); - - try { - await page.getByRole("button").click(); - await page.getByPlaceholder("Search models...").fill("opus"); - - await vi.waitFor(() => { - const listText = getModelPickerListText(); - expect(listText).toContain("OpenCode · GitHub Copilot"); - expect(listText).toContain("Claude"); - expect(listText).not.toContain("OpenCodeClaude Opus 4.6"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("toggles favorite stars when clicked", async () => { - localStorage.removeItem("t3code:client-settings:v1"); - - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude Opus 4.6"); - }); - - const getFavoriteButton = () => { - const modelRow = Array.from(document.querySelectorAll('[role="option"]')).find( - (row) => row.textContent?.includes("Claude Opus 4.6"), - ); - const starButton = modelRow?.querySelector( - 'button[aria-label*="favorites"]', - ); - expect(starButton).not.toBeNull(); - return starButton!; - }; - - const favoriteButton = getFavoriteButton(); - const initialAriaLabel = favoriteButton.getAttribute("aria-label"); - expect( - initialAriaLabel === "Add to favorites" || initialAriaLabel === "Remove from favorites", - ).toBe(true); - - await userEvent.click(favoriteButton); - - const expectedAriaLabel = - initialAriaLabel === "Add to favorites" ? "Remove from favorites" : "Add to favorites"; - - await vi.waitFor(() => { - expect(getFavoriteButton().getAttribute("aria-label")).toBe(expectedAriaLabel); - }); - } finally { - await mounted.cleanup(); - localStorage.removeItem("t3code:client-settings:v1"); - } - }); - - it("does not duplicate favorited models across favorites and all models sections", async () => { - localStorage.removeItem("t3code:client-settings:v1"); - - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude Opus 4.6"); - }); - - const favoriteButton = page.getByRole("button", { - name: "Add to favorites", - }); - await favoriteButton.first().click(); - - await vi.waitFor(async () => { - const favoritedModelRows = Array.from( - getModelPickerListElement().querySelectorAll("div.font-medium"), - ).filter((element) => element.textContent?.trim() === "Claude Opus 4.6"); - expect(favoritedModelRows.length).toBe(1); - }); - } finally { - await mounted.cleanup(); - localStorage.removeItem("t3code:client-settings:v1"); - } - }); - - it("shows favorited models first within the selected provider list", async () => { - localStorage.setItem( - "t3code:client-settings:v1", - JSON.stringify({ - ...DEFAULT_CLIENT_SETTINGS, - favorites: [{ provider: "codex", model: "gpt-5.3-codex" }], - }), - ); - - const mounted = await mountPicker({ - model: "gpt-5-codex", - lockedProvider: null, - }); - - try { - await page.getByRole("button").click(); - await page.getByRole("button", { name: "Codex", exact: true }).click(); - - await vi.waitFor(() => { - expect(getVisibleModelNames().slice(0, 2)).toEqual(["GPT-5.3 Codex", "GPT-5 Codex"]); - }); - } finally { - await mounted.cleanup(); - localStorage.removeItem("t3code:client-settings:v1"); - } - }); - - it("filters favorites to compatible models in locked mode", async () => { - localStorage.setItem( - "t3code:client-settings:v1", - JSON.stringify({ - ...DEFAULT_CLIENT_SETTINGS, - favorites: [ - { provider: "codex", model: "gpt-5.3-codex" }, - { provider: "claudeAgent", model: "claude-sonnet-4-6" }, - ], - }), - ); - - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: ProviderDriverKind.make("claudeAgent"), - }); - - try { - await page.getByRole("button").click(); - await page.getByRole("button", { name: "Favorites", exact: true }).click(); - - await vi.waitFor(() => { - expect(getVisibleModelNames()).toEqual(["Claude Sonnet 4.6"]); - expect(getModelPickerListText()).not.toContain("GPT-5.3 Codex"); - }); - } finally { - await mounted.cleanup(); - localStorage.removeItem("t3code:client-settings:v1"); - } - }); - - it("dispatches callback with correct provider and model when selected", async () => { - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: ProviderDriverKind.make("claudeAgent"), - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Claude Sonnet 4.6"); - }); - - // Click on a model - const modelRow = page.getByText("Claude Sonnet 4.6").first(); - await modelRow.click(); - - // Verify callback was called with correct values - expect(mounted.onProviderModelChange).toHaveBeenCalledWith( - "claudeAgent", - "claude-sonnet-4-6", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("does not select models blocked by the provider", async () => { - const disabledReason = - "This provider does not allow switching models after a conversation has started. Start a new thread to use this model."; - const mounted = await mountPicker({ - activeInstanceId: CLAUDE_INSTANCE_ID, - model: "claude-opus-4-6", - lockedProvider: ProviderDriverKind.make("claudeAgent"), - getModelDisabledReason: (instanceId, model) => - instanceId === CLAUDE_INSTANCE_ID && model !== "claude-opus-4-6" ? disabledReason : null, - }); - - try { - await page.getByRole("button").click(); - - const blockedModel = page.getByText("Claude Sonnet 4.6").first(); - await blockedModel.click(); - expect(mounted.onProviderModelChange).not.toHaveBeenCalled(); - expect(document.querySelector(".model-picker-list")).not.toBeNull(); - } finally { - await mounted.cleanup(); - } - }); - - it("only shows codex spark when the server reports it", async () => { - const providersWithoutSpark: ReadonlyArray = [ - buildCodexProvider([ - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - ]), - TEST_PROVIDERS[1]!, - ]; - const providersWithSpark: ReadonlyArray = [ - buildCodexProvider([ - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - { - slug: "gpt-5.3-codex-spark", - name: "GPT-5.3 Codex Spark", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "low", label: "low" }, - { id: "medium", label: "medium", isDefault: true }, - { id: "high", label: "high" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - ], - }), - }, - ]), - TEST_PROVIDERS[1]!, - ]; - - const hidden = await mountPicker({ - model: "gpt-5.3-codex", - lockedProvider: null, - providers: providersWithoutSpark, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("GPT-5.3 Codex"); - expect(text).not.toContain("GPT-5.3 Codex Spark"); - }); - } finally { - await hidden.cleanup(); - } - - const visible = await mountPicker({ - model: "gpt-5.3-codex", - lockedProvider: null, - providers: providersWithSpark, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark"); - }); - } finally { - await visible.cleanup(); - } - }); - - it("shows disabled providers grayed out in sidebar", async () => { - const disabledProviders = TEST_PROVIDERS.slice(); - const claudeIndex = disabledProviders.findIndex( - (provider) => provider.instanceId === ProviderInstanceId.make("claudeAgent"), - ); - if (claudeIndex >= 0) { - const claudeProvider = disabledProviders[claudeIndex]!; - disabledProviders[claudeIndex] = { - ...claudeProvider, - enabled: false, - status: "disabled", - }; - } - - const mounted = await mountPicker({ - model: "gpt-5-codex", - lockedProvider: null, - providers: disabledProviders, - }); - - try { - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("GPT-5 Codex"); - // Disabled provider should not have its models shown - expect(text).not.toContain("Claude Opus 4.6"); - }); - } finally { - await mounted.cleanup(); - } - }); - - it("accepts outline trigger styling", async () => { - const mounted = await mountPicker({ - model: "gpt-5-codex", - lockedProvider: null, - triggerVariant: "outline", - }); - - try { - const button = document.querySelector("button"); - if (!(button instanceof HTMLButtonElement)) { - throw new Error("Expected picker trigger button to be rendered."); - } - expect(button.className).toContain("border-input"); - expect(button.className).toContain("bg-popover"); - } finally { - await mounted.cleanup(); - } - }); -}); diff --git a/apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx b/apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx deleted file mode 100644 index a5dc52053e..0000000000 --- a/apps/web/src/components/clerk/DesktopClerkSignIn.browser.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import "../../index.css"; - -import { page, userEvent } from "vite-plus/test/browser"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -import type { DesktopCloudAuthOAuthOption } from "../../cloud/desktopAuth"; -import { DesktopClerkSignInCard } from "./DesktopClerkSignIn"; - -const GOOGLE: DesktopCloudAuthOAuthOption = { - strategy: "oauth_google", - label: "Google", - providerId: "google", - iconUrl: null, -}; - -const PROVIDERS: readonly DesktopCloudAuthOAuthOption[] = [ - { - strategy: "oauth_apple", - label: "Apple", - providerId: "apple", - iconUrl: null, - }, - GOOGLE, - { - strategy: "oauth_microsoft", - label: "Microsoft", - providerId: "microsoft", - iconUrl: null, - }, -]; - -describe("DesktopClerkSignInCard", () => { - afterEach(() => { - document.body.innerHTML = ""; - }); - - it("uses Clerk's compact provider grid when more than two providers are enabled", async () => { - await render( - , - ); - - expect(document.querySelectorAll('button[aria-label^="Continue with "]')).toHaveLength(3); - expect(document.body.textContent).toContain("Want early access?"); - expect(document.body.textContent).not.toContain("Continue with Google"); - }); - - it("renders a full provider label and starts OAuth for a single provider", async () => { - const onStartOAuth = vi.fn(); - await render( - , - ); - - await userEvent.click(page.getByRole("button", { name: "Continue with Google" })); - - expect(document.body.textContent).toContain("Continue with Google"); - expect(onStartOAuth).toHaveBeenCalledWith("oauth_google"); - }); -}); diff --git a/apps/web/src/components/cloud/RelayClientInstallDialog.browser.tsx b/apps/web/src/components/cloud/RelayClientInstallDialog.browser.tsx deleted file mode 100644 index b4bb763593..0000000000 --- a/apps/web/src/components/cloud/RelayClientInstallDialog.browser.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import "../../index.css"; - -import { page } from "vite-plus/test/browser"; -import { beforeEach, describe, expect, it } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -import { - finishRelayClientInstall, - readRelayClientInstallDialogState, - reportRelayClientInstallProgress, - requestRelayClientInstallConfirmation, - resetRelayClientInstallDialogForTests, -} from "../../cloud/relayClientInstallDialog"; -import { RelayClientInstallDialog } from "./RelayClientInstallDialog"; - -describe("RelayClientInstallDialog", () => { - beforeEach(() => { - resetRelayClientInstallDialogForTests(); - }); - - it("confirms installation and renders streamed progress", async () => { - render(); - const confirmation = requestRelayClientInstallConfirmation("2026.5.2"); - - await expect.element(page.getByText("Install relay client?")).toBeInTheDocument(); - await expect.element(page.getByText(/version 2026\.5\.2 locally/)).toBeInTheDocument(); - - await page.getByRole("button", { name: "Download and install" }).click(); - await expect(confirmation).resolves.toBe(true); - await expect - .element(page.getByRole("heading", { name: "Installing relay client" })) - .toBeInTheDocument(); - - reportRelayClientInstallProgress({ type: "progress", stage: "downloading" }); - await expect.element(page.getByText("Downloading relay client")).toBeInTheDocument(); - await expect - .element(page.getByRole("progressbar", { name: "Relay client installation progress" })) - .toHaveAttribute("value", "3"); - - finishRelayClientInstall(); - expect(readRelayClientInstallDialogState().status).toBe("closing"); - await expect - .element(page.getByRole("heading", { name: "Installing relay client" })) - .not.toBeInTheDocument(); - expect(readRelayClientInstallDialogState()).toEqual({ status: "idle" }); - }); -}); diff --git a/apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx b/apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx deleted file mode 100644 index 1f1bba90eb..0000000000 --- a/apps/web/src/components/diffs/AnnotatableFileDiff.browser.tsx +++ /dev/null @@ -1,122 +0,0 @@ -import "../../index.css"; - -import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; -import { render } from "vitest-browser-react"; - -import { useComposerDraftStore } from "~/composerDraftStore"; - -import { AnnotatableFileDiff } from "./AnnotatableFileDiff"; - -function dispatchPointer(target: EventTarget, type: string, pointerId: number): void { - target.dispatchEvent( - new PointerEvent(type, { - bubbles: true, - cancelable: true, - composed: true, - pointerId, - pointerType: "mouse", - }), - ); -} - -const threadRef = scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("thread-1")); - -function TestDiff() { - const fileDiff = parsePatchFiles( - [ - "diff --git a/src/app.ts b/src/app.ts", - "--- a/src/app.ts", - "+++ b/src/app.ts", - "@@ -1,3 +1,3 @@", - " one", - "-two", - "+TWO", - " three", - ].join("\n"), - "annotatable-file-diff-test", - )[0]!.files[0]!; - - return ( - null} - options={{ - diffStyle: "unified", - lineDiffType: "none", - themeType: "light", - }} - /> - ); -} - -async function getRenderedDiff() { - return vi.waitFor(() => { - const element = document.querySelector("diffs-container"); - expect(element?.shadowRoot).not.toBeNull(); - return element!; - }); -} - -describe("annotatable Pierre file diff", () => { - afterEach(() => { - document.body.innerHTML = ""; - useComposerDraftStore.getState().setReviewComments(threadRef, []); - }); - - it("creates a local annotation from the gutter and attaches it to the composer", async () => { - let screen = await render(); - - try { - const diff = await getRenderedDiff(); - const addedLineNumber = await vi.waitFor(() => { - const elements = Array.from( - diff.shadowRoot?.querySelectorAll('[data-column-number="2"]') ?? [], - ); - const element = elements.at(-1) ?? null; - expect(element).not.toBeNull(); - return element!; - }); - - dispatchPointer(addedLineNumber, "pointerdown", 1); - dispatchPointer(addedLineNumber, "pointerup", 1); - - const textarea = page.getByRole("textbox", { name: "Comment on lines +2" }); - await expect.element(textarea).toBeVisible(); - await textarea.fill("Use the compatible value."); - await page.getByRole("button", { name: "Comment" }).click(); - - await vi.waitFor(() => { - expect( - useComposerDraftStore.getState().getComposerDraft(threadRef)?.reviewComments, - ).toEqual([ - expect.objectContaining({ - sectionId: "turn:2", - filePath: "src/app.ts", - rangeLabel: "+2", - text: "Use the compatible value.", - diff: "@@ -0,0 +2,1 @@\n+TWO", - }), - ]); - }); - expect(document.querySelector("[data-file-comment-annotation]")?.textContent).toContain( - "Use the compatible value.", - ); - - await screen.unmount(); - screen = await render(); - await expect - .element(page.getByText("Use the compatible value.", { exact: true })) - .toBeVisible(); - } finally { - await screen.unmount(); - } - }); -}); diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.tsx deleted file mode 100644 index 7886e99cba..0000000000 --- a/apps/web/src/components/files/FilePreviewPanel.browser.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import "../../index.css"; - -import type { LineAnnotation, SelectedLineRange } from "@pierre/diffs"; -import { Editor } from "@pierre/diffs/editor"; -import { EditorProvider, File } from "@pierre/diffs/react"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; -import { render } from "vitest-browser-react"; -import { useEffect, useMemo, useRef, useState } from "react"; - -import { installFileEditorDismissal } from "./fileEditorDismissal"; - -interface AnnotationMetadata { - label: string; -} - -function dispatchPointer(target: EventTarget, type: string, pointerId: number): void { - target.dispatchEvent( - new PointerEvent(type, { - bubbles: true, - cancelable: true, - composed: true, - pointerId, - pointerType: "mouse", - }), - ); -} - -function EditableAnnotatedFile() { - const [selectedLines, setSelectedLines] = useState(null); - const [lineAnnotations, setLineAnnotations] = useState[]>([]); - const rootRef = useRef(null); - const editor = useMemo(() => new Editor(), []); - - useEffect(() => () => editor.cleanUp(), [editor]); - useEffect(() => { - const root = rootRef.current; - if (!root) return; - return installFileEditorDismissal({ - root, - editor, - isBlocked: () => false, - onDismiss: () => setSelectedLines(null), - }); - }, [editor]); - - return ( - <> -
- - - file={{ name: "example.ts", contents: "one\ntwo\nthree\n" }} - options={{ - disableFileHeader: true, - enableGutterUtility: true, - enableLineSelection: true, - onGutterUtilityClick: setSelectedLines, - onLineSelectionChange: setSelectedLines, - onLineSelectionEnd: (range) => { - setSelectedLines(range); - if (range) { - setLineAnnotations([ - { - lineNumber: Math.max(range.start, range.end), - metadata: { label: `${range.start}:${range.end}` }, - }, - ]); - } - }, - }} - selectedLines={selectedLines} - lineAnnotations={lineAnnotations} - renderAnnotation={(annotation) => ( -
- {annotation.metadata.label} -
- )} - disableWorkerPool - contentEditable - /> -
-
- - - ); -} - -async function getEditableFile() { - const file = await vi.waitFor(() => { - const element = document.querySelector("diffs-container"); - expect(element?.shadowRoot).not.toBeNull(); - return element!; - }); - const content = await vi.waitFor(() => { - const element = file?.shadowRoot?.querySelector("[data-content]") ?? null; - expect(element).not.toBeNull(); - return element!; - }); - return { file, content }; -} - -describe("editable Pierre file annotations", () => { - afterEach(() => { - document.body.innerHTML = ""; - }); - - it("keeps gutter selection and annotations enabled while the file is editable", async () => { - const screen = await render(); - - try { - const { file, content } = await getEditableFile(); - const secondLineNumber = await vi.waitFor(() => { - const element = - file?.shadowRoot?.querySelector('[data-column-number="2"]') ?? null; - expect(element).not.toBeNull(); - return element; - }); - await vi.waitFor(() => { - expect( - file?.shadowRoot?.querySelector("pre")?.hasAttribute("data-interactive-line-numbers"), - ).toBe(true); - }); - - dispatchPointer(secondLineNumber!, "pointerdown", 1); - dispatchPointer(secondLineNumber!, "pointerup", 1); - - await vi.waitFor(() => { - expect(document.querySelector("[data-test-file-annotation]")?.textContent).toBe("2:2"); - }); - - expect(content.contentEditable).toBe("true"); - expect(content.getAttribute("role")).toBe("textbox"); - } finally { - await screen.unmount(); - } - }); - - it("dismisses editor focus and selection with outside click or Escape", async () => { - const screen = await render(); - - try { - const { file, content } = await getEditableFile(); - content.focus(); - expect(file?.shadowRoot?.activeElement).toBe(content); - - await page.getByRole("button", { name: "Outside file" }).click(); - await vi.waitFor(() => { - expect(file?.shadowRoot?.activeElement).not.toBe(content); - }); - - content.focus(); - expect(file?.shadowRoot?.activeElement).toBe(content); - content.dispatchEvent( - new KeyboardEvent("keydown", { - key: "Escape", - bubbles: true, - cancelable: true, - composed: true, - }), - ); - await vi.waitFor(() => { - expect(file?.shadowRoot?.activeElement).not.toBe(content); - }); - } finally { - await screen.unmount(); - } - }); -}); diff --git a/apps/web/src/components/preview/PreviewChromeRow.browser.tsx b/apps/web/src/components/preview/PreviewChromeRow.browser.tsx deleted file mode 100644 index 8cb48c7e11..0000000000 --- a/apps/web/src/components/preview/PreviewChromeRow.browser.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import "../../index.css"; - -import { page } from "vite-plus/test/browser"; -import { describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; - -import { PreviewChromeRow } from "./PreviewChromeRow"; - -const defaultProps = { - url: "https://example.com/", - loading: false, - loadProgress: 0, - canGoBack: false, - canGoForward: false, - refreshDisabled: false, - onBack: vi.fn(), - onForward: vi.fn(), - onRefresh: vi.fn(), - onSubmit: vi.fn(), -}; - -describe("PreviewChromeRow", () => { - it("uses the shared compact surface subheader treatment", async () => { - const screen = await render(); - const subheader = screen.container.querySelector("[data-surface-subheader]"); - - expect(subheader).not.toBeNull(); - expect(subheader?.getBoundingClientRect().height).toBe(40); - expect(window.getComputedStyle(subheader!).borderTopWidth).toBe("0px"); - expect(window.getComputedStyle(subheader!).borderBottomWidth).toBe("1px"); - }); - - it("only focuses the URL input after an explicit focus request", async () => { - const previouslyFocused = document.createElement("button"); - document.body.append(previouslyFocused); - previouslyFocused.focus(); - - const screen = await render(); - const input = page.getByRole("textbox").element() as HTMLInputElement; - - expect(document.activeElement).toBe(previouslyFocused); - - await screen.rerender(); - - expect(document.activeElement).toBe(input); - expect(input.selectionStart).toBe(0); - expect(input.selectionEnd).toBe(input.value.length); - - previouslyFocused.remove(); - }); - - it("shows a friendly asset label until the URL input receives focus", async () => { - const fullUrl = "http://127.0.0.1:3773/api/assets/token/report.pdf"; - await render( - , - ); - const input = page.getByRole("textbox"); - - await expect.element(input).toHaveValue("Local environment · report.pdf"); - - await input.click(); - - await expect.element(input).toHaveValue(fullUrl); - - input.element().dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - - await expect.element(input).toHaveValue("Local environment · report.pdf"); - }); - - it("shows only the host for regular URLs until the input receives focus", async () => { - const fullUrl = "https://t3.chat/chat/18378834-f776-4507-ada7-6f79"; - await render(); - const input = page.getByRole("textbox"); - - await expect.element(input).toHaveValue("t3.chat"); - - await input.click(); - - await expect.element(input).toHaveValue(fullUrl); - }); -}); diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx deleted file mode 100644 index d3602860bc..0000000000 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ /dev/null @@ -1,2027 +0,0 @@ -import "../../index.css"; - -import { - type AuthAccessStreamEvent, - type AuthAccessSnapshot, - type AuthEnvironmentScope, - AuthSessionId, - DEFAULT_SERVER_SETTINGS, - EnvironmentId, - type DesktopBridge, - type DesktopUpdateChannel, - type DesktopUpdateState, - type LocalApi, - ProviderDriverKind, - ProviderInstanceId, - type ServerConfig, - type ServerProcessResourceHistoryResult, - type ServerProvider, - type SourceControlDiscoveryResult, -} from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import * as Option from "effect/Option"; -import { page } from "vite-plus/test/browser"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { render } from "vitest-browser-react"; -import type { ReactNode } from "react"; -import { - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from "@tanstack/react-router"; - -import { __resetLocalApiForTests } from "../../localApi"; -import { - appAtomRegistry, - AppAtomRegistryProvider, - resetAppAtomRegistryForTests, -} from "../../rpc/atomRegistry"; -import { useUiStateStore } from "../../uiStateStore"; -import { ConnectionsSettings } from "./ConnectionsSettings"; -import { DiagnosticsSettingsPanel } from "./DiagnosticsSettings"; -import { GeneralSettingsPanel, ProviderSettingsPanel } from "./SettingsPanels"; -import { SourceControlSettingsPanel } from "./SourceControlSettings"; - -function renderWithTestRouter(children: ReactNode) { - const rootRoute = createRootRoute({ - component: () => children, - }); - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: "/", - }); - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ["/"] }), - }); - - return render(); -} - -const authAccessHarness = vi.hoisted(() => { - type Snapshot = AuthAccessSnapshot; - let snapshot: Snapshot = { - pairingLinks: [], - clientSessions: [], - }; - let revision = 1; - let currentEvent: AuthAccessStreamEvent = { - version: 1, - revision, - type: "snapshot", - payload: snapshot, - }; - const listeners = new Set<() => void>(); - - const emitEvent = (event: AuthAccessStreamEvent) => { - currentEvent = event; - for (const listener of listeners) { - listener(); - } - }; - - return { - reset() { - snapshot = { - pairingLinks: [], - clientSessions: [], - }; - revision = 1; - currentEvent = { - version: 1, - revision, - type: "snapshot", - payload: snapshot, - }; - listeners.clear(); - }, - setSnapshot(next: Snapshot) { - snapshot = next; - currentEvent = { - version: 1, - revision, - type: "snapshot", - payload: snapshot, - }; - }, - emitSnapshot() { - emitEvent({ - version: 1 as const, - revision, - type: "snapshot" as const, - payload: snapshot, - }); - revision += 1; - }, - emitEvent, - emitPairingLinkUpserted(pairingLink: Snapshot["pairingLinks"][number]) { - emitEvent({ - version: 1, - revision, - type: "pairingLinkUpserted", - payload: pairingLink, - }); - revision += 1; - }, - emitPairingLinkRemoved(id: string) { - emitEvent({ - version: 1, - revision, - type: "pairingLinkRemoved", - payload: { id }, - }); - revision += 1; - }, - emitClientUpserted(clientSession: Snapshot["clientSessions"][number]) { - emitEvent({ - version: 1, - revision, - type: "clientUpserted", - payload: clientSession, - }); - revision += 1; - }, - emitClientRemoved(sessionId: string) { - emitEvent({ - version: 1, - revision, - type: "clientRemoved", - payload: { - sessionId: AuthSessionId.make(sessionId), - }, - }); - revision += 1; - }, - getSnapshot() { - return currentEvent; - }, - subscribe(listener: () => void) { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; - }, - }; -}); - -const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn()); -const mockGetClerkToken = vi.hoisted(() => vi.fn(async () => null)); -const mockConnectPairingEnvironment = vi.hoisted(() => vi.fn()); -const mockConnectRelayEnvironment = vi.hoisted(() => vi.fn()); -const mockRemoveEnvironment = vi.hoisted(() => vi.fn()); -const mockRetryEnvironment = vi.hoisted(() => vi.fn()); -const mockRefreshRelayEnvironments = vi.hoisted(() => vi.fn(async () => undefined)); -const mockRefreshProviders = vi.hoisted(() => - vi.fn(async ({ input }: { readonly input: Record }) => { - return window.nativeApi?.server.refreshProviders(input); - }), -); -const mockUpdateProvider = vi.hoisted(() => - vi.fn( - async ({ input }: { readonly input: Parameters[0] }) => { - return window.nativeApi?.server.updateProvider(input); - }, - ), -); -const directAtomMocks = vi.hoisted(() => ({ - authAccessQuery: Symbol("auth-access-query"), - connectPairingAction: Symbol("connect-pairing-action"), - connectSshEnvironmentAction: Symbol("connect-ssh-environment-action"), - environmentRegisterAction: Symbol("environment-register-action"), - environmentRemoveAction: Symbol("environment-remove-action"), - environmentRetryAction: Symbol("environment-retry-action"), - linkPrimaryEnvironmentAction: Symbol("link-primary-environment-action"), - openInEditorAction: Symbol("open-in-editor-action"), - refreshRelayEnvironmentsAction: Symbol("refresh-relay-environments-action"), - removeKeybindingAction: Symbol("remove-keybinding-action"), - refreshProvidersAction: Symbol("refresh-providers-action"), - signalProcessAction: Symbol("signal-process-action"), - updateProviderAction: Symbol("update-provider-action"), - updateSettingsAction: Symbol("update-settings-action"), - unlinkPrimaryEnvironmentAction: Symbol("unlink-primary-environment-action"), - upsertKeybindingAction: Symbol("upsert-keybinding-action"), -})); -const serverConfigHarness = vi.hoisted(() => ({ - configAtom: null as unknown, -})); - -function setServerConfigSnapshot(config: ServerConfig): void { - appAtomRegistry.set(serverConfigHarness.configAtom as never, config as never); -} - -function resetServerConfigSnapshot(): void { - appAtomRegistry.set(serverConfigHarness.configAtom as never, null as never); -} - -vi.mock("../../state/use-atom-command", async () => { - const { AsyncResult } = await import("effect/unstable/reactivity"); - const withSuccessfulResult = - , A>(run: (...args: Args) => A | Promise) => - async (...args: Args) => - AsyncResult.success(await run(...args)); - const refreshProviders = withSuccessfulResult(mockRefreshProviders); - const connectPairingEnvironment = withSuccessfulResult(mockConnectPairingEnvironment); - const connectDesktopSshEnvironment = withSuccessfulResult(mockConnectDesktopSshEnvironment); - const connectRelayEnvironment = withSuccessfulResult(mockConnectRelayEnvironment); - const removeEnvironment = withSuccessfulResult(mockRemoveEnvironment); - const retryEnvironment = withSuccessfulResult(mockRetryEnvironment); - const refreshRelayEnvironments = withSuccessfulResult(mockRefreshRelayEnvironments); - const updateProvider = withSuccessfulResult(mockUpdateProvider); - const signalProcess = withSuccessfulResult( - ({ input }: { readonly input: Parameters[0] }) => - window.nativeApi?.server.signalProcess(input), - ); - const openInEditor = withSuccessfulResult( - ({ - input, - }: { - readonly input: { - readonly cwd: string; - readonly editor: Parameters[1]; - }; - }) => window.nativeApi?.shell.openInEditor(input.cwd, input.editor), - ); - const succeedWithNoResult = async () => AsyncResult.success(undefined); - - return { - useAtomCommand: (command: unknown) => { - if (command === directAtomMocks.refreshProvidersAction) { - return refreshProviders; - } - if (command === directAtomMocks.connectPairingAction) { - return connectPairingEnvironment; - } - if (command === directAtomMocks.connectSshEnvironmentAction) { - return connectDesktopSshEnvironment; - } - if (command === directAtomMocks.environmentRegisterAction) { - return connectRelayEnvironment; - } - if (command === directAtomMocks.environmentRemoveAction) { - return removeEnvironment; - } - if (command === directAtomMocks.environmentRetryAction) { - return retryEnvironment; - } - if (command === directAtomMocks.refreshRelayEnvironmentsAction) { - return refreshRelayEnvironments; - } - if (command === directAtomMocks.updateProviderAction) { - return updateProvider; - } - if (command === directAtomMocks.signalProcessAction) { - return signalProcess; - } - if (command === directAtomMocks.openInEditorAction) { - return openInEditor; - } - if ( - command === directAtomMocks.linkPrimaryEnvironmentAction || - command === directAtomMocks.removeKeybindingAction || - command === directAtomMocks.unlinkPrimaryEnvironmentAction || - command === directAtomMocks.updateSettingsAction || - command === directAtomMocks.upsertKeybindingAction - ) { - return succeedWithNoResult; - } - throw new Error("Unexpected atom command in settings browser test."); - }, - }; -}); - -vi.mock("@clerk/react", () => ({ - useAuth: () => ({ - getToken: mockGetClerkToken, - isSignedIn: false, - }), -})); - -vi.mock("../../cloud/linkEnvironmentAtoms", () => ({ - linkPrimaryEnvironment: directAtomMocks.linkPrimaryEnvironmentAction, - unlinkPrimaryEnvironment: directAtomMocks.unlinkPrimaryEnvironmentAction, -})); - -vi.mock("../../connection/catalog", () => ({ - environmentCatalog: { - register: directAtomMocks.environmentRegisterAction, - remove: directAtomMocks.environmentRemoveAction, - retryNow: directAtomMocks.environmentRetryAction, - }, -})); - -vi.mock("../../connection/onboarding", () => ({ - connectPairing: directAtomMocks.connectPairingAction, - connectSshEnvironment: directAtomMocks.connectSshEnvironmentAction, -})); - -vi.mock("../../state/relay", () => ({ - relayEnvironmentDiscovery: { - refresh: directAtomMocks.refreshRelayEnvironmentsAction, - }, -})); - -vi.mock("../../lib/archivedThreadsState", () => ({ - refreshArchivedThreadsForEnvironment: vi.fn(), - useArchivedThreadSnapshots: () => ({ - snapshots: [], - error: null, - isLoading: false, - refresh: vi.fn(), - }), -})); - -const sourceControlDiscoveryQueryAtom = vi.hoisted(() => Symbol("source-control-discovery-query")); -const serverQueryHarness = vi.hoisted(() => { - const kinds = { - processDiagnostics: "process-diagnostics", - processResourceHistory: "process-resource-history", - traceDiagnostics: "trace-diagnostics", - } as const; - return { - kinds, - isMarker(atom: unknown) { - if (typeof atom !== "object" || atom === null || !("kind" in atom)) { - return false; - } - return Object.values(kinds).includes( - (atom as { readonly kind: (typeof kinds)[keyof typeof kinds] }).kind, - ); - }, - }; -}); - -type ServerQueryMarker = - | { - readonly kind: typeof serverQueryHarness.kinds.processDiagnostics; - } - | { - readonly kind: typeof serverQueryHarness.kinds.processResourceHistory; - readonly input: Parameters[0]; - } - | { - readonly kind: typeof serverQueryHarness.kinds.traceDiagnostics; - }; - -vi.mock("../../state/sourceControl", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - sourceControlEnvironment: { - ...actual.sourceControlEnvironment, - discovery: () => sourceControlDiscoveryQueryAtom, - }, - }; -}); - -vi.mock("../../state/query", async (importOriginal) => { - const React = await import("react"); - const actual = await importOriginal(); - type Snapshot = { - readonly data: SourceControlDiscoveryResult | null; - readonly error: string | null; - readonly isPending: boolean; - readonly refresh: () => void; - }; - type State = { - snapshot: Snapshot; - started: boolean; - readonly listeners: Set<() => void>; - }; - const disabledSnapshot: Snapshot = { - data: null, - error: null, - isPending: false, - refresh: () => undefined, - }; - const states = new WeakMap(); - - const stateFor = (api: LocalApi): State => { - const existing = states.get(api); - if (existing) { - return existing; - } - const listeners = new Set<() => void>(); - const state: State = { - started: false, - listeners, - snapshot: { - data: null, - error: null, - isPending: true, - refresh: () => { - state.started = false; - start(state, api); - }, - }, - }; - states.set(api, state); - return state; - }; - - const publish = (state: State, next: Omit) => { - state.snapshot = { - ...next, - refresh: state.snapshot.refresh, - }; - for (const listener of state.listeners) { - listener(); - } - }; - - const start = (state: State, api: LocalApi) => { - if (state.started) { - return; - } - state.started = true; - publish(state, { - data: state.snapshot.data, - error: null, - isPending: true, - }); - void api.server.discoverSourceControl().then( - (data) => - publish(state, { - data, - error: null, - isPending: false, - }), - (error) => - publish(state, { - data: state.snapshot.data, - error: error instanceof Error ? error.message : String(error), - isPending: false, - }), - ); - }; - - const useSourceControlDiscoveryQuery = (enabled: boolean) => { - const api = enabled ? window.nativeApi : undefined; - const state = React.useMemo(() => (api ? stateFor(api) : null), [api]); - const snapshot = React.useSyncExternalStore( - React.useCallback( - (listener) => { - state?.listeners.add(listener); - return () => { - state?.listeners.delete(listener); - }; - }, - [state], - ), - React.useCallback(() => state?.snapshot ?? disabledSnapshot, [state]), - ); - React.useEffect(() => { - if (state && api) { - start(state, api); - } - }, [api, state]); - return snapshot; - }; - - const useNativeQuery = ( - enabled: boolean, - load: () => Promise | undefined, - dependencies: React.DependencyList, - ) => { - const [state, setState] = React.useState<{ - readonly data: A | null; - readonly error: string | null; - readonly isPending: boolean; - }>({ - data: null, - error: null, - isPending: enabled, - }); - const refresh = React.useCallback(async () => { - if (!enabled) { - return; - } - setState((current) => ({ ...current, isPending: true })); - try { - const data = await load(); - setState({ - data: data ?? null, - error: null, - isPending: false, - }); - } catch (error) { - setState({ - data: null, - error: error instanceof Error ? error.message : String(error), - isPending: false, - }); - } - }, [enabled, ...dependencies]); - React.useEffect(() => { - if (enabled) { - void refresh(); - } - }, [enabled, refresh]); - return { ...state, refresh }; - }; - - return { - ...actual, - useEnvironmentQuery: (atom: unknown) => { - const isSourceControlDiscovery = atom === sourceControlDiscoveryQueryAtom; - const isAuthAccess = atom === directAtomMocks.authAccessQuery; - const serverQuery = serverQueryHarness.isMarker(atom) ? (atom as ServerQueryMarker) : null; - const isMockedQuery = isSourceControlDiscovery || isAuthAccess || serverQuery !== null; - const query = actual.useEnvironmentQuery(isMockedQuery ? null : (atom as never)); - const sourceControlDiscovery = useSourceControlDiscoveryQuery(isSourceControlDiscovery); - const authAccessEvent = React.useSyncExternalStore( - authAccessHarness.subscribe, - authAccessHarness.getSnapshot, - authAccessHarness.getSnapshot, - ); - const traceDiagnostics = useNativeQuery( - serverQuery?.kind === serverQueryHarness.kinds.traceDiagnostics, - () => window.nativeApi?.server.getTraceDiagnostics(), - [], - ); - const processDiagnostics = useNativeQuery( - serverQuery?.kind === serverQueryHarness.kinds.processDiagnostics, - () => window.nativeApi?.server.getProcessDiagnostics(), - [], - ); - const resourceInput = - serverQuery?.kind === serverQueryHarness.kinds.processResourceHistory - ? serverQuery.input - : null; - const processResourceHistory = useNativeQuery( - resourceInput !== null, - () => - resourceInput === null - ? Promise.resolve(undefined) - : window.nativeApi?.server.getProcessResourceHistory(resourceInput), - [resourceInput?.windowMs, resourceInput?.bucketMs], - ); - - if (isSourceControlDiscovery) { - return sourceControlDiscovery; - } - if (isAuthAccess) { - return { - data: authAccessEvent, - error: null, - isPending: false, - refresh: () => undefined, - }; - } - switch (serverQuery?.kind) { - case serverQueryHarness.kinds.traceDiagnostics: - return traceDiagnostics; - case serverQueryHarness.kinds.processDiagnostics: - return processDiagnostics; - case serverQueryHarness.kinds.processResourceHistory: - return processResourceHistory; - default: - return query; - } - }, - }; -}); - -vi.mock("../../state/server", async () => { - const { Atom } = await import("effect/unstable/reactivity"); - const { DEFAULT_RESOLVED_KEYBINDINGS } = await import("@t3tools/shared/keybindings"); - const { DEFAULT_SERVER_SETTINGS: defaultServerSettings } = await import("@t3tools/contracts"); - const configAtom = Atom.make(null); - serverConfigHarness.configAtom = configAtom; - - return { - primaryServerConfigAtom: configAtom, - primaryServerSettingsAtom: Atom.make( - (get) => get(configAtom)?.settings ?? defaultServerSettings, - ), - primaryServerProvidersAtom: Atom.make((get) => get(configAtom)?.providers ?? []), - primaryServerKeybindingsAtom: Atom.make( - (get) => get(configAtom)?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS, - ), - primaryServerAvailableEditorsAtom: Atom.make((get) => get(configAtom)?.availableEditors ?? []), - primaryServerKeybindingsConfigPathAtom: Atom.make( - (get) => get(configAtom)?.keybindingsConfigPath ?? null, - ), - primaryServerObservabilityAtom: Atom.make((get) => get(configAtom)?.observability ?? null), - serverEnvironment: { - processDiagnostics: () => ({ kind: serverQueryHarness.kinds.processDiagnostics }), - processResourceHistory: ({ - input, - }: { - readonly input: Parameters[0]; - }) => ({ - kind: serverQueryHarness.kinds.processResourceHistory, - input, - }), - refreshProviders: directAtomMocks.refreshProvidersAction, - removeKeybinding: directAtomMocks.removeKeybindingAction, - signalProcess: directAtomMocks.signalProcessAction, - traceDiagnostics: () => ({ kind: serverQueryHarness.kinds.traceDiagnostics }), - updateProvider: directAtomMocks.updateProviderAction, - updateSettings: directAtomMocks.updateSettingsAction, - upsertKeybinding: directAtomMocks.upsertKeybindingAction, - }, - }; -}); - -vi.mock("../../state/auth", async (importOriginal) => { - const actual = await importOriginal(); - - return { - ...actual, - authEnvironment: { - ...actual.authEnvironment, - accessChanges: () => directAtomMocks.authAccessQuery, - }, - }; -}); - -vi.mock("../../state/shell", async () => { - const { Atom } = await import("effect/unstable/reactivity"); - return { - environmentSnapshotAtom: Atom.family(() => Atom.make(null)), - environmentShellSummaryAtom: Atom.make([]), - shellEnvironment: { - openInEditor: directAtomMocks.openInEditorAction, - }, - }; -}); - -vi.mock("../../state/environments", async () => { - const React = await import("react"); - const { useAtomValue } = await import("@effect/atom-react"); - const EffectOption = await import("effect/Option"); - const { EnvironmentId: EnvironmentIdSchema } = await import("@t3tools/contracts"); - const environmentId = EnvironmentIdSchema.make("environment-local"); - - const usePrimaryEnvironment = () => { - const serverConfig = useAtomValue(serverConfigHarness.configAtom as never); - return React.useMemo( - () => ({ - environmentId, - label: "Local environment", - displayUrl: "http://localhost:3000", - relayManaged: false, - entry: { - target: { - _tag: "PrimaryConnectionTarget" as const, - environmentId, - label: "Local environment", - httpBaseUrl: "http://localhost:3000", - wsBaseUrl: "ws://localhost:3000", - }, - profile: EffectOption.none(), - }, - connection: { - phase: "connected" as const, - error: null, - traceId: null, - }, - serverConfig, - }), - [serverConfig], - ); - }; - - return { - useEnvironments: () => { - const primary = usePrimaryEnvironment(); - return { - isReady: true, - networkStatus: "online" as const, - environments: [primary], - presentationById: new Map([[environmentId, primary]]), - shellStateById: new Map(), - }; - }, - usePrimaryEnvironment: usePrimaryEnvironment, - useRelayEnvironmentDiscovery: () => ({ - environments: new Map(), - refreshing: false, - offline: false, - error: EffectOption.none(), - }), - useEnvironmentHttpBaseUrl: () => "http://localhost:3000", - }; -}); - -function createBaseServerConfig(): ServerConfig { - return { - environment: { - environmentId: EnvironmentId.make("environment-local"), - label: "Local environment", - platform: { os: "darwin" as const, arch: "arm64" as const }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }, - auth: { - policy: "loopback-browser", - bootstrapMethods: ["one-time-token"], - sessionMethods: ["browser-session-cookie", "bearer-access-token"], - sessionCookieName: "t3_session", - }, - cwd: "/repo/project", - keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", - keybindings: [], - issues: [], - providers: [], - availableEditors: ["cursor"], - observability: { - logsDirectoryPath: "/repo/project/.t3/logs", - localTracingEnabled: true, - otlpTracesUrl: "http://localhost:4318/v1/traces", - otlpTracesEnabled: true, - otlpMetricsEnabled: false, - }, - settings: DEFAULT_SERVER_SETTINGS, - }; -} - -function createOutdatedProvider( - driver: string, - updateCommand = "npm install -g openai/codex@latest", -): ServerProvider { - return { - instanceId: ProviderInstanceId.make(driver), - driver: ProviderDriverKind.make(driver), - enabled: true, - installed: true, - version: "1.0.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-05-04T10:00:00.000Z", - models: [], - slashCommands: [], - skills: [], - versionAdvisory: { - status: "behind_latest", - currentVersion: "1.0.0", - latestVersion: "1.1.0", - message: "Update available.", - checkedAt: "2026-05-04T10:00:00.000Z", - updateCommand, - canUpdate: true, - }, - }; -} - -function makeUtc(value: string) { - return DateTime.makeUnsafe(value); -} - -function createEmptyProcessResourceHistoryResult(): ServerProcessResourceHistoryResult { - return { - readAt: makeUtc("2036-04-07T00:00:00.000Z"), - windowMs: 15 * 60_000, - bucketMs: 60_000, - sampleIntervalMs: 5_000, - retainedSampleCount: 0, - totalCpuSecondsApprox: 0, - buckets: [], - topProcesses: [], - error: Option.none(), - }; -} - -function makePairingLink(input: { - readonly id: string; - readonly credential: string; - readonly scopes: ReadonlyArray; - readonly subject: string; - readonly label?: string; - readonly createdAt: string; - readonly expiresAt: string; -}): AuthAccessSnapshot["pairingLinks"][number] { - return { - ...input, - createdAt: makeUtc(input.createdAt), - expiresAt: makeUtc(input.expiresAt), - }; -} - -function makeClientSession(input: { - readonly sessionId: string; - readonly subject: string; - readonly scopes: ReadonlyArray; - readonly method: "browser-session-cookie"; - readonly client?: { - readonly label?: string; - readonly ipAddress?: string; - readonly userAgent?: string; - readonly deviceType?: "desktop" | "mobile" | "tablet" | "bot" | "unknown"; - readonly os?: string; - readonly browser?: string; - }; - readonly issuedAt: string; - readonly expiresAt: string; - readonly lastConnectedAt?: string | null; - readonly connected: boolean; - readonly current: boolean; -}): AuthAccessSnapshot["clientSessions"][number] { - return { - ...input, - client: { - deviceType: "unknown", - ...input.client, - }, - sessionId: AuthSessionId.make(input.sessionId), - issuedAt: makeUtc(input.issuedAt), - expiresAt: makeUtc(input.expiresAt), - lastConnectedAt: - input.lastConnectedAt === undefined || input.lastConnectedAt === null - ? null - : makeUtc(input.lastConnectedAt), - }; -} - -const createDesktopBridgeStub = (overrides?: { - readonly discoverSshHosts?: DesktopBridge["discoverSshHosts"]; - readonly serverExposureState?: Awaited>; - readonly advertisedEndpoints?: Awaited>; - readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"]; - readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"]; -}): DesktopBridge => { - const idleUpdateState: DesktopUpdateState = { - enabled: false, - status: "idle", - channel: "latest", - currentVersion: "0.0.0-test", - hostArch: "arm64", - appArch: "arm64", - runningUnderArm64Translation: false, - availableVersion: null, - downloadedVersion: null, - downloadPercent: null, - checkedAt: null, - message: null, - errorContext: null, - canRetry: false, - }; - - return { - getAppBranding: vi.fn().mockReturnValue(null), - getLocalEnvironmentBootstrap: () => ({ - label: "Local environment", - httpBaseUrl: "http://127.0.0.1:3773", - wsBaseUrl: "ws://127.0.0.1:3773", - bootstrapToken: "desktop-bootstrap-token", - }), - getClientSettings: vi.fn().mockResolvedValue(null), - setClientSettings: vi.fn().mockResolvedValue(undefined), - discoverSshHosts: overrides?.discoverSshHosts ?? vi.fn().mockResolvedValue([]), - ensureSshEnvironment: vi.fn().mockImplementation(async (target) => ({ - target, - httpBaseUrl: "http://127.0.0.1:3774/", - wsBaseUrl: "ws://127.0.0.1:3774/", - pairingToken: "ssh-pairing-token", - })), - disconnectSshEnvironment: vi.fn().mockResolvedValue(undefined), - fetchSshEnvironmentDescriptor: vi.fn().mockResolvedValue({ - environmentId: "environment-ssh", - label: "SSH environment", - platform: { - os: "linux", - arch: "x64", - }, - serverVersion: "0.0.0-test", - capabilities: { - repositoryIdentity: true, - }, - }), - bootstrapSshBearerSession: vi.fn().mockResolvedValue({ - access_token: "ssh-bearer-token", - issued_token_type: "urn:ietf:params:oauth:token-type:access_token", - token_type: "Bearer", - expires_in: 3_600, - scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read", - }), - fetchSshSessionState: vi.fn().mockResolvedValue({ - authenticated: true, - auth: { - policy: "remote-reachable", - bootstrapMethods: ["one-time-token"], - sessionMethods: ["browser-session-cookie", "bearer-access-token"], - sessionCookieName: "t3_session", - }, - scopes: ["orchestration:read", "access:write"], - sessionMethod: "bearer-access-token", - expiresAt: "2026-05-01T12:00:00.000Z", - }), - issueSshWebSocketTicket: vi.fn().mockResolvedValue({ - ticket: "ssh-ws-ticket", - expiresAt: "2026-05-01T12:05:00.000Z", - }), - onSshPasswordPrompt: vi.fn(() => () => {}), - resolveSshPasswordPrompt: vi.fn().mockResolvedValue(undefined), - getServerExposureState: vi.fn().mockResolvedValue( - overrides?.serverExposureState ?? { - mode: "local-only", - endpointUrl: null, - advertisedHost: null, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - ), - setServerExposureMode: - overrides?.setServerExposureMode ?? - vi.fn().mockImplementation(async (mode) => ({ - mode, - endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null, - advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - })), - setTailscaleServeEnabled: vi.fn().mockImplementation(async (input) => ({ - mode: overrides?.serverExposureState?.mode ?? "network-accessible", - endpointUrl: overrides?.serverExposureState?.endpointUrl ?? "http://192.168.1.44:3773", - advertisedHost: overrides?.serverExposureState?.advertisedHost ?? "192.168.1.44", - tailscaleServeEnabled: input.enabled, - tailscaleServePort: input.port ?? 443, - })), - getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []), - pickFolder: vi.fn().mockResolvedValue(null), - confirm: vi.fn().mockResolvedValue(false), - setTheme: vi.fn().mockResolvedValue(undefined), - showContextMenu: vi.fn().mockResolvedValue(null), - openExternal: vi.fn().mockResolvedValue(true), - createCloudAuthRequest: vi.fn().mockResolvedValue("t3code-dev://auth/callback?t3_state=test"), - getCloudAuthToken: vi.fn().mockResolvedValue(null), - setCloudAuthToken: vi.fn().mockResolvedValue(true), - clearCloudAuthToken: vi.fn().mockResolvedValue(undefined), - fetchCloudAuth: vi.fn().mockResolvedValue({ - ok: true, - status: 200, - statusText: "OK", - headers: {}, - body: "", - }), - onCloudAuthCallback: () => () => {}, - onMenuAction: () => () => {}, - getUpdateState: vi.fn().mockResolvedValue(idleUpdateState), - setUpdateChannel: - overrides?.setUpdateChannel ?? - vi.fn().mockImplementation(async (channel: DesktopUpdateChannel) => ({ - ...idleUpdateState, - channel, - })), - checkForUpdate: vi.fn().mockResolvedValue({ checked: false, state: idleUpdateState }), - downloadUpdate: vi - .fn() - .mockResolvedValue({ accepted: false, completed: false, state: idleUpdateState }), - installUpdate: vi - .fn() - .mockResolvedValue({ accepted: false, completed: false, state: idleUpdateState }), - onUpdateState: () => () => {}, - }; -}; - -describe("GeneralSettingsPanel observability", () => { - let mounted: - | (Awaited> & { - cleanup?: () => Promise; - unmount?: () => Promise; - }) - | null = null; - - beforeEach(async () => { - resetServerConfigSnapshot(); - await __resetLocalApiForTests(); - localStorage.clear(); - useUiStateStore.setState({ defaultAdvertisedEndpointKey: null }); - authAccessHarness.reset(); - mockConnectDesktopSshEnvironment.mockReset(); - }); - - afterEach(async () => { - if (mounted) { - const teardown = mounted.cleanup ?? mounted.unmount; - await teardown?.call(mounted).catch(() => {}); - } - mounted = null; - vi.unstubAllGlobals(); - Reflect.deleteProperty(window, "desktopBridge"); - Reflect.deleteProperty(window, "nativeApi"); - document.body.innerHTML = ""; - resetServerConfigSnapshot(); - await __resetLocalApiForTests(); - authAccessHarness.reset(); - }); - - it("hides owner pairing tools in browser-served loopback builds without remote exposure", async () => { - Reflect.deleteProperty(window, "desktopBridge"); - authAccessHarness.setSnapshot({ - pairingLinks: [], - clientSessions: [ - makeClientSession({ - sessionId: "session-owner", - subject: "browser-owner", - scopes: ["orchestration:read", "access:write"], - method: "browser-session-cookie", - client: { - label: "Chrome on Mac", - deviceType: "desktop", - os: "macOS", - browser: "Chrome", - ipAddress: "127.0.0.1", - }, - issuedAt: "2036-04-07T00:00:00.000Z", - expiresAt: "2036-05-07T00:00:00.000Z", - connected: true, - current: true, - }), - ], - }); - const fetchMock = vi.fn().mockImplementation(async (input) => { - const url = String(input); - if (url.endsWith("/api/auth/session")) { - return new Response( - JSON.stringify({ - authenticated: true, - auth: createBaseServerConfig().auth, - scopes: ["orchestration:read", "access:write"], - sessionMethod: "browser-session-cookie", - expiresAt: "2036-05-07T00:00:00.000Z", - }), - { - status: 200, - headers: { "content-type": "application/json" }, - }, - ); - } - - throw new Error(`Unhandled fetch GET ${url}`); - }); - vi.stubGlobal("fetch", fetchMock); - - mounted = await render( - - - , - ); - - await expect - .element(page.getByRole("heading", { name: "This environment", exact: true })) - .toBeInTheDocument(); - await expect.element(page.getByLabelText("Enable network access")).toBeDisabled(); - await expect - .element( - page.getByText( - "This backend is only reachable on this machine. Restart it with a non-loopback host to enable remote pairing.", - ), - ) - .toBeInTheDocument(); - await expect.element(page.getByText("Authorized clients")).not.toBeInTheDocument(); - await expect.element(page.getByText("Chrome on Mac")).not.toBeInTheDocument(); - await expect - .element(page.getByRole("heading", { name: "Remote environments", exact: true })) - .toBeInTheDocument(); - }); - - it("hides advertised endpoint rows when desktop network access is disabled", async () => { - window.desktopBridge = createDesktopBridgeStub({ - serverExposureState: { - mode: "local-only", - endpointUrl: null, - advertisedHost: null, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - advertisedEndpoints: [ - { - id: "loopback", - label: "This machine", - provider: { - id: "desktop-core", - label: "Desktop", - kind: "manual", - isAddon: false, - }, - httpBaseUrl: "http://127.0.0.1:3773/", - wsBaseUrl: "ws://127.0.0.1:3773/", - reachability: "loopback", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-core", - status: "available", - isDefault: true, - }, - { - id: "tailscale-ip", - label: "Tailscale IP", - provider: { - id: "tailscale", - label: "Tailscale", - kind: "private-network", - isAddon: true, - }, - httpBaseUrl: "http://100.105.39.17:3773/", - wsBaseUrl: "ws://100.105.39.17:3773/", - reachability: "private-network", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-addon", - status: "available", - }, - ], - }); - authAccessHarness.setSnapshot({ - pairingLinks: [], - clientSessions: [], - }); - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("Limited to this machine.")).toBeInTheDocument(); - await expect - .element(page.getByRole("heading", { name: "This machine", exact: true })) - .not.toBeInTheDocument(); - await expect - .element(page.getByRole("heading", { name: "Tailscale IP", exact: true })) - .not.toBeInTheDocument(); - }); - - it("collapses advertised endpoints behind the network access summary", async () => { - window.desktopBridge = createDesktopBridgeStub({ - serverExposureState: { - mode: "network-accessible", - endpointUrl: "http://192.168.86.39:3773", - advertisedHost: "192.168.86.39", - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - advertisedEndpoints: [ - { - id: "desktop-loopback:3773", - label: "This machine", - provider: { - id: "desktop-core", - label: "Desktop", - kind: "manual", - isAddon: false, - }, - httpBaseUrl: "http://127.0.0.1:3773/", - wsBaseUrl: "ws://127.0.0.1:3773/", - reachability: "loopback", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-core", - status: "available", - }, - { - id: "desktop-lan:http://192.168.86.39:3773", - label: "Local network", - provider: { - id: "desktop-core", - label: "Desktop", - kind: "manual", - isAddon: false, - }, - httpBaseUrl: "http://192.168.86.39:3773/", - wsBaseUrl: "ws://192.168.86.39:3773/", - reachability: "lan", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-core", - status: "available", - isDefault: true, - }, - { - id: "tailscale-ip:http://100.105.39.17:3773", - label: "Tailscale IP", - provider: { - id: "tailscale", - label: "Tailscale", - kind: "private-network", - isAddon: true, - }, - httpBaseUrl: "http://100.105.39.17:3773/", - wsBaseUrl: "ws://100.105.39.17:3773/", - reachability: "private-network", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-addon", - status: "available", - }, - ], - }); - authAccessHarness.setSnapshot({ - pairingLinks: [], - clientSessions: [], - }); - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("http://192.168.86.39:3773/")).toBeInTheDocument(); - await expect.element(page.getByRole("button", { name: "+2" })).toBeInTheDocument(); - await expect - .element(page.getByRole("heading", { name: "Local network", exact: true })) - .not.toBeInTheDocument(); - - await page.getByRole("button", { name: "+2" }).click(); - - await expect - .element(page.getByRole("heading", { name: "Local network", exact: true })) - .toBeInTheDocument(); - await expect.element(page.getByText("Default", { exact: true })).toBeInTheDocument(); - await page.getByRole("button", { name: "Set as default" }).first().click(); - await expect.element(page.getByText("http://127.0.0.1:3773/").first()).toBeInTheDocument(); - }); - - it("shows diagnostics inside About with a diagnostics link", async () => { - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await renderWithTestRouter( - - - , - ); - - await expect.element(page.getByText("About")).toBeInTheDocument(); - await expect - .element(page.getByRole("heading", { name: "Diagnostics", exact: true })) - .toBeInTheDocument(); - await expect.element(page.getByRole("link", { name: "View diagnostics" })).toBeInTheDocument(); - await expect - .element( - page.getByText( - "Local trace file. Exporting OTEL traces to http://localhost:4318/v1/traces.", - ), - ) - .toBeInTheDocument(); - }); - - it("creates and shows a pairing link when network access is enabled", async () => { - window.desktopBridge = createDesktopBridgeStub({ - serverExposureState: { - mode: "network-accessible", - endpointUrl: "http://192.168.1.44:3773", - advertisedHost: "192.168.1.44", - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - }); - let pairingLinks: Array = []; - let clientSessions: Array = [ - makeClientSession({ - sessionId: "session-owner", - subject: "desktop-bootstrap", - scopes: ["orchestration:read", "access:write"], - method: "browser-session-cookie", - client: { - label: "This Mac", - deviceType: "desktop", - os: "macOS", - browser: "Electron", - ipAddress: "127.0.0.1", - }, - issuedAt: "2036-04-07T00:00:00.000Z", - expiresAt: "2036-05-07T00:00:00.000Z", - connected: true, - current: true, - }), - ]; - authAccessHarness.setSnapshot({ - pairingLinks, - clientSessions, - }); - vi.stubGlobal( - "fetch", - vi.fn().mockImplementation(async (input, init) => { - const url = String(input); - const method = init?.method ?? "GET"; - if (url.endsWith("/api/auth/pairing-token") && method === "POST") { - pairingLinks = [ - makePairingLink({ - id: "pairing-link-1", - credential: "pairing-token", - scopes: ["orchestration:read"], - subject: "one-time-token", - label: "Julius iPhone", - createdAt: "2036-04-07T00:00:00.000Z", - expiresAt: "2036-04-10T00:05:00.000Z", - }), - ]; - clientSessions = [ - ...clientSessions, - makeClientSession({ - sessionId: "session-client", - subject: "one-time-token", - scopes: ["orchestration:read"], - method: "browser-session-cookie", - client: { - label: "Julius iPhone", - deviceType: "mobile", - os: "iOS", - browser: "Safari", - ipAddress: "192.168.1.88", - }, - issuedAt: "2036-04-07T00:01:00.000Z", - expiresAt: "2036-05-07T00:01:00.000Z", - connected: false, - current: false, - }), - ]; - authAccessHarness.setSnapshot({ - pairingLinks, - clientSessions, - }); - return new Response( - JSON.stringify({ - id: "pairing-link-1", - credential: "pairing-token", - label: "Julius iPhone", - expiresAt: "2036-04-10T00:05:00.000Z", - }), - { - status: 200, - headers: { "content-type": "application/json" }, - }, - ); - } - - throw new Error(`Unhandled fetch ${method} ${url}`); - }), - ); - - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("Authorized clients")).toBeInTheDocument(); - await expect.element(page.getByText("Revoke others")).toBeInTheDocument(); - await expect.element(page.getByText("This Mac")).toBeInTheDocument(); - await page.getByRole("button", { name: "Create link", exact: true }).click(); - await expect.element(page.getByText("Create pairing link")).toBeInTheDocument(); - await expect.element(page.getByRole("checkbox", { name: /View environment/ })).toBeChecked(); - await expect.element(page.getByRole("checkbox", { name: /Operate tasks/ })).toBeChecked(); - await page.getByRole("button", { name: "Read only", exact: true }).click(); - await expect.element(page.getByRole("checkbox", { name: /View environment/ })).toBeChecked(); - await expect.element(page.getByRole("checkbox", { name: /Operate tasks/ })).not.toBeChecked(); - await page.getByRole("button", { name: "Create link", exact: true }).click(); - authAccessHarness.emitPairingLinkUpserted(pairingLinks[0]!); - await expect - .element(page.getByRole("button", { name: "Pairing link scopes: show 1 scope" })) - .toBeInTheDocument(); - authAccessHarness.emitClientUpserted(clientSessions[1]!); - await expect - .element(page.getByText("Mobile · iOS · Safari · 192.168.1.88")) - .toBeInTheDocument(); - await page.getByRole("button", { name: "Client scopes: show 1 scope" }).click(); - await expect.element(page.getByText("orchestration:read", { exact: true })).toBeInTheDocument(); - await expect - .element(page.getByRole("button", { name: /^Copy pairing URL for:/ })) - .toBeInTheDocument(); - await expect.element(page.getByText("Revoke others")).toBeInTheDocument(); - }); - - it("keeps authorized clients within a five-row fading scroll area", async () => { - window.desktopBridge = createDesktopBridgeStub({ - serverExposureState: { - mode: "network-accessible", - endpointUrl: "http://192.168.1.44:3773", - advertisedHost: "192.168.1.44", - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - }); - authAccessHarness.setSnapshot({ - pairingLinks: [], - clientSessions: Array.from({ length: 7 }, (_, index) => - makeClientSession({ - sessionId: `session-client-${index}`, - subject: `client-${index}`, - scopes: ["orchestration:read"], - method: "browser-session-cookie", - client: { - label: `Client ${index + 1}`, - deviceType: "desktop", - os: "macOS", - browser: "Electron", - ipAddress: `192.168.1.${index + 10}`, - }, - issuedAt: "2036-04-07T00:00:00.000Z", - expiresAt: "2036-05-07T00:00:00.000Z", - connected: index === 0, - current: index === 0, - }), - ), - }); - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("Client 7")).toBeInTheDocument(); - const scrollArea = document.querySelector( - '[data-testid="authorized-clients-scroll-area"]', - ); - const viewport = scrollArea?.querySelector('[data-slot="scroll-area-viewport"]'); - - expect(scrollArea).not.toBeNull(); - expect(viewport).not.toBeNull(); - expect(scrollArea?.clientHeight).toBe(360); - expect(viewport?.scrollHeight).toBeGreaterThan(viewport?.clientHeight ?? 0); - expect(viewport?.className).toContain("mask-b-from"); - }); - - it("revokes all other paired clients from settings", async () => { - window.desktopBridge = createDesktopBridgeStub({ - serverExposureState: { - mode: "network-accessible", - endpointUrl: "http://192.168.1.44:3773", - advertisedHost: "192.168.1.44", - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - }); - let clientSessions: Array = [ - makeClientSession({ - sessionId: "session-owner", - subject: "desktop-bootstrap", - scopes: ["orchestration:read", "access:write"], - method: "browser-session-cookie", - client: { - label: "This Mac", - deviceType: "desktop", - os: "macOS", - browser: "Electron", - }, - issuedAt: "2036-04-05T00:00:00.000Z", - expiresAt: "2036-05-05T00:00:00.000Z", - connected: true, - current: true, - }), - makeClientSession({ - sessionId: "session-client", - subject: "one-time-token", - scopes: ["orchestration:read"], - method: "browser-session-cookie", - client: { - label: "Julius iPhone", - deviceType: "mobile", - os: "iOS", - browser: "Safari", - ipAddress: "192.168.1.88", - }, - issuedAt: "2036-04-05T00:01:00.000Z", - expiresAt: "2036-05-05T00:01:00.000Z", - connected: false, - current: false, - }), - ]; - authAccessHarness.setSnapshot({ - pairingLinks: [], - clientSessions, - }); - - const fetchMock = vi.fn().mockImplementation(async (input, init) => { - const url = String(input); - const method = init?.method ?? "GET"; - if (url.endsWith("/api/auth/clients/revoke-others") && method === "POST") { - clientSessions = clientSessions.filter((session) => session.current); - authAccessHarness.setSnapshot({ - pairingLinks: [], - clientSessions, - }); - authAccessHarness.emitClientRemoved("session-client"); - return new Response(JSON.stringify({ revokedCount: 1 }), { - status: 200, - headers: { "content-type": "application/json" }, - }); - } - - throw new Error(`Unhandled fetch ${method} ${url}`); - }); - vi.stubGlobal("fetch", fetchMock); - - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("Julius iPhone")).toBeInTheDocument(); - await page.getByRole("button", { name: "Revoke others", exact: true }).click(); - await expect.element(page.getByText("This Mac")).toBeInTheDocument(); - await expect.element(page.getByText("Julius iPhone")).not.toBeInTheDocument(); - expect(fetchMock).toHaveBeenCalled(); - }); - - it("shows a disabled network access toggle with guidance in desktop builds", async () => { - const desktopBridge = createDesktopBridgeStub(); - window.desktopBridge = desktopBridge; - - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - const networkAccessToggle = page.getByLabelText("Enable network access"); - await expect.element(networkAccessToggle).not.toBeDisabled(); - await networkAccessToggle.click(); - await expect.element(page.getByText("Enable network access?")).toBeInTheDocument(); - await expect - .element(page.getByText("T3 Code will restart to expose this environment over the network.")) - .toBeInTheDocument(); - await page.getByRole("button", { name: "Restart and enable", exact: true }).click(); - await vi.waitFor(() => { - expect(desktopBridge.setServerExposureMode).toHaveBeenCalledWith("network-accessible"); - }); - await expect.element(page.getByText("http://192.168.1.44:3773")).toBeInTheDocument(); - }); - - it("adds desktop ssh environments from the add-environment dialog", async () => { - const discoverSshHosts = vi.fn().mockResolvedValue([ - { - alias: "devbox", - hostname: "devbox.example.com", - username: "julius", - port: 22, - source: "ssh-config" as const, - }, - ]); - window.desktopBridge = createDesktopBridgeStub({ - discoverSshHosts, - }); - mockConnectDesktopSshEnvironment.mockResolvedValue({ - environmentId: EnvironmentId.make("environment-devbox"), - label: "Build box", - wsBaseUrl: "ws://127.0.0.1:3774/", - httpBaseUrl: "http://127.0.0.1:3774/", - createdAt: "2036-04-07T00:00:00.000Z", - lastConnectedAt: "2036-04-07T00:00:00.000Z", - desktopSsh: { - alias: "devbox.example.com", - hostname: "devbox.example.com", - username: "julius", - port: 2222, - }, - }); - - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await page.getByRole("button", { name: "Add environment", exact: true }).click(); - const addEnvironmentDialog = page.getByRole("dialog", { name: "Add Environment" }); - await expect - .element(addEnvironmentDialog.getByRole("heading", { name: "Add Environment", exact: true })) - .toBeInTheDocument(); - await addEnvironmentDialog.getByRole("button", { name: /^SSH\b/ }).click(); - await vi.waitFor(() => { - expect(discoverSshHosts).toHaveBeenCalledTimes(1); - }); - await expect - .element(page.getByRole("heading", { name: "devbox", exact: true })) - .toBeInTheDocument(); - - await addEnvironmentDialog.getByLabelText("SSH host or alias").fill("devbox.example.com"); - await addEnvironmentDialog.getByLabelText("Username").fill("julius"); - await addEnvironmentDialog.getByLabelText("Port").fill("2222"); - await addEnvironmentDialog - .getByRole("button", { name: "Add environment", exact: true }) - .first() - .click(); - - await vi.waitFor(() => { - expect(mockConnectDesktopSshEnvironment).toHaveBeenCalledWith({ - target: { - alias: "devbox.example.com", - hostname: "devbox.example.com", - username: "julius", - port: 2222, - }, - label: "", - }); - }); - }); - - it("opens the logs folder in the preferred editor", async () => { - const openInEditor = vi.fn().mockResolvedValue(undefined); - window.nativeApi = { - persistence: { - getClientSettings: vi.fn().mockResolvedValue(null), - setClientSettings: vi.fn().mockResolvedValue(undefined), - }, - shell: { - openInEditor, - }, - server: { - getProcessDiagnostics: vi.fn().mockResolvedValue({ - serverPid: 1234, - readAt: makeUtc("2036-04-07T00:00:00.000Z"), - processCount: 0, - totalRssBytes: 0, - totalCpuPercent: 0, - processes: [], - error: Option.none(), - }), - getProcessResourceHistory: vi - .fn() - .mockResolvedValue(createEmptyProcessResourceHistoryResult()), - getTraceDiagnostics: vi.fn().mockResolvedValue({ - traceFilePath: "/repo/project/.t3/traces.jsonl", - scannedFilePaths: ["/repo/project/.t3/traces.jsonl"], - readAt: makeUtc("2036-04-07T00:00:00.000Z"), - recordCount: 0, - parseErrorCount: 0, - firstSpanAt: Option.none(), - lastSpanAt: Option.none(), - failureCount: 0, - interruptionCount: 0, - slowSpanThresholdMs: 5_000, - slowSpanCount: 0, - logLevelCounts: {}, - topSpansByCount: [], - slowestSpans: [], - commonFailures: [], - latestFailures: [], - latestWarningAndErrorLogs: [], - partialFailure: Option.none(), - error: Option.none(), - }), - }, - } as unknown as LocalApi; - - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - const openLogsButton = page.getByLabelText("Open logs folder"); - await openLogsButton.click(); - - expect(openInEditor).toHaveBeenCalledWith("/repo/project/.t3/logs", "cursor"); - }); - - it("shows an OpenCode server URL field in provider settings", async () => { - setServerConfigSnapshot(createBaseServerConfig()); - - mounted = await render( - - - , - ); - - await page.getByLabelText("Toggle OpenCode details").click(); - - // The unified provider-instance card renders field labels without a - // driver-name prefix (the driver name is already shown in the card - // header), so the labels read "Server URL" / "Server password" - // rather than the old "OpenCode server URL" / "OpenCode server password". - await expect.element(page.getByText("Server URL")).toBeInTheDocument(); - await expect.element(page.getByPlaceholder("http://127.0.0.1:4096")).toBeInTheDocument(); - await expect.element(page.getByText("Server password")).toBeInTheDocument(); - await expect.element(page.getByPlaceholder("Optional")).toBeInTheDocument(); - }); - - it("runs one-click provider updates from the provider card", async () => { - const updateProvider = vi.fn().mockResolvedValue({ - providers: [createOutdatedProvider("codex")], - }); - window.nativeApi = { - persistence: { - getClientSettings: vi.fn().mockResolvedValue(null), - setClientSettings: vi.fn().mockResolvedValue(undefined), - }, - server: { - updateProvider, - }, - } as unknown as LocalApi; - - setServerConfigSnapshot({ - ...createBaseServerConfig(), - providers: [createOutdatedProvider("codex")], - }); - - mounted = await render( - - - , - ); - - await page.getByRole("button", { name: "Update available — view details" }).click(); - await expect.element(page.getByRole("button", { name: "Update now" })).toBeInTheDocument(); - await page.getByRole("button", { name: "Update now" }).click(); - - expect(updateProvider).toHaveBeenCalledWith({ - provider: ProviderDriverKind.make("codex"), - instanceId: ProviderInstanceId.make("codex"), - }); - }); - - it("keeps long provider update commands inside the fixed-width popover", async () => { - const longUpdateCommand = - "npm install -g @anthropic-ai/claude-code@latest --registry=https://registry.npmjs.org --cache=/tmp/t3code-provider-update-cache"; - - setServerConfigSnapshot({ - ...createBaseServerConfig(), - providers: [createOutdatedProvider("codex", longUpdateCommand)], - }); - - mounted = await render( - - - , - ); - - await page.getByRole("button", { name: "Update available — view details" }).click(); - await expect.element(page.getByText(longUpdateCommand)).toBeInTheDocument(); - - await vi.waitFor(() => { - const popup = document.querySelector('[data-slot="popover-popup"]'); - const commandCode = Array.from(document.querySelectorAll("code")).find( - (element) => element.textContent === longUpdateCommand, - ); - const scrollViewport = commandCode?.closest( - '[data-slot="scroll-area-viewport"]', - ); - - expect(popup).toBeTruthy(); - expect(commandCode).toBeTruthy(); - expect(scrollViewport).toBeTruthy(); - - const popupRect = popup!.getBoundingClientRect(); - const viewportRect = scrollViewport!.getBoundingClientRect(); - - expect(popupRect.width).toBeGreaterThan(300); - expect(popupRect.width).toBeLessThanOrEqual(337); - expect(viewportRect.right).toBeLessThanOrEqual(popupRect.right + 0.5); - expect(scrollViewport!.scrollWidth).toBeGreaterThan(scrollViewport!.clientWidth); - }); - }); -}); - -describe("SourceControlSettingsPanel discovery states", () => { - let mounted: - | (Awaited> & { - cleanup?: () => Promise; - unmount?: () => Promise; - }) - | null = null; - - beforeEach(async () => { - resetAppAtomRegistryForTests(); - await __resetLocalApiForTests(); - document.body.innerHTML = ""; - }); - - afterEach(async () => { - if (mounted) { - const teardown = mounted.cleanup ?? mounted.unmount; - await teardown?.call(mounted).catch(() => {}); - } - mounted = null; - Reflect.deleteProperty(window, "nativeApi"); - document.body.innerHTML = ""; - await __resetLocalApiForTests(); - resetAppAtomRegistryForTests(); - }); - - function setSourceControlDiscoveryStub( - discoverSourceControl: () => Promise, - ) { - window.nativeApi = { - persistence: { - getClientSettings: vi.fn().mockResolvedValue(null), - setClientSettings: vi.fn().mockResolvedValue(undefined), - }, - server: { - discoverSourceControl, - }, - } as unknown as LocalApi; - } - - it("shows skeleton sections while the first source control scan is pending", async () => { - setSourceControlDiscoveryStub(() => new Promise(() => {})); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("Version Control")).toBeInTheDocument(); - await expect.element(page.getByText("Source Control Providers")).toBeInTheDocument(); - await expect - .element(page.getByRole("button", { name: "Rescan server environment" })) - .toBeDisabled(); - await expect.element(page.getByText("Nothing detected yet")).not.toBeInTheDocument(); - }); - - it("uses the shared empty state when discovery completes without tools", async () => { - setSourceControlDiscoveryStub(async () => ({ - versionControlSystems: [], - sourceControlProviders: [], - })); - - mounted = await render( - - - , - ); - - await expect.element(page.getByText("Nothing detected yet")).toBeInTheDocument(); - await expect - .element( - page.getByText( - "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan.", - ), - ) - .toBeInTheDocument(); - await expect.element(page.getByRole("button", { name: "Scan" })).toBeInTheDocument(); - }); - - it("keeps discovered rows instead of showing the empty state", async () => { - setSourceControlDiscoveryStub(async () => ({ - versionControlSystems: [ - { - kind: "git", - label: "Git", - executable: "git", - implemented: true, - status: "available", - version: Option.some("git version 2.50.0"), - installHint: "Install Git.", - detail: Option.none(), - }, - ], - sourceControlProviders: [], - })); - - mounted = await render( - - - , - ); - - await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled(); - await expect.element(page.getByText("Nothing detected yet")).not.toBeInTheDocument(); - }); - - it("shows unauthenticated API providers as available but not enabled", async () => { - setSourceControlDiscoveryStub(async () => ({ - versionControlSystems: [], - sourceControlProviders: [ - { - kind: "bitbucket", - label: "Bitbucket", - status: "available", - version: Option.none(), - installHint: - "Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.", - detail: Option.none(), - auth: { - status: "unauthenticated", - account: Option.none(), - host: Option.some("bitbucket.org"), - detail: Option.some( - "Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.", - ), - }, - }, - ], - })); - - mounted = await render( - - - , - ); - - const bitbucketSwitch = page.getByRole("switch", { name: "Bitbucket availability" }); - - await expect.element(page.getByText("Not authenticated")).toBeInTheDocument(); - await expect - .element( - page.getByText( - "Available. Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.", - ), - ) - .toBeInTheDocument(); - await expect.element(bitbucketSwitch).toBeDisabled(); - await expect.element(bitbucketSwitch).not.toBeChecked(); - }); - - it("shows Git fetch interval settings inside the Git details dropdown", async () => { - setSourceControlDiscoveryStub(async () => ({ - versionControlSystems: [ - { - kind: "git", - label: "Git", - executable: "git", - implemented: true, - status: "available", - version: Option.some("git version 2.50.0"), - installHint: "Install Git.", - detail: Option.none(), - }, - ], - sourceControlProviders: [], - })); - - mounted = await render( - - - , - ); - - const toggle = page.getByRole("button", { name: "Toggle Git details" }); - await expect.element(toggle).toHaveAttribute("aria-expanded", "false"); - - await toggle.click(); - - await expect.element(toggle).toHaveAttribute("aria-expanded", "true"); - await expect - .element(page.getByLabelText("Automatic Git fetch interval in seconds")) - .toBeVisible(); - await expect - .element(page.getByText("Automatic Git fetches run every 30 seconds")) - .not.toBeInTheDocument(); - }); - - it("does not rescan on remount while the discovery atom is fresh", async () => { - let calls = 0; - setSourceControlDiscoveryStub(async () => { - calls += 1; - return { - versionControlSystems: [ - { - kind: "git", - label: "Git", - executable: "git", - implemented: true, - status: "available", - version: Option.some("git version 2.50.0"), - installHint: "Install Git.", - detail: Option.none(), - }, - ], - sourceControlProviders: [], - }; - }); - - mounted = await render( - - - , - ); - - await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled(); - expect(calls).toBe(1); - - const teardown = mounted.cleanup ?? mounted.unmount; - await teardown?.call(mounted).catch(() => {}); - mounted = null; - document.body.innerHTML = ""; - - mounted = await render( - - - , - ); - - await expect.element(page.getByRole("switch", { name: "Git availability" })).toBeDisabled(); - expect(calls).toBe(1); - }); -}); diff --git a/apps/web/test/authHttpHandlers.ts b/apps/web/test/authHttpHandlers.ts deleted file mode 100644 index a888f7fa5d..0000000000 --- a/apps/web/test/authHttpHandlers.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { - AuthSessionId, - EnvironmentAuthenticatedAuth, - EnvironmentAuthenticatedPrincipal, - EnvironmentAuthHttpApi, - EnvironmentId, - EnvironmentMetadataHttpApi, - type AuthEnvironmentScope, - type ExecutionEnvironmentDescriptor, - type ServerAuthDescriptor, -} from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import { HttpRouter, HttpServer } from "effect/unstable/http"; -import * as HttpApi from "effect/unstable/httpapi/HttpApi"; -import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; -import { http } from "msw"; - -const BrowserEnvironmentHttpApi = HttpApi.make("browserEnvironment") - .add(EnvironmentMetadataHttpApi) - .add(EnvironmentAuthHttpApi); - -const TEST_SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-05-01T12:00:00.000Z"); -const TEST_ENVIRONMENT_DESCRIPTOR: ExecutionEnvironmentDescriptor = { - environmentId: EnvironmentId.make("environment-local"), - label: "Local environment", - platform: { - os: "darwin", - arch: "arm64", - }, - serverVersion: "0.0.0-test", - capabilities: { - repositoryIdentity: true, - }, -}; - -const unexpectedEndpoint = (endpoint: string) => - Effect.die(new Error(`Unexpected browser environment HTTP endpoint: ${endpoint}`)); - -export function createAuthenticatedSessionHandlers(getAuthDescriptor: () => ServerAuthDescriptor) { - const authenticatedAuthLayer = Layer.succeed(EnvironmentAuthenticatedAuth, (httpEffect) => - httpEffect.pipe( - Effect.provideService(EnvironmentAuthenticatedPrincipal, { - sessionId: AuthSessionId.make("browser-session"), - subject: "browser-client", - method: "browser-session-cookie", - scopes: new Set(), - expiresAt: TEST_SESSION_EXPIRES_AT, - }), - ), - ); - const metadataLayer = HttpApiBuilder.group(BrowserEnvironmentHttpApi, "metadata", (handlers) => - handlers.handle("descriptor", () => Effect.succeed(TEST_ENVIRONMENT_DESCRIPTOR)), - ); - const authLayer = HttpApiBuilder.group(BrowserEnvironmentHttpApi, "auth", (handlers) => - handlers - .handle("session", () => - Effect.succeed({ - authenticated: true, - auth: getAuthDescriptor(), - sessionMethod: "browser-session-cookie", - expiresAt: TEST_SESSION_EXPIRES_AT, - }), - ) - .handle("browserSession", () => - Effect.succeed({ - authenticated: true, - scopes: [ - "orchestration:read", - "orchestration:operate", - "terminal:operate", - "review:write", - "relay:read", - ], - sessionMethod: "browser-session-cookie", - expiresAt: TEST_SESSION_EXPIRES_AT, - }), - ) - .handle("token", () => unexpectedEndpoint("auth.token")) - .handle("webSocketTicket", () => unexpectedEndpoint("auth.webSocketTicket")) - .handle("pairingCredential", () => unexpectedEndpoint("auth.pairingCredential")) - .handle("pairingLinks", () => unexpectedEndpoint("auth.pairingLinks")) - .handle("revokePairingLink", () => unexpectedEndpoint("auth.revokePairingLink")) - .handle("clients", () => unexpectedEndpoint("auth.clients")) - .handle("revokeClient", () => unexpectedEndpoint("auth.revokeClient")) - .handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients")), - ).pipe(Layer.provide(authenticatedAuthLayer)); - const { handler } = HttpRouter.toWebHandler( - HttpApiBuilder.layer(BrowserEnvironmentHttpApi).pipe( - Layer.provide(metadataLayer), - Layer.provide(authLayer), - Layer.provide(authenticatedAuthLayer), - Layer.provide(HttpServer.layerServices), - ), - { disableLogger: true }, - ); - - return [ - http.all("*/.well-known/t3/environment", ({ request }) => handler(request)), - http.all("*/api/auth/*", ({ request }) => handler(request)), - ] as const; -} diff --git a/apps/web/test/environmentHttpTest.ts b/apps/web/test/environmentHttpTest.ts deleted file mode 100644 index ce43faacc4..0000000000 --- a/apps/web/test/environmentHttpTest.ts +++ /dev/null @@ -1,136 +0,0 @@ -import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; -import { - AuthSessionId, - EnvironmentAuthenticatedAuth, - EnvironmentAuthenticatedPrincipal, - EnvironmentHttpApi, - type AuthBrowserSessionRequest, - type AuthBrowserSessionResult, - type AuthCreatePairingCredentialInput, - type AuthEnvironmentScope, - type AuthPairingCredentialResult, - type AuthSessionState, - type ExecutionEnvironmentDescriptor, - type EnvironmentAuthInvalidError, -} from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import type * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as ManagedRuntime from "effect/ManagedRuntime"; -import { HttpApiTest } from "effect/unstable/httpapi"; -import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; - -import { PrimaryEnvironmentHttpClient } from "../src/environments/primary/httpClient"; -import { __setPrimaryHttpRunnerForTests } from "../src/lib/runtime"; - -type BrowserSessionHandler = ( - payload: AuthBrowserSessionRequest, -) => Effect.Effect; - -interface EnvironmentHttpTestScenario { - readonly descriptor?: () => Effect.Effect; - readonly session?: () => Effect.Effect; - readonly browserSession?: BrowserSessionHandler; - readonly pairingCredential?: ( - payload: AuthCreatePairingCredentialInput, - ) => Effect.Effect; -} - -export interface EnvironmentHttpTestCalls { - descriptor: number; - session: number; - browserSession: Array; - pairingCredential: Array; -} - -const unexpectedEndpoint = (endpoint: string) => - Effect.die(new Error(`Unexpected environment HTTP endpoint: ${endpoint}`)); - -const authenticatedAuth: Context.Service.Shape = ( - httpEffect, -) => - httpEffect.pipe( - Effect.provideService(EnvironmentAuthenticatedPrincipal, { - sessionId: AuthSessionId.make("test-session"), - subject: "test-client", - method: "browser-session-cookie", - scopes: new Set(), - expiresAt: DateTime.makeUnsafe("2026-05-01T12:00:00.000Z"), - }), - ); - -export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestScenario) { - const calls: EnvironmentHttpTestCalls = { - descriptor: 0, - session: 0, - browserSession: [], - pairingCredential: [], - }; - - const client = await Effect.runPromise( - HttpApiTest.groups(EnvironmentHttpApi, ["metadata", "auth"]).pipe( - Effect.provide([ - NodeHttpServer.layerHttpServices, - HttpApiBuilder.group(EnvironmentHttpApi, "metadata", (handlers) => - handlers.handle( - "descriptor", - Effect.fn("test.environment.metadata.descriptor")(function* () { - calls.descriptor += 1; - return yield* scenario.descriptor?.() ?? unexpectedEndpoint("metadata.descriptor"); - }), - ), - ), - HttpApiBuilder.group(EnvironmentHttpApi, "auth", (handlers) => - handlers - .handle( - "session", - Effect.fn("test.environment.auth.session")(function* () { - calls.session += 1; - return yield* scenario.session?.() ?? unexpectedEndpoint("auth.session"); - }), - ) - .handle( - "browserSession", - Effect.fn("test.environment.auth.browserSession")(function* ({ payload }) { - calls.browserSession.push(payload); - return yield* ( - scenario.browserSession?.(payload) ?? unexpectedEndpoint("auth.browserSession") - ); - }), - ) - .handle("token", () => unexpectedEndpoint("auth.token")) - .handle("webSocketTicket", () => unexpectedEndpoint("auth.webSocketTicket")) - .handle( - "pairingCredential", - Effect.fn("test.environment.auth.pairingCredential")(function* ({ payload }) { - calls.pairingCredential.push(payload); - return yield* ( - scenario.pairingCredential?.(payload) ?? - unexpectedEndpoint("auth.pairingCredential") - ); - }), - ) - .handle("pairingLinks", () => unexpectedEndpoint("auth.pairingLinks")) - .handle("revokePairingLink", () => unexpectedEndpoint("auth.revokePairingLink")) - .handle("clients", () => unexpectedEndpoint("auth.clients")) - .handle("revokeClient", () => unexpectedEndpoint("auth.revokeClient")) - .handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients")), - ), - ]), - Effect.provideService(EnvironmentAuthenticatedAuth, authenticatedAuth), - Effect.scoped, - ), - ); - - const runtime = ManagedRuntime.make(Layer.succeed(PrimaryEnvironmentHttpClient, client)); - __setPrimaryHttpRunnerForTests((effect) => runtime.runPromise(effect)); - - return { - calls, - async dispose() { - __setPrimaryHttpRunnerForTests(); - await runtime.dispose(); - }, - }; -} diff --git a/apps/web/test/wsRpcHarness.ts b/apps/web/test/wsRpcHarness.ts deleted file mode 100644 index 1ebd082cff..0000000000 --- a/apps/web/test/wsRpcHarness.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { ORCHESTRATION_WS_METHODS, WS_METHODS, WsRpcGroup } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as PubSub from "effect/PubSub"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import { RpcMessage, RpcSerialization, RpcServer } from "effect/unstable/rpc"; - -type RpcServerInstance = RpcServer.RpcServer; - -type BrowserWsClient = { - send: (data: string) => void; -}; - -export type NormalizedWsRpcRequestBody = { - _tag: string; - [key: string]: unknown; -}; - -type UnaryResolverResult = unknown | Promise; - -interface BrowserWsRpcHarnessOptions { - readonly resolveUnary?: (request: NormalizedWsRpcRequestBody) => UnaryResolverResult; - readonly getInitialStreamValues?: ( - request: NormalizedWsRpcRequestBody, - ) => ReadonlyArray | undefined; -} - -const STREAM_METHODS = new Set([ - ORCHESTRATION_WS_METHODS.subscribeShell, - ORCHESTRATION_WS_METHODS.subscribeThread, - WS_METHODS.gitRunStackedAction, - WS_METHODS.terminalAttach, - WS_METHODS.subscribeVcsStatus, - WS_METHODS.subscribeTerminalEvents, - WS_METHODS.subscribeTerminalMetadata, - WS_METHODS.subscribePreviewEvents, - WS_METHODS.subscribeDiscoveredLocalServers, - WS_METHODS.previewAutomationConnect, - WS_METHODS.subscribeServerConfig, - WS_METHODS.subscribeServerLifecycle, - WS_METHODS.subscribeAuthAccess, -]); - -const ALL_RPC_METHODS = Array.from(WsRpcGroup.requests.keys()); - -function normalizeRequest(tag: string, payload: unknown): NormalizedWsRpcRequestBody { - if (payload && typeof payload === "object" && !Array.isArray(payload)) { - return { - _tag: tag, - ...(payload as Record), - }; - } - return { _tag: tag, payload }; -} - -function asEffect(result: UnaryResolverResult): Effect.Effect { - if (result instanceof Promise) { - return Effect.promise(() => result); - } - return Effect.succeed(result); -} - -export class BrowserWsRpcHarness { - readonly requests: Array = []; - - private readonly parser = RpcSerialization.json.makeUnsafe(); - private client: BrowserWsClient | null = null; - private scope: Scope.Closeable | null = null; - private serverReady: Promise | null = null; - private resolveUnary: NonNullable = () => ({}); - private getInitialStreamValues: NonNullable< - BrowserWsRpcHarnessOptions["getInitialStreamValues"] - > = () => []; - private streamPubSubs = new Map>(); - - async reset(options?: BrowserWsRpcHarnessOptions): Promise { - await this.disconnect(); - this.requests.length = 0; - this.resolveUnary = options?.resolveUnary ?? (() => ({})); - this.getInitialStreamValues = options?.getInitialStreamValues ?? (() => []); - this.initializeStreamPubSubs(); - } - - connect(client: BrowserWsClient): void { - if (this.scope) { - void Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined); - } - if (this.streamPubSubs.size === 0) { - this.initializeStreamPubSubs(); - } - this.client = client; - this.scope = Effect.runSync(Scope.make()); - this.serverReady = Effect.runPromise( - Scope.provide(this.scope)( - RpcServer.makeNoSerialization(WsRpcGroup, this.makeServerOptions()), - ).pipe(Effect.provide(this.makeLayer())), - ) as Promise; - } - - async disconnect(): Promise { - if (this.scope) { - await Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined); - this.scope = null; - } - for (const pubsub of this.streamPubSubs.values()) { - Effect.runSync(PubSub.shutdown(pubsub)); - } - this.streamPubSubs.clear(); - this.serverReady = null; - this.client = null; - } - - private initializeStreamPubSubs(): void { - this.streamPubSubs = new Map( - Array.from(STREAM_METHODS, (method) => [method, Effect.runSync(PubSub.unbounded())]), - ); - } - - async onMessage(rawData: string): Promise { - const server = await this.serverReady; - if (!server) { - return; - } - const messages = this.parser.decode(rawData); - for (const message of messages) { - if (message && typeof message === "object" && "_tag" in message && message._tag === "Ping") { - const encoded = this.parser.encode(RpcMessage.constPong); - if (typeof encoded === "string") { - this.client?.send(encoded); - } - continue; - } - await Effect.runPromise(server.write(0, message as never)); - } - } - - emitStreamValue(method: string, value: unknown): void { - const pubsub = this.streamPubSubs.get(method); - if (!pubsub) { - throw new Error(`No stream registered for ${method}`); - } - Effect.runSync(PubSub.publish(pubsub, value)); - } - - private makeLayer() { - const handlers: Record unknown> = {}; - for (const method of ALL_RPC_METHODS) { - handlers[method] = STREAM_METHODS.has(method) - ? (payload) => this.handleStream(method, payload) - : (payload) => this.handleUnary(method, payload); - } - return WsRpcGroup.toLayer(handlers as never); - } - - private makeServerOptions() { - return { - onFromServer: (response: unknown) => - Effect.sync(() => { - if (!this.client) { - return; - } - const encoded = this.parser.encode(response); - if (typeof encoded === "string") { - this.client.send(encoded); - } - }), - }; - } - - private handleUnary(method: string, payload: unknown) { - const request = normalizeRequest(method, payload); - this.requests.push(request); - return asEffect(this.resolveUnary(request)); - } - - private handleStream(method: string, payload: unknown) { - const request = normalizeRequest(method, payload); - this.requests.push(request); - const pubsub = this.streamPubSubs.get(method); - if (!pubsub) { - throw new Error(`No stream registered for ${method}`); - } - return Stream.fromIterable(this.getInitialStreamValues(request) ?? []).pipe( - Stream.concat(Stream.fromPubSub(pubsub)), - ); - } -} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 74209bca61..43c79eba30 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -2,7 +2,6 @@ import tailwindcss from "@tailwindcss/vite"; import react, { reactCompilerPreset } from "@vitejs/plugin-react"; import babel from "@rolldown/plugin-babel"; import { tanstackRouter } from "@tanstack/router-plugin/vite"; -import { playwright } from "vite-plus/test/browser-playwright"; import { defineProject, type TestProjectInlineConfiguration } from "vite-plus/test/config"; import "vite-plus/test/config"; import { defineConfig } from "vite-plus"; @@ -59,30 +58,6 @@ const unitTestProject = { }, } satisfies TestProjectInlineConfiguration; -const browserTestProject = { - extends: true, - server: { - // Browser tests need concurrent runs to claim the next available port. - strictPort: false, - }, - test: { - name: "browser", - include: ["src/components/**/*.browser.tsx"], - hookTimeout: 30_000, - testTimeout: 30_000, - browser: { - enabled: true, - provider: playwright() as never, - instances: [{ browser: "chromium" }], - headless: true, - api: { - strictPort: false, - }, - }, - fileParallelism: false, - }, -} satisfies TestProjectInlineConfiguration; - function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined { if (!wsUrl) { return undefined; @@ -188,7 +163,7 @@ export default defineConfig(() => { sourcemap: buildSourcemap, }, test: { - projects: [defineProject(unitTestProject), defineProject(browserTestProject)], + projects: [defineProject(unitTestProject)], }, }; }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 31227bc478..c60a06f16b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -607,9 +607,6 @@ importers: msw: specifier: 2.12.11 version: 2.12.11(@types/node@24.12.4)(typescript@6.0.3) - playwright: - specifier: ^1.58.2 - version: 1.60.0 tailwindcss: specifier: ^4.0.0 version: 4.3.0 @@ -619,9 +616,6 @@ importers: vite-plus: specifier: 'catalog:' version: 0.1.24(@types/node@24.12.4)(bufferutil@4.1.0)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) - vitest-browser-react: - specifier: ^2.0.5 - version: 2.2.0(@types/react-dom@19.2.3(@types/react@19.2.16))(@types/react@19.2.16)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)(vitest@4.1.8(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(msw@2.12.11(@types/node@24.12.4)(typescript@6.0.3))) infra/relay: dependencies: @@ -4670,35 +4664,6 @@ packages: babel-plugin-react-compiler: optional: true - '@vitest/expect@4.1.8': - resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==} - - '@vitest/mocker@4.1.8': - resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==} - peerDependencies: - msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 - peerDependenciesMeta: - msw: - optional: true - vite: - optional: true - - '@vitest/pretty-format@4.1.8': - resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==} - - '@vitest/runner@4.1.8': - resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==} - - '@vitest/snapshot@4.1.8': - resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==} - - '@vitest/spy@4.1.8': - resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==} - - '@vitest/utils@4.1.8': - resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==} - '@voidzero-dev/vite-plus-core@0.1.24': resolution: {integrity: sha512-iXPGBABnQnrDMx89H6MOCGcTZp+QW+3rY4YMVKdE6ydchSvPk2O3MI2vgaRVfOtWJ2IjnxSnf1n2yjP67ZBRFQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5363,10 +5328,6 @@ packages: ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} - chai@6.2.2: - resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} - engines: {node: '>=18'} - chalk@2.4.2: resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==} engines: {node: '>=4'} @@ -6100,9 +6061,6 @@ packages: estree-walker@2.0.2: resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} - estree-walker@3.0.3: - resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} - etag@1.8.1: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} @@ -6122,10 +6080,6 @@ packages: resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} engines: {node: '>=18.0.0'} - expect-type@1.3.0: - resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} - engines: {node: '>=12.0.0'} - expo-application@56.0.3: resolution: {integrity: sha512-DdGGPlMuM6cSTeKhbvh6OeLr2O/+EI5BHKYrD+Do8sJPYgLwzGrgESELfyjJCpEhFzT+TgKIdmLmWXhNUQnHiw==} peerDependencies: @@ -6583,11 +6537,6 @@ packages: fs.realpath@1.0.0: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} - fsevents@2.3.2: - resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -7937,10 +7886,6 @@ packages: obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} - obug@2.1.2: - resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==} - engines: {node: '>=12.20.0'} - ofetch@1.5.1: resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==} @@ -8194,11 +8139,6 @@ packages: engines: {node: '>=18'} hasBin: true - playwright@1.60.0: - resolution: {integrity: sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==} - engines: {node: '>=18'} - hasBin: true - plist@3.1.0: resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==} engines: {node: '>=10.4.0'} @@ -8912,9 +8852,6 @@ packages: resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} engines: {node: '>= 0.4'} - siginfo@2.0.0: - resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -8996,9 +8933,6 @@ packages: resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} engines: {node: '>=10'} - stackback@0.0.2: - resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} - stackframe@1.3.4: resolution: {integrity: sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw==} @@ -9196,10 +9130,6 @@ packages: resolution: {integrity: sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==} engines: {node: ^20.0.0 || >=22.0.0} - tinyrainbow@3.1.0: - resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} - engines: {node: '>=14.0.0'} - tldts-core@7.4.2: resolution: {integrity: sha512-nwEyF4vl4RSJjwSjBUmOSxc3BFPoIFdlRthJ6e+5v9P3bHNsoD06UjuqMUspqp7vsEZ1beaHi1km+optiE17yA==} @@ -9565,61 +9495,6 @@ packages: vite: optional: true - vitest-browser-react@2.2.0: - resolution: {integrity: sha512-oY3KM6305kwJMa6nHo92vVtkOsih7mjEf12dLKuphaF+9ywWPEc+qanIBd394SZ6m5LadVEaG6dicvvizOzmjA==} - peerDependencies: - '@types/react': ^18.0.0 || ^19.0.0 - '@types/react-dom': ^18.0.0 || ^19.0.0 - react: ^18.0.0 || ^19.0.0 - react-dom: ^18.0.0 || ^19.0.0 - vitest: ^4.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - vitest@4.1.8: - resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==} - engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} - hasBin: true - peerDependencies: - '@edge-runtime/vm': '*' - '@opentelemetry/api': ^1.9.0 - '@types/node': 24.12.4 - '@vitest/browser-playwright': 4.1.8 - '@vitest/browser-preview': 4.1.8 - '@vitest/browser-webdriverio': 4.1.8 - '@vitest/coverage-istanbul': 4.1.8 - '@vitest/coverage-v8': 4.1.8 - '@vitest/ui': 4.1.8 - happy-dom: '*' - jsdom: '*' - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 - peerDependenciesMeta: - '@edge-runtime/vm': - optional: true - '@opentelemetry/api': - optional: true - '@types/node': - optional: true - '@vitest/browser-playwright': - optional: true - '@vitest/browser-preview': - optional: true - '@vitest/browser-webdriverio': - optional: true - '@vitest/coverage-istanbul': - optional: true - '@vitest/coverage-v8': - optional: true - '@vitest/ui': - optional: true - happy-dom: - optional: true - jsdom: - optional: true - vlq@1.0.1: resolution: {integrity: sha512-gQpnTgkubC6hQgdIcRdYGDSDc+SaujOdyesZQMv6JlfQee/9Mp0Qhnys6WxDWvQnL5WZdT7o2Ul187aSt0Rq+w==} @@ -9763,11 +9638,6 @@ packages: engines: {node: ^20.17.0 || >=22.9.0} hasBin: true - why-is-node-running@2.3.0: - resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} - engines: {node: '>=8'} - hasBin: true - widest-line@6.0.0: resolution: {integrity: sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA==} engines: {node: '>=20'} @@ -13964,48 +13834,6 @@ snapshots: '@rolldown/plugin-babel': 0.2.3(@babel/core@7.29.7)(@babel/plugin-transform-runtime@7.29.7(@babel/core@7.29.7))(@babel/runtime@7.29.7)(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(rolldown@1.0.3) babel-plugin-react-compiler: 1.0.0 - '@vitest/expect@4.1.8': - dependencies: - '@standard-schema/spec': 1.1.0 - '@types/chai': 5.2.3 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 - chai: 6.2.2 - tinyrainbow: 3.1.0 - - '@vitest/mocker@4.1.8(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(msw@2.12.11(@types/node@24.12.4)(typescript@6.0.3))': - dependencies: - '@vitest/spy': 4.1.8 - estree-walker: 3.0.3 - magic-string: 0.30.21 - optionalDependencies: - msw: 2.12.11(@types/node@24.12.4)(typescript@6.0.3) - vite: '@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' - - '@vitest/pretty-format@4.1.8': - dependencies: - tinyrainbow: 3.1.0 - - '@vitest/runner@4.1.8': - dependencies: - '@vitest/utils': 4.1.8 - pathe: 2.0.3 - - '@vitest/snapshot@4.1.8': - dependencies: - '@vitest/pretty-format': 4.1.8 - '@vitest/utils': 4.1.8 - magic-string: 0.30.21 - pathe: 2.0.3 - - '@vitest/spy@4.1.8': {} - - '@vitest/utils@4.1.8': - dependencies: - '@vitest/pretty-format': 4.1.8 - convert-source-map: 2.0.0 - tinyrainbow: 3.1.0 - '@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)': dependencies: '@oxc-project/runtime': 0.133.0 @@ -14795,8 +14623,6 @@ snapshots: ccount@2.0.1: {} - chai@6.2.2: {} - chalk@2.4.2: dependencies: ansi-styles: 3.2.1 @@ -15469,10 +15295,6 @@ snapshots: estree-walker@2.0.2: {} - estree-walker@3.0.3: - dependencies: - '@types/estree': 1.0.9 - etag@1.8.1: {} event-target-shim@5.0.1: {} @@ -15485,8 +15307,6 @@ snapshots: dependencies: eventsource-parser: 3.1.0 - expect-type@1.3.0: {} - expo-application@56.0.3(expo@56.0.8): dependencies: expo: 56.0.8(@babel/core@7.29.7)(@expo/dom-webview@56.0.5)(@expo/metro-runtime@56.0.13)(bufferutil@4.1.0)(expo-router@56.2.8)(expo-widgets@56.0.16)(react-dom@19.2.3(react@19.2.3))(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.3(@babel/core@7.29.7))(react-native@0.85.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.3(@babel/core@7.29.7))(@types/react@19.2.16)(bufferutil@4.1.0)(react@19.2.3)(utf-8-validate@6.0.6))(react@19.2.3))(react-native@0.85.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.3(@babel/core@7.29.7))(@types/react@19.2.16)(bufferutil@4.1.0)(react@19.2.3)(utf-8-validate@6.0.6))(react@19.2.3)(typescript@6.0.3)(utf-8-validate@6.0.6) @@ -16086,9 +15906,6 @@ snapshots: fs.realpath@1.0.0: {} - fsevents@2.3.2: - optional: true - fsevents@2.3.3: optional: true @@ -17736,8 +17553,6 @@ snapshots: obug@2.1.1: {} - obug@2.1.2: {} - ofetch@1.5.1: dependencies: destr: 2.0.5 @@ -18017,12 +17832,6 @@ snapshots: playwright-core@1.60.0: {} - playwright@1.60.0: - dependencies: - playwright-core: 1.60.0 - optionalDependencies: - fsevents: 2.3.2 - plist@3.1.0: dependencies: '@xmldom/xmldom': 0.8.13 @@ -18960,8 +18769,6 @@ snapshots: side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 - siginfo@2.0.0: {} - signal-exit@3.0.7: {} signal-exit@4.1.0: {} @@ -19033,8 +18840,6 @@ snapshots: dependencies: escape-string-regexp: 2.0.0 - stackback@0.0.2: {} - stackframe@1.3.4: {} stacktrace-parser@0.1.11: @@ -19222,8 +19027,6 @@ snapshots: tinypool@2.1.0: {} - tinyrainbow@3.1.0: {} - tldts-core@7.4.2: {} tldts@7.4.2: @@ -19565,42 +19368,6 @@ snapshots: optionalDependencies: vite: '@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' - vitest-browser-react@2.2.0(@types/react-dom@19.2.3(@types/react@19.2.16))(@types/react@19.2.16)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)(vitest@4.1.8(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(msw@2.12.11(@types/node@24.12.4)(typescript@6.0.3))): - dependencies: - react: 19.2.6 - react-dom: 19.2.6(react@19.2.6) - vitest: 4.1.8(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(msw@2.12.11(@types/node@24.12.4)(typescript@6.0.3)) - optionalDependencies: - '@types/react': 19.2.16 - '@types/react-dom': 19.2.3(@types/react@19.2.16) - - vitest@4.1.8(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(msw@2.12.11(@types/node@24.12.4)(typescript@6.0.3)): - dependencies: - '@vitest/expect': 4.1.8 - '@vitest/mocker': 4.1.8(@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(msw@2.12.11(@types/node@24.12.4)(typescript@6.0.3)) - '@vitest/pretty-format': 4.1.8 - '@vitest/runner': 4.1.8 - '@vitest/snapshot': 4.1.8 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 - es-module-lexer: 2.1.0 - expect-type: 1.3.0 - magic-string: 0.30.21 - obug: 2.1.2 - pathe: 2.0.3 - picomatch: 4.0.4 - std-env: 4.1.0 - tinybench: 2.9.0 - tinyexec: 1.2.4 - tinyglobby: 0.2.17 - tinyrainbow: 3.1.0 - vite: '@voidzero-dev/vite-plus-core@0.1.24(@types/node@24.12.4)(esbuild@0.27.7)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' - why-is-node-running: 2.3.0 - optionalDependencies: - '@types/node': 24.12.4 - transitivePeerDependencies: - - msw - vlq@1.0.1: {} volar-service-css@0.0.70(@volar/language-service@2.4.28): @@ -19740,11 +19507,6 @@ snapshots: dependencies: isexe: 4.0.0 - why-is-node-running@2.3.0: - dependencies: - siginfo: 2.0.0 - stackback: 0.0.2 - widest-line@6.0.0: dependencies: string-width: 8.2.1