The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; |
| 2 | import { HtmlRenderDocument } from "../files/BrowserDocumentFrame"; |
| 3 | import { flushSync } from "react-dom"; |
| 4 | import { AudioPreview } from "../files/AudioPreview"; |
| 5 | import { cdp, page, userEvent } from "vite-plus/test/browser"; |
| 6 | import { |
| 7 | ComposerContextId, |
| 8 | EnvironmentId, |
| 9 | MessageId, |
| 10 | NodeId, |
| 11 | ProviderDriverKind, |
| 12 | ProviderInstanceId, |
| 13 | RunAttemptId, |
| 14 | RunId, |
| 15 | RuntimeRequestId, |
| 16 | TurnItemId, |
| 17 | ScheduledTaskId, |
| 18 | ThreadId, |
| 19 | type OrchestrationV2Subagent, |
| 20 | } from "@t3tools/contracts"; |
| 21 | import { LegendList, type LegendListRef } from "@legendapp/list/react"; |
| 22 | import { |
| 23 | createRef, |
| 24 | Profiler, |
| 25 | StrictMode, |
| 26 | useState, |
| 27 | type ComponentProps, |
| 28 | type ReactElement, |
| 29 | } from "react"; |
| 30 | import * as DateTime from "effect/DateTime"; |
| 31 | import { Atom, AsyncResult } from "effect/reactivity"; |
| 32 | import { describe, expect, it, onTestFinished, vi } from "vite-plus/test"; |
| 33 | |
| 34 | import "~/index.css"; |
| 35 | |
| 36 | import { environmentThreadDetails } from "../../state/threads"; |
| 37 | import { act, fakeTimers, render, stubGlobal } from "../../../test/render"; |
| 38 | import { ChangedFilesCard } from "./ChangedFilesTree"; |
| 39 | import { MessagesTimeline } from "./MessagesTimeline"; |
| 40 | import { createWorkspaceFocusController, workspaceAreaProps } from "../../lib/workspaceFocus"; |
| 41 | import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic"; |
| 42 | import { makeStreamingTimelineFixture } from "../../test-fixtures"; |
| 43 | import { |
| 44 | type PendingApproval, |
| 45 | deriveTimelineEntriesFromVisibleTurnItems, |
| 46 | } from "../../session-logic"; |
| 47 | import type { Root } from "mdast"; |
| 48 | import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; |
| 49 | import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; |
| 50 | import { TimelineRowCtx } from "./timelineRowContext"; |
| 51 | import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; |
| 52 | import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; |
| 53 | import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; |
| 54 | import { collectThreadFindRanges } from "./threadFindHighlights"; |
| 55 | import { toastManager } from "../ui/toast"; |
| 56 | import type { CitedHistory } from "./citationProcedure"; |
| 57 | import type { TimelineNavigation } from "./timelineViewport"; |
| 58 | import { rememberTimelinePosition } from "./timelineScrollAnchoring"; |
| 59 | import { |
| 60 | COMPOSER_CONTEXT_CLIPBOARD_MIME, |
| 61 | decodeComposerContextFragment, |
| 62 | } from "@t3tools/shared/composerContextClipboard"; |
| 63 | import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences"; |
| 64 | |
| 65 | const environmentQuery = vi.hoisted(() => ({ |
| 66 | error: "Pull request not found" as string | null, |
| 67 | data: null as unknown, |
| 68 | })); |
| 69 | vi.mock(import("~/state/query"), async (original) => ({ |
| 70 | ...(await original()), |
| 71 | useEnvironmentQuery: (() => ({ |
| 72 | data: environmentQuery.data, |
| 73 | dataUpdatedAt: 0, |
| 74 | error: environmentQuery.error, |
| 75 | failure: null, |
| 76 | isPending: false, |
| 77 | isSuccess: false, |
| 78 | refresh: () => {}, |
| 79 | })) as never, |
| 80 | })); |
| 81 | |
| 82 | const stubbedAsset = vi.hoisted(() => ({ url: "" })); |
| 83 | vi.mock(import("~/assets/assetUrls"), async (original) => { |
| 84 | const actual = await original(); |
| 85 | return { |
| 86 | ...actual, |
| 87 | useAssetUrlState: ((...args: Parameters<typeof actual.useAssetUrlState>) => |
| 88 | stubbedAsset.url |
| 89 | ? { _tag: "Success", url: stubbedAsset.url } |
| 90 | : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState, |
| 91 | useAssetUrls: ((...args: Parameters<typeof actual.useAssetUrls>) => |
| 92 | stubbedAsset.url |
| 93 | ? args[1].map(() => stubbedAsset.url) |
| 94 | : actual.useAssetUrls(...args)) as typeof actual.useAssetUrls, |
| 95 | }; |
| 96 | }); |
| 97 | |
| 98 | const ENVIRONMENT_ID = EnvironmentId.make("environment-local"); |
| 99 | const CREATED_AT = "2026-03-17T19:12:28.000Z"; |
| 100 | |
| 101 | type TimelineProps = ComponentProps<typeof MessagesTimeline>; |
| 102 | type Entry = TimelineProps["timelineEntries"][number]; |
| 103 | |
| 104 | // The timeline remembers scroll position and open disclosures per thread key, |
| 105 | // so every render gets a fresh thread. |
| 106 | function baseProps(): Omit<TimelineProps, "timelineEntries"> { |
| 107 | return { |
| 108 | isWorking: false, |
| 109 | listRef: createRef<LegendListRef | null>(), |
| 110 | latestRun: null, |
| 111 | turnDiffSummaries: [], |
| 112 | runs: [], |
| 113 | routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`, |
| 114 | onOpenTurnDiff: () => {}, |
| 115 | onOpenThread: () => {}, |
| 116 | onForkFromRun: async () => {}, |
| 117 | supportsConversationRollback: false, |
| 118 | onRevertToTurnCount: () => {}, |
| 119 | isRevertingCheckpoint: false, |
| 120 | onImageExpand: () => {}, |
| 121 | activeThreadEnvironmentId: ENVIRONMENT_ID, |
| 122 | markdownCwd: undefined, |
| 123 | resolvedTheme: "light", |
| 124 | timestampFormat: "locale", |
| 125 | workspaceRoot: undefined, |
| 126 | anchorMessageId: null, |
| 127 | onAnchorReady: () => {}, |
| 128 | onAnchorSizeChanged: () => {}, |
| 129 | contentInsetEndAdjustment: 0, |
| 130 | emptyPlaceholderInset: 0, |
| 131 | liveFollowEnabled: true, |
| 132 | onIsAtEndChange: () => {}, |
| 133 | }; |
| 134 | } |
| 135 | |
| 136 | function message( |
| 137 | text: string, |
| 138 | overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {}, |
| 139 | id = "message-1", |
| 140 | ): Entry { |
| 141 | return { |
| 142 | id: `entry-${id}`, |
| 143 | kind: "message", |
| 144 | createdAt: CREATED_AT, |
| 145 | message: { |
| 146 | id: MessageId.make(id), |
| 147 | role: "user", |
| 148 | text, |
| 149 | runId: null, |
| 150 | createdAt: CREATED_AT, |
| 151 | updatedAt: CREATED_AT, |
| 152 | streaming: false, |
| 153 | ...overrides, |
| 154 | }, |
| 155 | }; |
| 156 | } |
| 157 | |
| 158 | function work(id: string, entry: Record<string, unknown>): Entry { |
| 159 | return { |
| 160 | id, |
| 161 | kind: "work", |
| 162 | createdAt: CREATED_AT, |
| 163 | entry: { id, createdAt: CREATED_AT, ...entry }, |
| 164 | } as Entry; |
| 165 | } |
| 166 | |
| 167 | function v2Item(type: string, fields: Record<string, unknown>) { |
| 168 | const id = (fields.id as string | undefined) ?? type; |
| 169 | return { |
| 170 | position: 0, |
| 171 | visibility: "local", |
| 172 | sourceThreadId: "thread-1", |
| 173 | sourceItemId: id, |
| 174 | item: { |
| 175 | id, |
| 176 | threadId: "thread-1", |
| 177 | runId: "run-1", |
| 178 | nodeId: null, |
| 179 | providerThreadId: null, |
| 180 | providerTurnId: null, |
| 181 | nativeItemRef: null, |
| 182 | parentItemId: null, |
| 183 | ordinal: 0, |
| 184 | status: "completed", |
| 185 | title: null, |
| 186 | startedAt: null, |
| 187 | completedAt: null, |
| 188 | updatedAt: {}, |
| 189 | type, |
| 190 | ...fields, |
| 191 | }, |
| 192 | } as never; |
| 193 | } |
| 194 | |
| 195 | async function renderElement(element: ReactElement, options: { router?: false } = {}) { |
| 196 | const container = document.createElement("div"); |
| 197 | container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;"; |
| 198 | const screen = await render(element, { container, ...options }); |
| 199 | const buttons = (name: string | RegExp) => |
| 200 | [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => { |
| 201 | const label = button.getAttribute("aria-label") ?? button.textContent ?? ""; |
| 202 | return typeof name === "string" ? label === name : name.test(label); |
| 203 | }); |
| 204 | return Object.assign(screen, { |
| 205 | text: () => container.textContent ?? "", |
| 206 | buttons, |
| 207 | button: (name: string | RegExp) => { |
| 208 | const [match] = buttons(name); |
| 209 | if (!match) throw new Error(`Missing button: ${String(name)}`); |
| 210 | return match; |
| 211 | }, |
| 212 | }); |
| 213 | } |
| 214 | |
| 215 | function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) { |
| 216 | return renderElement( |
| 217 | <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />, |
| 218 | ); |
| 219 | } |
| 220 | |
| 221 | async function click(element: HTMLElement) { |
| 222 | await act(async () => element.click()); |
| 223 | } |
| 224 | |
| 225 | function setup({ scheduledTasks = [] as ReadonlyArray<{ id: string; title: string }> } = {}) { |
| 226 | environmentQuery.error = "Pull request not found"; |
| 227 | environmentQuery.data = { tasks: scheduledTasks }; |
| 228 | } |
| 229 | |
| 230 | const TASK_ID = ScheduledTaskId.make("task-1"); |
| 231 | const AUTOMATION_PROMPT = "Triage the inbox\n\nLabel every new issue and close duplicates."; |
| 232 | |
| 233 | describe("MessagesTimeline work rows", () => { |
| 234 | it("keeps a tall HTML preview in place when its last accordion opens at the bottom", async () => { |
| 235 | const props = baseProps(); |
| 236 | const html = injectHtmlRenderBootstrap(`<div style="height:1400px">Earlier preview content</div> |
| 237 | <details><summary>More rows</summary><div style="height:900px">More rows</div></details> |
| 238 | <script>addEventListener('message', e => { if(e.data === 'toggle') document.querySelector('details').open = !document.querySelector('details').open; }); parent.postMessage('listening', '*');</script>`); |
| 239 | const src = URL.createObjectURL(new Blob([html], { type: "text/html" })); |
| 240 | using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(src) }; |
| 241 | // The frame loads on its own clock, and a toggle posted before its script runs is lost. |
| 242 | const listening = new Promise<void>((resolve) => { |
| 243 | const onMessage = (event: MessageEvent) => { |
| 244 | if (event.data !== "listening") return; |
| 245 | window.removeEventListener("message", onMessage); |
| 246 | resolve(); |
| 247 | }; |
| 248 | window.addEventListener("message", onMessage); |
| 249 | }); |
| 250 | function Preview() { |
| 251 | const [height, setHeight] = useState(1437); |
| 252 | return ( |
| 253 | <div style={{ height }}> |
| 254 | <HtmlRenderDocument |
| 255 | src={src} |
| 256 | title="Tall preview" |
| 257 | className="size-full" |
| 258 | onContentHeight={setHeight} |
| 259 | /> |
| 260 | </div> |
| 261 | ); |
| 262 | } |
| 263 | const container = document.createElement("div"); |
| 264 | container.style.cssText = "height:600px;width:900px;display:flex;flex-direction:column"; |
| 265 | await using screen = await render( |
| 266 | <MessagesTimeline |
| 267 | {...props} |
| 268 | renderHtmlRender={() => <Preview />} |
| 269 | timelineEntries={[ |
| 270 | { |
| 271 | id: "preview", |
| 272 | kind: "html-render", |
| 273 | createdAt: CREATED_AT, |
| 274 | runId: RunId.make("preview-run"), |
| 275 | htmlRender: { attachmentId: "preview", title: "Tall preview", height: 1450 }, |
| 276 | }, |
| 277 | message("Done", { role: "assistant" }, "preview-done"), |
| 278 | ]} |
| 279 | />, |
| 280 | { container }, |
| 281 | ); |
| 282 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 283 | const frame = screen.getByTitle("Tall preview").element() as HTMLIFrameElement; |
| 284 | await vi.waitFor(() => { |
| 285 | expect(frame.clientHeight).toBe(1437); |
| 286 | expect(viewport.scrollTop).toBeGreaterThan(0); |
| 287 | expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); |
| 288 | }); |
| 289 | await listening; |
| 290 | const top = frame.getBoundingClientRect().top; |
| 291 | frame.focus(); |
| 292 | frame.contentWindow!.postMessage("toggle", "*"); |
| 293 | await vi.waitFor(() => { |
| 294 | expect(frame.clientHeight).toBe(2337); |
| 295 | expect(frame.getBoundingClientRect().top).toBeCloseTo(top, 0); |
| 296 | }); |
| 297 | frame.contentWindow!.postMessage("toggle", "*"); |
| 298 | await vi.waitFor(() => { |
| 299 | expect(frame.clientHeight).toBe(1437); |
| 300 | expect(frame.getBoundingClientRect().top).toBeCloseTo(top, 0); |
| 301 | }); |
| 302 | }); |
| 303 | |
| 304 | it("keeps the worked-for heading in place when expanded at the bottom", async () => { |
| 305 | const props = baseProps(); |
| 306 | const runId = RunId.make("completed-run"); |
| 307 | const container = document.createElement("div"); |
| 308 | // Keep the heading on screen so Playwright does not scroll it before clicking. |
| 309 | container.style.cssText = |
| 310 | "height: min(600px, 100vh); width: 900px; display: flex; flex-direction: column;"; |
| 311 | await using screen = await render( |
| 312 | <MessagesTimeline |
| 313 | {...props} |
| 314 | timelineEntries={[ |
| 315 | ...Array.from({ length: 12 }, (_, index) => |
| 316 | message(`Earlier context ${index}`, {}, `context-${index}`), |
| 317 | ), |
| 318 | message("Progress details\n\n".repeat(50), { role: "assistant", runId }, "progress"), |
| 319 | message("Done", { role: "assistant", runId }, "final"), |
| 320 | ]} |
| 321 | />, |
| 322 | { container }, |
| 323 | ); |
| 324 | const heading = screen.getByRole("button", { name: /^Worked for/ }); |
| 325 | // LegendList keeps rows click-through until its initial scroll settles on animation |
| 326 | // frames, which the fake clock below would freeze. |
| 327 | await expect.element(heading).toHaveStyle({ pointerEvents: "auto" }); |
| 328 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 329 | // Legend keeps rows transparent and unclickable until its initial scroll settles. |
| 330 | await vi.waitFor(() => { |
| 331 | expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); |
| 332 | expect(heading.element().checkVisibility({ opacityProperty: true })).toBe(true); |
| 333 | }); |
| 334 | expect(viewport.scrollTop).toBeGreaterThan(0); |
| 335 | const top = heading.element().getBoundingClientRect().top; |
| 336 | const height = viewport.scrollHeight; |
| 337 | using _timers = fakeTimers(); |
| 338 | await heading.click(); |
| 339 | await act(() => vi.advanceTimersByTime(1000)); |
| 340 | await vi.waitFor(() => { |
| 341 | expect(viewport.scrollHeight).toBeGreaterThan(height + 500); |
| 342 | expect(heading.element().getBoundingClientRect().top).toBeCloseTo(top, 0); |
| 343 | expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan( |
| 344 | 500, |
| 345 | ); |
| 346 | }); |
| 347 | }); |
| 348 | |
| 349 | it("keeps following a streaming turn after a heading is expanded at the bottom", async () => { |
| 350 | const props = { ...baseProps(), isWorking: true }; |
| 351 | const runId = RunId.make("live-run"); |
| 352 | const container = document.createElement("div"); |
| 353 | container.style.cssText = |
| 354 | "height: min(600px, 100vh); width: 900px; display: flex; flex-direction: column;"; |
| 355 | const entries = [ |
| 356 | ...Array.from({ length: 12 }, (_, index) => |
| 357 | message(`Earlier context ${index}`, {}, `context-${index}`), |
| 358 | ), |
| 359 | message("Progress details\n\n".repeat(50), { role: "assistant", runId }, "progress"), |
| 360 | message("Done", { role: "assistant", runId }, "final"), |
| 361 | ]; |
| 362 | await using screen = await render(<MessagesTimeline {...props} timelineEntries={entries} />, { |
| 363 | container, |
| 364 | }); |
| 365 | const heading = screen.getByRole("button", { name: /^Worked for/ }); |
| 366 | await expect.element(heading).toHaveStyle({ pointerEvents: "auto" }); |
| 367 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 368 | const distanceFromEnd = () => |
| 369 | viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop; |
| 370 | await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThan(2)); |
| 371 | await heading.click(); |
| 372 | await screen.rerender( |
| 373 | <MessagesTimeline |
| 374 | {...props} |
| 375 | timelineEntries={[ |
| 376 | ...entries, |
| 377 | message("Streamed reply\n\n".repeat(40), { role: "assistant", runId }, "streamed"), |
| 378 | ]} |
| 379 | />, |
| 380 | ); |
| 381 | await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThan(2)); |
| 382 | }); |
| 383 | |
| 384 | it.each(["delegated", "legacy", "missing"] as const)( |
| 385 | "uses the reported task for %s completion notifications", |
| 386 | async (source) => { |
| 387 | setup(); |
| 388 | const now = DateTime.makeUnsafe(CREATED_AT); |
| 389 | const childThreadId = ThreadId.make("shared-child"); |
| 390 | const task = ( |
| 391 | id: string, |
| 392 | status: OrchestrationV2Subagent["status"], |
| 393 | result: string, |
| 394 | ): OrchestrationV2Subagent => ({ |
| 395 | id: NodeId.make(id), |
| 396 | threadId: ThreadId.make("thread-1"), |
| 397 | runId: null, |
| 398 | parentNodeId: NodeId.make("parent-root"), |
| 399 | origin: "app_owned", |
| 400 | createdBy: "agent", |
| 401 | driver: ProviderDriverKind.make("claudeAgent"), |
| 402 | providerInstanceId: ProviderInstanceId.make("claudeAgent"), |
| 403 | providerThreadId: null, |
| 404 | childThreadId, |
| 405 | nativeTaskRef: null, |
| 406 | prompt: "Simplify delivery", |
| 407 | title: "Simplify delivery", |
| 408 | model: null, |
| 409 | status, |
| 410 | result, |
| 411 | startedAt: now, |
| 412 | completedAt: now, |
| 413 | updatedAt: now, |
| 414 | }); |
| 415 | const tasks = [ |
| 416 | task("original", "interrupted", "Old interrupted progress"), |
| 417 | task("continued", "completed", "Final implementation report"), |
| 418 | task("follow-up", "completed", "Follow-up explanation"), |
| 419 | ]; |
| 420 | using _threadAtom = vi.spyOn(environmentThreadDetails, "threadAtom").mockReturnValue( |
| 421 | Atom.make({ |
| 422 | projection: { subagents: tasks, turnItems: [], visibleTurnItems: [] }, |
| 423 | }) as never, |
| 424 | ); |
| 425 | const onOpenThread = vi.fn(); |
| 426 | await using screen = await renderTimeline( |
| 427 | (source === "delegated" ? ["continued", "follow-up"] : [source]).map((id) => |
| 428 | work(`notification-${id}`, { |
| 429 | label: "Notification fallback", |
| 430 | tone: "info", |
| 431 | itemType: "notification", |
| 432 | projectedItem: v2Item("notification", { |
| 433 | id: `notification-${id}`, |
| 434 | source: |
| 435 | source === "legacy" |
| 436 | ? { kind: "subagent", childThreadId } |
| 437 | : { kind: "delegated_task", childThreadId, taskIds: [NodeId.make(id)] }, |
| 438 | outcome: "completed", |
| 439 | summary: "Notification fallback", |
| 440 | }), |
| 441 | }), |
| 442 | ), |
| 443 | { onOpenThread }, |
| 444 | ); |
| 445 | if (source === "delegated") { |
| 446 | expect(screen.text()).toContain("Final implementation report"); |
| 447 | expect(screen.text()).toContain("Follow-up explanation"); |
| 448 | expect(screen.text()).not.toContain("Old interrupted progress"); |
| 449 | await click(screen.buttons("Open Simplify delivery")[0]!); |
| 450 | // A subagent's card says how it was clicked, so it opens beside the thread or in its place. |
| 451 | expect(onOpenThread).toHaveBeenCalledWith(childThreadId, undefined, "primary"); |
| 452 | } else if (source === "legacy") { |
| 453 | expect(screen.text()).toContain("Old interrupted progress"); |
| 454 | } else { |
| 455 | expect(screen.text()).toContain("Notification fallback"); |
| 456 | expect(screen.text()).not.toContain("Old interrupted progress"); |
| 457 | } |
| 458 | }, |
| 459 | ); |
| 460 | }); |
| 461 | |
| 462 | describe("MessagesTimeline messages", () => { |
| 463 | it("settles when equally long messages have very different rendered heights", async () => { |
| 464 | const props = baseProps(); |
| 465 | const tall = message("a\n\n".repeat(6000), { role: "assistant" }, "tall"); |
| 466 | const earlier = Array.from({ length: 80 }, (_, index) => |
| 467 | message( |
| 468 | `<details><summary>Reply ${index}</summary>${"compact ".repeat(2250)}</details>`, |
| 469 | { role: "assistant" }, |
| 470 | `earlier-${index}`, |
| 471 | ), |
| 472 | ); |
| 473 | let nestedCommits = 0; |
| 474 | let maxNestedCommits = 0; |
| 475 | const onRender = (_id: string, phase: string) => { |
| 476 | nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0; |
| 477 | maxNestedCommits = Math.max(maxNestedCommits, nestedCommits); |
| 478 | }; |
| 479 | const timeline = (entries: Entry[]) => ( |
| 480 | <Profiler id="timeline" onRender={onRender}> |
| 481 | <MessagesTimeline {...props} timelineEntries={entries} /> |
| 482 | </Profiler> |
| 483 | ); |
| 484 | await using screen = await renderElement(timeline([tall])); |
| 485 | await vi.waitFor(() => |
| 486 | expect(props.listRef.current?.getState().sizeAtIndex(0)).toBeGreaterThan(100_000), |
| 487 | ); |
| 488 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 489 | await act(() => { |
| 490 | viewport.scrollTop = 0; |
| 491 | viewport.dispatchEvent(new Event("scroll")); |
| 492 | }); |
| 493 | await screen.rerender(timeline([...earlier, tall])); |
| 494 | await act(() => { |
| 495 | void props.listRef.current!.scrollToIndex({ index: 0, animated: false }); |
| 496 | }); |
| 497 | await vi.waitFor(async () => { |
| 498 | await act(() => { |
| 499 | viewport.scrollTop = 0; |
| 500 | viewport.dispatchEvent(new Event("scroll")); |
| 501 | }); |
| 502 | expect(screen.text().includes("Reply 0")).toBe(true); |
| 503 | expect(props.listRef.current!.getState().sizeAtIndex(0)).toBeGreaterThan(0); |
| 504 | }); |
| 505 | expect(maxNestedCommits).toBeLessThan(20); |
| 506 | }); |
| 507 | |
| 508 | it("folds a user message only when the fold hides at least as much as it shows", async () => { |
| 509 | setup(); |
| 510 | const lines = (count: number) => |
| 511 | Array.from({ length: count }, (_, index) => `Line ${index}`).join("\n"); |
| 512 | await using screen = await renderTimeline([ |
| 513 | message(lines(12), {}, "medium"), |
| 514 | message(lines(60), {}, "long"), |
| 515 | ]); |
| 516 | await vi.waitFor(() => expect(screen.buttons("Show full message")).toHaveLength(1)); |
| 517 | const [medium, long] = [ |
| 518 | ...screen.container.querySelectorAll<HTMLElement>("[data-user-message-body]"), |
| 519 | ]; |
| 520 | expect(medium!.dataset.userMessageCollapsible).toBe("false"); |
| 521 | expect(medium!.textContent).toContain("Line 11"); |
| 522 | const foldedHeight = long!.offsetHeight; |
| 523 | await click(screen.button("Show full message")); |
| 524 | expect(long!.offsetHeight).toBeGreaterThanOrEqual(foldedHeight * 2); |
| 525 | }); |
| 526 | |
| 527 | it("keeps the first and last message headings reachable from either end", async () => { |
| 528 | setup(); |
| 529 | const props = baseProps(); |
| 530 | // Folded messages at both ends: their headings must not live inside the fold. |
| 531 | const entries = Array.from({ length: 120 }, (_, index) => |
| 532 | index === 0 |
| 533 | ? message("First turn", { scheduledTaskId: TASK_ID }, "turn-0") |
| 534 | : index === 119 |
| 535 | ? message( |
| 536 | "Last turn", |
| 537 | { createdBy: "agent", senderThreadId: ThreadId.make("thread-sender") }, |
| 538 | "turn-119", |
| 539 | ) |
| 540 | : message( |
| 541 | `Turn ${index}:\n\n${"x ".repeat(200)}`, |
| 542 | { role: index % 2 === 0 ? "user" : "assistant" }, |
| 543 | `turn-${index}`, |
| 544 | ), |
| 545 | ); |
| 546 | await using screen = await renderElement( |
| 547 | <MessagesTimeline {...props} timelineEntries={entries} />, |
| 548 | ); |
| 549 | const headings = () => [...screen.container.querySelectorAll("h3")]; |
| 550 | const headingFor = (text: string) => |
| 551 | headings().find((heading) => heading.parentElement?.textContent?.includes(text)); |
| 552 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 553 | // A screen reader scrolls the heading it moves to into view. |
| 554 | const expectHeadingInView = async (text: string, neighbour: string) => { |
| 555 | await act(() => headingFor(text)!.scrollIntoView({ block: "start" })); |
| 556 | await vi.waitFor(() => expect(screen.text()).toContain(neighbour)); |
| 557 | const row = headingFor(text)!.parentElement!.getBoundingClientRect(); |
| 558 | const view = viewport.getBoundingClientRect(); |
| 559 | expect(row.top).toBeLessThan(view.bottom); |
| 560 | expect(row.bottom).toBeGreaterThan(view.top); |
| 561 | }; |
| 562 | |
| 563 | await vi.waitFor(() => expect(screen.text()).toContain("Turn 118:")); |
| 564 | expect(screen.text()).not.toContain("Turn 60:"); |
| 565 | // Wrapping follows DOM order, so the ends must also sit first and last. |
| 566 | await vi.waitFor(() => { |
| 567 | expect(headings()[0]).toBe(headingFor("First turn")); |
| 568 | expect(headings().at(-1)).toBe(headingFor("Last turn")); |
| 569 | }); |
| 570 | |
| 571 | await expectHeadingInView("First turn", "Turn 1:"); |
| 572 | expect(headingFor("Last turn")).toBeDefined(); |
| 573 | await expectHeadingInView("Last turn", "Turn 118:"); |
| 574 | }); |
| 575 | |
| 576 | it("scrolls from the keyboard once F6 moves into the conversation", async () => { |
| 577 | setup(); |
| 578 | const props = baseProps(); |
| 579 | const entries = Array.from({ length: 40 }, (_, index) => |
| 580 | message(`Turn ${index}:\n\n${"x ".repeat(200)}`, {}, `turn-${index}`), |
| 581 | ); |
| 582 | await using _screen = await renderElement( |
| 583 | <> |
| 584 | <div |
| 585 | {...workspaceAreaProps("conversation", 1, "Conversation")} |
| 586 | className="relative flex min-h-0 flex-1 flex-col" |
| 587 | > |
| 588 | <MessagesTimeline {...props} timelineEntries={entries} /> |
| 589 | </div> |
| 590 | <div {...workspaceAreaProps("composer", 2, "Message input")}> |
| 591 | <button type="button">Send</button> |
| 592 | </div> |
| 593 | </>, |
| 594 | ); |
| 595 | const focus = createWorkspaceFocusController(document); |
| 596 | using _focus = { [Symbol.dispose]: focus.dispose }; |
| 597 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 598 | await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0)); |
| 599 | const atEnd = viewport.scrollTop; |
| 600 | page.getByRole("button", { name: "Send" }).element().focus(); |
| 601 | await userEvent.keyboard("{F6}"); |
| 602 | focus.move(-1); |
| 603 | expect(viewport).toHaveAttribute("data-workspace-keyboard-focus"); |
| 604 | await userEvent.keyboard("{PageUp}"); |
| 605 | await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); |
| 606 | }); |
| 607 | |
| 608 | it("disables the minimap's next turn button at the bottom of the thread", async () => { |
| 609 | setup(); |
| 610 | const props = baseProps(); |
| 611 | const entries = Array.from({ length: 16 }, (_, index) => [ |
| 612 | message(`Question ${index}`, {}, `user-${index}`), |
| 613 | message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`), |
| 614 | ]).flat(); |
| 615 | await using screen = await renderTimeline(entries, props); |
| 616 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 617 | const strips = () => [ |
| 618 | ...screen.container.querySelectorAll<HTMLElement>("[data-minimap-strip]"), |
| 619 | ]; |
| 620 | // Several final turns share the last screen, so the current turn is not the last one. |
| 621 | await vi.waitFor(() => { |
| 622 | expect(viewport.scrollTop).toBeGreaterThan(0); |
| 623 | expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); |
| 624 | expect(strips()[0]?.dataset.inView).toBe("false"); |
| 625 | expect( |
| 626 | strips() |
| 627 | .slice(-2) |
| 628 | .map((strip) => strip.dataset.inView), |
| 629 | ).toEqual(["true", "true"]); |
| 630 | expect(screen.button("Previous turn")).not.toBeDisabled(); |
| 631 | }); |
| 632 | |
| 633 | expect(screen.button("Next turn")).toBeDisabled(); |
| 634 | |
| 635 | viewport.scrollTop -= 30; |
| 636 | await vi.waitFor(() => expect(screen.button("Next turn")).not.toBeDisabled()); |
| 637 | // Legend keeps its initial end anchor until a scroll leaves the end, and re-pins on resize. |
| 638 | viewport.scrollTop = 0; |
| 639 | await vi.waitFor(() => expect(strips()[0]?.dataset.inView).toBe("true")); |
| 640 | |
| 641 | // Shrinking a detached viewport moves the bottom away without a scroll event. |
| 642 | await screen.rerender( |
| 643 | <MessagesTimeline {...props} timelineEntries={entries} liveFollowEnabled={false} />, |
| 644 | ); |
| 645 | viewport.scrollTop = viewport.scrollHeight; |
| 646 | await vi.waitFor(() => expect(screen.button("Next turn")).toBeDisabled()); |
| 647 | screen.container.style.height = "600px"; |
| 648 | await vi.waitFor(() => { |
| 649 | expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan( |
| 650 | 500, |
| 651 | ); |
| 652 | expect(screen.button("Next turn")).not.toBeDisabled(); |
| 653 | }); |
| 654 | |
| 655 | // So does a footer that grows below a detached bottom. |
| 656 | viewport.scrollTop = viewport.scrollHeight; |
| 657 | await vi.waitFor(() => expect(screen.button("Next turn")).toBeDisabled()); |
| 658 | await screen.rerender( |
| 659 | <MessagesTimeline |
| 660 | {...props} |
| 661 | timelineEntries={entries} |
| 662 | liveFollowEnabled={false} |
| 663 | footer={<div style={{ height: 400 }} />} |
| 664 | />, |
| 665 | ); |
| 666 | await vi.waitFor(() => { |
| 667 | expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan( |
| 668 | 300, |
| 669 | ); |
| 670 | expect(screen.button("Next turn")).not.toBeDisabled(); |
| 671 | }); |
| 672 | }); |
| 673 | |
| 674 | it("enables the minimap's next turn button on a thread restored above its bottom", async () => { |
| 675 | setup(); |
| 676 | const base = baseProps(); |
| 677 | const turns = (prefix: string) => |
| 678 | Array.from({ length: 16 }, (_, index) => [ |
| 679 | message(`${prefix} question ${index}`, {}, `${prefix}-user-${index}`), |
| 680 | message(`${prefix} answer ${index}`, { role: "assistant" }, `${prefix}-assistant-${index}`), |
| 681 | ]).flat(); |
| 682 | const other = "environment-local:thread-minimap-restored"; |
| 683 | rememberTimelinePosition( |
| 684 | other, |
| 685 | { rowId: "entry-b-user-4", offsetWithinRow: 0, scrollOffset: 0, atEnd: false }, |
| 686 | false, |
| 687 | ); |
| 688 | await using screen = await renderElement( |
| 689 | <MessagesTimeline {...base} timelineEntries={turns("a")} />, |
| 690 | ); |
| 691 | const viewport = base.listRef.current!.getScrollableNode()!; |
| 692 | await vi.waitFor(() => { |
| 693 | expect(viewport.scrollTop).toBeGreaterThan(0); |
| 694 | expect(screen.button("Next turn")).toBeDisabled(); |
| 695 | }); |
| 696 | |
| 697 | await screen.rerender( |
| 698 | <MessagesTimeline |
| 699 | {...base} |
| 700 | routeThreadKey={other} |
| 701 | timelineEntries={turns("b")} |
| 702 | liveFollowEnabled={false} |
| 703 | />, |
| 704 | ); |
| 705 | await vi.waitFor(() => { |
| 706 | const row = screen.container.querySelector('[data-timeline-row-id="entry-b-user-4"]'); |
| 707 | expect(row).not.toBeNull(); |
| 708 | expect( |
| 709 | Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top), |
| 710 | ).toBeLessThanOrEqual(2); |
| 711 | expect(screen.button("Next turn")).not.toBeDisabled(); |
| 712 | }); |
| 713 | }); |
| 714 | |
| 715 | it("keeps rows in item order after a reload or thread switch, before any timer runs", async () => { |
| 716 | setup(); |
| 717 | // NVDA's browse mode keeps the first DOM order it reads, so a timer that sorts rows later is too late. |
| 718 | using _timers = fakeTimers(); |
| 719 | const thread = (name: string) => |
| 720 | Array.from({ length: 120 }, (_, index) => |
| 721 | message( |
| 722 | `${name} turn ${index}:\n\n${"x ".repeat(200)}`, |
| 723 | { role: index % 2 === 0 ? "user" : "assistant" }, |
| 724 | `${name}-${index}`, |
| 725 | ), |
| 726 | ); |
| 727 | const props = baseProps(); |
| 728 | await using screen = await renderElement( |
| 729 | <MessagesTimeline {...props} timelineEntries={thread("A")} />, |
| 730 | ); |
| 731 | const turnsInDomOrder = () => |
| 732 | [...screen.container.querySelectorAll("h3")].map((heading) => |
| 733 | Number(/turn (\d+):/.exec(heading.parentElement?.textContent ?? "")?.[1]), |
| 734 | ); |
| 735 | const expectItemOrder = () => { |
| 736 | const turns = turnsInDomOrder(); |
| 737 | expect(turns).toEqual(turns.toSorted((a, b) => a - b)); |
| 738 | }; |
| 739 | |
| 740 | expect(screen.text()).toContain("A turn 118:"); |
| 741 | expect(turnsInDomOrder()).toContain(0); |
| 742 | expectItemOrder(); |
| 743 | |
| 744 | await screen.rerender( |
| 745 | <MessagesTimeline |
| 746 | {...props} |
| 747 | routeThreadKey={`${props.routeThreadKey}-other`} |
| 748 | timelineEntries={thread("B")} |
| 749 | />, |
| 750 | ); |
| 751 | expect(screen.text()).toContain("B turn 118:"); |
| 752 | expect(screen.text()).not.toContain("A turn"); |
| 753 | expectItemOrder(); |
| 754 | }); |
| 755 | |
| 756 | it("puts rows back in item order soon after a continuous scroll stops", async () => { |
| 757 | setup(); |
| 758 | const props = baseProps(); |
| 759 | await using screen = await renderElement( |
| 760 | <MessagesTimeline |
| 761 | {...props} |
| 762 | timelineEntries={Array.from({ length: 120 }, (_, index) => |
| 763 | message( |
| 764 | `Turn ${index}:\n\n${"x ".repeat(200)}`, |
| 765 | { role: index % 2 === 0 ? "user" : "assistant" }, |
| 766 | `turn-${index}`, |
| 767 | ), |
| 768 | )} |
| 769 | />, |
| 770 | ); |
| 771 | await vi.waitFor(() => expect(screen.text()).toContain("Turn 118:")); |
| 772 | using _timers = fakeTimers(); |
| 773 | const turnsInDomOrder = () => |
| 774 | [...screen.container.querySelectorAll("h3")].map((heading) => |
| 775 | Number(/Turn (\d+):/.exec(heading.parentElement?.textContent ?? "")?.[1]), |
| 776 | ); |
| 777 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 778 | |
| 779 | const scroll = async (by: number) => { |
| 780 | for (let step = 0; step < 40; step++) { |
| 781 | await act(() => { |
| 782 | viewport.scrollTop += by; |
| 783 | viewport.dispatchEvent(new Event("scroll")); |
| 784 | vi.advanceTimersByTime(16); |
| 785 | }); |
| 786 | } |
| 787 | // Wrapping right after a scroll must still reach the first and last message. |
| 788 | expect(turnsInDomOrder()[0]).toBe(0); |
| 789 | expect(turnsInDomOrder().at(-1)).toBe(119); |
| 790 | }; |
| 791 | |
| 792 | await act(() => { |
| 793 | viewport.scrollTop = 0; |
| 794 | viewport.dispatchEvent(new Event("scroll")); |
| 795 | vi.advanceTimersByTime(300); |
| 796 | }); |
| 797 | await scroll(300); |
| 798 | expect(turnsInDomOrder().filter((turn) => turn > 0 && turn < 100).length).toBeGreaterThan(0); |
| 799 | await scroll(-300); |
| 800 | |
| 801 | await act(() => vi.advanceTimersByTime(300)); |
| 802 | const turns = turnsInDomOrder(); |
| 803 | expect(turns).toEqual(turns.toSorted((a, b) => a - b)); |
| 804 | }); |
| 805 | |
| 806 | it("steps the minimap's next turn past two adjacent user messages", async () => { |
| 807 | const props = baseProps(); |
| 808 | const reply = (id: string) => message("Reply.\n\n".repeat(120), { role: "assistant" }, id); |
| 809 | const userIds = ["turn-0", "turn-1", "turn-2", "pair-a", "pair-b", "turn-3", "turn-4"]; |
| 810 | const entries = [ |
| 811 | ...["turn-0", "turn-1", "turn-2"].flatMap((id) => [message(id, {}, id), reply(`${id}-r`)]), |
| 812 | message("pair-a", {}, "pair-a"), |
| 813 | message("pair-b", {}, "pair-b"), |
| 814 | reply("pair-b-r"), |
| 815 | ...["turn-3", "turn-4"].flatMap((id) => [message(id, {}, id), reply(`${id}-r`)]), |
| 816 | ]; |
| 817 | const session = cdp(); |
| 818 | await session.send("Emulation.setEmulatedMedia", { |
| 819 | features: [{ name: "prefers-reduced-motion", value: "reduce" }], |
| 820 | }); |
| 821 | try { |
| 822 | await using screen = await renderTimeline(entries, props); |
| 823 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 824 | const strips = () => [...screen.container.querySelectorAll("[data-minimap-strip]")]; |
| 825 | const turnAtTop = () => |
| 826 | userIds.find((id) => { |
| 827 | const row = screen.container.querySelector(`[data-message-id="${id}"]`); |
| 828 | if (!row) return false; |
| 829 | const offset = row.getBoundingClientRect().top - viewport.getBoundingClientRect().top; |
| 830 | return offset >= 0 && offset < 100; |
| 831 | }); |
| 832 | await act(() => { |
| 833 | void props.listRef.current!.scrollToIndex({ index: 0, animated: false }); |
| 834 | }); |
| 835 | await vi.waitFor(() => expect(strips()[0]?.getAttribute("data-in-view")).toBe("true")); |
| 836 | |
| 837 | // Clicks again while the view has not moved, as a user would. |
| 838 | for (const id of userIds.slice(1)) { |
| 839 | const from = turnAtTop(); |
| 840 | await vi.waitFor(async () => { |
| 841 | if (turnAtTop() === from) await click(screen.button("Next turn")); |
| 842 | expect(turnAtTop(), "turn at the top after Next turn").toBe(id); |
| 843 | }); |
| 844 | } |
| 845 | } finally { |
| 846 | await session.send("Emulation.setEmulatedMedia", { features: [] }); |
| 847 | } |
| 848 | }); |
| 849 | |
| 850 | it("preserves XML-like tags and comparisons in user messages as text", async () => { |
| 851 | const source = [ |
| 852 | 'Without reading a file, do you have <global-agent-instructions scope="workspace">', |
| 853 | 'Before <nested data-value="a&b">inside</nested> after', |
| 854 | "</global-agent-instructions> in your context?", |
| 855 | "Comparison: 2 < 3 and 5 > 4.", |
| 856 | ]; |
| 857 | await using screen = await renderTimeline([message(source.join("\n"))]); |
| 858 | for (const line of source) expect(screen.text()).toContain(line); |
| 859 | expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull(); |
| 860 | }); |
| 861 | |
| 862 | it("renders unsafe user HTML as inert source text", async () => { |
| 863 | const source = |
| 864 | '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">'; |
| 865 | await using screen = await renderTimeline([message(source)]); |
| 866 | expect(screen.text()).toContain(source); |
| 867 | expect(screen.container.querySelector("script, img")).toBeNull(); |
| 868 | expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); |
| 869 | }); |
| 870 | |
| 871 | it("shows the spaces typed at the start of user lines, where find also matches them", async () => { |
| 872 | const source = "Plan\n Step one\n\tDetail"; |
| 873 | await using screen = await renderTimeline([ |
| 874 | message(source), |
| 875 | message(source, { role: "assistant" }, "assistant-1"), |
| 876 | ]); |
| 877 | const [user, assistant] = screen.container.querySelectorAll<HTMLElement>( |
| 878 | "[data-timeline-row-kind=message]", |
| 879 | ); |
| 880 | expect(user?.querySelector<HTMLElement>("[data-user-message-body]")?.innerText).toBe(source); |
| 881 | expect(assistant?.querySelector<HTMLElement>(".chat-markdown")?.innerText).toBe( |
| 882 | "Plan Step one Detail", |
| 883 | ); |
| 884 | const query = " Step one"; |
| 885 | const indexed = searchableMessageSegments({ role: "user", text: source, streaming: false }); |
| 886 | const ranges = collectThreadFindRanges(screen.container, query); |
| 887 | expect(ranges.map(({ rowId, range }) => [rowId, range.toString()])).toEqual([ |
| 888 | [user?.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id"), query], |
| 889 | ]); |
| 890 | expect( |
| 891 | indexed?.reduce((count, segment) => count + countThreadSearchOccurrences(segment, query), 0), |
| 892 | ).toBe(ranges.length); |
| 893 | }); |
| 894 | |
| 895 | it("keeps single tildes in user paths literal without changing double tildes or assistant text", async () => { |
| 896 | const source = |
| 897 | "Install the skill as ~/folder-a/skills/x, then follow the guide (~/folder-a/guide.md)."; |
| 898 | await using screen = await renderTimeline([ |
| 899 | message(source), |
| 900 | message("Drop ~~the old plan~~", {}, "message-2"), |
| 901 | message(source, { role: "assistant" }, "assistant-1"), |
| 902 | ]); |
| 903 | const [user, doubleTilde, assistant] = screen.container.querySelectorAll<HTMLElement>( |
| 904 | "[data-timeline-row-kind=message]", |
| 905 | ); |
| 906 | expect(user?.textContent).toContain(source); |
| 907 | expect(user?.querySelector("del")).toBeNull(); |
| 908 | expect(doubleTilde?.querySelector("del")?.textContent).toBe("the old plan"); |
| 909 | expect(assistant?.querySelector("del")?.textContent).toBe( |
| 910 | "/folder-a/skills/x, then follow the guide (", |
| 911 | ); |
| 912 | }); |
| 913 | |
| 914 | it("renders sanitized raw HTML in assistant messages", async () => { |
| 915 | await using screen = await renderTimeline([ |
| 916 | message( |
| 917 | [ |
| 918 | '<details onclick="globalThis.__t3Xss = 1">', |
| 919 | "<summary>Safe details</summary>", |
| 920 | "<script>globalThis.__t3Xss = 2</script>", |
| 921 | '<img src="x" onerror="globalThis.__t3Xss = 3">', |
| 922 | '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>', |
| 923 | "</details>", |
| 924 | ].join(""), |
| 925 | { role: "assistant" }, |
| 926 | ), |
| 927 | ]); |
| 928 | expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain( |
| 929 | "Safe details", |
| 930 | ); |
| 931 | expect(screen.text()).not.toContain("<details"); |
| 932 | expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull(); |
| 933 | expect(screen.container.innerHTML).not.toContain("javascript:"); |
| 934 | await click(screen.button("Safe details")); |
| 935 | expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); |
| 936 | }); |
| 937 | |
| 938 | const revealModes = ["inline", "at-end", "delayed", "grouped-delayed", "grouped-end"]; |
| 939 | it.each(revealModes)("reveals %s output", async (mode) => { |
| 940 | const inline = mode === "inline" || mode === "at-end"; |
| 941 | setup(); |
| 942 | environmentQuery.data = |
| 943 | mode === "grouped-end" |
| 944 | ? { |
| 945 | output: { text: `${"output line\n".repeat(10)}TOOL_INPUT_END`, truncated: false }, |
| 946 | running: false, |
| 947 | } |
| 948 | : null; |
| 949 | environmentQuery.error = null; |
| 950 | const props = baseProps(); |
| 951 | const composerOverlayHeight = mode === "grouped-end" ? 140 : 200; |
| 952 | const tallEntries = Array.from({ length: 12 }, (_, index) => |
| 953 | message( |
| 954 | `Message ${index}\n\n${"Long paragraph. ".repeat(80)}`, |
| 955 | { role: "assistant" }, |
| 956 | `tall-${index}`, |
| 957 | ), |
| 958 | ); |
| 959 | const projectedItem = makeStreamingTimelineFixture().visibleTurnItems[1]!; |
| 960 | const source = { |
| 961 | detail: () => Atom.make(AsyncResult.initial()), |
| 962 | commandOutput: () => Atom.make(AsyncResult.initial()), |
| 963 | }; |
| 964 | let outerGrowth = false; |
| 965 | let routeThreadKey = props.routeThreadKey; |
| 966 | const timeline = () => ( |
| 967 | <MessagesTimeline |
| 968 | {...props} |
| 969 | routeThreadKey={routeThreadKey} |
| 970 | liveFollowEnabled={false} |
| 971 | {...(inline |
| 972 | ? {} |
| 973 | : { |
| 974 | turnItemSource: { |
| 975 | detail: () => source.detail(), |
| 976 | commandOutput: () => source.commandOutput(), |
| 977 | }, |
| 978 | })} |
| 979 | contentInsetEndAdjustment={composerOverlayHeight} |
| 980 | timelineEntries={[ |
| 981 | ...tallEntries.slice(0, 6), |
| 982 | { |
| 983 | id: "tool-near-composer", |
| 984 | kind: "work", |
| 985 | createdAt: CREATED_AT, |
| 986 | entry: { |
| 987 | id: "tool-near-composer", |
| 988 | createdAt: CREATED_AT, |
| 989 | label: "Example tool", |
| 990 | toolTitle: "Example tool", |
| 991 | tone: "tool", |
| 992 | itemType: "dynamic_tool", |
| 993 | toolLifecycleStatus: "completed", |
| 994 | toolData: { input: { query: `${"x".repeat(1200)} TOOL_INPUT_END` } }, |
| 995 | ...(inline |
| 996 | ? {} |
| 997 | : { |
| 998 | itemType: "command_execution", |
| 999 | projectedItem, |
| 1000 | structuredPayload: projectedItem.item, |
| 1001 | }), |
| 1002 | }, |
| 1003 | }, |
| 1004 | ...(mode.startsWith("grouped-") |
| 1005 | ? [ |
| 1006 | { |
| 1007 | id: "another-tool", |
| 1008 | kind: "work" as const, |
| 1009 | createdAt: CREATED_AT, |
| 1010 | entry: { |
| 1011 | id: "another-tool", |
| 1012 | createdAt: CREATED_AT, |
| 1013 | label: "Other tool", |
| 1014 | tone: "tool" as const, |
| 1015 | itemType: "dynamic_tool" as const, |
| 1016 | toolLifecycleStatus: "completed" as const, |
| 1017 | toolData: { input: { query: "other" } }, |
| 1018 | }, |
| 1019 | }, |
| 1020 | ] |
| 1021 | : []), |
| 1022 | ...(mode === "grouped-end" |
| 1023 | ? [message("Completed.", { role: "assistant" }, "final-message")] |
| 1024 | : mode === "at-end" |
| 1025 | ? [message("Done.", { role: "assistant" }, "final-message")] |
| 1026 | : tallEntries.slice(6)), |
| 1027 | ...(outerGrowth |
| 1028 | ? [message("Later output\n\n".repeat(20), { role: "assistant" }, "outer-growth")] |
| 1029 | : []), |
| 1030 | ]} |
| 1031 | /> |
| 1032 | ); |
| 1033 | await using screen = await renderElement( |
| 1034 | mode === "grouped-delayed" ? ( |
| 1035 | <MessagesTimeline {...props} timelineEntries={[message("Previous thread")]} /> |
| 1036 | ) : ( |
| 1037 | timeline() |
| 1038 | ), |
| 1039 | ); |
| 1040 | if (mode === "grouped-end") screen.container.style.height = "648px"; |
| 1041 | await vi.waitFor(() => expect(props.listRef.current?.getScrollableNode()).toBeTruthy()); |
| 1042 | const viewport = props.listRef.current!.getScrollableNode()!; |
| 1043 | if (mode === "grouped-delayed") { |
| 1044 | routeThreadKey = `${routeThreadKey}-switched`; |
| 1045 | await screen.rerender(timeline()); |
| 1046 | await vi.waitFor(() => expect(viewport.scrollHeight).toBeGreaterThan(3000)); |
| 1047 | await act(() => viewport.dispatchEvent(new WheelEvent("wheel", { deltaY: -1 }))); |
| 1048 | } |
| 1049 | if (mode.startsWith("grouped-")) { |
| 1050 | await act(() => { |
| 1051 | void props.listRef.current!.scrollToIndex({ index: 6, animated: false }); |
| 1052 | }); |
| 1053 | await vi.waitFor(() => |
| 1054 | expect( |
| 1055 | screen.container.querySelector('[data-timeline-row-kind="work-toggle"] button'), |
| 1056 | ).not.toBeNull(), |
| 1057 | ); |
| 1058 | const group = () => |
| 1059 | screen.container.querySelector<HTMLElement>( |
| 1060 | '[data-timeline-row-kind="work-toggle"] button', |
| 1061 | )!; |
| 1062 | await click(group()); |
| 1063 | await vi.waitFor(() => |
| 1064 | expect( |
| 1065 | screen.container.querySelector('[data-work-entry-id="tool-near-composer"]'), |
| 1066 | ).not.toBeNull(), |
| 1067 | ); |
| 1068 | if (mode === "grouped-delayed") { |
| 1069 | await click( |
| 1070 | screen.container.querySelector<HTMLElement>('[data-work-entry-id="tool-near-composer"]')!, |
| 1071 | ); |
| 1072 | await vi.waitFor(() => expect(screen.text()).toContain("Loading output")); |
| 1073 | await click(group()); |
| 1074 | } |
| 1075 | } |
| 1076 | const header = () => { |
| 1077 | if (mode === "grouped-end") |
| 1078 | return screen.container.querySelector<HTMLElement>( |
| 1079 | '[data-work-entry-id="tool-near-composer"]', |
| 1080 | )!; |
| 1081 | if (mode === "grouped-delayed") |
| 1082 | return screen.container.querySelector<HTMLElement>( |
| 1083 | '[data-timeline-row-kind="work-toggle"] button', |
| 1084 | )!; |
| 1085 | const rows = screen.container.querySelectorAll<HTMLElement>( |
| 1086 | '[data-timeline-row-kind="work"] [role="button"]', |
| 1087 | ); |
| 1088 | if (!rows[0]) throw new Error(screen.text()); |
| 1089 | return rows[0]; |
| 1090 | }; |
| 1091 | const visibleBottom = () => viewport.getBoundingClientRect().bottom - composerOverlayHeight; |
| 1092 | await act(() => { |
| 1093 | void props.listRef.current!.scrollToIndex({ index: 6, animated: false }); |
| 1094 | }); |
| 1095 | if (mode === "at-end") { |
| 1096 | await act(() => { |
| 1097 | void props.listRef.current!.scrollToEnd({ animated: false }); |
| 1098 | }); |
| 1099 | await vi.waitFor(() => |
| 1100 | expect(resolveTimelineIsAtEnd(props.listRef.current!.getState())).toBe(true), |
| 1101 | ); |
| 1102 | } else { |
| 1103 | await vi.waitFor(async () => { |
| 1104 | await act(() => { |
| 1105 | viewport.scrollTop += header().getBoundingClientRect().bottom - (visibleBottom() - 8); |
| 1106 | viewport.dispatchEvent(new Event("scroll")); |
| 1107 | }); |
| 1108 | expect(resolveTimelineIsAtEnd(props.listRef.current!.getState())).toBe(false); |
| 1109 | expect(header().getBoundingClientRect().bottom).toBeLessThanOrEqual(visibleBottom()); |
| 1110 | expect(header().getBoundingClientRect().top).toBeGreaterThan( |
| 1111 | viewport.getBoundingClientRect().top, |
| 1112 | ); |
| 1113 | }); |
| 1114 | } |
| 1115 | |
| 1116 | const collapsedScrollTop = viewport.scrollTop; |
| 1117 | using scrollBy = vi.spyOn(viewport, "scrollBy"); |
| 1118 | // The nested row can measure before the outer scroller gains its new range. |
| 1119 | if (mode === "grouped-delayed") scrollBy.mockImplementationOnce(() => {}); |
| 1120 | await click(header()); |
| 1121 | if (mode === "grouped-delayed") { |
| 1122 | await vi.waitFor(() => expect(scrollBy).toHaveBeenCalled()); |
| 1123 | outerGrowth = true; |
| 1124 | await screen.rerender(timeline()); |
| 1125 | await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(collapsedScrollTop)); |
| 1126 | } |
| 1127 | if (!inline && mode !== "grouped-end") { |
| 1128 | await vi.waitFor(() => |
| 1129 | expect(header().getBoundingClientRect().bottom).toBeLessThanOrEqual(visibleBottom() + 1), |
| 1130 | ); |
| 1131 | await vi.waitFor(() => expect(screen.text()).toContain("Loading output")); |
| 1132 | environmentQuery.data = { |
| 1133 | output: { text: `${"output line\n".repeat(20)}TOOL_INPUT_END`, truncated: false }, |
| 1134 | running: false, |
| 1135 | }; |
| 1136 | await screen.rerender(timeline()); |
| 1137 | } |
| 1138 | const inputEnd = () => |
| 1139 | Array.from(screen.container.querySelectorAll<HTMLElement>("*")).findLast((element) => |
| 1140 | element.textContent?.includes("TOOL_INPUT_END"), |
| 1141 | )!; |
| 1142 | await vi.waitFor(() => |
| 1143 | expect(inputEnd().getBoundingClientRect().bottom).toBeLessThanOrEqual(visibleBottom() + 1), |
| 1144 | ); |
| 1145 | await vi.waitFor(() => |
| 1146 | expect(header().getBoundingClientRect().top).toBeGreaterThanOrEqual( |
| 1147 | viewport.getBoundingClientRect().top, |
| 1148 | ), |
| 1149 | ); |
| 1150 | }); |
| 1151 | }); |
| 1152 | |
| 1153 | function usageLimitEntries(resetAt: string) { |
| 1154 | const threadId = ThreadId.make("usage-limit-thread"); |
| 1155 | const at = DateTime.makeUnsafe(CREATED_AT); |
| 1156 | return deriveTimelineEntriesFromVisibleTurnItems({ |
| 1157 | visibleTurnItems: [ |
| 1158 | { |
| 1159 | position: 0, |
| 1160 | visibility: "local", |
| 1161 | sourceThreadId: threadId, |
| 1162 | sourceItemId: TurnItemId.make("usage-limit"), |
| 1163 | item: { |
| 1164 | id: TurnItemId.make("usage-limit"), |
| 1165 | threadId, |
| 1166 | runId: RunId.make("usage-limit-run"), |
| 1167 | nodeId: null, |
| 1168 | providerThreadId: null, |
| 1169 | providerTurnId: null, |
| 1170 | nativeItemRef: null, |
| 1171 | parentItemId: null, |
| 1172 | ordinal: 0, |
| 1173 | title: null, |
| 1174 | startedAt: at, |
| 1175 | completedAt: at, |
| 1176 | updatedAt: at, |
| 1177 | type: "error", |
| 1178 | status: "failed", |
| 1179 | failure: { |
| 1180 | class: "usage_limit", |
| 1181 | message: "You've hit your usage limit.", |
| 1182 | code: null, |
| 1183 | retryable: true, |
| 1184 | resetAt, |
| 1185 | }, |
| 1186 | }, |
| 1187 | }, |
| 1188 | ], |
| 1189 | optimisticMessages: [], |
| 1190 | }); |
| 1191 | } |
| 1192 | |
| 1193 | describe("MessagesTimeline usage limit notice", () => { |
| 1194 | it("labels the retry time with the viewer's timezone", async () => { |
| 1195 | await using screen = await renderTimeline(usageLimitEntries("2026-03-17T19:30:00.000Z")); |
| 1196 | const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; |
| 1197 | expect(screen.text()).toMatch(/Usage limit reached\. Retry after .+\./); |
| 1198 | expect(screen.text()).toContain(`(${timeZone})`); |
| 1199 | }); |
| 1200 | |
| 1201 | it("keeps the retry time in the named zone after the viewer's timezone changes", async () => { |
| 1202 | const resetAt = "2026-07-01T19:30:00.000Z"; |
| 1203 | const session = cdp(); |
| 1204 | await session.send("Emulation.setTimezoneOverride", { timezoneId: "Europe/Madrid" }); |
| 1205 | try { |
| 1206 | { |
| 1207 | await using _madrid = await renderTimeline(usageLimitEntries(resetAt)); |
| 1208 | } |
| 1209 | await session.send("Emulation.setTimezoneOverride", { timezoneId: "America/New_York" }); |
| 1210 | await using screen = await renderTimeline(usageLimitEntries(resetAt)); |
| 1211 | const newYorkTime = new Date(resetAt).toLocaleTimeString(undefined, { |
| 1212 | hour: "numeric", |
| 1213 | minute: "2-digit", |
| 1214 | timeZone: "America/New_York", |
| 1215 | }); |
| 1216 | expect(screen.text()).toContain(`${newYorkTime} (America/New_York)`); |
| 1217 | } finally { |
| 1218 | await session.send("Emulation.setTimezoneOverride", { timezoneId: "" }); |
| 1219 | } |
| 1220 | }); |
| 1221 | }); |
| 1222 | |
| 1223 | const CITATION_REQUEST = { |
| 1224 | key: "activation-1", |
| 1225 | citation: { |
| 1226 | version: 1, |
| 1227 | environmentId: ENVIRONMENT_ID, |
| 1228 | threadId: ThreadId.make("thread-cited"), |
| 1229 | messageId: MessageId.make("cited"), |
| 1230 | text: "the cited answer", |
| 1231 | start: 0, |
| 1232 | end: 16, |
| 1233 | prefix: "", |
| 1234 | suffix: "", |
| 1235 | }, |
| 1236 | } satisfies NonNullable<TimelineProps["citationRequest"]>; |
| 1237 | |
| 1238 | describe("MessagesTimeline citations", () => { |
| 1239 | it("offers Cite for text an agent sent with send_to_user", async () => { |
| 1240 | const text = "The draft the next question refers to"; |
| 1241 | await using screen = await renderTimeline( |
| 1242 | [ |
| 1243 | { |
| 1244 | id: "sent", |
| 1245 | kind: "sent-message", |
| 1246 | createdAt: CREATED_AT, |
| 1247 | runId: RunId.make("run-sent"), |
| 1248 | text, |
| 1249 | }, |
| 1250 | ], |
| 1251 | { onCiteAssistantText: () => true }, |
| 1252 | ); |
| 1253 | await expect.element(screen.getByText(text)).toHaveStyle({ pointerEvents: "auto" }); |
| 1254 | await userEvent.tripleClick(screen.getByText(text)); |
| 1255 | await expect |
| 1256 | .element(page.getByRole("button", { name: "Cite selection in composer" })) |
| 1257 | .toBeVisible(); |
| 1258 | }); |
| 1259 | |
| 1260 | it("lands a citation present at mount under StrictMode", async () => { |
| 1261 | await using _screen = await renderElement( |
| 1262 | <StrictMode> |
| 1263 | <MessagesTimeline |
| 1264 | {...baseProps()} |
| 1265 | timelineEntries={[ |
| 1266 | message("A question", {}, "question"), |
| 1267 | message("the cited answer", { role: "assistant" }, "cited"), |
| 1268 | ]} |
| 1269 | citationRequest={CITATION_REQUEST} |
| 1270 | citationHistory={{ _tag: "found" }} |
| 1271 | /> |
| 1272 | </StrictMode>, |
| 1273 | // The test router mounts route content without StrictMode's effect replay. |
| 1274 | { router: false }, |
| 1275 | ); |
| 1276 | // StrictMode replays effect cleanups on mount; the activation must survive them. |
| 1277 | await vi.waitFor(() => |
| 1278 | expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain( |
| 1279 | "the cited answer", |
| 1280 | ), |
| 1281 | ); |
| 1282 | }); |
| 1283 | |
| 1284 | it("moves focus to the cited response so screen readers follow it", async () => { |
| 1285 | await using _screen = await renderTimeline( |
| 1286 | [ |
| 1287 | message("A question", {}, "question"), |
| 1288 | message("the cited answer", { role: "assistant" }, "cited"), |
| 1289 | ], |
| 1290 | { citationRequest: CITATION_REQUEST, citationHistory: { _tag: "found" } }, |
| 1291 | ); |
| 1292 | await vi.waitFor(() => { |
| 1293 | const cited = document.querySelector("[data-citation-highlighted]"); |
| 1294 | expect(cited?.textContent).toContain("the cited answer"); |
| 1295 | expect(cited?.contains(document.activeElement)).toBe(true); |
| 1296 | }); |
| 1297 | }); |
| 1298 | |
| 1299 | it("opens the superseded attempt that folds the cited response", async () => { |
| 1300 | const runId = RunId.make("run-steered"); |
| 1301 | const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({ |
| 1302 | id: RunAttemptId.make(id), |
| 1303 | runId, |
| 1304 | attemptOrdinal: ordinal, |
| 1305 | rootNodeId: `node-${id}` as never, |
| 1306 | status, |
| 1307 | completedAt: null, |
| 1308 | }); |
| 1309 | const superseded = attempt("attempt-1", 1, "superseded"); |
| 1310 | const active = attempt("attempt-2", 2, "running"); |
| 1311 | const inAttempt = (entry: Entry, entryAttempt: typeof superseded): Entry => ({ |
| 1312 | ...entry, |
| 1313 | attempt: entryAttempt, |
| 1314 | }); |
| 1315 | await using _screen = await renderTimeline( |
| 1316 | [ |
| 1317 | inAttempt(message("Build it", { runId }, "question"), superseded), |
| 1318 | inAttempt(message("the cited answer", { role: "assistant", runId }, "cited"), superseded), |
| 1319 | inAttempt(message("Change direction", { runId }, "steer"), active), |
| 1320 | inAttempt(message("Current response", { role: "assistant", runId }, "current"), active), |
| 1321 | ], |
| 1322 | { |
| 1323 | latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null }, |
| 1324 | citationRequest: CITATION_REQUEST, |
| 1325 | citationHistory: { _tag: "found" }, |
| 1326 | }, |
| 1327 | ); |
| 1328 | await vi.waitFor(() => |
| 1329 | expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain( |
| 1330 | "the cited answer", |
| 1331 | ), |
| 1332 | ); |
| 1333 | }); |
| 1334 | |
| 1335 | it("waits for cited history to load before giving up on a response outside the window", async () => { |
| 1336 | using toast = vi.spyOn(toastManager, "add"); |
| 1337 | const props = baseProps(); |
| 1338 | const citationRequest = CITATION_REQUEST; |
| 1339 | const recent = message("A recent question", {}, "recent"); |
| 1340 | const timeline = (entries: Entry[], citationHistory: CitedHistory) => ( |
| 1341 | <MessagesTimeline |
| 1342 | {...props} |
| 1343 | timelineEntries={entries} |
| 1344 | citationRequest={citationRequest} |
| 1345 | citationHistory={citationHistory} |
| 1346 | /> |
| 1347 | ); |
| 1348 | await using screen = await renderElement(timeline([recent], { _tag: "loading" })); |
| 1349 | await expect.element(screen.getByText("A recent question")).toBeVisible(); |
| 1350 | |
| 1351 | await screen.rerender( |
| 1352 | timeline([message("the cited answer", { role: "assistant" }, "cited"), recent], { |
| 1353 | _tag: "found", |
| 1354 | }), |
| 1355 | ); |
| 1356 | await expect.element(screen.getByText("the cited answer")).toBeVisible(); |
| 1357 | expect(toast).not.toHaveBeenCalled(); |
| 1358 | }); |
| 1359 | }); |
| 1360 | |
| 1361 | describe("MessagesTimeline automation prompts", () => { |
| 1362 | it("folds an automation prompt into a bubble titled by its task", async () => { |
| 1363 | setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] }); |
| 1364 | await using screen = await renderTimeline([ |
| 1365 | message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }), |
| 1366 | ]); |
| 1367 | const row = screen.button(/^Automation/); |
| 1368 | expect(row.textContent).toContain("Nightly triage"); |
| 1369 | expect(row.getAttribute("aria-expanded")).toBe("false"); |
| 1370 | expect(screen.text()).not.toContain("close duplicates"); |
| 1371 | |
| 1372 | await click(row); |
| 1373 | expect(screen.text()).toContain("Label every new issue and close duplicates."); |
| 1374 | const link = [...screen.container.querySelectorAll("a")].find( |
| 1375 | (anchor) => anchor.textContent === "Open automation", |
| 1376 | ); |
| 1377 | expect(link?.getAttribute("href")).toContain(`taskId=${TASK_ID}`); |
| 1378 | expect(screen.buttons(/copy/i)).not.toHaveLength(0); |
| 1379 | }); |
| 1380 | |
| 1381 | it("falls back to the prompt's first line without a task title", async () => { |
| 1382 | setup(); |
| 1383 | await using screen = await renderTimeline([ |
| 1384 | message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }), |
| 1385 | ]); |
| 1386 | expect(screen.button(/^Automation/).textContent).toContain("Triage the inbox"); |
| 1387 | }); |
| 1388 | |
| 1389 | it("leaves ordinary user messages as full bubbles", async () => { |
| 1390 | setup(); |
| 1391 | await using screen = await renderTimeline([message(AUTOMATION_PROMPT)]); |
| 1392 | expect(screen.buttons(/^Automation/)).toHaveLength(0); |
| 1393 | expect(screen.text()).toContain("Label every new issue and close duplicates."); |
| 1394 | }); |
| 1395 | |
| 1396 | it("reveals a find match beyond the folded automation prompt's initial viewport", async () => { |
| 1397 | setup(); |
| 1398 | const prompt = `${"Inspect the next item.\n\n".repeat(16)}Close duplicates.`; |
| 1399 | await using screen = await renderTimeline([message(prompt, { scheduledTaskId: TASK_ID })], { |
| 1400 | findExpanded: true, |
| 1401 | findQuery: "duplicates", |
| 1402 | activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 }, |
| 1403 | }); |
| 1404 | await vi.waitFor(() => |
| 1405 | expect(screen.button(/^Automation/).getAttribute("aria-expanded")).toBe("true"), |
| 1406 | ); |
| 1407 | const { range } = collectThreadFindRanges(screen.container, "duplicates")[0]!; |
| 1408 | const details = screen.container.querySelector("[data-thread-find-text]")!; |
| 1409 | expect(range.getBoundingClientRect().top - details.getBoundingClientRect().top).toBeGreaterThan( |
| 1410 | 384, |
| 1411 | ); |
| 1412 | expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual( |
| 1413 | details.getBoundingClientRect().bottom, |
| 1414 | ); |
| 1415 | }); |
| 1416 | |
| 1417 | it("shows edit-from-here once an automation prompt is expanded", async () => { |
| 1418 | setup(); |
| 1419 | const runId = RunId.make("run-1"); |
| 1420 | await using screen = await renderTimeline( |
| 1421 | [ |
| 1422 | message( |
| 1423 | AUTOMATION_PROMPT, |
| 1424 | { scheduledTaskId: TASK_ID, runId, inputIntent: "turn_start" }, |
| 1425 | "user-1", |
| 1426 | ), |
| 1427 | message("Done", { role: "assistant", runId }, "assistant-1"), |
| 1428 | ], |
| 1429 | { |
| 1430 | supportsConversationRollback: true, |
| 1431 | threadStartCheckpointAvailable: true, |
| 1432 | turnDiffSummaries: [ |
| 1433 | { |
| 1434 | runId, |
| 1435 | checkpointTurnCount: 1, |
| 1436 | checkpointRef: "checkpoint-1" as never, |
| 1437 | status: "ready", |
| 1438 | files: [], |
| 1439 | assistantMessageId: MessageId.make("assistant-1"), |
| 1440 | completedAt: CREATED_AT, |
| 1441 | }, |
| 1442 | ], |
| 1443 | }, |
| 1444 | ); |
| 1445 | expect(screen.buttons("Edit from here")).toHaveLength(0); |
| 1446 | await click(screen.button(/^Automation/)); |
| 1447 | expect(screen.buttons("Edit from here")).toHaveLength(1); |
| 1448 | }); |
| 1449 | }); |
| 1450 | |
| 1451 | const SENDER_THREAD_ID = ThreadId.make("thread-sender"); |
| 1452 | const AGENT_MESSAGE = "Review finished\n\nThe migration drops the index before backfilling it."; |
| 1453 | |
| 1454 | describe("MessagesTimeline agent messages", () => { |
| 1455 | it("folds a message from another agent into a one-line preview", async () => { |
| 1456 | setup(); |
| 1457 | const onOpenThread = vi.fn(); |
| 1458 | await using screen = await renderTimeline( |
| 1459 | [ |
| 1460 | message(AGENT_MESSAGE, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID }), |
| 1461 | // Sent from a linked environment this client does not reach. |
| 1462 | message( |
| 1463 | "Linked review finished", |
| 1464 | { |
| 1465 | createdBy: "agent", |
| 1466 | linkedSender: { |
| 1467 | environmentId: EnvironmentId.make("environment-linked"), |
| 1468 | threadId: SENDER_THREAD_ID, |
| 1469 | title: "Release lead", |
| 1470 | }, |
| 1471 | }, |
| 1472 | "message-linked", |
| 1473 | ), |
| 1474 | ], |
| 1475 | { onOpenThread }, |
| 1476 | ); |
| 1477 | const row = screen.button(/^Agent/); |
| 1478 | expect(row.textContent).toContain("Review finished"); |
| 1479 | expect(row.getAttribute("aria-expanded")).toBe("false"); |
| 1480 | expect(screen.text()).not.toContain("drops the index"); |
| 1481 | expect(screen.buttons("Open thread")).toHaveLength(0); |
| 1482 | |
| 1483 | await click(row); |
| 1484 | expect(screen.text()).toContain("The migration drops the index before backfilling it."); |
| 1485 | await click(screen.button("Open thread")); |
| 1486 | expect(onOpenThread).toHaveBeenCalledWith(SENDER_THREAD_ID, ENVIRONMENT_ID); |
| 1487 | |
| 1488 | await click(screen.button(/^Agent/)); |
| 1489 | expect(screen.text()).not.toContain("drops the index"); |
| 1490 | |
| 1491 | // The linked sender shows the title it sent, and its thread cannot be opened from here. |
| 1492 | await click(screen.button(/^Release lead/)); |
| 1493 | expect(screen.buttons("Open thread")).toHaveLength(0); |
| 1494 | }); |
| 1495 | |
| 1496 | it("leaves messages sent by T3 Code as full bubbles", async () => { |
| 1497 | setup(); |
| 1498 | await using screen = await renderTimeline([ |
| 1499 | message(AGENT_MESSAGE, { createdBy: "agent", creationSource: "server" }), |
| 1500 | ]); |
| 1501 | expect(screen.buttons(/^Agent/)).toHaveLength(0); |
| 1502 | expect(screen.text()).toContain("drops the index"); |
| 1503 | }); |
| 1504 | |
| 1505 | it("reveals a find match inside a folded agent message", async () => { |
| 1506 | setup(); |
| 1507 | const text = `${"Checked the next file.\n\n".repeat(16)}The migration drops the index.`; |
| 1508 | await using screen = await renderTimeline( |
| 1509 | [message(text, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })], |
| 1510 | { |
| 1511 | findExpanded: true, |
| 1512 | findQuery: "drops the index", |
| 1513 | activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 }, |
| 1514 | }, |
| 1515 | ); |
| 1516 | await vi.waitFor(() => |
| 1517 | expect(screen.button(/^Agent/).getAttribute("aria-expanded")).toBe("true"), |
| 1518 | ); |
| 1519 | const { range } = collectThreadFindRanges(screen.container, "drops the index")[0]!; |
| 1520 | const body = screen.container.querySelector("[data-user-message-body]")!; |
| 1521 | expect(range.getBoundingClientRect().height).toBeGreaterThan(0); |
| 1522 | expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual( |
| 1523 | body.getBoundingClientRect().bottom, |
| 1524 | ); |
| 1525 | }); |
| 1526 | }); |
| 1527 | |
| 1528 | describe("MessagesTimeline attachments", () => { |
| 1529 | it.each(["image", "file"] as const)( |
| 1530 | "copies only matching context records for a wordless %s attachment", |
| 1531 | async (kind) => { |
| 1532 | const attachment = { |
| 1533 | type: kind, |
| 1534 | id: "media", |
| 1535 | name: kind === "image" ? "photo.png" : "clip.mp4", |
| 1536 | mimeType: kind === "image" ? "image/png" : "video/mp4", |
| 1537 | sizeBytes: 100, |
| 1538 | downloadable: false, |
| 1539 | }; |
| 1540 | const record = { |
| 1541 | version: 1 as const, |
| 1542 | ...(kind === "image" ? { kind: "image" as const } : { kind: "file" as const }), |
| 1543 | contextId: ComposerContextId.make("media-context"), |
| 1544 | label: attachment.name, |
| 1545 | attachmentId: attachment.id, |
| 1546 | name: attachment.name, |
| 1547 | mimeType: attachment.mimeType, |
| 1548 | sizeBytes: attachment.sizeBytes, |
| 1549 | }; |
| 1550 | await using screen = await renderTimeline([message("", { attachments: [attachment] })]); |
| 1551 | expect(screen.buttons("Copy message")).toHaveLength(0); |
| 1552 | await screen.rerender( |
| 1553 | <MessagesTimeline |
| 1554 | {...baseProps()} |
| 1555 | timelineEntries={[ |
| 1556 | message("", { |
| 1557 | attachments: [attachment], |
| 1558 | context: { version: 1, records: [{ ...record, attachmentId: "other" }] }, |
| 1559 | }), |
| 1560 | ]} |
| 1561 | />, |
| 1562 | ); |
| 1563 | expect(screen.buttons("Copy message")).toHaveLength(0); |
| 1564 | await screen.rerender( |
| 1565 | <MessagesTimeline |
| 1566 | {...baseProps()} |
| 1567 | timelineEntries={[ |
| 1568 | message("", { |
| 1569 | attachments: [attachment], |
| 1570 | context: { |
| 1571 | version: 1, |
| 1572 | records: [ |
| 1573 | record, |
| 1574 | { |
| 1575 | ...record, |
| 1576 | contextId: ComposerContextId.make("other-context"), |
| 1577 | attachmentId: "other", |
| 1578 | }, |
| 1579 | ], |
| 1580 | }, |
| 1581 | }), |
| 1582 | ]} |
| 1583 | />, |
| 1584 | ); |
| 1585 | using write = vi.spyOn(navigator.clipboard, "write").mockResolvedValue(); |
| 1586 | await click(screen.button("Copy message")); |
| 1587 | await vi.waitFor(() => expect(write).toHaveBeenCalledOnce()); |
| 1588 | const [item] = write.mock.calls[0]![0]; |
| 1589 | const text = await (await item!.getType("text/plain")).text(); |
| 1590 | const fragment = await (await item!.getType(COMPOSER_CONTEXT_CLIPBOARD_MIME)).text(); |
| 1591 | expect( |
| 1592 | collectComposerContextReferences(text).map((reference) => reference.contextId), |
| 1593 | ).toEqual([record.contextId]); |
| 1594 | expect(decodeComposerContextFragment(fragment)?.records).toEqual([record]); |
| 1595 | }, |
| 1596 | ); |
| 1597 | |
| 1598 | it.each(["loadedmetadata", "loadeddata", "canplay"])( |
| 1599 | "plays audio with unknown duration after %s and updates the total later", |
| 1600 | async (readyEvent) => { |
| 1601 | const onOpen = vi.fn(); |
| 1602 | const preview = (failed = false) => ( |
| 1603 | <AudioPreview |
| 1604 | compact |
| 1605 | src="data:audio/webm;base64," |
| 1606 | name="recording.webm" |
| 1607 | failed={failed} |
| 1608 | onOpen={onOpen} |
| 1609 | /> |
| 1610 | ); |
| 1611 | await using screen = await renderElement(<div dir="rtl">{preview()}</div>); |
| 1612 | const audio = screen.container.querySelector("audio")!; |
| 1613 | const duration = vi.spyOn(audio, "duration", "get").mockReturnValue(Infinity); |
| 1614 | const play = vi.spyOn(audio, "play").mockResolvedValue(); |
| 1615 | expect(screen.button("Loading recording.webm")).toHaveProperty("disabled", true); |
| 1616 | await act(() => audio.dispatchEvent(new Event(readyEvent))); |
| 1617 | expect(screen.button("Play recording.webm")).toHaveProperty("disabled", false); |
| 1618 | expect(screen.text()).toContain("0:00"); |
| 1619 | expect(screen.text()).not.toContain("/"); |
| 1620 | await click(screen.button("Play recording.webm")); |
| 1621 | expect(play).toHaveBeenCalledOnce(); |
| 1622 | await act(() => { |
| 1623 | vi.spyOn(audio, "currentTime", "get").mockReturnValue(3); |
| 1624 | audio.dispatchEvent(new Event("play")); |
| 1625 | audio.dispatchEvent(new Event("timeupdate")); |
| 1626 | }); |
| 1627 | expect(screen.button("Pause recording.webm")).toHaveProperty("disabled", false); |
| 1628 | expect(screen.text()).toContain("0:03"); |
| 1629 | const progress = screen.container.querySelector<HTMLElement>("span[aria-hidden]")!; |
| 1630 | expect(progress.style.width).toBe("0%"); |
| 1631 | await act(() => { |
| 1632 | duration.mockReturnValue(10); |
| 1633 | audio.dispatchEvent(new Event("durationchange")); |
| 1634 | }); |
| 1635 | expect(screen.text()).toContain("0:03 / 0:10"); |
| 1636 | expect( |
| 1637 | getComputedStyle(screen.container.querySelector("audio")!.previousElementSibling!) |
| 1638 | .direction, |
| 1639 | ).toBe("ltr"); |
| 1640 | expect(progress.style.width).toBe("30%"); |
| 1641 | await act(() => { |
| 1642 | duration.mockReturnValue(NaN); |
| 1643 | audio.dispatchEvent(new Event("durationchange")); |
| 1644 | }); |
| 1645 | expect(screen.text()).not.toContain("/"); |
| 1646 | expect(progress.style.width).toBe("0%"); |
| 1647 | expect(screen.button("Pause recording.webm")).toHaveProperty("disabled", false); |
| 1648 | await screen.rerender(preview(true)); |
| 1649 | expect(screen.text()).toContain("Unavailable"); |
| 1650 | await click(screen.button("Audio unavailable. Open recording.webm")); |
| 1651 | expect(onOpen).toHaveBeenCalledOnce(); |
| 1652 | }, |
| 1653 | ); |
| 1654 | |
| 1655 | it.each(["pause", "error"])("unpins audio after %s", async (event) => { |
| 1656 | const NativeObserver = IntersectionObserver; |
| 1657 | using _observer = stubGlobal( |
| 1658 | "IntersectionObserver", |
| 1659 | class extends NativeObserver { |
| 1660 | constructor( |
| 1661 | private readonly notify: IntersectionObserverCallback, |
| 1662 | options?: IntersectionObserverInit, |
| 1663 | ) { |
| 1664 | super(notify, options); |
| 1665 | } |
| 1666 | override observe(target: Element) { |
| 1667 | this.notify([{ target, isIntersecting: true } as IntersectionObserverEntry], this); |
| 1668 | } |
| 1669 | }, |
| 1670 | ); |
| 1671 | const src = |
| 1672 | "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA"; |
| 1673 | stubbedAsset.url = src; |
| 1674 | onTestFinished(() => { |
| 1675 | stubbedAsset.url = ""; |
| 1676 | }); |
| 1677 | const props = baseProps(); |
| 1678 | await using screen = await renderTimeline( |
| 1679 | [ |
| 1680 | // The first message row is always mounted, so the recordings go in the second. |
| 1681 | message("Start of the thread.", { role: "user" }, "opening"), |
| 1682 | message( |
| 1683 | "Two recordings.", |
| 1684 | { |
| 1685 | attachments: ["one", "two"].map((name) => ({ |
| 1686 | type: "file", |
| 1687 | id: `attachment-${name}`, |
| 1688 | name: `${name}.wav`, |
| 1689 | mimeType: "audio/wav", |
| 1690 | sizeBytes: 45, |
| 1691 | previewUrl: src, |
| 1692 | })), |
| 1693 | }, |
| 1694 | "audio", |
| 1695 | ), |
| 1696 | ...Array.from({ length: 40 }, (_, index) => |
| 1697 | message("Conversation history. ".repeat(40), { role: "user" }, `history-${index}`), |
| 1698 | ), |
| 1699 | ], |
| 1700 | props, |
| 1701 | ); |
| 1702 | screen.container.style.height = "600px"; |
| 1703 | screen.container.scrollIntoView({ block: "start" }); |
| 1704 | await vi.waitFor( |
| 1705 | async () => { |
| 1706 | await act(() => { |
| 1707 | void props.listRef.current?.scrollToIndex({ index: 1, animated: false }); |
| 1708 | }); |
| 1709 | expect(screen.container.querySelectorAll("audio")).toHaveLength(2); |
| 1710 | }, |
| 1711 | { timeout: 5000 }, |
| 1712 | ); |
| 1713 | const [one, two] = [...screen.container.querySelectorAll("audio")]; |
| 1714 | await act(async () => { |
| 1715 | vi.spyOn(one!, "paused", "get").mockReturnValue(false); |
| 1716 | vi.spyOn(two!, "paused", "get").mockReturnValue(false); |
| 1717 | one!.dispatchEvent(new Event("play")); |
| 1718 | two!.dispatchEvent(new Event("play")); |
| 1719 | }); |
| 1720 | await vi.waitFor(async () => { |
| 1721 | await act(() => { |
| 1722 | void props.listRef.current!.scrollToEnd({ animated: false }); |
| 1723 | }); |
| 1724 | const scroll = props.listRef.current!.getScrollableNode()!; |
| 1725 | expect(scroll.scrollTop).toBeGreaterThan(5000); |
| 1726 | }); |
| 1727 | expect(one!.isConnected).toBe(true); |
| 1728 | expect(two!.isConnected).toBe(true); |
| 1729 | await act(async () => { |
| 1730 | vi.spyOn(one!, "paused", "get").mockReturnValue(true); |
| 1731 | one!.dispatchEvent(new Event("pause")); |
| 1732 | }); |
| 1733 | expect(two!.isConnected).toBe(true); |
| 1734 | await act(async () => { |
| 1735 | if (event === "pause") vi.spyOn(two!, "paused", "get").mockReturnValue(true); |
| 1736 | two!.dispatchEvent(new Event(event)); |
| 1737 | }); |
| 1738 | await act(() => { |
| 1739 | void props.listRef.current!.scrollToIndex({ index: 20, animated: false }); |
| 1740 | }); |
| 1741 | await vi.waitFor(() => expect(one!.isConnected).toBe(false)); |
| 1742 | }); |
| 1743 | |
| 1744 | it("opens a viewed image as a gallery of the images beside it", async () => { |
| 1745 | stubbedAsset.url = |
| 1746 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; |
| 1747 | onTestFinished(() => { |
| 1748 | stubbedAsset.url = ""; |
| 1749 | }); |
| 1750 | const onImageExpand = vi.fn<ComponentProps<typeof MessagesTimeline>["onImageExpand"]>(); |
| 1751 | await using screen = await renderElement( |
| 1752 | <TimelineRowCtx |
| 1753 | value={ |
| 1754 | { |
| 1755 | threadRef: { environmentId: ENVIRONMENT_ID, threadId: ThreadId.make("thread-1") }, |
| 1756 | workspaceRoot: "/repo", |
| 1757 | onImageExpand, |
| 1758 | } as never |
| 1759 | } |
| 1760 | > |
| 1761 | <ViewedImagesTimelineRow |
| 1762 | row={{ |
| 1763 | kind: "viewed-images", |
| 1764 | id: "viewed", |
| 1765 | createdAt: CREATED_AT, |
| 1766 | paths: ["/repo/first.png", "/repo/second.png", "/repo/third.png"], |
| 1767 | }} |
| 1768 | /> |
| 1769 | </TimelineRowCtx>, |
| 1770 | ); |
| 1771 | await screen.getByRole("button", { name: "Preview second.png" }).click(); |
| 1772 | expect(onImageExpand).toHaveBeenCalledExactlyOnceWith( |
| 1773 | expect.objectContaining({ |
| 1774 | index: 1, |
| 1775 | images: ["first.png", "second.png", "third.png"].map((name) => |
| 1776 | expect.objectContaining({ name }), |
| 1777 | ), |
| 1778 | }), |
| 1779 | ); |
| 1780 | }); |
| 1781 | |
| 1782 | it("opens an image from an expanded tool row as a gallery of the turn's viewed images", async () => { |
| 1783 | stubbedAsset.url = |
| 1784 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; |
| 1785 | onTestFinished(() => { |
| 1786 | stubbedAsset.url = ""; |
| 1787 | }); |
| 1788 | const onImageExpand = vi.fn<ComponentProps<typeof MessagesTimeline>["onImageExpand"]>(); |
| 1789 | const read = (name: string) => |
| 1790 | work(`read-${name}`, { |
| 1791 | label: `Read ${name}`, |
| 1792 | toolTitle: "Read", |
| 1793 | tone: "tool", |
| 1794 | itemType: "dynamic_tool", |
| 1795 | toolLifecycleStatus: "completed", |
| 1796 | viewedImagePath: `/repo/${name}`, |
| 1797 | }); |
| 1798 | await using screen = await renderTimeline( |
| 1799 | [read("first.png"), read("second.png"), read("third.png")], |
| 1800 | { onImageExpand, workspaceRoot: "/repo" }, |
| 1801 | ); |
| 1802 | await click(screen.button(/^Read 3 files/)); |
| 1803 | await vi.waitFor(() => expect(screen.buttons("Read")).toHaveLength(3)); |
| 1804 | await click(screen.buttons("Read")[1]!); |
| 1805 | const inRow = await vi.waitFor(() => { |
| 1806 | const image = [...screen.container.querySelectorAll("img")].find( |
| 1807 | (img) => img.alt === "second.png" && !img.closest("[data-image-gallery]"), |
| 1808 | ); |
| 1809 | expect(image).toBeTruthy(); |
| 1810 | return image!; |
| 1811 | }); |
| 1812 | await click(inRow.closest<HTMLElement>("button, [role=button]")!); |
| 1813 | expect(onImageExpand).toHaveBeenCalledExactlyOnceWith( |
| 1814 | expect.objectContaining({ |
| 1815 | index: 1, |
| 1816 | images: ["first.png", "second.png", "third.png"].map((name) => |
| 1817 | expect.objectContaining({ name }), |
| 1818 | ), |
| 1819 | }), |
| 1820 | ); |
| 1821 | }); |
| 1822 | }); |
| 1823 | |
| 1824 | describe("MessagesTimeline thread find", () => { |
| 1825 | // Opening find is navigation; on a list already showing the thread the open |
| 1826 | // action navigates, so the list itself releases follow only when it starts |
| 1827 | // showing a thread whose find is already open. |
| 1828 | function renderObserved() { |
| 1829 | const navigations: TimelineNavigation[] = []; |
| 1830 | const base = baseProps(); |
| 1831 | const element = (next: Partial<TimelineProps>) => ( |
| 1832 | <MessagesTimeline |
| 1833 | {...base} |
| 1834 | timelineEntries={[message("Where is the sidebar fix?")]} |
| 1835 | onViewportAttach={(viewport) => |
| 1836 | viewport.subscribe((navigation) => navigations.push(navigation)) |
| 1837 | } |
| 1838 | {...next} |
| 1839 | /> |
| 1840 | ); |
| 1841 | return { navigations, element }; |
| 1842 | } |
| 1843 | const released = { source: "command", releasesFollow: true }; |
| 1844 | |
| 1845 | it("reveals the previous match in a table without scrolling a sibling table", async () => { |
| 1846 | setup(); |
| 1847 | const columns = Array.from({ length: 12 }, (_, index) => `DiagnosticsColumn${index}`); |
| 1848 | const cells = ["needle", ...columns.slice(1, -1), "needle"]; |
| 1849 | const table = [columns, columns.map(() => "---"), cells] |
| 1850 | .map((row) => `| ${row.join(" | ")} |`) |
| 1851 | .join("\n"); |
| 1852 | const entry = message(`${table}\n\n${table}`); |
| 1853 | const props = { |
| 1854 | ...baseProps(), |
| 1855 | timelineEntries: [entry], |
| 1856 | liveFollowEnabled: false, |
| 1857 | findOpen: true, |
| 1858 | findExpanded: true, |
| 1859 | findQuery: "needle", |
| 1860 | }; |
| 1861 | const element = (occurrence: number, navigationId: number) => ( |
| 1862 | <MessagesTimeline |
| 1863 | {...props} |
| 1864 | activeFindMatch={{ entryId: entry.id, runId: null, occurrence }} |
| 1865 | findNavigationId={navigationId} |
| 1866 | /> |
| 1867 | ); |
| 1868 | await using screen = await renderElement(element(1, 1)); |
| 1869 | const [viewport, sibling] = await vi.waitFor(() => { |
| 1870 | const tables = screen.container.querySelectorAll<HTMLElement>( |
| 1871 | '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', |
| 1872 | ); |
| 1873 | expect(tables).toHaveLength(2); |
| 1874 | return [tables[0]!, tables[1]!] as const; |
| 1875 | }); |
| 1876 | viewport.scrollLeft = viewport.scrollWidth; |
| 1877 | sibling.scrollLeft = sibling.scrollWidth; |
| 1878 | const siblingOffset = sibling.scrollLeft; |
| 1879 | const clip = viewport.getBoundingClientRect(); |
| 1880 | expect(viewport.querySelector("td")!.getBoundingClientRect().right).toBeLessThan(clip.left); |
| 1881 | expect(siblingOffset).toBeGreaterThan(0); |
| 1882 | |
| 1883 | await screen.rerender(element(0, 2)); |
| 1884 | await vi.waitFor(() => { |
| 1885 | const [match] = CSS.highlights.get("t3-thread-find-active") ?? []; |
| 1886 | if (!(match instanceof Range)) throw new Error("Missing active match range"); |
| 1887 | expect(match.startContainer.parentElement?.closest("td")).toBe(viewport.querySelector("td")); |
| 1888 | expect(match.getBoundingClientRect().left).toBeGreaterThanOrEqual(clip.left - 1); |
| 1889 | }); |
| 1890 | expect(sibling.scrollLeft).toBe(siblingOffset); |
| 1891 | }); |
| 1892 | |
| 1893 | it("reveals a match in a nested table clipped by the outer table", async () => { |
| 1894 | setup(); |
| 1895 | const columns = Array.from({ length: 12 }, (_, index) => `<td>DiagnosticsColumn${index}</td>`); |
| 1896 | const entry = message( |
| 1897 | `<table><tbody><tr>${columns.join("")}<td><table><tbody><tr><td>needle</td></tr></tbody></table></td></tr></tbody></table>`, |
| 1898 | { role: "assistant" }, |
| 1899 | ); |
| 1900 | const props = { |
| 1901 | ...baseProps(), |
| 1902 | timelineEntries: [entry], |
| 1903 | liveFollowEnabled: false, |
| 1904 | findOpen: true, |
| 1905 | findExpanded: true, |
| 1906 | findQuery: "needle", |
| 1907 | }; |
| 1908 | await using screen = await renderElement(<MessagesTimeline {...props} />); |
| 1909 | const outerViewport = await vi.waitFor(() => { |
| 1910 | const viewport = screen.container.querySelector( |
| 1911 | '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', |
| 1912 | ); |
| 1913 | const nestedCell = viewport?.querySelector("table table td"); |
| 1914 | expect(nestedCell?.textContent).toBe("needle"); |
| 1915 | expect(nestedCell!.getBoundingClientRect().left).toBeGreaterThan( |
| 1916 | viewport!.getBoundingClientRect().right, |
| 1917 | ); |
| 1918 | return viewport!; |
| 1919 | }); |
| 1920 | |
| 1921 | await screen.rerender( |
| 1922 | <MessagesTimeline |
| 1923 | {...props} |
| 1924 | activeFindMatch={{ entryId: entry.id, runId: null, occurrence: 0 }} |
| 1925 | findNavigationId={1} |
| 1926 | />, |
| 1927 | ); |
| 1928 | await vi.waitFor(() => { |
| 1929 | const [match] = CSS.highlights.get("t3-thread-find-active") ?? []; |
| 1930 | if (!(match instanceof Range)) throw new Error("Missing active match range"); |
| 1931 | const bounds = match.getBoundingClientRect(); |
| 1932 | const clip = outerViewport.getBoundingClientRect(); |
| 1933 | expect(bounds.left).toBeGreaterThanOrEqual(clip.left - 1); |
| 1934 | expect(bounds.right).toBeLessThanOrEqual(clip.right + 1); |
| 1935 | }); |
| 1936 | }); |
| 1937 | |
| 1938 | it("releases follow once when it starts showing a thread whose find is open", async () => { |
| 1939 | setup(); |
| 1940 | const { navigations, element } = renderObserved(); |
| 1941 | await using screen = await renderElement(element({})); |
| 1942 | expect(navigations).toEqual([]); |
| 1943 | |
| 1944 | const other = "environment-local:thread-find-open"; |
| 1945 | await screen.rerender(element({ routeThreadKey: other, findOpen: true })); |
| 1946 | expect(navigations).toEqual([released]); |
| 1947 | await screen.rerender(element({ routeThreadKey: other, findOpen: false })); |
| 1948 | await screen.rerender(element({ routeThreadKey: other, findOpen: true })); |
| 1949 | expect(navigations).toEqual([released]); |
| 1950 | }); |
| 1951 | |
| 1952 | it("releases follow once when it mounts on a thread whose find is open", async () => { |
| 1953 | setup(); |
| 1954 | const { navigations, element } = renderObserved(); |
| 1955 | await using screen = await renderElement(element({ findOpen: true })); |
| 1956 | await screen.rerender(element({ findOpen: true })); |
| 1957 | expect(navigations).toEqual([released]); |
| 1958 | }); |
| 1959 | |
| 1960 | it("still restores the position of a thread it switches to whose find is open", async () => { |
| 1961 | setup(); |
| 1962 | const base = baseProps(); |
| 1963 | const other = "environment-local:thread-find-open-positioned"; |
| 1964 | const replies = Array.from({ length: 40 }, (_, index) => |
| 1965 | message(`Reply ${index}\n\n${"line\n\n".repeat(8)}`, { role: "assistant" }, `r-${index}`), |
| 1966 | ); |
| 1967 | rememberTimelinePosition( |
| 1968 | other, |
| 1969 | { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false }, |
| 1970 | false, |
| 1971 | ); |
| 1972 | await using screen = await renderElement( |
| 1973 | <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />, |
| 1974 | ); |
| 1975 | await screen.rerender( |
| 1976 | <MessagesTimeline |
| 1977 | {...base} |
| 1978 | routeThreadKey={other} |
| 1979 | timelineEntries={replies} |
| 1980 | liveFollowEnabled={false} |
| 1981 | findOpen |
| 1982 | />, |
| 1983 | ); |
| 1984 | const viewport = base.listRef.current!.getScrollableNode()!; |
| 1985 | await vi.waitFor(() => { |
| 1986 | const row = screen.container.querySelector('[data-timeline-row-id="entry-r-20"]'); |
| 1987 | expect(row).not.toBeNull(); |
| 1988 | expect( |
| 1989 | Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top), |
| 1990 | ).toBeLessThanOrEqual(2); |
| 1991 | }); |
| 1992 | }); |
| 1993 | it("reveals find's match, not the remembered row, on a thread it switches to", async () => { |
| 1994 | setup(); |
| 1995 | const base = baseProps(); |
| 1996 | const other = "environment-local:thread-find-open-match"; |
| 1997 | const replies = Array.from({ length: 40 }, (_, index) => |
| 1998 | message( |
| 1999 | `${index === 5 ? "Needle here" : `Reply ${index}`}\n\n${"line\n\n".repeat(8)}`, |
| 2000 | { role: "assistant" }, |
| 2001 | `r-${index}`, |
| 2002 | ), |
| 2003 | ); |
| 2004 | rememberTimelinePosition( |
| 2005 | other, |
| 2006 | { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false }, |
| 2007 | false, |
| 2008 | ); |
| 2009 | await using screen = await renderElement( |
| 2010 | <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />, |
| 2011 | ); |
| 2012 | await screen.rerender( |
| 2013 | <MessagesTimeline |
| 2014 | {...base} |
| 2015 | routeThreadKey={other} |
| 2016 | timelineEntries={replies} |
| 2017 | liveFollowEnabled={false} |
| 2018 | findOpen |
| 2019 | findExpanded |
| 2020 | findQuery="Needle" |
| 2021 | activeFindMatch={{ entryId: "entry-r-5", runId: null, occurrence: 0 }} |
| 2022 | />, |
| 2023 | ); |
| 2024 | const viewport = base.listRef.current!.getScrollableNode()!; |
| 2025 | await vi.waitFor(() => { |
| 2026 | const row = screen.container.querySelector('[data-timeline-row-id="entry-r-5"]'); |
| 2027 | expect(row).not.toBeNull(); |
| 2028 | const bounds = viewport.getBoundingClientRect(); |
| 2029 | const top = row!.getBoundingClientRect().top; |
| 2030 | expect(top).toBeGreaterThanOrEqual(bounds.top); |
| 2031 | expect(top).toBeLessThan(bounds.bottom); |
| 2032 | }); |
| 2033 | }); |
| 2034 | }); |
| 2035 | |
| 2036 | describe("compact reasoning math", () => { |
| 2037 | it.each([ |
| 2038 | [ |
| 2039 | "## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]", |
| 2040 | [ |
| 2041 | ["text", "Reasoning Use norm "], |
| 2042 | ["inlineMath", "|x|"], |
| 2043 | ["text", " and "], |
| 2044 | ["inlineMath", "x^2"], |
| 2045 | ], |
| 2046 | ], |
| 2047 | [ |
| 2048 | " Lead **bold**\n\n *em* `code` \n\n- one\n- two\n\n> quote\n> more\n\ntrail ", |
| 2049 | [["text", "Lead bold em code one two quote more trail"]], |
| 2050 | ], |
| 2051 | [ |
| 2052 | "$a$ starts, ends with $b$", |
| 2053 | [ |
| 2054 | ["inlineMath", "a"], |
| 2055 | ["text", " starts, ends with "], |
| 2056 | ["inlineMath", "b"], |
| 2057 | ], |
| 2058 | ], |
| 2059 | [ |
| 2060 | "before $x$\n\n$$\ny\n$$\n\n after", |
| 2061 | [ |
| 2062 | ["text", "before "], |
| 2063 | ["inlineMath", "x"], |
| 2064 | ["text", " "], |
| 2065 | ["inlineMath", "y"], |
| 2066 | ["text", " after"], |
| 2067 | ], |
| 2068 | ], |
| 2069 | [ |
| 2070 | "a *b*$c$**d** e", |
| 2071 | [ |
| 2072 | ["text", "a b"], |
| 2073 | ["inlineMath", "c"], |
| 2074 | ["text", "d e"], |
| 2075 | ], |
| 2076 | ], |
| 2077 | [ |
| 2078 | "$a$$b$", |
| 2079 | [ |
| 2080 | ["inlineMath", "a"], |
| 2081 | ["text", ""], |
| 2082 | ["inlineMath", "b"], |
| 2083 | ], |
| 2084 | ], |
| 2085 | [ |
| 2086 | "| a | b |\n| - | - |\n| $x$ | y z |", |
| 2087 | [ |
| 2088 | ["text", "a b "], |
| 2089 | ["inlineMath", "x"], |
| 2090 | ["text", " y z"], |
| 2091 | ], |
| 2092 | ], |
| 2093 | [ |
| 2094 | 'See [a link](https://example.com "t")  <b>bold</b> <!-- c -->\n\n[ref]: https://example.com\n\n:::note\nbody\n:::', |
| 2095 | [["text", "See a link alt text bold :::note body :::"]], |
| 2096 | ], |
| 2097 | [ |
| 2098 | "line one\r\nline two\r\n\r\nnext nbsp wide 😀𝑥 end", |
| 2099 | [["text", "line one line two next nbsp wide 😀𝑥 end"]], |
| 2100 | ], |
| 2101 | [ |
| 2102 | `${"x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 1)}😀 tail`, |
| 2103 | [["text", "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 1)]], |
| 2104 | ], |
| 2105 | ["\\$5 and \\$6, \\*not em\\*", [["text", "$5 and $6, *not em*"]]], |
| 2106 | ["hard \nbreak\\\nagain", [["text", "hard break again"]]], |
| 2107 | ["<div>only html</div>", [["text", "Reasoning"]]], |
| 2108 | ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { |
| 2109 | const tree = parseMarkdownWithMath(source); |
| 2110 | remarkThoughtPreview("Reasoning")(tree); |
| 2111 | expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( |
| 2112 | expected, |
| 2113 | ); |
| 2114 | }); |
| 2115 | |
| 2116 | it("stops reading the tree once the preview is full", () => { |
| 2117 | const beyondCap = (): string => { |
| 2118 | throw new Error("read beyond cap"); |
| 2119 | }; |
| 2120 | const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); |
| 2121 | const tree: Root = { |
| 2122 | type: "root", |
| 2123 | children: [ |
| 2124 | { |
| 2125 | type: "paragraph", |
| 2126 | children: [ |
| 2127 | { type: "text", value: head }, |
| 2128 | { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, |
| 2129 | { |
| 2130 | type: "inlineMath", |
| 2131 | get value() { |
| 2132 | return beyondCap(); |
| 2133 | }, |
| 2134 | }, |
| 2135 | ], |
| 2136 | }, |
| 2137 | { |
| 2138 | type: "paragraph", |
| 2139 | children: [ |
| 2140 | { |
| 2141 | type: "text", |
| 2142 | get value() { |
| 2143 | return beyondCap(); |
| 2144 | }, |
| 2145 | }, |
| 2146 | ], |
| 2147 | }, |
| 2148 | ], |
| 2149 | }; |
| 2150 | remarkThoughtPreview("Reasoning")(tree); |
| 2151 | expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); |
| 2152 | }); |
| 2153 | }); |
| 2154 | |
| 2155 | it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => { |
| 2156 | setup(); |
| 2157 | const fixture = makeStreamingTimelineFixture(); |
| 2158 | const prompt = fixture.visibleTurnItems[3]!; |
| 2159 | const assistant = fixture.visibleTurnItems[5]!; |
| 2160 | if (prompt.item.type !== "user_message" || assistant.item.type !== "assistant_message") { |
| 2161 | throw new Error("Expected streaming fixture messages"); |
| 2162 | } |
| 2163 | const promptItem = prompt.item; |
| 2164 | const compaction = { |
| 2165 | ...assistant, |
| 2166 | item: { |
| 2167 | ...assistant.item, |
| 2168 | type: "compaction" as const, |
| 2169 | driver: null, |
| 2170 | beforeTokenCount: 899_000, |
| 2171 | }, |
| 2172 | }; |
| 2173 | const entries = (completed: boolean) => |
| 2174 | deriveTimelineEntriesFromVisibleTurnItems({ |
| 2175 | visibleTurnItems: [ |
| 2176 | { |
| 2177 | ...prompt, |
| 2178 | item: { ...promptItem, text: "/compact", idleCompaction: "beforeCacheExpires" }, |
| 2179 | }, |
| 2180 | { |
| 2181 | ...compaction, |
| 2182 | item: { |
| 2183 | ...compaction.item, |
| 2184 | status: completed ? "completed" : "running", |
| 2185 | afterTokenCount: completed ? 19_000 : undefined, |
| 2186 | }, |
| 2187 | }, |
| 2188 | ], |
| 2189 | optimisticMessages: [], |
| 2190 | }); |
| 2191 | const props = baseProps(); |
| 2192 | const ui = (completed: boolean) => ( |
| 2193 | <MessagesTimeline |
| 2194 | {...props} |
| 2195 | timelineEntries={entries(completed)} |
| 2196 | isWorking={!completed} |
| 2197 | isCompacting={!completed} |
| 2198 | activeTurnStartedAt={fixture.time(5)} |
| 2199 | latestRun={{ |
| 2200 | runId: fixture.runId, |
| 2201 | status: completed ? "completed" : "running", |
| 2202 | startedAt: fixture.time(5), |
| 2203 | completedAt: completed ? fixture.time(9) : null, |
| 2204 | }} |
| 2205 | /> |
| 2206 | ); |
| 2207 | const container = document.createElement("div"); |
| 2208 | container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;"; |
| 2209 | await using screen = await render(ui(false), { container }); |
| 2210 | await expect |
| 2211 | .element(screen.getByRole("separator", { name: "Compacting before the cache expires…" })) |
| 2212 | .toBeVisible(); |
| 2213 | expect(container.textContent).not.toContain("/compact"); |
| 2214 | expect(container.textContent).not.toContain("Thinking"); |
| 2215 | expect(container.textContent).not.toContain("Working"); |
| 2216 | expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1); |
| 2217 | await screen.rerender(ui(true)); |
| 2218 | await expect |
| 2219 | .element( |
| 2220 | screen.getByRole("separator", { |
| 2221 | name: "Auto-compacted before cache expiry 899K → 19K tokens", |
| 2222 | }), |
| 2223 | ) |
| 2224 | .toBeVisible(); |
| 2225 | expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1); |
| 2226 | expect(container.textContent).not.toContain("Compacting before"); |
| 2227 | }); |
| 2228 | |
| 2229 | function TimelineChangedFilesCard() { |
| 2230 | const [expanded, setExpanded] = useState(true); |
| 2231 | return ( |
| 2232 | <ChangedFilesCard |
| 2233 | runId={RunId.make("run-1")} |
| 2234 | files={["src/a.ts", "src/b.ts", "src/c.ts"].map((path) => ({ |
| 2235 | path, |
| 2236 | kind: "modified", |
| 2237 | additions: 1, |
| 2238 | deletions: 0, |
| 2239 | }))} |
| 2240 | totals={{ count: 3, additions: 3, deletions: 0 }} |
| 2241 | allDirectoriesExpanded={expanded} |
| 2242 | resolvedTheme="light" |
| 2243 | onToggleAllDirectories={() => setExpanded((value) => !value)} |
| 2244 | onOpenTurnDiff={() => {}} |
| 2245 | /> |
| 2246 | ); |
| 2247 | } |
| 2248 | |
| 2249 | function ChangedFilesTimeline() { |
| 2250 | return ( |
| 2251 | <LegendList |
| 2252 | data={["files", "after"]} |
| 2253 | keyExtractor={(item) => item} |
| 2254 | estimatedItemSize={100} |
| 2255 | recycleItems={false} |
| 2256 | className="h-[600px]" |
| 2257 | renderItem={({ item }) => |
| 2258 | item === "files" ? <TimelineChangedFilesCard /> : <div data-testid="after">After</div> |
| 2259 | } |
| 2260 | /> |
| 2261 | ); |
| 2262 | } |
| 2263 | |
| 2264 | describe("ChangedFilesCard", () => { |
| 2265 | it.each(["folder", "all folders"])( |
| 2266 | "measures %s collapse and expansion in the same commit", |
| 2267 | async (toggle) => { |
| 2268 | await using screen = await render(<ChangedFilesTimeline />); |
| 2269 | const after = () => |
| 2270 | screen.container.querySelector('[data-testid="after"]')!.getBoundingClientRect().top; |
| 2271 | const cardBottom = () => |
| 2272 | screen.container.querySelector("[data-changed-files-state]")!.getBoundingClientRect() |
| 2273 | .bottom; |
| 2274 | await vi.waitFor(() => expect(after()).toBe(cardBottom())); |
| 2275 | const topBefore = after(); |
| 2276 | const button = () => |
| 2277 | screen.container.querySelector<HTMLButtonElement>( |
| 2278 | toggle === "folder" |
| 2279 | ? '[data-changed-file-row="src"] button' |
| 2280 | : 'button[aria-label$="all folders"]', |
| 2281 | )!; |
| 2282 | await act(() => { |
| 2283 | flushSync(() => button().click()); |
| 2284 | expect(screen.container.textContent).not.toContain("a.ts"); |
| 2285 | expect(after()).toBe(topBefore - 3 * 28); |
| 2286 | }); |
| 2287 | await act(() => { |
| 2288 | flushSync(() => button().click()); |
| 2289 | expect(screen.container.textContent).toContain("a.ts"); |
| 2290 | expect(after()).toBe(topBefore); |
| 2291 | }); |
| 2292 | }, |
| 2293 | ); |
| 2294 | }); |
| 2295 | |
| 2296 | it("keeps concurrent approvals actionable outside collapsed work and restores settled rows", async () => { |
| 2297 | setup(); |
| 2298 | const fixture = makeStreamingTimelineFixture(); |
| 2299 | const source = fixture.visibleTurnItems[4]!; |
| 2300 | if (source.item.type !== "dynamic_tool") throw new Error("Expected fixture tool"); |
| 2301 | const sourceItem = source.item; |
| 2302 | const commandRequest = RuntimeRequestId.make("command-approval"); |
| 2303 | const appRequest = RuntimeRequestId.make("app-approval"); |
| 2304 | const approvals: PendingApproval[] = [ |
| 2305 | { |
| 2306 | requestId: commandRequest, |
| 2307 | requestKind: "command", |
| 2308 | createdAt: fixture.time(6), |
| 2309 | detail: "printf '" + "long-command ".repeat(80) + "'", |
| 2310 | reason: "Needs permission to run the command", |
| 2311 | fullAccessOverride: "ask_rule", |
| 2312 | responseCapability: "live", |
| 2313 | }, |
| 2314 | { |
| 2315 | requestId: appRequest, |
| 2316 | requestKind: "permission", |
| 2317 | createdAt: fixture.time(6), |
| 2318 | detail: "Open the current tab", |
| 2319 | appName: "Safari", |
| 2320 | options: [ |
| 2321 | { decision: "decline", label: "Deny" }, |
| 2322 | { decision: "accept", label: "Allow once" }, |
| 2323 | { |
| 2324 | decision: "acceptAlways", |
| 2325 | label: "Always allow Safari", |
| 2326 | warning: "Applies to future requests", |
| 2327 | }, |
| 2328 | ], |
| 2329 | responseCapability: "live", |
| 2330 | }, |
| 2331 | ]; |
| 2332 | const entries = (completed = false) => |
| 2333 | deriveTimelineEntriesFromVisibleTurnItems({ |
| 2334 | visibleTurnItems: [ |
| 2335 | { ...source, item: { ...sourceItem, status: completed ? "completed" : sourceItem.status } }, |
| 2336 | ...approvals.map((approval, index) => ({ |
| 2337 | ...source, |
| 2338 | position: source.position + index + 1, |
| 2339 | sourceItemId: TurnItemId.make(`approval-${index}`), |
| 2340 | item: { |
| 2341 | ...sourceItem, |
| 2342 | id: TurnItemId.make(`approval-${index}`), |
| 2343 | type: "approval_request" as const, |
| 2344 | status: completed ? ("completed" as const) : ("waiting" as const), |
| 2345 | requestId: approval.requestId, |
| 2346 | requestKind: approval.requestKind, |
| 2347 | prompt: approval.detail, |
| 2348 | }, |
| 2349 | })), |
| 2350 | ], |
| 2351 | optimisticMessages: [], |
| 2352 | }); |
| 2353 | const props = baseProps(); |
| 2354 | const onRespondToApproval = vi.fn(async () => {}); |
| 2355 | const ui = (overrides: Partial<TimelineProps> = {}) => ( |
| 2356 | <MessagesTimeline |
| 2357 | {...props} |
| 2358 | timelineEntries={entries()} |
| 2359 | pendingApprovals={approvals} |
| 2360 | canOperateThread |
| 2361 | onRespondToApproval={onRespondToApproval} |
| 2362 | isWorking |
| 2363 | runningRunId={fixture.runId} |
| 2364 | {...overrides} |
| 2365 | /> |
| 2366 | ); |
| 2367 | await using screen = await renderElement(ui()); |
| 2368 | await expect.element(screen.getByRole("group", { name: "Command approval" })).toBeVisible(); |
| 2369 | await expect |
| 2370 | .element(screen.getByRole("group", { name: "App permission approval" })) |
| 2371 | .toBeVisible(); |
| 2372 | await expect.element(screen.getByText(approvals[0]!.detail!, { exact: true })).toBeVisible(); |
| 2373 | await expect.element(screen.getByText("Needs permission to run the command")).toBeVisible(); |
| 2374 | await vi.waitFor(() => { |
| 2375 | expect( |
| 2376 | getComputedStyle(screen.getByLabelText("Command", { exact: true }).element()).userSelect, |
| 2377 | ).toBe("text"); |
| 2378 | expect( |
| 2379 | getComputedStyle(screen.getByText("Needs permission to run the command").element()) |
| 2380 | .userSelect, |
| 2381 | ).toBe("text"); |
| 2382 | }); |
| 2383 | await expect.element(screen.getByText("Safari", { exact: true })).toBeVisible(); |
| 2384 | await click(screen.button("Why am I being asked this?")); |
| 2385 | await expect.element(page.getByText(/an ask rule in the agent's own settings/)).toBeVisible(); |
| 2386 | await click(screen.button("Why am I being asked this?")); |
| 2387 | await click(screen.buttons("More approval options")[1]!); |
| 2388 | await expect.element(page.getByRole("menuitem", { name: "Always allow Safari" })).toBeVisible(); |
| 2389 | await page.getByRole("menuitem", { name: "Always allow Safari" }).click(); |
| 2390 | expect(onRespondToApproval).toHaveBeenLastCalledWith(appRequest, "acceptAlways"); |
| 2391 | await click(screen.buttons("More approval options")[0]!); |
| 2392 | await expect.element(page.getByRole("menuitem", { name: "Cancel", exact: true })).toBeVisible(); |
| 2393 | await page.getByRole("menuitem", { name: "Always allow this session" }).click(); |
| 2394 | expect(onRespondToApproval).toHaveBeenLastCalledWith(commandRequest, "acceptForSession"); |
| 2395 | await click(screen.button("Decline")); |
| 2396 | expect(onRespondToApproval).toHaveBeenLastCalledWith(commandRequest, "decline"); |
| 2397 | await click(screen.button("Allow once")); |
| 2398 | expect(onRespondToApproval).toHaveBeenLastCalledWith(appRequest, "accept"); |
| 2399 | for (const timelineEntries of [entries(), []]) { |
| 2400 | await screen.rerender( |
| 2401 | ui({ timelineEntries, heldApprovalRequestIds: new Set([commandRequest]) }), |
| 2402 | ); |
| 2403 | await expect |
| 2404 | .element(screen.getByRole("group", { name: "Command approval" })) |
| 2405 | .not.toBeInTheDocument(); |
| 2406 | await vi.waitFor(() => expect(screen.buttons("Approve")).toHaveLength(0)); |
| 2407 | await expect |
| 2408 | .element(screen.getByRole("button", { name: "Allow once", exact: true })) |
| 2409 | .toBeVisible(); |
| 2410 | await screen.rerender(ui({ timelineEntries })); |
| 2411 | await expect.element(screen.getByRole("group", { name: "Command approval" })).toBeVisible(); |
| 2412 | await vi.waitFor(() => expect(screen.buttons("Approve")).toHaveLength(1)); |
| 2413 | } |
| 2414 | await screen.rerender(ui({ timelineEntries: [], isWorking: false })); |
| 2415 | await expect.element(screen.getByRole("group", { name: "Command approval" })).toBeVisible(); |
| 2416 | await click(screen.button("Approve")); |
| 2417 | expect(onRespondToApproval).toHaveBeenLastCalledWith(commandRequest, "accept"); |
| 2418 | await click(screen.button("Deny")); |
| 2419 | expect(onRespondToApproval).toHaveBeenLastCalledWith(appRequest, "decline"); |
| 2420 | await screen.rerender( |
| 2421 | ui({ |
| 2422 | timelineEntries: [], |
| 2423 | isWorking: false, |
| 2424 | pendingApprovals: [{ ...approvals[0]!, detail: "" }], |
| 2425 | }), |
| 2426 | ); |
| 2427 | await expect |
| 2428 | .element(screen.getByLabelText("Command", { exact: true })) |
| 2429 | .toHaveTextContent("Command approval"); |
| 2430 | await screen.rerender(ui({ canOperateThread: false })); |
| 2431 | await expect.element(screen.getByRole("button", { name: "Approve", exact: true })).toBeDisabled(); |
| 2432 | await vi.waitFor(() => |
| 2433 | expect( |
| 2434 | screen.buttons("More approval options").every((button) => button.hasAttribute("disabled")), |
| 2435 | ).toBe(true), |
| 2436 | ); |
| 2437 | await screen.rerender(ui({ respondingRequestIds: [commandRequest] })); |
| 2438 | await expect.element(screen.getByRole("button", { name: "Approve", exact: true })).toBeDisabled(); |
| 2439 | await expect |
| 2440 | .element(screen.getByRole("button", { name: "Allow once", exact: true })) |
| 2441 | .toBeEnabled(); |
| 2442 | await screen.rerender( |
| 2443 | ui({ pendingApprovals: [{ ...approvals[0]!, responseCapability: "not_resumable" }] }), |
| 2444 | ); |
| 2445 | await expect |
| 2446 | .element(screen.getByText("Provider process is gone. Interrupt or restart the run to respond.")) |
| 2447 | .toBeVisible(); |
| 2448 | await vi.waitFor(() => expect(screen.buttons("Approve")).toHaveLength(0)); |
| 2449 | await screen.rerender( |
| 2450 | ui({ pendingApprovals: [], timelineEntries: entries(true), isWorking: false }), |
| 2451 | ); |
| 2452 | await expect |
| 2453 | .element(screen.getByRole("group", { name: "Command approval" })) |
| 2454 | .not.toBeInTheDocument(); |
| 2455 | await vi.waitFor(() => expect(screen.text()).not.toContain("Waiting for approval")); |
| 2456 | await screen.getByRole("button", { expanded: false }).click(); |
| 2457 | await expect |
| 2458 | .element(screen.getByRole("button", { name: approvals[0]!.detail!, exact: true })) |
| 2459 | .toBeVisible(); |
| 2460 | await expect |
| 2461 | .element(screen.getByRole("button", { name: "Open the current tab", exact: true })) |
| 2462 | .toBeVisible(); |
| 2463 | }); |