| 1 | // Run: tsx src/__tests__/composer-run-strip.test.tsx |
| 2 | // |
| 3 | // Ordinary work keeps the perimeter trace and now carries a live |
| 4 | // token/throughput strip too; the accessible announcement still speaks the |
| 5 | // stable state text alone. Timing/throughput detail lives in the context |
| 6 | // popover; approval/ask retain an in-card attention strip, and stop keeps a |
| 7 | // fixed home next to send. |
| 8 | |
| 9 | import { readFileSync } from "node:fs"; |
| 10 | import { dirname, resolve } from "node:path"; |
| 11 | import { fileURLToPath } from "node:url"; |
| 12 | import { JSDOM } from "jsdom"; |
| 13 | import React from "react"; |
| 14 | import { act } from "react"; |
| 15 | import { createRoot } from "react-dom/client"; |
| 16 | import { Composer } from "../components/Composer"; |
| 17 | import { LocaleProvider } from "../lib/i18n"; |
| 18 | import { ToastProvider } from "../lib/toast"; |
| 19 | import type { CollaborationMode, ToolApprovalMode } from "../lib/types"; |
| 20 | |
| 21 | let passed = 0; |
| 22 | let failed = 0; |
| 23 | |
| 24 | function ok(value: boolean, label: string) { |
| 25 | if (value) { |
| 26 | process.stdout.write(` PASS ${label}\n`); |
| 27 | passed += 1; |
| 28 | } else { |
| 29 | process.stdout.write(` FAIL ${label}\n`); |
| 30 | failed += 1; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | function eq(actual: unknown, expected: unknown, label: string) { |
| 35 | if (actual === expected) ok(true, label); |
| 36 | else ok(false, `${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`); |
| 37 | } |
| 38 | |
| 39 | function flushTimers(): Promise<void> { |
| 40 | return new Promise((resolve) => setTimeout(resolve, 0)); |
| 41 | } |
| 42 | |
| 43 | async function readRunMetrics() { |
| 44 | await act(async () => { |
| 45 | const ring = document.querySelector(".context-ring") as HTMLButtonElement; |
| 46 | if (ring.getAttribute("aria-expanded") !== "true") ring.click(); |
| 47 | await flushTimers(); |
| 48 | }); |
| 49 | return ` ${document.querySelector(".context-ring-popover")?.textContent ?? ""}`; |
| 50 | } |
| 51 | |
| 52 | class TestResizeObserver { |
| 53 | observe() {} |
| 54 | unobserve() {} |
| 55 | disconnect() {} |
| 56 | } |
| 57 | |
| 58 | function installDom() { |
| 59 | const dom = new JSDOM("<!doctype html><html><body><div id=\"root\"></div></body></html>", { |
| 60 | pretendToBeVisual: true, |
| 61 | url: "http://localhost/", |
| 62 | }); |
| 63 | (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; |
| 64 | globalThis.window = dom.window as unknown as Window & typeof globalThis; |
| 65 | globalThis.document = dom.window.document; |
| 66 | Object.defineProperty(globalThis, "navigator", { configurable: true, value: dom.window.navigator }); |
| 67 | globalThis.Node = dom.window.Node; |
| 68 | globalThis.HTMLElement = dom.window.HTMLElement; |
| 69 | globalThis.HTMLTextAreaElement = dom.window.HTMLTextAreaElement; |
| 70 | globalThis.Event = dom.window.Event; |
| 71 | globalThis.CustomEvent = dom.window.CustomEvent; |
| 72 | globalThis.KeyboardEvent = dom.window.KeyboardEvent; |
| 73 | globalThis.InputEvent = dom.window.InputEvent; |
| 74 | globalThis.MouseEvent = dom.window.MouseEvent; |
| 75 | globalThis.PointerEvent = dom.window.MouseEvent as unknown as typeof PointerEvent; |
| 76 | globalThis.MutationObserver = dom.window.MutationObserver; |
| 77 | globalThis.File = dom.window.File; |
| 78 | globalThis.FileReader = dom.window.FileReader; |
| 79 | globalThis.localStorage = dom.window.localStorage; |
| 80 | globalThis.requestAnimationFrame = dom.window.requestAnimationFrame.bind(dom.window); |
| 81 | globalThis.cancelAnimationFrame = dom.window.cancelAnimationFrame.bind(dom.window); |
| 82 | globalThis.ResizeObserver = TestResizeObserver; |
| 83 | Object.defineProperty(dom.window.HTMLElement.prototype, "attachEvent", { configurable: true, value: () => {} }); |
| 84 | Object.defineProperty(dom.window.HTMLElement.prototype, "detachEvent", { configurable: true, value: () => {} }); |
| 85 | Object.defineProperty(window, "matchMedia", { |
| 86 | configurable: true, |
| 87 | value: () => ({ |
| 88 | matches: true, |
| 89 | media: "(prefers-reduced-motion: reduce)", |
| 90 | onchange: null, |
| 91 | addEventListener() {}, |
| 92 | removeEventListener() {}, |
| 93 | addListener() {}, |
| 94 | removeListener() {}, |
| 95 | dispatchEvent: () => false, |
| 96 | }), |
| 97 | }); |
| 98 | return dom; |
| 99 | } |
| 100 | |
| 101 | async function renderComposer(props: Partial<Parameters<typeof Composer>[0]> = {}) { |
| 102 | const rootEl = document.getElementById("root"); |
| 103 | if (!rootEl) throw new Error("missing root"); |
| 104 | const root = createRoot(rootEl); |
| 105 | const calls = { cancel: 0, approvalModes: [] as ToolApprovalMode[] }; |
| 106 | let currentProps: Parameters<typeof Composer>[0] = { |
| 107 | running: false, |
| 108 | collaborationMode: "normal" as CollaborationMode, |
| 109 | toolApprovalMode: "workspace-write" as ToolApprovalMode, |
| 110 | goal: "", |
| 111 | cwd: "/repo", |
| 112 | modelLabel: "DeepSeek-R1", |
| 113 | onSend: () => {}, |
| 114 | onCancel: () => { |
| 115 | calls.cancel += 1; |
| 116 | return undefined; |
| 117 | }, |
| 118 | onCycleMode: () => {}, |
| 119 | onSetMode: () => {}, |
| 120 | onSetCollaborationMode: () => {}, |
| 121 | onSetToolApprovalMode: (mode) => { |
| 122 | calls.approvalModes.push(mode); |
| 123 | }, |
| 124 | onClearGoal: () => {}, |
| 125 | onSwitchModel: () => {}, |
| 126 | onSetEffort: () => {}, |
| 127 | ready: true, |
| 128 | ...props, |
| 129 | }; |
| 130 | const paint = async (nextProps: Partial<Parameters<typeof Composer>[0]> = {}) => { |
| 131 | currentProps = { ...currentProps, ...nextProps }; |
| 132 | await act(async () => { |
| 133 | root.render( |
| 134 | <LocaleProvider> |
| 135 | <ToastProvider> |
| 136 | <Composer {...currentProps} /> |
| 137 | </ToastProvider> |
| 138 | </LocaleProvider>, |
| 139 | ); |
| 140 | await flushTimers(); |
| 141 | }); |
| 142 | }; |
| 143 | await paint(); |
| 144 | return { root, calls, rerender: paint }; |
| 145 | } |
| 146 | |
| 147 | function installWindowTimerQueue() { |
| 148 | let clock = 0; |
| 149 | let nextId = 1; |
| 150 | const tasks = new Map<number, { at: number; callback: () => void }>(); |
| 151 | const originalSetTimeout = window.setTimeout; |
| 152 | const originalClearTimeout = window.clearTimeout; |
| 153 | |
| 154 | window.setTimeout = ((handler: TimerHandler, delay = 0, ...args: unknown[]) => { |
| 155 | if (typeof handler !== "function") throw new Error("string timers are unsupported in tests"); |
| 156 | const id = nextId++; |
| 157 | tasks.set(id, { at: clock + Number(delay), callback: () => handler(...args) }); |
| 158 | return id; |
| 159 | }) as typeof window.setTimeout; |
| 160 | window.clearTimeout = ((id?: number) => { |
| 161 | if (id !== undefined) tasks.delete(id); |
| 162 | }) as typeof window.clearTimeout; |
| 163 | |
| 164 | return { |
| 165 | advance(ms: number) { |
| 166 | clock += ms; |
| 167 | while (true) { |
| 168 | const next = [...tasks.entries()] |
| 169 | .filter(([, task]) => task.at <= clock) |
| 170 | .sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0]; |
| 171 | if (!next) break; |
| 172 | tasks.delete(next[0]); |
| 173 | next[1].callback(); |
| 174 | } |
| 175 | }, |
| 176 | restore() { |
| 177 | tasks.clear(); |
| 178 | window.setTimeout = originalSetTimeout; |
| 179 | window.clearTimeout = originalClearTimeout; |
| 180 | }, |
| 181 | }; |
| 182 | } |
| 183 | |
| 184 | console.log("\ncomposer run strip"); |
| 185 | |
| 186 | // Idle: no strip, no stop button, plain send arrow. |
| 187 | { |
| 188 | const dom = installDom(); |
| 189 | const { root, calls, rerender } = await renderComposer({ workspaceRoot: "/repo" }); |
| 190 | |
| 191 | eq(document.querySelector(".composer-run-strip"), null, "idle composer renders no run strip"); |
| 192 | eq(document.querySelector(".composer__btn--stop"), null, "idle composer renders no stop button"); |
| 193 | ok(document.querySelector(".composer__btn--send") !== null, "idle composer keeps the send button"); |
| 194 | eq(document.querySelector(".composer-toolbar--status-only"), null, "floating status pill is gone"); |
| 195 | await act(async () => { |
| 196 | document.querySelector<HTMLButtonElement>(".composer-meta__control--approval button")?.click(); |
| 197 | await flushTimers(); |
| 198 | }); |
| 199 | const fullAccess = document.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')[2]; |
| 200 | ok(fullAccess !== null, "permission menu exposes Read only, Workspace write, and Full access"); |
| 201 | await act(async () => { |
| 202 | fullAccess?.click(); |
| 203 | await flushTimers(); |
| 204 | }); |
| 205 | eq(calls.approvalModes.length, 0, "selecting Full access waits for explicit risk acknowledgement"); |
| 206 | const dialog = document.querySelector<HTMLElement>('[role="dialog"]'); |
| 207 | ok(dialog?.textContent?.includes("Enable Full access?"), "Full access opens the Harness-style risk confirmation"); |
| 208 | const checkbox = dialog?.querySelector<HTMLInputElement>('input[type="checkbox"]'); |
| 209 | const enable = Array.from(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? []) |
| 210 | .find(button => button.textContent?.includes("Enable Full access")); |
| 211 | ok(Boolean(checkbox), "risk confirmation includes the explicit acknowledgement checkbox"); |
| 212 | ok(Boolean(enable?.disabled), "Full access stays disabled before acknowledgement"); |
| 213 | await act(async () => { |
| 214 | checkbox?.click(); |
| 215 | await flushTimers(); |
| 216 | }); |
| 217 | eq(enable?.disabled, false, "acknowledgement enables the Full access action"); |
| 218 | await act(async () => { |
| 219 | enable?.click(); |
| 220 | await flushTimers(); |
| 221 | }); |
| 222 | eq(calls.approvalModes.at(-1), "danger-full-access", "confirmed Full access reaches the session permission owner"); |
| 223 | eq(document.querySelector('[role="dialog"]'), null, "confirmation closes after submission"); |
| 224 | |
| 225 | await act(async () => { |
| 226 | document.querySelector<HTMLButtonElement>(".composer-meta__control--approval button")?.click(); |
| 227 | await flushTimers(); |
| 228 | document.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')[2]?.click(); |
| 229 | await flushTimers(); |
| 230 | }); |
| 231 | eq(document.querySelector('[role="dialog"]'), null, |
| 232 | "a project that already acknowledged Full access does not show the warning again"); |
| 233 | eq(calls.approvalModes.length, 2, |
| 234 | "remembered project acknowledgement selects Full access immediately"); |
| 235 | |
| 236 | await rerender({ cwd: "/another-project/subdirectory", workspaceRoot: "/another-project" }); |
| 237 | await act(async () => { |
| 238 | document.querySelector<HTMLButtonElement>(".composer-meta__control--approval button")?.click(); |
| 239 | await flushTimers(); |
| 240 | document.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')[2]?.click(); |
| 241 | await flushTimers(); |
| 242 | }); |
| 243 | const cancelledDialog = document.querySelector<HTMLElement>('[role="dialog"]'); |
| 244 | ok(cancelledDialog !== null, "a different project still requires its own Full access confirmation"); |
| 245 | const cancelledCheckbox = cancelledDialog?.querySelector<HTMLInputElement>('input[type="checkbox"]'); |
| 246 | await act(async () => { |
| 247 | cancelledCheckbox?.click(); |
| 248 | Array.from(cancelledDialog?.querySelectorAll<HTMLButtonElement>("button") ?? []) |
| 249 | .find(button => button.textContent?.trim() === "Cancel")?.click(); |
| 250 | await flushTimers(); |
| 251 | }); |
| 252 | eq(calls.approvalModes.length, 2, "cancelling a later Full access attempt does not submit another change"); |
| 253 | |
| 254 | await act(async () => { |
| 255 | document.querySelector<HTMLButtonElement>(".composer-meta__control--approval button")?.click(); |
| 256 | await flushTimers(); |
| 257 | document.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')[2]?.click(); |
| 258 | await flushTimers(); |
| 259 | }); |
| 260 | eq(document.querySelector<HTMLInputElement>('[role="dialog"] input[type="checkbox"]')?.checked, false, |
| 261 | "a new Full access attempt never reuses an earlier acknowledgement"); |
| 262 | |
| 263 | await rerender({ disabled: true }); |
| 264 | eq(document.querySelector('[role="dialog"]'), null, |
| 265 | "locking the composer closes a pending Full access confirmation"); |
| 266 | eq(calls.approvalModes.length, 2, |
| 267 | "locking the composer cannot submit a pending Full access change"); |
| 268 | |
| 269 | await rerender({ disabled: false }); |
| 270 | await act(async () => { |
| 271 | document.querySelector<HTMLButtonElement>(".composer-meta__control--approval button")?.click(); |
| 272 | await flushTimers(); |
| 273 | document.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')[2]?.click(); |
| 274 | await flushTimers(); |
| 275 | }); |
| 276 | ok(document.querySelector('[role="dialog"]') !== null, |
| 277 | "Full access confirmation can reopen after the composer unlocks"); |
| 278 | await rerender({ tabId: "next-tab", sessionKey: "next-session" }); |
| 279 | eq(document.querySelector('[role="dialog"]'), null, |
| 280 | "switching sessions closes a pending Full access confirmation"); |
| 281 | eq(calls.approvalModes.length, 2, |
| 282 | "switching sessions cannot approve the previous session's Full access change"); |
| 283 | |
| 284 | await act(async () => { |
| 285 | root.unmount(); |
| 286 | }); |
| 287 | dom.window.close(); |
| 288 | } |
| 289 | |
| 290 | // Execution modes and the independent quality-floor selector are gone. |
| 291 | { |
| 292 | const dom = installDom(); |
| 293 | const { root } = await renderComposer(); |
| 294 | |
| 295 | eq(document.querySelector(".composer-profile-trigger"), null, "composer has no execution-setting trigger"); |
| 296 | eq(document.querySelector(".composer-profile-menu"), null, "composer has no execution-setting menu"); |
| 297 | const chrome = document.body.textContent ?? ""; |
| 298 | eq(chrome.includes("Execution setting"), false, "composer chrome does not mention execution setting"); |
| 299 | |
| 300 | const intentTrigger = document.querySelector(".composer-content-trigger") as HTMLButtonElement | null; |
| 301 | if (!intentTrigger) throw new Error("task intent trigger did not render"); |
| 302 | await act(async () => { |
| 303 | intentTrigger.click(); |
| 304 | await flushTimers(); |
| 305 | }); |
| 306 | eq(document.querySelector(".composer-intent-menu")?.textContent?.includes("Work mode"), false, "task-intent menu does not own a work-mode section"); |
| 307 | eq(document.querySelectorAll('.composer-intent-menu [role="menuitemradio"]').length, 2, "task method menu exposes plan and goal"); |
| 308 | |
| 309 | await act(async () => { |
| 310 | root.unmount(); |
| 311 | }); |
| 312 | dom.window.close(); |
| 313 | } |
| 314 | |
| 315 | // A short Creation hover must stay a no-op. In particular, leaving before the |
| 316 | // 120ms open delay must not manufacture a closing-only popover or flash the |
| 317 | // trigger's open styling 140ms later. |
| 318 | { |
| 319 | const dom = installDom(); |
| 320 | const timers = installWindowTimerQueue(); |
| 321 | const { root } = await renderComposer({ showContextWindowRing: true, collaborationMode: "plan" }); |
| 322 | |
| 323 | for (const selector of [".composer-task-mode-trigger"]) { |
| 324 | const trigger = document.querySelector(selector) as HTMLButtonElement | null; |
| 325 | if (!trigger) throw new Error(`missing Creation hover trigger: ${selector}`); |
| 326 | |
| 327 | await act(async () => { |
| 328 | trigger.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, relatedTarget: null })); |
| 329 | timers.advance(119); |
| 330 | trigger.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body })); |
| 331 | timers.advance(140); |
| 332 | }); |
| 333 | |
| 334 | ok(!trigger.classList.contains(`${selector.slice(1)}--open`), `${selector} stays visually closed after a short hover`); |
| 335 | ok( |
| 336 | document.querySelector(".composer-intent-menu") === null, |
| 337 | `${selector} does not render a closing-only menu`, |
| 338 | ); |
| 339 | } |
| 340 | |
| 341 | const intentTrigger = document.querySelector(".composer-task-mode-trigger") as HTMLButtonElement | null; |
| 342 | if (!intentTrigger) throw new Error("missing Creation intent trigger"); |
| 343 | await act(async () => { |
| 344 | intentTrigger.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, relatedTarget: null })); |
| 345 | timers.advance(120); |
| 346 | }); |
| 347 | ok(intentTrigger.classList.contains("composer-task-mode-trigger--removable"), "mode chip exposes its dismiss interaction"); |
| 348 | ok(document.querySelector(".composer-intent-menu") === null, "hovering a mode chip does not open the add menu"); |
| 349 | |
| 350 | timers.restore(); |
| 351 | await act(async () => { |
| 352 | root.unmount(); |
| 353 | }); |
| 354 | dom.window.close(); |
| 355 | } |
| 356 | |
| 357 | // Runtime controller transitions disable collaboration, approval, and submit |
| 358 | // together, so rapid Goal + approval-mode clicks cannot mutate a half-rebuilt runtime. |
| 359 | { |
| 360 | const dom = installDom(); |
| 361 | const { root } = await renderComposer({ disabled: true, goal: "ship it", collaborationMode: "goal" }); |
| 362 | const task = document.querySelector<HTMLButtonElement>(".composer-task-mode-trigger"); |
| 363 | const approvals = Array.from(document.querySelectorAll<HTMLButtonElement>(".composer-meta__control--approval button")); |
| 364 | const send = document.querySelector<HTMLButtonElement>(".composer__btn--send"); |
| 365 | eq(document.querySelector(".composer-profile-trigger"), null, "runtime transition has no execution-setting control"); |
| 366 | ok(Boolean(task?.disabled), "runtime transition disables Goal mode changes"); |
| 367 | ok(approvals.length === 1 && approvals.every((button) => button.disabled), "runtime transition disables permission preset changes"); |
| 368 | ok(Boolean(send?.disabled), "runtime transition disables submit"); |
| 369 | |
| 370 | await act(async () => { |
| 371 | root.unmount(); |
| 372 | }); |
| 373 | dom.window.close(); |
| 374 | } |
| 375 | |
| 376 | // Running: no visible strip, stable accessible announcement, stop cancels. |
| 377 | { |
| 378 | const dom = installDom(); |
| 379 | const { root, calls } = await renderComposer({ running: true, turnStartAt: Date.now() }); |
| 380 | |
| 381 | const strip = document.querySelector(".composer-card .composer-run-strip"); |
| 382 | eq(strip?.querySelector(".composer-run-strip__text")?.textContent, "Reasonix is working", |
| 383 | "ordinary running state shows the run strip"); |
| 384 | const live = document.querySelector(".composer-card .sr-only[role=\"status\"]"); |
| 385 | eq(live?.textContent, "Reasonix is working", "live region announces the stable state text only"); |
| 386 | ok(document.querySelector(".composer-card--running") !== null, "running card keeps its running modifier"); |
| 387 | eq(document.querySelector(".composer-glowring")?.getAttribute("aria-hidden"), "true", "active work mounts a decorative perimeter trace"); |
| 388 | |
| 389 | const stop = document.querySelector(".composer__btn--stop") as HTMLButtonElement | null; |
| 390 | if (!stop) throw new Error("running composer stop button did not render"); |
| 391 | await act(async () => { |
| 392 | stop.click(); |
| 393 | await flushTimers(); |
| 394 | }); |
| 395 | eq(calls.cancel, 1, "stop button next to send cancels the turn"); |
| 396 | |
| 397 | await act(async () => { |
| 398 | root.unmount(); |
| 399 | }); |
| 400 | dom.window.close(); |
| 401 | } |
| 402 | |
| 403 | // Waiting on approval: strip switches to the waiting state and stops ticking. |
| 404 | { |
| 405 | const dom = installDom(); |
| 406 | const { root, rerender } = await renderComposer({ running: true, turnStartAt: Date.now() }); |
| 407 | |
| 408 | await rerender({ pendingApprovalLabel: "Run command", disabled: true }); |
| 409 | |
| 410 | const strip = document.querySelector(".composer-run-strip"); |
| 411 | ok(strip?.classList.contains("composer-run-strip--waiting") === true, "pending approval shifts the strip into waiting"); |
| 412 | const text = strip?.querySelector(".composer-run-strip__text"); |
| 413 | eq(text?.textContent, "Waiting for your approval — Run command", "waiting strip names the tool awaiting approval"); |
| 414 | eq(text?.getAttribute("aria-hidden"), null, "waiting text is static and stays accessible"); |
| 415 | eq(document.querySelector(".composer-card--running"), null, "waiting card hands the running accent off to the prompt card"); |
| 416 | ok(document.querySelector(".composer-card--waiting") !== null, "waiting card takes the waiting modifier"); |
| 417 | eq(document.querySelector(".composer-glowring"), null, "waiting removes the trace rather than running an invisible animation"); |
| 418 | |
| 419 | const modeButtons = [...document.querySelectorAll(".composer-meta__control--approval button")] as HTMLButtonElement[]; |
| 420 | ok(modeButtons.length === 1 && modeButtons.every((b) => !b.disabled), "approval bar stays usable while its own prompt disables the composer"); |
| 421 | |
| 422 | await rerender({ pendingApprovalLabel: null, pendingAsk: true }); |
| 423 | eq( |
| 424 | document.querySelector(".composer-run-strip__text")?.textContent, |
| 425 | "Waiting for your answer", |
| 426 | "pending ask question shows the ask waiting state", |
| 427 | ); |
| 428 | ok( |
| 429 | modeButtons.every((b) => b.disabled), |
| 430 | "approval bar stays disabled for non-approval reasons", |
| 431 | ); |
| 432 | |
| 433 | await rerender({ pendingAsk: false, disabled: false }); |
| 434 | const resolved = document.querySelector(".composer-run-strip"); |
| 435 | eq(resolved?.classList.contains("composer-run-strip--waiting"), false, |
| 436 | "resolving the prompt removes the attention strip"); |
| 437 | eq(resolved?.querySelector(".composer-run-strip__text")?.textContent, "Reasonix is working", |
| 438 | "the resolved prompt falls back to the ordinary work strip"); |
| 439 | |
| 440 | await act(async () => { |
| 441 | root.unmount(); |
| 442 | }); |
| 443 | dom.window.close(); |
| 444 | } |
| 445 | |
| 446 | // Cancel restores queued guidance: stop means "stop acting", never "discard |
| 447 | // what I typed". |
| 448 | { |
| 449 | const dom = installDom(); |
| 450 | const { root, calls } = await renderComposer({ |
| 451 | running: true, |
| 452 | turnStartAt: Date.now(), |
| 453 | guidanceQueuePreviewItems: ["数到一半改用英文", "最后给出一句总结"], |
| 454 | }); |
| 455 | |
| 456 | ok(document.querySelector(".composer-guidance-shelf") !== null, "queued guidance renders in the shelf"); |
| 457 | |
| 458 | const stop = document.querySelector(".composer__btn--stop") as HTMLButtonElement | null; |
| 459 | if (!stop) throw new Error("stop button did not render"); |
| 460 | await act(async () => { |
| 461 | stop.click(); |
| 462 | await flushTimers(); |
| 463 | }); |
| 464 | |
| 465 | eq(calls.cancel, 1, "stop cancels the running turn"); |
| 466 | const ta = document.querySelector("textarea") as HTMLTextAreaElement; |
| 467 | eq(ta.value, "数到一半改用英文\n最后给出一句总结", "stop folds unconsumed queued guidance back into the draft"); |
| 468 | eq(document.querySelector(".composer-guidance-shelf"), null, "restored queue clears the shelf"); |
| 469 | |
| 470 | await act(async () => { |
| 471 | root.unmount(); |
| 472 | }); |
| 473 | dom.window.close(); |
| 474 | } |
| 475 | |
| 476 | // Waiting on the user pauses the ticker clock: elapsed time means model time. |
| 477 | { |
| 478 | const dom = installDom(); |
| 479 | const start = Date.now() - 30000; |
| 480 | const { root, rerender } = await renderComposer({ running: true, turnStartAt: start }); |
| 481 | |
| 482 | await rerender({ pendingApprovalLabel: "Run command", disabled: true }); |
| 483 | await act(async () => { |
| 484 | await new Promise((resolve) => setTimeout(resolve, 2400)); |
| 485 | }); |
| 486 | await rerender({ pendingApprovalLabel: null, disabled: false }); |
| 487 | |
| 488 | const ticker = await readRunMetrics(); |
| 489 | ok(/30s|31s/.test(ticker), `ticker excludes the time spent waiting for approval (got "${ticker}")`); |
| 490 | ok(!/ 32s| 33s/.test(ticker), "ticker does not count the ~2.4s approval wait as model time"); |
| 491 | |
| 492 | await act(async () => { |
| 493 | root.unmount(); |
| 494 | }); |
| 495 | dom.window.close(); |
| 496 | } |
| 497 | |
| 498 | // Decision surface suspension pauses the clock without a waiting strip. |
| 499 | { |
| 500 | const dom = installDom(); |
| 501 | const start = Date.now() - 15000; |
| 502 | const { root, rerender } = await renderComposer({ running: true, turnStartAt: start }); |
| 503 | |
| 504 | await rerender({ suspendedByDecision: true, disabled: true }); |
| 505 | eq(document.querySelector(".composer-run-strip--waiting"), null, "decision suspension does not render a waiting strip"); |
| 506 | await act(async () => { |
| 507 | await new Promise((resolve) => setTimeout(resolve, 2400)); |
| 508 | }); |
| 509 | await rerender({ suspendedByDecision: false, disabled: false }); |
| 510 | |
| 511 | const ticker = await readRunMetrics(); |
| 512 | ok(/15s|16s/.test(ticker), `suspendedByDecision excludes wait time from model clock (got "${ticker}")`); |
| 513 | ok(!/ 17s| 18s/.test(ticker), "suspended wait is not counted as model work"); |
| 514 | |
| 515 | await act(async () => { |
| 516 | root.unmount(); |
| 517 | }); |
| 518 | dom.window.close(); |
| 519 | } |
| 520 | |
| 521 | // Background user-wait is controller-scoped: B already waited ~3s off-screen |
| 522 | // while A was foregrounded. Model work for B must stay ~5s (8s turn − 3s wait), |
| 523 | // and tab A's local pause must never be subtracted from B. |
| 524 | { |
| 525 | const dom = installDom(); |
| 526 | const tabAStart = Date.now() - 60_000; |
| 527 | const tabBStart = Date.now() - 8_000; |
| 528 | const tabBWaitStarted = Date.now() - 3_000; |
| 529 | const { root, rerender } = await renderComposer({ |
| 530 | running: true, |
| 531 | turnStartAt: tabAStart, |
| 532 | sessionKey: "tab-a", |
| 533 | suspendedByDecision: true, |
| 534 | disabled: true, |
| 535 | }); |
| 536 | |
| 537 | // A stays locally suspended for a while (clear-context style / no controller wait). |
| 538 | await act(async () => { |
| 539 | await new Promise((resolve) => setTimeout(resolve, 2400)); |
| 540 | }); |
| 541 | |
| 542 | // Switch to B, already awaiting approval since tabBWaitStarted (background). |
| 543 | await rerender({ |
| 544 | sessionKey: "tab-b", |
| 545 | turnStartAt: tabBStart, |
| 546 | turnWaitAccumMs: 0, |
| 547 | promptWaitStartedAt: tabBWaitStarted, |
| 548 | suspendedByDecision: true, |
| 549 | disabled: true, |
| 550 | }); |
| 551 | await act(async () => { |
| 552 | await new Promise((resolve) => setTimeout(resolve, 300)); |
| 553 | }); |
| 554 | |
| 555 | // Controller closes the open wait into turnWaitAccumMs on resolve. |
| 556 | const closedWaitMs = Date.now() - tabBWaitStarted; |
| 557 | await rerender({ |
| 558 | suspendedByDecision: false, |
| 559 | disabled: false, |
| 560 | promptWaitStartedAt: undefined, |
| 561 | turnWaitAccumMs: closedWaitMs, |
| 562 | }); |
| 563 | |
| 564 | const ticker = await readRunMetrics(); |
| 565 | // 8s turn age − ~3.3s user wait ≈ 5s model work (not ~8s wall, not ~0–2s from A leak). |
| 566 | ok(/4s|5s|6s/.test(ticker), `tab B excludes background user-wait from model clock (got "${ticker}")`); |
| 567 | ok(!/ 7s| 8s| 9s| 10s| 11s/.test(ticker), "background suspension is not counted as model work"); |
| 568 | ok(!/ 5[5-9]s| 6[0-9]s/.test(ticker), "tab B does not show tab A's ~60s turn age as model time"); |
| 569 | |
| 570 | await act(async () => { |
| 571 | root.unmount(); |
| 572 | }); |
| 573 | dom.window.close(); |
| 574 | } |
| 575 | |
| 576 | // Streaming TPS combines completed usage with only the current request's live |
| 577 | // character estimate, and divides by provider-output time rather than turn age. |
| 578 | { |
| 579 | const dom = installDom(); |
| 580 | const live = { id: "assistant-1", text: "x".repeat(40), reasoning: "", reasoningComplete: false }; |
| 581 | const { root } = await renderComposer({ |
| 582 | running: true, |
| 583 | tabId: "tab-tps", |
| 584 | turnStartAt: Date.now() - 60_000, |
| 585 | turnTokens: 8, |
| 586 | turnOutputTokens: 10, |
| 587 | turnOutputCharsAtUsage: 0, |
| 588 | turnModelActiveMs: 2_000, |
| 589 | liveStore: { |
| 590 | subscribe: () => () => {}, |
| 591 | getSnapshot: () => live, |
| 592 | }, |
| 593 | }); |
| 594 | |
| 595 | const ticker = await readRunMetrics(); |
| 596 | ok(ticker.includes("10 t/s"), "streaming TPS uses provider-output time instead of full turn age"); |
| 597 | ok(ticker.includes("≈10 t/s"), "the streaming reading carries the estimate marker"); |
| 598 | ok(ticker.includes("18 tokens"), "streaming token total adds the current request estimate to completed usage"); |
| 599 | |
| 600 | await act(async () => { |
| 601 | root.unmount(); |
| 602 | }); |
| 603 | dom.window.close(); |
| 604 | } |
| 605 | |
| 606 | // The run strip carries those same readings during ordinary work, and withholds |
| 607 | // throughput once the model stops emitting rather than freezing a stale rate. |
| 608 | { |
| 609 | const dom = installDom(); |
| 610 | const live = { id: "assistant-1", text: "x".repeat(40), reasoning: "", reasoningComplete: false }; |
| 611 | const stripText = () => document.querySelector(".composer-run-strip__text")?.textContent ?? ""; |
| 612 | const { root, rerender } = await renderComposer({ |
| 613 | running: true, |
| 614 | tabId: "tab-strip", |
| 615 | turnStartAt: Date.now() - 60_000, |
| 616 | turnTokens: 8, |
| 617 | turnOutputTokens: 10, |
| 618 | turnOutputCharsAtUsage: 0, |
| 619 | turnModelActiveMs: 2_000, |
| 620 | turnModelActiveAt: Date.now(), |
| 621 | liveStore: { subscribe: () => () => {}, getSnapshot: () => live }, |
| 622 | }); |
| 623 | |
| 624 | ok(stripText().includes("18 tokens"), "the run strip carries the live token readout"); |
| 625 | ok(stripText().includes("10 t/s"), "an emitting model contributes throughput to the strip"); |
| 626 | eq((stripText().match(/≈/g) ?? []).length, 1, "the strip marks the estimate once"); |
| 627 | ok(!/[()·]/.test(stripText()), "no grouping punctuation: colour and position do the separating"); |
| 628 | const readings = document.querySelector(".composer-run-strip__metrics"); |
| 629 | const readingsText = readings?.textContent ?? ""; |
| 630 | ok(/^ \d+(m \d+)?s ≈18 tokens 10 t\/s$/.test(readingsText), |
| 631 | `readings read as clock, tokens, throughput (got "${readingsText}")`); |
| 632 | const shed = document.querySelector(".composer-run-strip__metric--optional"); |
| 633 | eq(shed?.textContent, " 10 t/s", "throughput owns the trailing segment so a narrow strip sheds it whole"); |
| 634 | ok(!(shed?.textContent ?? "").includes("tokens"), |
| 635 | "the clock and token count sit outside the shedable segment and are never cut"); |
| 636 | |
| 637 | await rerender({ turnModelActiveAt: undefined }); |
| 638 | ok(stripText().includes("18 tokens"), "the token readout survives the model going quiet"); |
| 639 | ok(!stripText().includes("t/s"), "a quiet model withholds throughput instead of freezing a rate"); |
| 640 | eq(document.querySelector(".composer-run-strip__metric--optional"), null, |
| 641 | "a quiet model contributes no shedable segment"); |
| 642 | |
| 643 | await rerender({ running: false, turnDoneAt: Date.now() }); |
| 644 | ok(stripText() === "", "a settled turn drops the strip readings"); |
| 645 | |
| 646 | await act(async () => { |
| 647 | root.unmount(); |
| 648 | }); |
| 649 | dom.window.close(); |
| 650 | } |
| 651 | |
| 652 | // Metrics survive wait/retry/completion and derive completed time from the |
| 653 | // controller timestamp, including when mounting an already completed tab. |
| 654 | { |
| 655 | const dom = installDom(); |
| 656 | const start = Date.now() - 30_000; |
| 657 | const { root, rerender } = await renderComposer({ |
| 658 | running: true, turnStartAt: start, turnTokens: 100, |
| 659 | turnOutputTokens: 20, turnModelActiveMs: 2_000, |
| 660 | }); |
| 661 | await rerender({ pendingApprovalLabel: "Run command", disabled: true }); |
| 662 | ok((await readRunMetrics()).includes("100 tokens"), "approval wait retains turn tokens"); |
| 663 | await rerender({ pendingApprovalLabel: null, disabled: false, |
| 664 | retry: { attempt: 1, max: 3 } }); |
| 665 | ok((await readRunMetrics()).includes("10 t/s"), "retry retains throughput"); |
| 666 | await rerender({ running: false, retry: undefined, turnDoneAt: start + 20_000, |
| 667 | lastTurnOutputTokens: 24, turnWaitAccumMs: 0 }); |
| 668 | const completed = await readRunMetrics(); |
| 669 | ok(/19s|20s/.test(completed), `completed duration uses the controller timestamp minus local wait (got "${completed}")`); |
| 670 | ok(completed.includes("104 tokens"), "completion keeps final in-flight token estimates"); |
| 671 | await rerender({ lastTurnWaitAccumMs: 0, turnWaitAccumMs: 60_000 }); |
| 672 | ok((await readRunMetrics()).includes("20s"), "later wait accounting cannot change the frozen completion duration"); |
| 673 | await rerender({ sessionKey: "completed-tab", tabId: "completed-tab" }); |
| 674 | ok((await readRunMetrics()).includes("20s"), "switching to a completed tab preserves its duration"); |
| 675 | await rerender({ running: true, turnStartAt: Date.now(), turnDoneAt: 0, |
| 676 | turnTokens: 0, turnOutputTokens: 0, turnModelActiveMs: 0 }); |
| 677 | ok(!(await readRunMetrics()).includes("104 tokens"), "new turn does not inherit previous turn metrics"); |
| 678 | await act(async () => { root.unmount(); }); |
| 679 | dom.window.close(); |
| 680 | } |
| 681 | |
| 682 | { |
| 683 | const dom = installDom(); |
| 684 | const picked: string[] = []; |
| 685 | let modelChanges = 0; |
| 686 | const { root, rerender } = await renderComposer({ |
| 687 | effort: { supported: true, current: "auto", default: "high", levels: ["auto", "high", "max"] }, |
| 688 | onSetEffort: level => picked.push(level), |
| 689 | onSwitchModel: () => { modelChanges += 1; }, |
| 690 | }); |
| 691 | const trigger = document.querySelector<HTMLButtonElement>(".composer-effort-control button"); |
| 692 | if (!trigger) throw new Error("missing independent effort selector"); |
| 693 | await act(async () => { trigger.click(); await flushTimers(); }); |
| 694 | const high = [...document.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')].find(e => e.textContent === "high"); |
| 695 | if (!high) throw new Error("missing high effort option"); |
| 696 | await act(async () => { high.click(); await flushTimers(); }); |
| 697 | eq(picked.join(","), "high", "separate effort selector changes reasoning effort"); |
| 698 | eq(modelChanges, 0, "changing effort does not switch models"); |
| 699 | eq(trigger.getAttribute("aria-expanded"), "false", "effort menu closes after selection"); |
| 700 | await rerender({ effort: { supported: false, current: "auto", default: "auto", levels: [] } }); |
| 701 | eq(document.querySelector(".composer-effort-control"), null, "unsupported models hide effort control"); |
| 702 | await act(async () => root.unmount()); |
| 703 | dom.window.close(); |
| 704 | } |
| 705 | |
| 706 | { |
| 707 | const dom = installDom(); |
| 708 | const modeChanges: string[] = []; |
| 709 | const { root } = await renderComposer({ collaborationMode: "plan", onSetCollaborationMode: mode => modeChanges.push(mode) }); |
| 710 | eq(document.querySelector(".composer-delivery-trigger"), null, "composer has no delivery chip"); |
| 711 | await act(async () => { |
| 712 | document.querySelector<HTMLButtonElement>(".composer-content-trigger")?.click(); |
| 713 | await flushTimers(); |
| 714 | }); |
| 715 | const toggle = document.querySelector<HTMLButtonElement>('[role="menuitemcheckbox"]'); |
| 716 | eq(toggle, null, "content menu has no delivery toggle"); |
| 717 | eq(modeChanges.length, 0, "opening the menu does not change Plan mode"); |
| 718 | await act(async () => root.unmount()); |
| 719 | dom.window.close(); |
| 720 | } |
| 721 | |
| 722 | // Resize consistency: --composer-height always carries the logical height in |
| 723 | // every writer (React render, live drag, keyboard), with the run strip's |
| 724 | // reservation isolated in a CSS calc. A manual height is the draft's minimum, |
| 725 | // so content can grow above it without changing the saved resize baseline. |
| 726 | { |
| 727 | const stylesSource = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../styles.css"), "utf8"); |
| 728 | ok( |
| 729 | stylesSource.includes("calc(var(--composer-height) + var(--composer-run-strip-reserved, 0px))"), |
| 730 | "resized card height combines logical height and strip reservation in CSS", |
| 731 | ); |
| 732 | |
| 733 | const dom = installDom(); |
| 734 | const { root, rerender } = await renderComposer({ running: true, turnStartAt: Date.now() }); |
| 735 | |
| 736 | const handle = document.querySelector(".composer-resize-handle") as HTMLButtonElement; |
| 737 | eq((document.querySelector(".composer-card") as HTMLElement).style.getPropertyValue("--composer-height"), "140px", "fresh composer defaults to the selected 140px height"); |
| 738 | await act(async () => { |
| 739 | handle.focus(); |
| 740 | handle.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Home", bubbles: true })); |
| 741 | await flushTimers(); |
| 742 | }); |
| 743 | |
| 744 | const card = document.querySelector(".composer-card") as HTMLElement; |
| 745 | eq(card.style.getPropertyValue("--composer-height"), "104px", "render path writes the logical height, not a compensated one"); |
| 746 | eq(card.style.getPropertyValue("--composer-run-strip-reserved"), "30px", "ordinary running state reserves the metrics strip height"); |
| 747 | |
| 748 | // Drag while running: the live writer stays in logical-height space. |
| 749 | await act(async () => { |
| 750 | handle.dispatchEvent(new window.MouseEvent("pointerdown", { bubbles: true, clientY: 300 })); |
| 751 | await flushTimers(); |
| 752 | }); |
| 753 | eq(card.style.getPropertyValue("--composer-height"), "104px", "drag start does not flash-shrink the running card"); |
| 754 | |
| 755 | await act(async () => { |
| 756 | document.dispatchEvent(new window.MouseEvent("pointermove", { bubbles: true, clientY: 280 })); |
| 757 | document.dispatchEvent(new window.MouseEvent("pointerup", { bubbles: true, clientY: 280 })); |
| 758 | await flushTimers(); |
| 759 | }); |
| 760 | eq(card.style.getPropertyValue("--composer-height"), "124px", "drag release keeps the same logical-height space as the render path"); |
| 761 | eq(card.style.getPropertyValue("--composer-run-strip-reserved"), "30px", "dragging keeps the running strip reservation"); |
| 762 | eq(handle.getAttribute("aria-valuenow"), "124", "separator reports the logical height"); |
| 763 | |
| 764 | await rerender({ running: false, turnStartAt: undefined }); |
| 765 | eq(card.style.getPropertyValue("--composer-run-strip-reserved"), "0px", "idle card releases the strip reservation"); |
| 766 | eq(card.style.getPropertyValue("--composer-height"), "124px", "idle card keeps the user's logical height"); |
| 767 | |
| 768 | const textarea = document.querySelector(".composer__input") as HTMLTextAreaElement; |
| 769 | const measureTextarea = document.querySelector(".composer__input--measure") as HTMLTextAreaElement; |
| 770 | let measuredDraftHeight = 108; |
| 771 | Object.defineProperty(measureTextarea, "scrollHeight", { |
| 772 | configurable: true, |
| 773 | get: () => measuredDraftHeight, |
| 774 | }); |
| 775 | const updateDraft = async (value: string) => { |
| 776 | await act(async () => { |
| 777 | textarea.focus(); |
| 778 | textarea.setSelectionRange(0, textarea.value.length); |
| 779 | const paste = new window.Event("paste", { bubbles: true, cancelable: true }); |
| 780 | Object.defineProperty(paste, "clipboardData", { |
| 781 | configurable: true, |
| 782 | value: { |
| 783 | files: [], |
| 784 | items: [], |
| 785 | types: ["text/plain"], |
| 786 | getData: (kind: string) => (kind === "text" || kind === "text/plain" ? value : ""), |
| 787 | }, |
| 788 | }); |
| 789 | textarea.dispatchEvent(paste); |
| 790 | await flushTimers(); |
| 791 | }); |
| 792 | }; |
| 793 | |
| 794 | await updateDraft("a longer pasted draft"); |
| 795 | eq(card.style.getPropertyValue("--composer-height"), "166px", "longer draft grows above the manual baseline"); |
| 796 | eq(textarea.style.height, "108px", "content-derived input height reveals the longer draft"); |
| 797 | eq(textarea.style.overflowY, "hidden", "draft stays scrollbar-free below the cap"); |
| 798 | |
| 799 | measuredDraftHeight = 22; |
| 800 | await updateDraft("short"); |
| 801 | eq(card.style.getPropertyValue("--composer-height"), "124px", "shorter draft returns to the manual baseline"); |
| 802 | eq(textarea.style.height, "66px", "manual baseline remains available to short drafts"); |
| 803 | |
| 804 | measuredDraftHeight = 420; |
| 805 | await updateDraft("an oversized pasted draft"); |
| 806 | const viewportCap = Math.min(360, Math.floor(window.innerHeight * 0.4)); |
| 807 | eq(card.style.getPropertyValue("--composer-height"), `${viewportCap}px`, "oversized draft stops at the viewport-aware cap"); |
| 808 | eq(textarea.style.height, `${viewportCap - 58}px`, "oversized input uses the capped content viewport"); |
| 809 | eq(textarea.style.overflowY, "auto", "oversized draft scrolls only after reaching the cap"); |
| 810 | |
| 811 | measuredDraftHeight = 22; |
| 812 | await updateDraft(""); |
| 813 | await act(async () => { |
| 814 | handle.dispatchEvent(new window.MouseEvent("dblclick", { bubbles: true })); |
| 815 | await flushTimers(); |
| 816 | }); |
| 817 | eq(card.style.getPropertyValue("--composer-height"), "140px", "reset restores the 140px default after manual resizing"); |
| 818 | |
| 819 | await act(async () => { |
| 820 | root.unmount(); |
| 821 | }); |
| 822 | dom.window.close(); |
| 823 | } |
| 824 | |
| 825 | console.log(`\n${passed} passed, ${failed} failed`); |
| 826 | if (failed > 0) process.exit(1); |
| 827 |