The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets"; |
| 2 | import { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 3 | import { AsyncResult } from "effect/reactivity"; |
| 4 | import { type ReactElement } from "react"; |
| 5 | import remarkGfm from "remark-gfm"; |
| 6 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 7 | import { page, userEvent } from "vite-plus/test/browser"; |
| 8 | |
| 9 | import { act, render } from "../../test/render"; |
| 10 | import "../index.css"; |
| 11 | |
| 12 | import { filesystemEnvironment } from "../state/filesystem"; |
| 13 | import { |
| 14 | hostRightPanel, |
| 15 | selectActiveRightPanelSurface, |
| 16 | useRightPanelStore, |
| 17 | } from "../rightPanelStore"; |
| 18 | import { |
| 19 | CHAT_USER_MARKDOWN_REMARK_PLUGINS, |
| 20 | remarkEnableOrderedListNumbers, |
| 21 | } from "@t3tools/shared/markdownPipeline"; |
| 22 | import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; |
| 23 | import { HostImageUrlContext } from "./chat/hostImageUrl"; |
| 24 | import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; |
| 25 | |
| 26 | const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ |
| 27 | workspaceSearch: vi.fn(), |
| 28 | filesystemMetadata: vi.fn(), |
| 29 | })); |
| 30 | const parsedSources = vi.hoisted(() => [] as string[]); |
| 31 | vi.mock(import("mdast-util-from-markdown"), async (original) => { |
| 32 | const actual = await original(); |
| 33 | return { |
| 34 | ...actual, |
| 35 | fromMarkdown: ((source: string, ...rest: never[]) => { |
| 36 | parsedSources.push(String(source)); |
| 37 | return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest); |
| 38 | }) as typeof actual.fromMarkdown, |
| 39 | }; |
| 40 | }); |
| 41 | |
| 42 | vi.mock(import("../state/use-atom-query-runner"), async (original) => ({ |
| 43 | ...(await original()), |
| 44 | useAtomQueryRunner: ((family: unknown) => |
| 45 | family === filesystemEnvironment.getMetadata ? filesystemMetadata : workspaceSearch) as never, |
| 46 | })); |
| 47 | |
| 48 | // Atoms derived from the server config run in the real registry over a missing config. |
| 49 | vi.mock(import("../state/server"), async (original) => { |
| 50 | const actual = await original(); |
| 51 | const { Atom } = await import("effect/reactivity"); |
| 52 | const noConfig = Atom.make(null); |
| 53 | const modelsConfig = Atom.make({ |
| 54 | environment: { platform: { os: "darwin" }, capabilities: {} }, |
| 55 | availableEditors: [], |
| 56 | settings: { providerInstances: {} }, |
| 57 | providers: [ |
| 58 | { |
| 59 | instanceId: "codex", |
| 60 | driver: "codex", |
| 61 | displayName: "Codex", |
| 62 | models: [{ slug: "gpt-6.1", name: "GPT-6.1", isCustom: false, capabilities: {} }], |
| 63 | }, |
| 64 | ], |
| 65 | }); |
| 66 | return { |
| 67 | ...actual, |
| 68 | serverEnvironment: { |
| 69 | ...actual.serverEnvironment, |
| 70 | configValueAtom: ((environmentId: string) => |
| 71 | environmentId === "models" ? modelsConfig : noConfig) as never, |
| 72 | }, |
| 73 | }; |
| 74 | }); |
| 75 | vi.mock(import("../state/session"), async (original) => { |
| 76 | const { AuthStandardClientScopes } = await import("@t3tools/contracts"); |
| 77 | const granted = new Set<string>(AuthStandardClientScopes); |
| 78 | const hasScope = (environmentId: unknown, scope: string) => |
| 79 | environmentId !== null && granted.has(scope); |
| 80 | return { |
| 81 | ...(await original()), |
| 82 | useEnvironmentScope: hasScope as never, |
| 83 | readEnvironmentScope: hasScope as never, |
| 84 | }; |
| 85 | }); |
| 86 | const deniedEnvironmentId = vi.hoisted(() => "denied-environment"); |
| 87 | vi.mock(import("../state/filesystem"), async (original) => { |
| 88 | const actual = await original(); |
| 89 | return { |
| 90 | ...actual, |
| 91 | useFilesystemReadAccess: ((environmentId: EnvironmentId | null) => |
| 92 | environmentId === deniedEnvironmentId |
| 93 | ? { canReadFiles: false, isPending: false, error: null } |
| 94 | : actual.useFilesystemReadAccess(environmentId)) as never, |
| 95 | }; |
| 96 | }); |
| 97 | vi.mock(import("../remoteOpen"), async (original) => ({ |
| 98 | ...(await original()), |
| 99 | useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never, |
| 100 | })); |
| 101 | const { renderDiagram } = vi.hoisted(() => ({ |
| 102 | renderDiagram: vi.fn<(source: string) => Promise<string> | undefined>(), |
| 103 | })); |
| 104 | // Control rendering latency without running Mermaid layout. |
| 105 | vi.mock(import("./chat/MermaidDiagram"), async (original) => { |
| 106 | const { use } = await import("react"); |
| 107 | return { |
| 108 | ...(await original()), |
| 109 | MermaidDiagram: ({ source }: { source: string }) => { |
| 110 | const pending = renderDiagram(source); |
| 111 | return <svg role="img" aria-label={pending ? use(pending) : "Diagram"} />; |
| 112 | }, |
| 113 | }; |
| 114 | }); |
| 115 | |
| 116 | const appearance = vi.hoisted(() => ({ |
| 117 | value: "light" as "light" | "dark", |
| 118 | listeners: new Set<() => void>(), |
| 119 | })); |
| 120 | vi.mock(import("../hooks/useTheme"), async (original) => { |
| 121 | const { useSyncExternalStore } = await import("react"); |
| 122 | const subscribe = (listener: () => void) => { |
| 123 | appearance.listeners.add(listener); |
| 124 | return () => appearance.listeners.delete(listener); |
| 125 | }; |
| 126 | return { |
| 127 | ...(await original()), |
| 128 | useRenderedAppearance: () => useSyncExternalStore(subscribe, () => appearance.value), |
| 129 | }; |
| 130 | }); |
| 131 | |
| 132 | const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false })); |
| 133 | vi.mock(import("../hooks/useSettings"), async (original) => { |
| 134 | const actual = await original(); |
| 135 | type Settings = ReturnType<typeof actual.getClientSettings>; |
| 136 | function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T { |
| 137 | const settings = { ...actual.getClientSettings(), ...settingsOverrides }; |
| 138 | return select ? select(settings) : (settings as T); |
| 139 | } |
| 140 | return { ...actual, useClientSettings }; |
| 141 | }); |
| 142 | |
| 143 | import ChatMarkdown from "./ChatMarkdown"; |
| 144 | import { |
| 145 | chatMarkdownClipboardPayload, |
| 146 | serializeRenderedMarkdownFragment, |
| 147 | } from "../markdown-clipboard"; |
| 148 | import { AudioPreview } from "./files/AudioPreview"; |
| 149 | |
| 150 | it("keeps compact audio playback loaded across signed URL renewals", async () => { |
| 151 | const original = |
| 152 | "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA"; |
| 153 | const renewed = `${original}#renewed`; |
| 154 | const preview = (src: string, revision = "clip-v1") => ( |
| 155 | <AudioPreview compact name="clip.wav" src={src} revision={revision} /> |
| 156 | ); |
| 157 | await using screen = await render(preview(original)); |
| 158 | const audio = screen.container.querySelector("audio")!; |
| 159 | await act(() => { |
| 160 | audio.dispatchEvent(new Event("loadedmetadata")); |
| 161 | audio.dispatchEvent(new Event("play")); |
| 162 | }); |
| 163 | await screen.rerender(preview(renewed)); |
| 164 | expect(screen.container.querySelector("audio")).toBe(audio); |
| 165 | expect(audio.getAttribute("src")).toBe(original); |
| 166 | await expect.element(screen.getByRole("button", { name: "Pause clip.wav" })).toBeEnabled(); |
| 167 | await screen.rerender(preview(renewed, "clip-v2")); |
| 168 | expect(screen.container.querySelector("audio")).not.toBe(audio); |
| 169 | expect(screen.container.querySelector("audio")?.getAttribute("src")).toBe(renewed); |
| 170 | }); |
| 171 | |
| 172 | function setup() { |
| 173 | appearance.value = "light"; |
| 174 | parsedSources.length = 0; |
| 175 | settingsOverrides.mathRenderingEnabled = false; |
| 176 | renderDiagram.mockReset(); |
| 177 | workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] })); |
| 178 | filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] })); |
| 179 | } |
| 180 | |
| 181 | function renderText(text: string, props: Partial<Parameters<typeof ChatMarkdown>[0]> = {}) { |
| 182 | return render(<ChatMarkdown cwd="/tmp/project" text={text} {...props} />); |
| 183 | } |
| 184 | |
| 185 | function buttonsLabelled(container: HTMLElement, label: string) { |
| 186 | return [...container.querySelectorAll<HTMLButtonElement>("button")].filter( |
| 187 | (button) => button.getAttribute("aria-label") === label, |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; |
| 192 | |
| 193 | it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { |
| 194 | setup(); |
| 195 | const text = "1. Outer\n 1. Nested\n 7. Skipped\n 1. Deeper\n 4. Fourth"; |
| 196 | await using screen = await render( |
| 197 | <div className="grid grid-cols-2 gap-8 p-8"> |
| 198 | <section> |
| 199 | <h2>User message</h2> |
| 200 | <ChatMarkdown |
| 201 | cwd={undefined} |
| 202 | text={text} |
| 203 | className="user-message-markdown" |
| 204 | extraRemarkPlugins={SOURCE_NUMBER_PLUGINS} |
| 205 | /> |
| 206 | </section> |
| 207 | <section> |
| 208 | <h2>Markdown preview</h2> |
| 209 | <ChatMarkdown cwd={undefined} text={text} /> |
| 210 | </section> |
| 211 | </div>, |
| 212 | ); |
| 213 | await expect.element(screen.getByText("User message", { exact: true })).toBeVisible(); |
| 214 | const [message, preview] = screen.container.querySelectorAll(".chat-markdown"); |
| 215 | expect( |
| 216 | [...message!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType), |
| 217 | ).toEqual(["decimal", "decimal", "decimal"]); |
| 218 | expect( |
| 219 | [...preview!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType), |
| 220 | ).toEqual(["decimal", "lower-alpha", "lower-roman"]); |
| 221 | }); |
| 222 | |
| 223 | it("shows unavailable audio when a workspace embed has no thread", async () => { |
| 224 | setup(); |
| 225 | await using screen = await renderText(""); |
| 226 | expect(screen.container.textContent).toContain("Audio unavailable"); |
| 227 | expect(screen.container.textContent).not.toContain("Loading audio"); |
| 228 | expect(screen.container.querySelector("audio")).toBeNull(); |
| 229 | }); |
| 230 | |
| 231 | it("loads a host image through the page's own route when there is no environment", async () => { |
| 232 | setup(); |
| 233 | const pixel = |
| 234 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; |
| 235 | const hostImageUrl = vi.fn((_path: string) => pixel); |
| 236 | await using screen = await render( |
| 237 | <HostImageUrlContext value={hostImageUrl}> |
| 238 | <ChatMarkdown cwd={undefined} text="" /> |
| 239 | </HostImageUrlContext>, |
| 240 | ); |
| 241 | await expect.element(screen.getByAltText("Shot")).toHaveAttribute("src", pixel); |
| 242 | expect(new Set(hostImageUrl.mock.calls.map(([path]) => path))).toEqual( |
| 243 | new Set(["/work/my shot.png"]), |
| 244 | ); |
| 245 | }); |
| 246 | |
| 247 | it("loads the <picture> source for the current theme through the image route", async () => { |
| 248 | setup(); |
| 249 | const pixel = |
| 250 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; |
| 251 | const hostImageUrl = (path: string) => `${pixel}#${path}`; |
| 252 | await using screen = await render( |
| 253 | <HostImageUrlContext value={hostImageUrl}> |
| 254 | <ChatMarkdown |
| 255 | cwd={undefined} |
| 256 | text={ |
| 257 | '<picture><source media="(prefers-color-scheme: dark)" srcset="/work/dark.png"><img src="/work/light.png" alt="Shot"></picture>' |
| 258 | } |
| 259 | /> |
| 260 | </HostImageUrlContext>, |
| 261 | ); |
| 262 | await expect |
| 263 | .element(screen.getByAltText("Shot")) |
| 264 | .toHaveAttribute("src", `${pixel}#/work/light.png`); |
| 265 | |
| 266 | await act(() => { |
| 267 | appearance.value = "dark"; |
| 268 | for (const listener of appearance.listeners) listener(); |
| 269 | }); |
| 270 | await expect |
| 271 | .element(screen.getByAltText("Shot")) |
| 272 | .toHaveAttribute("src", `${pixel}#/work/dark.png`); |
| 273 | }); |
| 274 | |
| 275 | it("sizes a raw HTML image by width and height written with px units", async () => { |
| 276 | setup(); |
| 277 | const largeImage = `data:image/svg+xml,${encodeURIComponent( |
| 278 | '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"/>', |
| 279 | )}`; |
| 280 | await using screen = await render( |
| 281 | <HostImageUrlContext value={() => largeImage}> |
| 282 | <ChatMarkdown |
| 283 | cwd={undefined} |
| 284 | parseRawHtml |
| 285 | text={ |
| 286 | '### PR Review in progress <img src="/work/spinner.gif" alt="spinner" width="14px" height="7px" />' |
| 287 | } |
| 288 | /> |
| 289 | </HostImageUrlContext>, |
| 290 | ); |
| 291 | const image = screen.getByAltText("spinner"); |
| 292 | await expect.element(image).toHaveAttribute("src", largeImage); |
| 293 | const element = image.element() as HTMLImageElement; |
| 294 | await element.decode(); |
| 295 | const { width, height } = element.getBoundingClientRect(); |
| 296 | expect({ width, height }).toEqual({ width: 14, height: 7 }); |
| 297 | }); |
| 298 | |
| 299 | it("reuses the parse of a streaming reply's finished blocks when it remounts", async () => { |
| 300 | setup(); |
| 301 | const message = ( |
| 302 | <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\nStill growing"} isStreaming /> |
| 303 | ); |
| 304 | { |
| 305 | await using first = await render( |
| 306 | <ChatMarkdown cwd="/tmp/project" text={"Finished block\n\n"} isStreaming />, |
| 307 | ); |
| 308 | await first.rerender(message); |
| 309 | } |
| 310 | await using screen = await render(message); |
| 311 | await expect.element(screen.getByText("Still growing")).toBeVisible(); |
| 312 | expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1); |
| 313 | }); |
| 314 | |
| 315 | it("reuses the parse of a remounted message that has stable extra plugins", async () => { |
| 316 | setup(); |
| 317 | const parsed = vi.fn(); |
| 318 | const countingPlugins = [() => () => void parsed()]; |
| 319 | const message = ( |
| 320 | <ChatMarkdown cwd="/tmp/project" text="Cached text" extraRemarkPlugins={countingPlugins} /> |
| 321 | ); |
| 322 | { |
| 323 | await using first = await render( |
| 324 | <ChatMarkdown |
| 325 | cwd="/tmp/project" |
| 326 | text="Cached text" |
| 327 | extraRemarkPlugins={countingPlugins} |
| 328 | isStreaming |
| 329 | />, |
| 330 | ); |
| 331 | await first.rerender(message); |
| 332 | } |
| 333 | await using screen = await render(message); |
| 334 | await expect.element(screen.getByText("Cached text")).toBeVisible(); |
| 335 | expect(parsed).toHaveBeenCalledTimes(1); |
| 336 | const changed = vi.fn(); |
| 337 | await screen.rerender( |
| 338 | <ChatMarkdown |
| 339 | cwd="/tmp/project" |
| 340 | text="Cached text" |
| 341 | extraRemarkPlugins={[() => () => void changed()]} |
| 342 | />, |
| 343 | ); |
| 344 | expect(changed).toHaveBeenCalledTimes(1); |
| 345 | }); |
| 346 | |
| 347 | it("highlights a code block's own source when an earlier block of the same length was cached", async () => { |
| 348 | setup(); |
| 349 | const highlightedText = (container: HTMLElement) => |
| 350 | container.querySelector(".chat-markdown-shiki")?.textContent?.trim(); |
| 351 | // These two lines share a 32-bit FNV-1a hash and a length. |
| 352 | const first = 'const commitSha = "f36a6d8fe0aa";'; |
| 353 | const second = 'const commitSha = "cb06f8d135b3";'; |
| 354 | // The block suspends until the shared highlighter loads, which can outlast vi.waitFor on a busy runner. |
| 355 | await getSyntaxHighlighterPromise("ts"); |
| 356 | { |
| 357 | await using screen = await renderText(`\`\`\`ts\n${first}\n\`\`\``); |
| 358 | await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(first)); |
| 359 | } |
| 360 | await using screen = await renderText(`\`\`\`ts\n${second}\n\`\`\``); |
| 361 | await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(second)); |
| 362 | }); |
| 363 | |
| 364 | describe("ChatMarkdown favicon privacy", () => { |
| 365 | it("suppresses private link images while preserving public links across updates", async () => { |
| 366 | setup(); |
| 367 | const markdown = (url: string) => <ChatMarkdown cwd="/tmp/project" text={`[Link](${url})`} />; |
| 368 | await using screen = await render(markdown("https://example.com")); |
| 369 | const { container, rerender } = screen; |
| 370 | expect([...container.querySelectorAll("img")].map((image) => image.src)).toEqual([ |
| 371 | "https://www.google.com/s2/favicons?domain=example.com&sz=32", |
| 372 | ]); |
| 373 | for (const url of ["http://192.168.1.10:8080", "http://localhost:3000", "http://home.arpa"]) { |
| 374 | await rerender(markdown(url)); |
| 375 | expect(container.querySelectorAll("img")).toHaveLength(0); |
| 376 | } |
| 377 | await rerender(markdown("https://example.com")); |
| 378 | expect(container.querySelectorAll("img")).toHaveLength(1); |
| 379 | await rerender(markdown("https://github.com/pingdotgg/t3code/pull/1")); |
| 380 | expect(container.querySelectorAll("img")).toHaveLength(0); |
| 381 | expect(container.querySelector("a svg")).not.toBeNull(); |
| 382 | }); |
| 383 | }); |
| 384 | |
| 385 | describe("ChatMarkdown external link labels", () => { |
| 386 | it("keeps a leading emoji whole", async () => { |
| 387 | setup(); |
| 388 | await using screen = await render( |
| 389 | <ChatMarkdown cwd="/tmp/project" text="[😀 Read the documentation](https://example.com)" />, |
| 390 | ); |
| 391 | await vi.waitFor(() => { |
| 392 | const link = screen.container.querySelector("a"); |
| 393 | expect(link?.textContent).toContain("😀 Read"); |
| 394 | const walker = document.createTreeWalker(link!, NodeFilter.SHOW_TEXT); |
| 395 | const textNodes: string[] = []; |
| 396 | while (walker.nextNode()) textNodes.push(walker.currentNode.nodeValue ?? ""); |
| 397 | expect(textNodes.filter((node) => /\p{Surrogate}/u.test(node))).toEqual([]); |
| 398 | }); |
| 399 | }); |
| 400 | }); |
| 401 | |
| 402 | describe("ChatMarkdown streaming", () => { |
| 403 | it("runs only a complete single-line shell block after a click", async () => { |
| 404 | setup(); |
| 405 | const onRunShellCommand = vi.fn(); |
| 406 | const message = (text: string, isStreaming = false) => ( |
| 407 | <ChatMarkdown |
| 408 | cwd="/tmp/project" |
| 409 | text={text} |
| 410 | isStreaming={isStreaming} |
| 411 | onRunShellCommand={onRunShellCommand} |
| 412 | /> |
| 413 | ); |
| 414 | await using screen = await render(message("```bash\necho hello\n```", true)); |
| 415 | const { container, rerender } = screen; |
| 416 | const runButtons = () => buttonsLabelled(container, "Run in terminal"); |
| 417 | expect(runButtons()).toHaveLength(0); |
| 418 | |
| 419 | await rerender(message("```bash\necho hello\n```")); |
| 420 | await act(async () => runButtons()[0]!.click()); |
| 421 | expect(onRunShellCommand).toHaveBeenCalledExactlyOnceWith("echo hello"); |
| 422 | |
| 423 | for (const text of [ |
| 424 | "~~~bash\necho tilde\n~~~", |
| 425 | "> ```bash\n> echo quote\n> ```", |
| 426 | "````bash\necho four\n````", |
| 427 | "- Command\n\n ```bash\n echo list\n ```", |
| 428 | "```bash\r\necho crlf\r\n```\r", |
| 429 | ]) { |
| 430 | await rerender(message(text)); |
| 431 | expect(runButtons()).toHaveLength(1); |
| 432 | } |
| 433 | |
| 434 | for (const text of [ |
| 435 | "```bash\necho one\necho two\n```", |
| 436 | "```typescript\necho hello\n```", |
| 437 | "```bash\n\n```", |
| 438 | "```bash\necho hello\n\n```", |
| 439 | "```bash\necho hello\\\n```", |
| 440 | "```bash\necho safe \u202e#\n```", |
| 441 | "```bash\necho incomplete", |
| 442 | "~~~bash\necho incomplete", |
| 443 | "````bash\necho incomplete\n```", |
| 444 | '<pre><code class="language-bash">echo html</code></pre>', |
| 445 | ]) { |
| 446 | await rerender(message(text)); |
| 447 | expect(runButtons()).toHaveLength(0); |
| 448 | } |
| 449 | }); |
| 450 | |
| 451 | it("edits the current task text and marker after reusing a renderer", async () => { |
| 452 | setup(); |
| 453 | let editedText: string | undefined; |
| 454 | let rerender: (next: ReactElement) => Promise<void> = async () => {}; |
| 455 | const message = (text: string): ReactElement => ( |
| 456 | <ChatMarkdown |
| 457 | cwd="/tmp/project" |
| 458 | text={text} |
| 459 | onTaskListChange={({ markerOffset, checked }) => { |
| 460 | editedText = setMarkdownTaskChecked(text, markerOffset, checked); |
| 461 | void rerender(message(editedText)); |
| 462 | }} |
| 463 | /> |
| 464 | ); |
| 465 | await using rendered = await render(message("- [ ] First\n- [ ] Second")); |
| 466 | rerender = rendered.rerender; |
| 467 | const { container } = rendered; |
| 468 | const checkboxes = () => container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'); |
| 469 | const original = checkboxes()[1]!; |
| 470 | await rerender(message("- [ ] A longer first task\n- [ ] Second")); |
| 471 | expect(checkboxes()[1]).toBe(original); |
| 472 | |
| 473 | await act(async () => original.click()); |
| 474 | expect(editedText).toBe("- [ ] A longer first task\n- [x] Second"); |
| 475 | await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true)); |
| 476 | await rerender(message("- [ ] A longer first task\n- [ ] Second")); |
| 477 | expect(checkboxes()[1]).toBe(original); |
| 478 | expect(checkboxes()[1]!.checked).toBe(false); |
| 479 | }); |
| 480 | |
| 481 | it.each([ |
| 482 | ["read-only", undefined], |
| 483 | ["editable", () => {}], |
| 484 | ])( |
| 485 | "unchecks the remaining %s task when the checked row above it is removed", |
| 486 | async (_, onTaskListChange) => { |
| 487 | setup(); |
| 488 | const message = (text: string) => ( |
| 489 | <ChatMarkdown cwd="/tmp/project" text={text} onTaskListChange={onTaskListChange} /> |
| 490 | ); |
| 491 | await using screen = await render(message("- [x] Completed item\n- [ ] Pending item")); |
| 492 | await screen.rerender(message("- [ ] Pending item")); |
| 493 | const checkboxes = |
| 494 | screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'); |
| 495 | expect(checkboxes).toHaveLength(1); |
| 496 | expect(checkboxes[0]!.checked).toBe(false); |
| 497 | }, |
| 498 | ); |
| 499 | }); |
| 500 | |
| 501 | describe("ChatMarkdown workspace file opens", () => { |
| 502 | const threadRef = { |
| 503 | environmentId: EnvironmentId.make("workspace"), |
| 504 | threadId: ThreadId.make("thread"), |
| 505 | }; |
| 506 | |
| 507 | it("keeps a newer absolute file open when an earlier repo-relative lookup finishes", async () => { |
| 508 | setup(); |
| 509 | const result = AsyncResult.success({ |
| 510 | entries: [{ path: "notes/a.md", kind: "file" }], |
| 511 | truncated: false, |
| 512 | }); |
| 513 | let resolvePending!: (value: typeof result) => void; |
| 514 | const pending = new Promise<typeof result>((resolve) => { |
| 515 | resolvePending = resolve; |
| 516 | }); |
| 517 | workspaceSearch.mockReturnValueOnce(pending); |
| 518 | using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile"); |
| 519 | await using screen = await renderText( |
| 520 | "[Notes](physics/notes/a.md) and [Other](/elsewhere/b.md:9)", |
| 521 | { |
| 522 | cwd: "/school/physics", |
| 523 | threadRef, |
| 524 | }, |
| 525 | ); |
| 526 | const { container } = screen; |
| 527 | const [notes, other] = container.querySelectorAll("a"); |
| 528 | await act(async () => notes!.click()); |
| 529 | expect(workspaceSearch).toHaveBeenCalledOnce(); |
| 530 | expect(openFile).not.toHaveBeenCalled(); |
| 531 | |
| 532 | await act(async () => other!.click()); |
| 533 | await act(async () => resolvePending(result)); |
| 534 | |
| 535 | expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/elsewhere/b.md", 9); |
| 536 | expect(workspaceSearch).toHaveBeenCalledOnce(); |
| 537 | }); |
| 538 | |
| 539 | it.each([ |
| 540 | ["its own panel", "thread-own-panel", false], |
| 541 | ["its parent's panel from a side chat", "thread-side-chat", true], |
| 542 | ])( |
| 543 | "keeps a file opened elsewhere in %s when an earlier link lookup finishes", |
| 544 | async (_, threadId, sideChat) => { |
| 545 | setup(); |
| 546 | const host = { environmentId: threadRef.environmentId, threadId: ThreadId.make(threadId) }; |
| 547 | const linkRef = sideChat ? { ...host, threadId: ThreadId.make(`${threadId}-guest`) } : host; |
| 548 | using _hosted = { [Symbol.dispose]: sideChat ? hostRightPanel(linkRef, host) : () => {} }; |
| 549 | const result = AsyncResult.success({ |
| 550 | entries: [{ path: "notes/cited-note.txt", kind: "file" }], |
| 551 | truncated: false, |
| 552 | }); |
| 553 | const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>(); |
| 554 | workspaceSearch.mockReturnValueOnce(pending); |
| 555 | await using screen = await renderText("[Cited](cited-note.txt)", { |
| 556 | cwd: "/repo", |
| 557 | threadRef: linkRef, |
| 558 | }); |
| 559 | await act(async () => screen.container.querySelector("a")!.click()); |
| 560 | expect(workspaceSearch).toHaveBeenCalledOnce(); |
| 561 | |
| 562 | useRightPanelStore.getState().openFile(host, "picker-note.txt"); |
| 563 | await act(async () => resolvePending(result)); |
| 564 | |
| 565 | expect( |
| 566 | selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, host), |
| 567 | ).toMatchObject({ kind: "file", relativePath: "picker-note.txt" }); |
| 568 | }, |
| 569 | ); |
| 570 | |
| 571 | it.each([ |
| 572 | ["open a link in another panel", "separate-panels"], |
| 573 | ["unhost the side chat", "unhosted-side-chat"], |
| 574 | ] as const)("keeps a citation in its original panel scope if you %s", async (action, scope) => { |
| 575 | setup(); |
| 576 | const host = { ...threadRef, threadId: ThreadId.make(`${scope}-host`) }; |
| 577 | const guest = { ...threadRef, threadId: ThreadId.make(`${scope}-guest`) }; |
| 578 | const other = { ...threadRef, threadId: ThreadId.make(`${scope}-other`) }; |
| 579 | const unhost = hostRightPanel(guest, host); |
| 580 | using _hosted = { [Symbol.dispose]: unhost }; |
| 581 | const result = AsyncResult.success({ |
| 582 | entries: [{ path: "notes/cited-note.txt", kind: "file" }], |
| 583 | truncated: false, |
| 584 | }); |
| 585 | const { promise: pending, resolve: resolvePending } = Promise.withResolvers<typeof result>(); |
| 586 | workspaceSearch.mockReturnValueOnce(pending); |
| 587 | await using screen = await render( |
| 588 | <> |
| 589 | <ChatMarkdown cwd="/repo" threadRef={guest} text="[Cited](cited-note.txt)" /> |
| 590 | <ChatMarkdown cwd="/repo" threadRef={other} text="[Other](/elsewhere/other.md)" /> |
| 591 | </>, |
| 592 | ); |
| 593 | const [cited, otherLink] = screen.container.querySelectorAll("a"); |
| 594 | await act(async () => cited!.click()); |
| 595 | expect(workspaceSearch).toHaveBeenCalledOnce(); |
| 596 | if (action === "open a link in another panel") { |
| 597 | await act(async () => otherLink!.click()); |
| 598 | } else { |
| 599 | unhost(); |
| 600 | } |
| 601 | await act(async () => resolvePending(result)); |
| 602 | |
| 603 | const { byThreadKey } = useRightPanelStore.getState(); |
| 604 | expect(selectActiveRightPanelSurface(byThreadKey, guest)).toBeNull(); |
| 605 | if (action === "unhost the side chat") { |
| 606 | expect(selectActiveRightPanelSurface(byThreadKey, host)).toBeNull(); |
| 607 | } else { |
| 608 | expect(selectActiveRightPanelSurface(byThreadKey, host)).toMatchObject({ |
| 609 | kind: "file", |
| 610 | relativePath: "notes/cited-note.txt", |
| 611 | }); |
| 612 | expect(selectActiveRightPanelSurface(byThreadKey, other)).toMatchObject({ |
| 613 | kind: "file", |
| 614 | relativePath: "/elsewhere/other.md", |
| 615 | }); |
| 616 | } |
| 617 | }); |
| 618 | }); |
| 619 | |
| 620 | describe("ChatMarkdown skill chips", () => { |
| 621 | it("shows the skill's details and opens its instructions, closing the details", async () => { |
| 622 | setup(); |
| 623 | const threadRef = { |
| 624 | environmentId: EnvironmentId.make("workspace"), |
| 625 | threadId: ThreadId.make("thread"), |
| 626 | }; |
| 627 | await using screen = await renderText("Run $review now", { |
| 628 | threadRef, |
| 629 | skills: [ |
| 630 | { |
| 631 | name: "review", |
| 632 | displayName: "Review", |
| 633 | description: "Reviews the current branch.", |
| 634 | path: "/skills/review/SKILL.md", |
| 635 | enabled: true, |
| 636 | }, |
| 637 | ], |
| 638 | }); |
| 639 | using openFile = vi |
| 640 | .spyOn(useRightPanelStore.getState(), "openFile") |
| 641 | .mockImplementation(() => {}); |
| 642 | |
| 643 | await userEvent.click(screen.getByRole("button", { name: "Skill Review. Show details" })); |
| 644 | await expect.element(page.getByText("Reviews the current branch.")).toBeVisible(); |
| 645 | await userEvent.click(page.getByRole("button", { name: "View instructions" })); |
| 646 | |
| 647 | expect(openFile).toHaveBeenCalledExactlyOnceWith(threadRef, "/skills/review/SKILL.md"); |
| 648 | await expect.element(page.getByText("Reviews the current branch.")).not.toBeInTheDocument(); |
| 649 | }); |
| 650 | |
| 651 | it("names a mentioned model as its provider does, without a thread", async () => { |
| 652 | setup(); |
| 653 | await using screen = await renderText("Ask (model:codex/gpt-6.1), not model:openai/gpt-4o.", { |
| 654 | environmentId: EnvironmentId.make("models"), |
| 655 | }); |
| 656 | |
| 657 | await expect |
| 658 | .element(screen.getByRole("button", { name: "Model GPT-6.1. Show details" })) |
| 659 | .toBeVisible(); |
| 660 | expect(buttonsLabelled(screen.container, "Model gpt-4o. Show details")).toEqual([]); |
| 661 | expect(screen.container.textContent).toBe("Ask (GPT-6.1), not model:openai/gpt-4o."); |
| 662 | }); |
| 663 | }); |
| 664 | |
| 665 | describe("ChatMarkdown headings", () => { |
| 666 | it("keeps insight streaming, reference links, and heading anchors in one message", async () => { |
| 667 | setup(); |
| 668 | const rule = "─".repeat(20); |
| 669 | const text = `## Setup\n\nBefore [source][src].\n\n★ Insight ${rule}\nA **streaming** note.`; |
| 670 | const message = (text: string, isStreaming: boolean) => ( |
| 671 | <ChatMarkdown |
| 672 | cwd={undefined} |
| 673 | text={text} |
| 674 | renderInsights |
| 675 | lineBreaks |
| 676 | isStreaming={isStreaming} |
| 677 | /> |
| 678 | ); |
| 679 | await using screen = await render(message(text, true)); |
| 680 | await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note."); |
| 681 | await screen.rerender( |
| 682 | message( |
| 683 | `${text}\n${rule}\n\n## Setup\n\nAfter [source][src].\n\n[src]:\n https://example.com`, |
| 684 | false, |
| 685 | ), |
| 686 | ); |
| 687 | await expect.element(screen.getByRole("note")).toHaveTextContent("Insight A streaming note."); |
| 688 | expect([...screen.container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([ |
| 689 | "user-content-setup", |
| 690 | "user-content-setup-1", |
| 691 | ]); |
| 692 | expect( |
| 693 | [...screen.container.querySelectorAll("a")].filter( |
| 694 | (link) => link.href === "https://example.com/", |
| 695 | ), |
| 696 | ).toHaveLength(2); |
| 697 | await expect.element(screen.getByRole("note")).not.toHaveTextContent("After"); |
| 698 | }); |
| 699 | |
| 700 | it("never gives two headings the same id, even when a suffix matches another heading", async () => { |
| 701 | setup(); |
| 702 | await using screen = await renderText( |
| 703 | '## Setup\n\n## Setup\n\n## Setup-1\n\n<h2 id="install-1">Pinned</h2>\n\n## Install\n\n## Install', |
| 704 | { parseRawHtml: true }, |
| 705 | ); |
| 706 | const { container } = screen; |
| 707 | expect([...container.querySelectorAll("h2")].map((heading) => heading.id)).toEqual([ |
| 708 | "user-content-setup", |
| 709 | "user-content-setup-1", |
| 710 | "user-content-setup-1-1", |
| 711 | "user-content-install-1", |
| 712 | "user-content-install", |
| 713 | "user-content-install-2", |
| 714 | ]); |
| 715 | }); |
| 716 | }); |
| 717 | |
| 718 | describe("ChatMarkdown inline code selection", () => { |
| 719 | it("selects only a word on double-click in inline and fenced code", async () => { |
| 720 | setup(); |
| 721 | await using screen = await renderText( |
| 722 | "Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```", |
| 723 | ); |
| 724 | await userEvent.dblClick(screen.getByText("migration-gate --dry-run"), { |
| 725 | position: { x: 12, y: 8 }, |
| 726 | }); |
| 727 | expect(window.getSelection()?.toString()).toBe("migration"); |
| 728 | |
| 729 | window.getSelection()?.removeAllRanges(); |
| 730 | const fenced = screen.container.querySelector("pre code")!; |
| 731 | await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } }); |
| 732 | expect(window.getSelection()?.toString()).toBe("fenced"); |
| 733 | }); |
| 734 | |
| 735 | it("selects the whole line on triple-click beside a favicon link or a file chip", async () => { |
| 736 | setup(); |
| 737 | await using screen = await renderText( |
| 738 | "Before [docs](https://example.com/docs) after words\n\nBefore [App.tsx](/tmp/project/src/App.tsx) after words", |
| 739 | ); |
| 740 | const tripleClickWord = async (paragraph: HTMLElement, word: string) => { |
| 741 | const text = [...paragraph.childNodes].find((node) => node.textContent?.includes(word))!; |
| 742 | const range = document.createRange(); |
| 743 | range.setStart(text, text.textContent!.indexOf(word)); |
| 744 | range.setEnd(text, text.textContent!.indexOf(word) + word.length); |
| 745 | const wordBox = range.getBoundingClientRect(); |
| 746 | const paragraphBox = paragraph.getBoundingClientRect(); |
| 747 | window.getSelection()?.removeAllRanges(); |
| 748 | await userEvent.tripleClick(paragraph, { |
| 749 | position: { |
| 750 | x: wordBox.left - paragraphBox.left + wordBox.width / 2, |
| 751 | y: wordBox.top - paragraphBox.top + wordBox.height / 2, |
| 752 | }, |
| 753 | }); |
| 754 | return window.getSelection()?.toString().trim(); |
| 755 | }; |
| 756 | |
| 757 | const paragraphs = screen.container.querySelectorAll("p"); |
| 758 | expect(paragraphs).toHaveLength(2); |
| 759 | const selections = []; |
| 760 | const lines = []; |
| 761 | for (const paragraph of paragraphs) { |
| 762 | lines.push(paragraph.textContent?.trim(), paragraph.textContent?.trim()); |
| 763 | selections.push( |
| 764 | await tripleClickWord(paragraph, "Before"), |
| 765 | await tripleClickWord(paragraph, "after"), |
| 766 | ); |
| 767 | } |
| 768 | expect(selections).toEqual(lines); |
| 769 | }); |
| 770 | }); |
| 771 | |
| 772 | describe("ChatMarkdown copy", () => { |
| 773 | it("copies a fully selected callout as alert Markdown and a partial one as text", async () => { |
| 774 | setup(); |
| 775 | await using screen = await renderText("> [!WARNING]\n> Back up first."); |
| 776 | const [label, body] = screen.container.querySelectorAll('[role="note"] > p'); |
| 777 | const select = (startNode: Node, endNode: Node, endOffset: number) => { |
| 778 | const range = document.createRange(); |
| 779 | range.setStart(startNode, 0); |
| 780 | range.setEnd(endNode, endOffset); |
| 781 | const selection = window.getSelection()!; |
| 782 | selection.removeAllRanges(); |
| 783 | selection.addRange(range); |
| 784 | return chatMarkdownClipboardPayload(selection)?.text; |
| 785 | }; |
| 786 | const labelText = label!.lastChild!; |
| 787 | const bodyText = body!.firstChild!; |
| 788 | |
| 789 | expect(select(labelText, bodyText, bodyText.textContent!.length)).toBe( |
| 790 | "> [!WARNING]\n> Back up first.", |
| 791 | ); |
| 792 | expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up"); |
| 793 | }); |
| 794 | |
| 795 | it.each([ |
| 796 | { text: " Plan\nnext" }, |
| 797 | { text: "Plan\n Deep\n Deeper" }, |
| 798 | { text: "Plan\n\tTabbed\n \t Mixed" }, |
| 799 | { text: "- item\n more\n deeper\n- next" }, |
| 800 | { text: "Plan\n Step one\n Detail a", from: "Step one" }, |
| 801 | ])( |
| 802 | "copies and selects user lines the same whether their typed indentation shows: $text", |
| 803 | async (copy) => { |
| 804 | setup(); |
| 805 | const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { |
| 806 | await using screen = await renderText(copy.text, { |
| 807 | className: "user-message-markdown", |
| 808 | lineBreaks: true, |
| 809 | parseRawHtml: false, |
| 810 | extraRemarkPlugins, |
| 811 | }); |
| 812 | const range = document.createRange(); |
| 813 | range.selectNodeContents(screen.container); |
| 814 | if (copy.from) { |
| 815 | const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT); |
| 816 | let line = walker.nextNode(); |
| 817 | while (line && !line.textContent!.includes(copy.from)) line = walker.nextNode(); |
| 818 | // Start mid-line, three characters into the line's text. |
| 819 | range.setStart(line!, line!.textContent!.indexOf(copy.from) + 3); |
| 820 | } |
| 821 | const selection = window.getSelection()!; |
| 822 | selection.removeAllRanges(); |
| 823 | selection.addRange(range); |
| 824 | // A drag or anything else that reads the selection gets its text, not the copy payload. |
| 825 | return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; |
| 826 | }; |
| 827 | const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); |
| 828 | // The user pipeline as it was before typed indentation was shown. |
| 829 | expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); |
| 830 | }, |
| 831 | ); |
| 832 | |
| 833 | it("copies part of inline code without prose escapes", async () => { |
| 834 | setup(); |
| 835 | await using screen = await renderText("Read `items[0]*_x` and a*b*c."); |
| 836 | const code = screen.container.querySelector("p code")!.firstChild!; |
| 837 | const range = document.createRange(); |
| 838 | range.setStart(code, 0); |
| 839 | range.setEnd(code, "items[0]*_".length); |
| 840 | const selection = window.getSelection()!; |
| 841 | selection.removeAllRanges(); |
| 842 | selection.addRange(range); |
| 843 | expect(chatMarkdownClipboardPayload(selection)?.text).toBe("items[0]*_"); |
| 844 | }); |
| 845 | |
| 846 | it.each([ |
| 847 | { |
| 848 | source: "10. First\n11. Second\n12. Third\n\nAfter.", |
| 849 | from: "Second", |
| 850 | text: "11. Second\n12. Third\n\nAfter.", |
| 851 | }, |
| 852 | { |
| 853 | source: "1. A\n2. B\n7. C\n8. D\n\nAfter.", |
| 854 | from: "D", |
| 855 | userMessage: true, |
| 856 | text: "8. D\n\nAfter.", |
| 857 | }, |
| 858 | { |
| 859 | source: "1. Outer\n2. Next\n 1. Inner\n 2. Deeper\n\nAfter.", |
| 860 | from: "Deeper", |
| 861 | text: "2. 2. Deeper\n\nAfter.", |
| 862 | }, |
| 863 | { |
| 864 | source: "1. Install\n2. Configure\n3. Deploy", |
| 865 | from: "Configure", |
| 866 | to: "Deploy", |
| 867 | text: "2. Configure\n3. Deploy", |
| 868 | }, |
| 869 | { |
| 870 | source: "1. A\n2. B\n7. C\n8. D", |
| 871 | from: "B", |
| 872 | to: "C", |
| 873 | userMessage: true, |
| 874 | text: "2. B\n7. C", |
| 875 | }, |
| 876 | { |
| 877 | source: "- Install\n- Configure\n- Deploy", |
| 878 | from: "Configure", |
| 879 | to: "Deploy", |
| 880 | text: "- Configure\n- Deploy", |
| 881 | }, |
| 882 | ])( |
| 883 | "copies $text with the markers its list shows", |
| 884 | async ({ source, from, to, userMessage, text }) => { |
| 885 | setup(); |
| 886 | await using screen = await renderText( |
| 887 | source, |
| 888 | userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {}, |
| 889 | ); |
| 890 | const itemText = (shown: string) => |
| 891 | [...screen.container.querySelectorAll("li")] |
| 892 | .flatMap((item) => [...item.childNodes]) |
| 893 | .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === shown)!; |
| 894 | const end = to |
| 895 | ? itemText(to) |
| 896 | : [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!; |
| 897 | const range = document.createRange(); |
| 898 | range.setStart(itemText(from), 0); |
| 899 | range.setEnd(end, end.textContent!.length); |
| 900 | const selection = window.getSelection()!; |
| 901 | selection.removeAllRanges(); |
| 902 | selection.addRange(range); |
| 903 | const payload = chatMarkdownClipboardPayload(selection); |
| 904 | expect(payload?.text).toBe(text); |
| 905 | // Rich paste reads back as the same list. |
| 906 | expect( |
| 907 | serializeRenderedMarkdownFragment( |
| 908 | new DOMParser().parseFromString(payload!.html, "text/html").body, |
| 909 | ), |
| 910 | ).toBe(text); |
| 911 | }, |
| 912 | ); |
| 913 | |
| 914 | it.each([ |
| 915 | { |
| 916 | source: "1. [ ] Install\n2. [x] Configure\n3. [ ] Test\n4. [x] Deploy", |
| 917 | from: "Configure", |
| 918 | to: "Deploy", |
| 919 | text: "2. [x] Configure\n3. [ ] Test\n4. [x] Deploy", |
| 920 | htmlText: "2. Configure\n3. Test\n4. Deploy", |
| 921 | }, |
| 922 | { |
| 923 | source: |
| 924 | "1. First\n2. [x] Outer\n 1. [ ] Setup\n 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.", |
| 925 | from: "Configure", |
| 926 | text: "2. [x] 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.", |
| 927 | htmlText: "2. 2. Configure\n 3. Deploy\n\nAfter.", |
| 928 | }, |
| 929 | ])( |
| 930 | "copies task items with the markers its list shows: $text", |
| 931 | async ({ source, from, to, text, htmlText }) => { |
| 932 | setup(); |
| 933 | await using screen = await renderText(source); |
| 934 | const itemText = (label: string) => |
| 935 | [...screen.container.querySelectorAll("li")] |
| 936 | .flatMap((item) => [...item.childNodes]) |
| 937 | .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim() === label)!; |
| 938 | const start = itemText(from); |
| 939 | const end = to ? itemText(to) : screen.container.querySelector("p")!.firstChild!; |
| 940 | const range = document.createRange(); |
| 941 | range.setStart(start, start.textContent!.indexOf(from)); |
| 942 | range.setEnd(end, end.textContent!.length); |
| 943 | const selection = window.getSelection()!; |
| 944 | selection.removeAllRanges(); |
| 945 | selection.addRange(range); |
| 946 | const payload = chatMarkdownClipboardPayload(selection); |
| 947 | expect(payload?.text).toBe(text); |
| 948 | // HTML sanitization strips form controls. |
| 949 | expect( |
| 950 | serializeRenderedMarkdownFragment( |
| 951 | new DOMParser().parseFromString(payload!.html, "text/html").body, |
| 952 | ), |
| 953 | ).toBe(htmlText); |
| 954 | }, |
| 955 | ); |
| 956 | |
| 957 | it.each([ |
| 958 | { |
| 959 | source: "1. First\n2. Second\n\nAfter.", |
| 960 | from: "First", |
| 961 | skipFrom: true, |
| 962 | text: "2. Second\n\nAfter.", |
| 963 | items: 1, |
| 964 | }, |
| 965 | { |
| 966 | source: "Before.\n\n1. First\n2. Second", |
| 967 | from: "Before.", |
| 968 | to: "Second", |
| 969 | skipTo: true, |
| 970 | text: "Before.\n\n1. First", |
| 971 | items: 1, |
| 972 | }, |
| 973 | { |
| 974 | source: "1. Outer\n 1. Inner\n 2. Deeper\n2. Next", |
| 975 | from: "Inner", |
| 976 | to: "Next", |
| 977 | skipFrom: true, |
| 978 | text: "1. 2. Deeper\n2. Next", |
| 979 | items: 3, |
| 980 | }, |
| 981 | { |
| 982 | source: "1. Outer\n 1. Inner\n2. Next", |
| 983 | from: "Inner", |
| 984 | to: "Next", |
| 985 | skipFrom: true, |
| 986 | text: "2. Next", |
| 987 | items: 1, |
| 988 | }, |
| 989 | ])( |
| 990 | "omits edge items outside the selection when copying with the markers its list shows: $text", |
| 991 | async ({ source, from, to, skipFrom, skipTo, text, items }) => { |
| 992 | setup(); |
| 993 | await using screen = await renderText(source); |
| 994 | const textNode = (shown: string) => { |
| 995 | const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT); |
| 996 | for (let node = walker.nextNode(); node; node = walker.nextNode()) { |
| 997 | if (node.textContent === shown) return node; |
| 998 | } |
| 999 | throw new Error(`Could not find text: ${shown}`); |
| 1000 | }; |
| 1001 | const end = to ? textNode(to) : textNode("After."); |
| 1002 | const range = document.createRange(); |
| 1003 | range.setStart(textNode(from), skipFrom ? from.length : 0); |
| 1004 | range.setEnd(end, skipTo ? 0 : end.textContent!.length); |
| 1005 | const selection = window.getSelection()!; |
| 1006 | selection.removeAllRanges(); |
| 1007 | selection.addRange(range); |
| 1008 | |
| 1009 | const payload = chatMarkdownClipboardPayload(selection); |
| 1010 | expect(payload?.text).toBe(text); |
| 1011 | const pasted = new DOMParser().parseFromString(payload!.html, "text/html"); |
| 1012 | expect(serializeRenderedMarkdownFragment(pasted.body)).toBe(text); |
| 1013 | expect(pasted.querySelectorAll("li")).toHaveLength(items); |
| 1014 | }, |
| 1015 | ); |
| 1016 | |
| 1017 | it("omits an end item whose selected edge sits inside its link", async () => { |
| 1018 | setup(); |
| 1019 | await using screen = await renderText( |
| 1020 | "1. Install\n2. Configure\n3. Deploy\n4. [Verify](https://example.com/verify)", |
| 1021 | ); |
| 1022 | const items = [...screen.container.querySelectorAll("li")]; |
| 1023 | const start = items.find((item) => item.textContent === "Configure")!.firstChild!; |
| 1024 | const end = items.at(-1)!.querySelector("a > span")!.lastChild!; |
| 1025 | const range = document.createRange(); |
| 1026 | range.setStart(start, 0); |
| 1027 | range.setEnd(end, 0); |
| 1028 | const selection = window.getSelection()!; |
| 1029 | selection.removeAllRanges(); |
| 1030 | selection.addRange(range); |
| 1031 | |
| 1032 | const payload = chatMarkdownClipboardPayload(selection); |
| 1033 | expect(payload?.text).toBe("2. Configure\n3. Deploy"); |
| 1034 | const pasted = new DOMParser().parseFromString(payload!.html, "text/html"); |
| 1035 | expect( |
| 1036 | [...pasted.querySelectorAll('ol[start="2"] > li')].map((item) => item.textContent), |
| 1037 | ).toEqual(["Configure", "Deploy"]); |
| 1038 | }); |
| 1039 | }); |
| 1040 | |
| 1041 | describe("ChatMarkdown file chip tooltips", () => { |
| 1042 | it("wraps a long path so its file name stays inside the tooltip", async () => { |
| 1043 | setup(); |
| 1044 | const path = |
| 1045 | "/tmp/project/packages/client-runtime/src/state/generated/environment-connection-handshake-retry-policy-fixtures.ts"; |
| 1046 | await using screen = await renderText(`See [the fixtures](${path}).`); |
| 1047 | |
| 1048 | await userEvent.hover(screen.container.querySelector(".chat-markdown-file-link")!); |
| 1049 | const tooltip = page.getByText(path); |
| 1050 | await expect.element(tooltip).toBeVisible(); |
| 1051 | |
| 1052 | const popup = tooltip.element().closest("[data-side]")!; |
| 1053 | const pathEnd = document.createRange(); |
| 1054 | pathEnd.selectNodeContents(tooltip.element()); |
| 1055 | expect(pathEnd.getBoundingClientRect().right).toBeLessThanOrEqual( |
| 1056 | popup.getBoundingClientRect().right, |
| 1057 | ); |
| 1058 | }); |
| 1059 | }); |
| 1060 | |
| 1061 | describe("ChatMarkdown editor deep links", () => { |
| 1062 | const hrefs = (container: HTMLElement) => |
| 1063 | [...container.querySelectorAll("a")].map((link) => link.getAttribute("href")); |
| 1064 | |
| 1065 | it("keeps local editor file links", async () => { |
| 1066 | setup(); |
| 1067 | await using screen = await renderText( |
| 1068 | "[file.md line 3](cursor://file/Users/me/repo/file.md:3) and [same](vscode://file/Users/me/repo/file.md:3:7)", |
| 1069 | ); |
| 1070 | expect(hrefs(screen.container)).toEqual([ |
| 1071 | "cursor://file/Users/me/repo/file.md:3", |
| 1072 | "vscode://file/Users/me/repo/file.md:3:7", |
| 1073 | ]); |
| 1074 | }); |
| 1075 | |
| 1076 | it("still drops other editor links and unknown schemes", async () => { |
| 1077 | setup(); |
| 1078 | await using screen = await renderText( |
| 1079 | "[prompt](cursor://anysphere.cursor-deeplink/prompt?text=hi) [user](cursor://me@file/Users/me/file.md) [unknown](foo://file/Users/me/file.md)", |
| 1080 | ); |
| 1081 | expect(screen.container.innerHTML).not.toContain("://"); |
| 1082 | expect(hrefs(screen.container).filter(Boolean)).toEqual([]); |
| 1083 | }); |
| 1084 | }); |
| 1085 | |
| 1086 | describe("ChatMarkdown Windows file links", () => { |
| 1087 | const environmentId = EnvironmentId.make("env-windows"); |
| 1088 | const renderWindows = (text: string, parseRawHtml: boolean) => |
| 1089 | renderText(text, { |
| 1090 | cwd: "C:/Users/shawn/project", |
| 1091 | environmentId, |
| 1092 | lineBreaks: !parseRawHtml, |
| 1093 | parseRawHtml, |
| 1094 | }); |
| 1095 | const fileHrefs = (container: HTMLElement) => |
| 1096 | [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) => |
| 1097 | chip.getAttribute("href"), |
| 1098 | ); |
| 1099 | |
| 1100 | it("still rejects unsafe schemes", async () => { |
| 1101 | setup(); |
| 1102 | for (const parseRawHtml of [true, false]) { |
| 1103 | await using screen = await renderWindows( |
| 1104 | "[unsafe](javascript:alert(1)) and [unknown](d:alert(1))", |
| 1105 | parseRawHtml, |
| 1106 | ); |
| 1107 | const { container } = screen; |
| 1108 | expect(container.innerHTML).not.toContain("javascript:"); |
| 1109 | expect(container.innerHTML).not.toContain("d:alert"); |
| 1110 | expect(fileHrefs(container)).toEqual([]); |
| 1111 | } |
| 1112 | }); |
| 1113 | }); |
| 1114 | |
| 1115 | describe("ChatMarkdown host media", () => { |
| 1116 | it("explains a host video the connection cannot read instead of offering a retry", async () => { |
| 1117 | setup(); |
| 1118 | await using screen = await renderText("", { |
| 1119 | threadRef: { |
| 1120 | environmentId: EnvironmentId.make(deniedEnvironmentId), |
| 1121 | threadId: ThreadId.make("thread"), |
| 1122 | }, |
| 1123 | }); |
| 1124 | await vi.waitFor(() => |
| 1125 | expect(screen.container.textContent).toContain(MISSING_FILE_ACCESS_MESSAGE), |
| 1126 | ); |
| 1127 | expect(screen.container.textContent).not.toContain("Retry video"); |
| 1128 | }); |
| 1129 | }); |