| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { readFile } from "node:fs/promises"; |
| 4 | |
| 5 | import { |
| 6 | NO_TARGET, |
| 7 | PEEK_DEFAULT_ENTRIES, |
| 8 | PEEK_EXPANDED_ENTRIES, |
| 9 | approvalCardCopy, |
| 10 | composerPlaceholderFor, |
| 11 | headerTitleFor, |
| 12 | peekCanShowEarlier, |
| 13 | peekOmittedLabel, |
| 14 | savedSessionNotice, |
| 15 | showNoMatchingThreads, |
| 16 | STREAM_EVENT_NAMES, |
| 17 | answersForUserInput, |
| 18 | applyRuntimeEvent, |
| 19 | applySnapshot, |
| 20 | buildCreateThreadRequest, |
| 21 | claimInFlight, |
| 22 | collectProviderModelPages, |
| 23 | createThreadState, |
| 24 | createWebSessionFetch, |
| 25 | createStreamConnector, |
| 26 | eventStreamUrl, |
| 27 | formatRuntimeProvenance, |
| 28 | imageInputPresentation, |
| 29 | isComposerSubmitKey, |
| 30 | groupThreadSummaries, |
| 31 | modeLabel, |
| 32 | modelOptionLabel, |
| 33 | newThreadDefaults, |
| 34 | pendingAttentionCount, |
| 35 | pendingAttentionLabel, |
| 36 | providerOptionLabel, |
| 37 | receiptPresentation, |
| 38 | recoverSnapshotAndSubscribe, |
| 39 | renderRuntimeProvenance, |
| 40 | resolveUserInputTarget, |
| 41 | restoreDraft, |
| 42 | runtimeEventContinuity, |
| 43 | saveDraft, |
| 44 | sessionTarget, |
| 45 | setSafeText, |
| 46 | snapshotThenSubscribe, |
| 47 | threadTarget, |
| 48 | threadProviderLabel, |
| 49 | } from "../src/runtime_web/app.mjs"; |
| 50 | |
| 51 | function snapshot(threadId = "thread-a", latestSeq = 7) { |
| 52 | return { |
| 53 | thread: { id: threadId, title: "Test", model: "test", mode: "agent" }, |
| 54 | turns: [{ id: "turn-1", status: "in_progress" }], |
| 55 | items: [ |
| 56 | { |
| 57 | id: "item-1", |
| 58 | turn_id: "turn-1", |
| 59 | kind: "agent_message", |
| 60 | status: "in_progress", |
| 61 | summary: "", |
| 62 | detail: "Hello", |
| 63 | }, |
| 64 | ], |
| 65 | latest_seq: latestSeq, |
| 66 | }; |
| 67 | } |
| 68 | |
| 69 | function runtimeEvent(sequence, event, payload = {}, overrides = {}) { |
| 70 | return { |
| 71 | schema_version: 1, |
| 72 | seq: sequence, |
| 73 | event, |
| 74 | kind: event, |
| 75 | thread_id: "thread-a", |
| 76 | turn_id: "turn-1", |
| 77 | item_id: null, |
| 78 | payload, |
| 79 | ...overrides, |
| 80 | }; |
| 81 | } |
| 82 | |
| 83 | function cssDeclarations(styles, selectorPattern) { |
| 84 | const match = styles.match(new RegExp(`${selectorPattern}\\s*\\{([^}]*)\\}`)); |
| 85 | assert.ok(match, `missing CSS rule matching ${selectorPattern}`); |
| 86 | return match[1]; |
| 87 | } |
| 88 | |
| 89 | test("embedded web client uses the Ocean Blue Stage semantic palette", async () => { |
| 90 | const [styles, html] = await Promise.all([ |
| 91 | readFile(new URL("../src/runtime_web/styles.css", import.meta.url), "utf8"), |
| 92 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 93 | ]); |
| 94 | |
| 95 | for (const token of [ |
| 96 | "--bg: #020711", |
| 97 | "--sidebar: #050b16", |
| 98 | "--surface: #0e1a30", |
| 99 | "--surface-raised: #172945", |
| 100 | "--stage-surface: #142747", |
| 101 | "--text: #f6f2e8", |
| 102 | "--action: #6aaef2", |
| 103 | "--status-human: #f6c453", |
| 104 | "--status-live: #4fd1c5", |
| 105 | "--status-warning: #ff7a59", |
| 106 | "--status-danger: #ff86b2", |
| 107 | "--ok: #9bd66f", |
| 108 | "--radius-control: 6px", |
| 109 | "--radius-card: 12px", |
| 110 | "--radius-composer: 16px", |
| 111 | "--rail: 256px", |
| 112 | ]) { |
| 113 | assert.match(styles, new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); |
| 114 | } |
| 115 | assert.match( |
| 116 | cssDeclarations(styles, "\\.primary-button,\\s*\\.send-button"), |
| 117 | /background: var\(--action\)/, |
| 118 | ); |
| 119 | assert.match( |
| 120 | cssDeclarations(styles, "\\.status-pip\\.running"), |
| 121 | /background: var\(--live\)/, |
| 122 | ); |
| 123 | assert.match( |
| 124 | cssDeclarations(styles, "\\.message\\.user \\.message-body"), |
| 125 | /background: var\(--plate\)/, |
| 126 | ); |
| 127 | assert.match( |
| 128 | cssDeclarations(styles, "\\.attention-card"), |
| 129 | /border: 1px solid rgba\(246, 196, 83/, |
| 130 | ); |
| 131 | assert.match( |
| 132 | cssDeclarations(styles, "\\.status-banner"), |
| 133 | /color: var\(--warning\)/, |
| 134 | ); |
| 135 | assert.match( |
| 136 | cssDeclarations(styles, "\\.connection-dot\\.ready"), |
| 137 | /background: var\(--ok\)/, |
| 138 | ); |
| 139 | assert.match(html, /name="theme-color" content="#020711"/); |
| 140 | }); |
| 141 | |
| 142 | test("embedded web client keeps the CWC stage, transcript, and receipt hierarchy quiet", async () => { |
| 143 | const [styles, html, source] = await Promise.all([ |
| 144 | readFile(new URL("../src/runtime_web/styles.css", import.meta.url), "utf8"), |
| 145 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 146 | readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"), |
| 147 | ]); |
| 148 | |
| 149 | assert.match(cssDeclarations(styles, "\\.session"), /background: var\(--stage-surface\)/); |
| 150 | assert.match(cssDeclarations(styles, "\\.transcript"), /background: var\(--stage-surface\)/); |
| 151 | assert.match(cssDeclarations(styles, "\\.receipt"), /display:\s*flex/); |
| 152 | assert.match(cssDeclarations(styles, "\\.receipt-dot"), /background: var\(--live\)/); |
| 153 | assert.match( |
| 154 | cssDeclarations(styles, "\\.message\\.user \\.message-label"), |
| 155 | /display:\s*none/, |
| 156 | ); |
| 157 | assert.match(html, /id="transcript" role="log"[^>]+aria-relevant="additions"/); |
| 158 | assert.doesNotMatch(html, /id="transcript" role="log"[^>]+aria-relevant="[^"]*text/); |
| 159 | assert.match(source, /card\.append\(element\("span", "receipt-dot"\)\)/); |
| 160 | }); |
| 161 | |
| 162 | test("thread rail groups typed pending requests without disturbing server order", async () => { |
| 163 | const summaries = [ |
| 164 | { id: "newest-recent", pending_attention_count: 0 }, |
| 165 | { id: "newest-needs-you", pending_attention_count: 2 }, |
| 166 | { id: "older-needs-you", pending_attention_count: 1 }, |
| 167 | { id: "older-recent", pending_attention_count: 0 }, |
| 168 | ]; |
| 169 | const groups = groupThreadSummaries(summaries); |
| 170 | |
| 171 | assert.deepEqual(groups.needsYou.map(({ id }) => id), ["newest-needs-you", "older-needs-you"]); |
| 172 | assert.deepEqual(groups.recent.map(({ id }) => id), ["newest-recent", "older-recent"]); |
| 173 | assert.deepEqual(summaries.map(({ id }) => id), [ |
| 174 | "newest-recent", |
| 175 | "newest-needs-you", |
| 176 | "older-needs-you", |
| 177 | "older-recent", |
| 178 | ]); |
| 179 | assert.equal(pendingAttentionCount({ pending_attention_count: -1 }), 0); |
| 180 | assert.equal(pendingAttentionLabel({ pending_attention_count: 1 }), "1 item needs your attention"); |
| 181 | assert.equal(pendingAttentionLabel({ pending_attention_count: 2 }), "2 items need your attention"); |
| 182 | |
| 183 | const [html, source] = await Promise.all([ |
| 184 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 185 | readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"), |
| 186 | ]); |
| 187 | assert.match(html, /id="thread-list" aria-label="Live threads"/); |
| 188 | assert.match(source, /group\.setAttribute\("aria-labelledby", headingId\)/); |
| 189 | assert.match(source, /attention\.setAttribute\("aria-label", pendingAttentionLabel\(summary\)\)/); |
| 190 | }); |
| 191 | |
| 192 | test("mobile drawer owns focus and background interaction while it is open", async () => { |
| 193 | const [html, source] = await Promise.all([ |
| 194 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 195 | readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"), |
| 196 | ]); |
| 197 | |
| 198 | assert.match(html, /id="rail-open"[^>]+aria-controls="thread-rail"[^>]+aria-expanded="false"/); |
| 199 | assert.match(html, /id="rail-scrim"[^>]+tabindex="-1" hidden/); |
| 200 | assert.match(source, /function openRail\(\)[\s\S]*dom\.railClose\.focus/); |
| 201 | assert.match(source, /dom\.session\.setAttribute\("aria-hidden", "true"\)[\s\S]*setInert\(dom\.session, true\)/); |
| 202 | assert.match(source, /function closeRail[\s\S]*returnTarget\.focus[\s\S]*applyClosedMobileRailAccessibility/); |
| 203 | assert.match(source, /function trapFocusWithin[\s\S]*event\.key !== "Tab"[\s\S]*first\.focus/); |
| 204 | assert.match(source, /function trapRailFocus[\s\S]*trapFocusWithin\(event, dom\.rail\)/); |
| 205 | assert.match(source, /document\.addEventListener\("keydown", \(event\) => \{\s+if \(dom\.newThreadDialog\.open\) return;\s+if \(trapRailFocus\(event\)\) return;/); |
| 206 | assert.match(source, /event\.key === "Escape"[\s\S]*closeRail\(\)/); |
| 207 | }); |
| 208 | |
| 209 | test("mobile viewport and truth controls survive the software keyboard and coarse input", async () => { |
| 210 | const [styles, source] = await Promise.all([ |
| 211 | readFile(new URL("../src/runtime_web/styles.css", import.meta.url), "utf8"), |
| 212 | readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"), |
| 213 | ]); |
| 214 | |
| 215 | assert.match(styles, /height: var\(--visual-viewport-height\)/); |
| 216 | assert.match(source, /globalThis\.visualViewport\?\.addEventListener\("resize", syncVisualViewport\)/); |
| 217 | assert.match(styles, /@media \(pointer: coarse\)[\s\S]*min-height: 44px/); |
| 218 | assert.match( |
| 219 | styles, |
| 220 | /@media \(max-width: 800px\)[\s\S]*\.composer textarea,[\s\S]*font-size: 16px/, |
| 221 | ); |
| 222 | assert.match(styles, /@media \(max-width: 430px\)[\s\S]*\.session-facts \{[\s\S]*display: flex/); |
| 223 | assert.match(styles, /\.session-facts \.fact-chip\[data-fact="workspace"\][\s\S]*display: none/); |
| 224 | assert.match(source, /chip\.dataset\.fact = String\(label \|\| ""\)\.toLowerCase\(\)/); |
| 225 | }); |
| 226 | |
| 227 | test("stream reconciliation preserves live controls, disclosures, and selected transcript text", async () => { |
| 228 | const [html, source] = await Promise.all([ |
| 229 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 230 | readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"), |
| 231 | ]); |
| 232 | |
| 233 | assert.match(html, /id="attention" role="region"[^>]+aria-live="assertive"[^>]+aria-relevant="additions"/); |
| 234 | assert.equal(source.includes("dom.transcript.replaceChildren"), false); |
| 235 | assert.equal(source.includes("dom.attention.replaceChildren"), false); |
| 236 | assert.match(source, /function reconcileChildren\(/); |
| 237 | assert.match(source, /captureTranscriptSelection\(\)[\s\S]*restoreTranscriptSelection\(selection\)/); |
| 238 | assert.match(source, /card\.dataset\.attentionKey = key/); |
| 239 | assert.equal(source.includes("focusPendingAttention"), false); |
| 240 | assert.doesNotMatch(source, /card\.tabIndex = -1/); |
| 241 | }); |
| 242 | |
| 243 | test("attention requests stay single-flight without stealing the active control", async () => { |
| 244 | const requests = new Set(); |
| 245 | assert.equal(claimInFlight(requests, "approval:one"), true); |
| 246 | assert.equal(claimInFlight(requests, "approval:one"), false); |
| 247 | requests.delete("approval:one"); |
| 248 | assert.equal(claimInFlight(requests, "approval:one"), true); |
| 249 | |
| 250 | const source = await readFile( |
| 251 | new URL("../src/runtime_web/app.mjs", import.meta.url), |
| 252 | "utf8", |
| 253 | ); |
| 254 | assert.match(source, /if \(!claimInFlight\(app\.inFlightActions, action\)\) return;/); |
| 255 | assert.match(source, /setAttentionCardBusy\(action, true\)/); |
| 256 | assert.match(source, /finally \{\s+app\.inFlightActions\.delete\(action\);\s+setAttentionCardBusy\(action, false\);/); |
| 257 | }); |
| 258 | |
| 259 | test("degraded workflow receipts surface rejected dispatches as attention", () => { |
| 260 | const detail = JSON.stringify({ |
| 261 | status: "degraded", |
| 262 | dispatch_failure_count: 2, |
| 263 | dispatch_failures: [{ label: "review", message: "profile unavailable" }], |
| 264 | }); |
| 265 | assert.deepEqual(receiptPresentation({ |
| 266 | kind: "tool_call", |
| 267 | status: "completed", |
| 268 | summary: "workflow: degraded", |
| 269 | detail, |
| 270 | metadata: { status: "degraded", dispatch_failure_count: 2 }, |
| 271 | }), { |
| 272 | label: "Workflow · Needs attention", |
| 273 | summary: "2 task dispatches were rejected", |
| 274 | raw: `workflow: degraded\n\n${detail}`, |
| 275 | failed: true, |
| 276 | }); |
| 277 | }); |
| 278 | |
| 279 | test("rail New thread cannot paint over the session fact chips", async () => { |
| 280 | const styles = await readFile( |
| 281 | new URL("../src/runtime_web/styles.css", import.meta.url), |
| 282 | "utf8", |
| 283 | ); |
| 284 | assert.match(cssDeclarations(styles, "\\.rail"), /overflow:\s*hidden/); |
| 285 | assert.match(cssDeclarations(styles, "\\.new-thread"), /max-width:\s*100%/); |
| 286 | assert.match(cssDeclarations(styles, "\\.session-header"), /overflow:\s*hidden/); |
| 287 | assert.match(cssDeclarations(styles, "\\.session-facts"), /flex-wrap:\s*nowrap/); |
| 288 | }); |
| 289 | |
| 290 | test("production shell keeps readable type, controls, focus, and motion contracts", async () => { |
| 291 | const [styles, html] = await Promise.all([ |
| 292 | readFile(new URL("../src/runtime_web/styles.css", import.meta.url), "utf8"), |
| 293 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 294 | ]); |
| 295 | |
| 296 | assert.match(cssDeclarations(styles, "\\.thread-row"), /min-height:\s*62px/); |
| 297 | assert.match(cssDeclarations(styles, "\\.thread-title"), /font-size:\s*14px/); |
| 298 | assert.match(cssDeclarations(styles, "\\.message-body"), /font-size:\s*15\.5px/); |
| 299 | assert.match(cssDeclarations(styles, "\\.composer textarea"), /font-size:\s*15\.5px/); |
| 300 | assert.match(cssDeclarations(styles, "\\.composer textarea"), /max-height:\s*220px/); |
| 301 | assert.match( |
| 302 | styles, |
| 303 | /\.primary-button,[\s\S]*?\.icon-button\s*\{[\s\S]*?min-height:\s*36px/, |
| 304 | ); |
| 305 | assert.match( |
| 306 | styles, |
| 307 | /button:focus-visible,[\s\S]*?outline:\s*3px solid var\(--action\)/, |
| 308 | ); |
| 309 | assert.match( |
| 310 | styles, |
| 311 | /@media \(prefers-reduced-motion: reduce\)[\s\S]*scroll-behavior: auto !important/, |
| 312 | ); |
| 313 | assert.match(html, /Enter send · Shift\+Enter newline/); |
| 314 | }); |
| 315 | |
| 316 | test("composer Enter sends without interrupting newlines or IME composition", () => { |
| 317 | assert.equal(isComposerSubmitKey({ key: "Enter" }), true); |
| 318 | assert.equal(isComposerSubmitKey({ key: "Enter", metaKey: true }), true); |
| 319 | assert.equal(isComposerSubmitKey({ key: "Enter", ctrlKey: true }), true); |
| 320 | assert.equal(isComposerSubmitKey({ key: "Enter", shiftKey: true }), false); |
| 321 | assert.equal(isComposerSubmitKey({ key: "Enter", isComposing: true }), false); |
| 322 | assert.equal(isComposerSubmitKey({ key: "a" }), false); |
| 323 | }); |
| 324 | |
| 325 | test("new thread selection keeps provider and model scoped to the create request", () => { |
| 326 | const catalog = { |
| 327 | current: "deepseek", |
| 328 | providers: [ |
| 329 | { id: "openai", default_model: "gpt-5.6" }, |
| 330 | { id: "deepseek", default_model: "deepseek-v4-pro" }, |
| 331 | ], |
| 332 | }; |
| 333 | assert.deepEqual(newThreadDefaults(catalog), { |
| 334 | providerId: "deepseek", |
| 335 | modelProviderId: "", |
| 336 | model: "deepseek-v4-pro", |
| 337 | }); |
| 338 | assert.deepEqual( |
| 339 | buildCreateThreadRequest(" deepseek ", " deepseek-v4-flash-vision-exp "), |
| 340 | { |
| 341 | model_provider: "deepseek", |
| 342 | model: "deepseek-v4-flash-vision-exp", |
| 343 | }, |
| 344 | ); |
| 345 | assert.throws(() => buildCreateThreadRequest("deepseek", ""), /provider and a model/); |
| 346 | |
| 347 | const namedCustom = { |
| 348 | current: "custom", |
| 349 | current_provider_id: "seer-vibe", |
| 350 | providers: [ |
| 351 | { |
| 352 | id: "custom", |
| 353 | model_provider_id: "another-gateway", |
| 354 | default_model: "other-model", |
| 355 | }, |
| 356 | { |
| 357 | id: "custom", |
| 358 | model_provider_id: "seer-vibe", |
| 359 | default_model: "deepseek/deepseek-flash", |
| 360 | }, |
| 361 | ], |
| 362 | }; |
| 363 | assert.deepEqual(newThreadDefaults(namedCustom), { |
| 364 | providerId: "custom", |
| 365 | modelProviderId: "seer-vibe", |
| 366 | model: "deepseek/deepseek-flash", |
| 367 | }); |
| 368 | assert.deepEqual( |
| 369 | buildCreateThreadRequest("custom", "deepseek/deepseek-flash", "seer-vibe"), |
| 370 | { |
| 371 | model_provider: "custom", |
| 372 | model: "deepseek/deepseek-flash", |
| 373 | model_provider_id: "seer-vibe", |
| 374 | }, |
| 375 | ); |
| 376 | assert.equal( |
| 377 | providerOptionLabel({ |
| 378 | id: "custom", |
| 379 | display_name: "Custom", |
| 380 | model_provider_id: "lm-studio", |
| 381 | }), |
| 382 | "Custom · lm-studio", |
| 383 | ); |
| 384 | assert.equal(threadProviderLabel({ |
| 385 | model_provider: "custom", |
| 386 | model_provider_id: "lm-studio", |
| 387 | }), "lm-studio"); |
| 388 | assert.equal(threadProviderLabel({ model_provider: "deepseek" }), "deepseek"); |
| 389 | }); |
| 390 | |
| 391 | test("named custom model catalogs request and validate the exact route identity", async () => { |
| 392 | const paths = []; |
| 393 | const models = await collectProviderModelPages("custom", async (path) => { |
| 394 | paths.push(path); |
| 395 | return { |
| 396 | provider: "custom", |
| 397 | model_provider_id: "seer-vibe", |
| 398 | models: [{ id: "deepseek/deepseek-flash" }], |
| 399 | total: 1, |
| 400 | }; |
| 401 | }, "seer-vibe"); |
| 402 | |
| 403 | assert.equal(models[0].id, "deepseek/deepseek-flash"); |
| 404 | assert.equal(new URL(paths[0], "http://runtime.local").searchParams.get("model_provider_id"), "seer-vibe"); |
| 405 | await assert.rejects(collectProviderModelPages("custom", async () => ({ |
| 406 | provider: "custom", |
| 407 | model_provider_id: "another-gateway", |
| 408 | models: [], |
| 409 | total: 0, |
| 410 | }), "seer-vibe"), /different provider/); |
| 411 | }); |
| 412 | |
| 413 | test("thread facts keep exact named provider identity visible after creation", async () => { |
| 414 | const source = await readFile( |
| 415 | new URL("../src/runtime_web/app.mjs", import.meta.url), |
| 416 | "utf8", |
| 417 | ); |
| 418 | assert.match(source, /const provider = threadProviderLabel\(thread\)/); |
| 419 | assert.match(source, /factChip\("Provider", provider\)/); |
| 420 | }); |
| 421 | |
| 422 | test("composer send guard survives rerenders until the request settles", async () => { |
| 423 | const source = await readFile( |
| 424 | new URL("../src/runtime_web/app.mjs", import.meta.url), |
| 425 | "utf8", |
| 426 | ); |
| 427 | assert.match(source, /const sending = app\.inFlightActions\.has\(composerSendAction\)/); |
| 428 | assert.match(source, /dom\.composerInput\.disabled = sending \|\| !ready/); |
| 429 | assert.match(source, /dom\.send\.disabled = sending \|\| !ready/); |
| 430 | assert.match(source, /if \(!claimInFlight\(app\.inFlightActions, composerSendAction\)\) return;/); |
| 431 | assert.match(source, /finally \{\s+app\.inFlightActions\.delete\(composerSendAction\);\s+renderComposer\(\);/); |
| 432 | }); |
| 433 | |
| 434 | test("new thread dialog labels exact vision capability without exposing attachments", async () => { |
| 435 | const [html, source] = await Promise.all([ |
| 436 | readFile(new URL("../src/runtime_web/index.html", import.meta.url), "utf8"), |
| 437 | readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"), |
| 438 | ]); |
| 439 | const vision = { id: "deepseek-v4-flash-vision-exp", image_input: "supported" }; |
| 440 | assert.equal(modelOptionLabel(vision), "deepseek-v4-flash-vision-exp · Vision"); |
| 441 | assert.equal(imageInputPresentation("supported").label, "Vision"); |
| 442 | assert.equal(imageInputPresentation("unsupported").label, "Text only"); |
| 443 | assert.equal(imageInputPresentation("unknown").state, "unknown"); |
| 444 | |
| 445 | assert.match(html, /id="new-thread-dialog"[^>]+tabindex="-1"[^>]+aria-labelledby="new-thread-title"/); |
| 446 | assert.match(html, /id="new-thread-cancel"[^>]+autofocus/); |
| 447 | assert.match(html, /id="new-thread-provider" required disabled/); |
| 448 | assert.match(html, /id="new-thread-model" required disabled/); |
| 449 | assert.match(html, /does not change your Runtime defaults/); |
| 450 | assert.doesNotMatch(html, /type="file"/); |
| 451 | assert.match(source, /api\("\/v1\/providers"\)/); |
| 452 | // The dialog loads the catalog through the bounded, paginated collector |
| 453 | // keyed by the provider kind and exact custom route id. |
| 454 | assert.match(source, /collectProviderModelPages\(provider\.id/); |
| 455 | assert.match(source, /provider\.model_provider_id\);/); |
| 456 | assert.match(source, /query\.set\("model_provider_id", exactProviderId\)/); |
| 457 | assert.match(source, /\/v1\/providers\/\$\{encodeURIComponent\(provider\)\}\/models\?\$\{query\.toString\(\)\}/); |
| 458 | assert.match(source, /body: JSON\.stringify\(request\)/); |
| 459 | assert.match(source, /function trapFocusWithin\(event, container\)/); |
| 460 | assert.match(source, /dom\.newThreadCancel\.focus\(\{ preventScroll: true \}\)/); |
| 461 | assert.match(source, /trapFocusWithin\(event, dom\.newThreadDialog\)/); |
| 462 | assert.doesNotMatch(source, /\/v1\/providers\/[^`"']+\/switch/); |
| 463 | }); |
| 464 | |
| 465 | test("uses the v0.9.6 Work vocabulary for the agent wire mode", () => { |
| 466 | assert.equal(modeLabel("agent"), "Work"); |
| 467 | assert.equal(modeLabel("plan"), "Plan"); |
| 468 | assert.equal(modeLabel("operate"), "Operate"); |
| 469 | }); |
| 470 | |
| 471 | test("formats and renders exact Runtime build provenance with honest fallbacks", () => { |
| 472 | const exactCommit = "abcdef0123456789abcdef0123456789abcdef01"; |
| 473 | const stamped = { |
| 474 | codewhale_version: "0.9.6", |
| 475 | codewhale_commit: exactCommit, |
| 476 | }; |
| 477 | assert.equal(formatRuntimeProvenance(stamped), "0.9.6 · abcdef012345"); |
| 478 | |
| 479 | const rendered = { textContent: "" }; |
| 480 | renderRuntimeProvenance(rendered, stamped); |
| 481 | assert.equal(rendered.textContent, "0.9.6 · abcdef012345"); |
| 482 | |
| 483 | assert.equal( |
| 484 | formatRuntimeProvenance({ codewhale_version: "0.9.6", codewhale_commit: "unknown" }), |
| 485 | "0.9.6 · source unknown", |
| 486 | ); |
| 487 | assert.equal( |
| 488 | formatRuntimeProvenance({ version: "0.9.6", codewhale_commit: "too-short" }), |
| 489 | "0.9.6 · source unknown", |
| 490 | ); |
| 491 | assert.equal(formatRuntimeProvenance(null), "version unknown · source unknown"); |
| 492 | }); |
| 493 | |
| 494 | test("loads a consistent snapshot before subscribing from latest_seq", async () => { |
| 495 | const state = createThreadState("thread-a"); |
| 496 | const order = []; |
| 497 | const subscribed = await snapshotThenSubscribe({ |
| 498 | state, |
| 499 | threadId: "thread-a", |
| 500 | loadSnapshot: async () => { |
| 501 | order.push("snapshot"); |
| 502 | return snapshot("thread-a", 42); |
| 503 | }, |
| 504 | subscribe: (threadId, sequence) => order.push(`subscribe:${threadId}:${sequence}`), |
| 505 | }); |
| 506 | |
| 507 | assert.equal(subscribed, true); |
| 508 | assert.deepEqual(order, ["snapshot", "subscribe:thread-a:42"]); |
| 509 | assert.equal(state.latestSeq, 42); |
| 510 | }); |
| 511 | |
| 512 | test("snapshot recovery waits for the replacement stream to open", async () => { |
| 513 | const state = createThreadState("thread-a"); |
| 514 | let finishOpening; |
| 515 | let settled = false; |
| 516 | const opening = new Promise((resolve) => { |
| 517 | finishOpening = resolve; |
| 518 | }); |
| 519 | const recovery = snapshotThenSubscribe({ |
| 520 | state, |
| 521 | threadId: "thread-a", |
| 522 | loadSnapshot: async () => snapshot("thread-a", 43), |
| 523 | subscribe: () => opening, |
| 524 | }).then((result) => { |
| 525 | settled = true; |
| 526 | return result; |
| 527 | }); |
| 528 | |
| 529 | await Promise.resolve(); |
| 530 | assert.equal(settled, false, "snapshot success alone must not finish recovery"); |
| 531 | finishOpening(); |
| 532 | assert.equal(await recovery, true); |
| 533 | assert.equal(settled, true); |
| 534 | }); |
| 535 | |
| 536 | test("a failed replacement stream keeps the gap until a later stream opens", async () => { |
| 537 | const state = createThreadState("thread-a"); |
| 538 | let gap = true; |
| 539 | let attempts = 0; |
| 540 | const recover = () => recoverSnapshotAndSubscribe({ |
| 541 | state, |
| 542 | threadId: "thread-a", |
| 543 | loadSnapshot: async () => snapshot("thread-a", 44 + attempts), |
| 544 | subscribe: async () => { |
| 545 | attempts += 1; |
| 546 | if (attempts === 1) throw new Error("replacement stream did not reopen"); |
| 547 | }, |
| 548 | }, () => { |
| 549 | gap = false; |
| 550 | }); |
| 551 | |
| 552 | await assert.rejects(recover(), /did not reopen/); |
| 553 | assert.equal(gap, true, "snapshot success must not hide a failed stream handshake"); |
| 554 | assert.equal(await recover(), true); |
| 555 | assert.equal(gap, false, "a later snapshot plus open stream clears the gap"); |
| 556 | }); |
| 557 | |
| 558 | test("drops a stale snapshot selection without opening an event stream", async () => { |
| 559 | const state = createThreadState("thread-a"); |
| 560 | let current = true; |
| 561 | let subscribed = false; |
| 562 | const result = await snapshotThenSubscribe({ |
| 563 | state, |
| 564 | threadId: "thread-a", |
| 565 | loadSnapshot: async () => { |
| 566 | current = false; |
| 567 | return snapshot(); |
| 568 | }, |
| 569 | subscribe: () => { |
| 570 | subscribed = true; |
| 571 | }, |
| 572 | isCurrent: () => current, |
| 573 | }); |
| 574 | assert.equal(result, false); |
| 575 | assert.equal(subscribed, false); |
| 576 | }); |
| 577 | |
| 578 | test("reconnect cursor advances monotonically and duplicate or stale-thread events are ignored", () => { |
| 579 | const state = createThreadState("thread-a"); |
| 580 | assert.equal(applySnapshot(state, snapshot("thread-a", 7)), true); |
| 581 | |
| 582 | assert.equal( |
| 583 | applyRuntimeEvent( |
| 584 | state, |
| 585 | runtimeEvent(8, "item.delta", { delta: " world", kind: "agent_message" }, { item_id: "item-1" }), |
| 586 | ), |
| 587 | true, |
| 588 | ); |
| 589 | assert.equal( |
| 590 | applyRuntimeEvent( |
| 591 | state, |
| 592 | runtimeEvent(8, "item.delta", { delta: " duplicate", kind: "agent_message" }, { item_id: "item-1" }), |
| 593 | ), |
| 594 | false, |
| 595 | ); |
| 596 | assert.equal( |
| 597 | applyRuntimeEvent(state, runtimeEvent(99, "turn.completed", {}, { thread_id: "thread-b" })), |
| 598 | false, |
| 599 | ); |
| 600 | assert.equal(state.items.get("item-1").detail, "Hello world"); |
| 601 | assert.equal(state.latestSeq, 8); |
| 602 | assert.equal(eventStreamUrl("thread-a", state.latestSeq), "/v1/threads/thread-a/events?since_seq=8"); |
| 603 | }); |
| 604 | |
| 605 | test("uses the stream predecessor cursor to detect real gaps without assuming global sequences are contiguous", () => { |
| 606 | const state = createThreadState("thread-a"); |
| 607 | applySnapshot(state, snapshot("thread-a", 7)); |
| 608 | |
| 609 | const interleaved = runtimeEvent( |
| 610 | 12, |
| 611 | "item.delta", |
| 612 | { delta: " after other threads", kind: "agent_message" }, |
| 613 | { item_id: "item-1", previous_seq: 7 }, |
| 614 | ); |
| 615 | assert.equal(runtimeEventContinuity(state, interleaved), "next"); |
| 616 | assert.equal(applyRuntimeEvent(state, interleaved), true); |
| 617 | assert.equal(state.latestSeq, 12); |
| 618 | |
| 619 | const gap = runtimeEvent( |
| 620 | 15, |
| 621 | "approval.required", |
| 622 | { approval_id: "approval-missed", tool_name: "exec_shell" }, |
| 623 | { previous_seq: 14 }, |
| 624 | ); |
| 625 | assert.equal(runtimeEventContinuity(state, gap), "gap"); |
| 626 | assert.equal(applyRuntimeEvent(state, gap), false); |
| 627 | assert.equal(state.latestSeq, 12); |
| 628 | assert.equal(state.approvals.has("approval-missed"), false); |
| 629 | }); |
| 630 | |
| 631 | test("registers the full emitted Runtime vocabulary and advances continuity for every event", async () => { |
| 632 | const runtimeSource = ( |
| 633 | await Promise.all( |
| 634 | ["../../engine/src/runtime_threads.rs", "../../engine/src/runtime_threads/manager.rs"].map((path) => |
| 635 | readFile(new URL(path, import.meta.url), "utf8"), |
| 636 | ), |
| 637 | ) |
| 638 | ).join("\n"); |
| 639 | const emittedNames = new Set( |
| 640 | [...runtimeSource.matchAll( |
| 641 | /"((?:thread|turn|item|approval|user_input|sandbox|agent|tool_call|tool)\.[a-z_]+)"/g, |
| 642 | )].map((match) => match[1]), |
| 643 | ); |
| 644 | assert.deepEqual(new Set(STREAM_EVENT_NAMES), emittedNames); |
| 645 | assert.equal(STREAM_EVENT_NAMES.includes("thread.created"), false); |
| 646 | |
| 647 | const state = createThreadState("thread-a"); |
| 648 | applySnapshot(state, snapshot("thread-a", 7)); |
| 649 | let previousSeq = 7; |
| 650 | for (const eventName of STREAM_EVENT_NAMES) { |
| 651 | const sequence = previousSeq + 2; |
| 652 | const turnBefore = state.turns.get("turn-1"); |
| 653 | const payload = eventName === "turn.usage" |
| 654 | ? { usage: { input_tokens: 100, output_tokens: 20 } } |
| 655 | : {}; |
| 656 | const envelope = runtimeEvent(sequence, eventName, payload, { previous_seq: previousSeq }); |
| 657 | assert.equal(runtimeEventContinuity(state, envelope), "next", eventName); |
| 658 | assert.equal(applyRuntimeEvent(state, envelope), true, eventName); |
| 659 | assert.equal(state.latestSeq, sequence, eventName); |
| 660 | if (eventName === "turn.usage") { |
| 661 | // Request diagnostics advance continuity; only the settled turn owns totals. |
| 662 | assert.equal(state.turns.get("turn-1"), turnBefore); |
| 663 | assert.equal(applyRuntimeEvent(state, envelope), false); |
| 664 | } |
| 665 | previousSeq = sequence; |
| 666 | } |
| 667 | const settledTurn = { |
| 668 | id: "turn-1", |
| 669 | status: "completed", |
| 670 | usage: { input_tokens: 300, output_tokens: 60 }, |
| 671 | }; |
| 672 | assert.equal(applyRuntimeEvent(state, runtimeEvent( |
| 673 | previousSeq + 1, |
| 674 | "turn.completed", |
| 675 | { turn: settledTurn }, |
| 676 | { previous_seq: previousSeq }, |
| 677 | )), true); |
| 678 | assert.deepEqual(state.turns.get("turn-1"), settledTurn); |
| 679 | }); |
| 680 | |
| 681 | test("gap recovery snapshot restores approval and user-input attention before resubscribing", async () => { |
| 682 | const state = createThreadState("thread-a"); |
| 683 | applySnapshot(state, snapshot("thread-a", 7)); |
| 684 | const subscriptions = []; |
| 685 | |
| 686 | const recovered = await snapshotThenSubscribe({ |
| 687 | state, |
| 688 | threadId: "thread-a", |
| 689 | loadSnapshot: async () => ({ |
| 690 | ...snapshot("thread-a", 15), |
| 691 | pending_approvals: [{ |
| 692 | id: "approval-recovered", |
| 693 | turn_id: "turn-1", |
| 694 | tool_name: "exec_command", |
| 695 | description: "Run a local check", |
| 696 | }], |
| 697 | pending_user_inputs: [{ |
| 698 | id: "input-recovered", |
| 699 | turn_id: "turn-1", |
| 700 | request: { questions: [{ id: "choice", question: "Continue?", options: [] }] }, |
| 701 | }], |
| 702 | pending_dynamic_tool_calls: [{ |
| 703 | thread_id: "thread-a", |
| 704 | turn_id: "turn-1", |
| 705 | call_id: "call-recovered", |
| 706 | namespace: "bench", |
| 707 | tool: "lookup", |
| 708 | arguments: { id: "7" }, |
| 709 | }], |
| 710 | }), |
| 711 | subscribe: (threadId, sequence) => subscriptions.push([threadId, sequence]), |
| 712 | }); |
| 713 | |
| 714 | assert.equal(recovered, true); |
| 715 | assert.equal(state.approvals.size, 1); |
| 716 | assert.equal(state.approvals.has("approval-recovered"), true); |
| 717 | assert.equal(state.userInputs.size, 1); |
| 718 | assert.equal(state.userInputs.has("input-recovered"), true); |
| 719 | assert.equal(state.dynamicToolCalls.size, 1); |
| 720 | assert.equal(state.dynamicToolCalls.get("call-recovered").tool, "lookup"); |
| 721 | assert.deepEqual(subscriptions, [["thread-a", 15]]); |
| 722 | |
| 723 | const duplicate = runtimeEvent( |
| 724 | 15, |
| 725 | "approval.required", |
| 726 | { approval_id: "approval-recovered", tool_name: "exec_command" }, |
| 727 | { previous_seq: 14 }, |
| 728 | ); |
| 729 | assert.equal(applyRuntimeEvent(state, duplicate), false); |
| 730 | assert.equal(state.approvals.size, 1); |
| 731 | }); |
| 732 | |
| 733 | test("browser clears its surfaced gap only after a replacement snapshot subscribes", async () => { |
| 734 | const source = await readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"); |
| 735 | assert.match( |
| 736 | source, |
| 737 | /async function recoverProjection[\s\S]*?connectStream\(id, sequence, generation, true\)/, |
| 738 | ); |
| 739 | assert.match( |
| 740 | source, |
| 741 | /async function recoverProjection[\s\S]*?recoverSnapshotAndSubscribe\([\s\S]*?app\.streamGap = false;[\s\S]*?if \(!subscribed\) return;\s+renderAll\(\);/, |
| 742 | ); |
| 743 | }); |
| 744 | |
| 745 | test("user-input answers stay bound to the selected live thread and pending request", () => { |
| 746 | const state = createThreadState("thread-a"); |
| 747 | state.userInputs.set("input-1", {}); |
| 748 | |
| 749 | assert.deepEqual( |
| 750 | resolveUserInputTarget("input-1", threadTarget("thread-a"), state), |
| 751 | { ok: true, threadId: "thread-a", inputId: "input-1" }, |
| 752 | ); |
| 753 | assert.deepEqual( |
| 754 | resolveUserInputTarget("input-1", sessionTarget("session-a"), state), |
| 755 | { ok: false, reason: "session-not-live" }, |
| 756 | ); |
| 757 | assert.deepEqual( |
| 758 | resolveUserInputTarget("input-1", NO_TARGET, state), |
| 759 | { ok: false, reason: "no-target" }, |
| 760 | ); |
| 761 | assert.deepEqual( |
| 762 | resolveUserInputTarget("input-2", threadTarget("thread-a"), state), |
| 763 | { ok: false, reason: "stale-user-input" }, |
| 764 | ); |
| 765 | assert.deepEqual( |
| 766 | resolveUserInputTarget("input-1", threadTarget("thread-b"), state), |
| 767 | { ok: false, reason: "stale-target" }, |
| 768 | ); |
| 769 | }); |
| 770 | |
| 771 | test("user-input payloads preserve TUI custom-answer parity and single-select cardinality", () => { |
| 772 | const single = { |
| 773 | questions: [{ |
| 774 | id: "path", |
| 775 | header: "Path", |
| 776 | question: "Which path?", |
| 777 | options: [{ label: "A" }, { label: "B" }], |
| 778 | allow_free_text: false, |
| 779 | multi_select: false, |
| 780 | }], |
| 781 | }; |
| 782 | assert.deepEqual(answersForUserInput(single, {}, { path: "A different path" }), { |
| 783 | ok: true, |
| 784 | answers: [{ id: "path", label: "Other", value: "A different path" }], |
| 785 | }); |
| 786 | assert.equal( |
| 787 | answersForUserInput(single, { path: ["A"] }, { path: "also B" }).reason, |
| 788 | "multiple-answers", |
| 789 | ); |
| 790 | assert.equal( |
| 791 | answersForUserInput(single, { path: ["forged"] }, {}).reason, |
| 792 | "invalid-option", |
| 793 | ); |
| 794 | assert.equal(answersForUserInput(single, {}, {}).reason, "missing-answer"); |
| 795 | |
| 796 | const multi = { |
| 797 | questions: [{ |
| 798 | ...single.questions[0], |
| 799 | id: "checks", |
| 800 | multi_select: true, |
| 801 | }], |
| 802 | }; |
| 803 | assert.deepEqual( |
| 804 | answersForUserInput(multi, { checks: ["A", "B"] }, { checks: "C" }), |
| 805 | { |
| 806 | ok: true, |
| 807 | answers: [ |
| 808 | { id: "checks", label: "A", value: "A" }, |
| 809 | { id: "checks", label: "B", value: "B" }, |
| 810 | { id: "checks", label: "Other", value: "C" }, |
| 811 | ], |
| 812 | }, |
| 813 | ); |
| 814 | }); |
| 815 | |
| 816 | test("assembles deltas and replaces the live item with its settled receipt", () => { |
| 817 | const state = createThreadState("thread-a"); |
| 818 | applySnapshot(state, { ...snapshot(), items: [], latest_seq: 1 }); |
| 819 | applyRuntimeEvent( |
| 820 | state, |
| 821 | runtimeEvent(2, "item.delta", { delta: "one", kind: "agent_message" }, { item_id: "item-new" }), |
| 822 | ); |
| 823 | applyRuntimeEvent( |
| 824 | state, |
| 825 | runtimeEvent(3, "item.delta", { delta: " two", kind: "agent_message" }, { item_id: "item-new" }), |
| 826 | ); |
| 827 | assert.equal(state.items.get("item-new").detail, "one two"); |
| 828 | |
| 829 | applyRuntimeEvent( |
| 830 | state, |
| 831 | runtimeEvent( |
| 832 | 4, |
| 833 | "item.completed", |
| 834 | { |
| 835 | item: { |
| 836 | id: "item-new", |
| 837 | turn_id: "turn-1", |
| 838 | kind: "agent_message", |
| 839 | status: "completed", |
| 840 | summary: "one two", |
| 841 | detail: "one two", |
| 842 | }, |
| 843 | }, |
| 844 | { item_id: "item-new" }, |
| 845 | ), |
| 846 | ); |
| 847 | assert.equal(state.items.get("item-new").status, "completed"); |
| 848 | assert.deepEqual(state.itemOrder, ["item-new"]); |
| 849 | |
| 850 | applyRuntimeEvent( |
| 851 | state, |
| 852 | runtimeEvent(5, "item.delta", { delta: "partial", kind: "tool_call" }, { item_id: "item-stop" }), |
| 853 | ); |
| 854 | applyRuntimeEvent( |
| 855 | state, |
| 856 | runtimeEvent( |
| 857 | 6, |
| 858 | "item.interrupted", |
| 859 | { |
| 860 | item: { |
| 861 | id: "item-stop", |
| 862 | turn_id: "turn-1", |
| 863 | kind: "tool_call", |
| 864 | status: "interrupted", |
| 865 | summary: "Interrupted", |
| 866 | detail: "partial", |
| 867 | }, |
| 868 | }, |
| 869 | { item_id: "item-stop" }, |
| 870 | ), |
| 871 | ); |
| 872 | assert.equal(state.items.get("item-stop").status, "interrupted"); |
| 873 | |
| 874 | applyRuntimeEvent( |
| 875 | state, |
| 876 | runtimeEvent( |
| 877 | 7, |
| 878 | "item.canceled", |
| 879 | { |
| 880 | item: { |
| 881 | id: "item-compact", |
| 882 | turn_id: "turn-1", |
| 883 | kind: "compaction", |
| 884 | status: "canceled", |
| 885 | summary: "Compaction canceled", |
| 886 | detail: "Compaction canceled", |
| 887 | }, |
| 888 | }, |
| 889 | { item_id: "item-compact" }, |
| 890 | ), |
| 891 | ); |
| 892 | assert.equal(state.items.get("item-compact").status, "canceled"); |
| 893 | assert.deepEqual(state.itemOrder, ["item-new", "item-stop", "item-compact"]); |
| 894 | }); |
| 895 | |
| 896 | test("projects agent lifecycle receipts live and settles them without a snapshot reload", () => { |
| 897 | const state = createThreadState("thread-a"); |
| 898 | applySnapshot(state, { ...snapshot(), items: [], latest_seq: 1 }); |
| 899 | |
| 900 | const agentItem = (status, summary) => ({ |
| 901 | id: "item-agent", |
| 902 | turn_id: "turn-1", |
| 903 | kind: "status", |
| 904 | status, |
| 905 | summary, |
| 906 | detail: summary, |
| 907 | }); |
| 908 | applyRuntimeEvent( |
| 909 | state, |
| 910 | runtimeEvent(2, "agent.spawned", { item: agentItem("in_progress", "Agent spawned") }), |
| 911 | ); |
| 912 | assert.equal(state.items.get("item-agent").status, "in_progress"); |
| 913 | assert.deepEqual(state.itemOrder, ["item-agent"]); |
| 914 | |
| 915 | applyRuntimeEvent( |
| 916 | state, |
| 917 | runtimeEvent(3, "agent.progress", { item: agentItem("in_progress", "Agent checking") }), |
| 918 | ); |
| 919 | applyRuntimeEvent( |
| 920 | state, |
| 921 | runtimeEvent(4, "agent.completed", { item: agentItem("completed", "Agent completed") }), |
| 922 | ); |
| 923 | assert.equal(state.items.get("item-agent").status, "completed"); |
| 924 | assert.equal(state.items.get("item-agent").summary, "Agent completed"); |
| 925 | assert.deepEqual(state.itemOrder, ["item-agent"]); |
| 926 | |
| 927 | applyRuntimeEvent( |
| 928 | state, |
| 929 | runtimeEvent(5, "agent.list", { |
| 930 | item: { |
| 931 | id: "item-agent-list", |
| 932 | turn_id: "turn-1", |
| 933 | kind: "status", |
| 934 | status: "completed", |
| 935 | summary: "Agent list refreshed", |
| 936 | detail: "Agent list refreshed", |
| 937 | }, |
| 938 | }), |
| 939 | ); |
| 940 | assert.equal(state.items.get("item-agent-list").status, "completed"); |
| 941 | assert.deepEqual(state.itemOrder, ["item-agent", "item-agent-list"]); |
| 942 | assert.equal(state.latestSeq, 5); |
| 943 | }); |
| 944 | |
| 945 | test("tracks approval and user-input attention until each is resolved", () => { |
| 946 | const state = createThreadState("thread-a"); |
| 947 | applySnapshot(state, snapshot()); |
| 948 | applyRuntimeEvent( |
| 949 | state, |
| 950 | runtimeEvent(8, "approval.required", { approval_id: "approval-1", tool_name: "exec_shell" }), |
| 951 | ); |
| 952 | applyRuntimeEvent( |
| 953 | state, |
| 954 | runtimeEvent(9, "user_input.required", { |
| 955 | id: "input-1", |
| 956 | request: { questions: [{ id: "choice", question: "Choose?", options: [] }] }, |
| 957 | }), |
| 958 | ); |
| 959 | assert.equal(state.approvals.has("approval-1"), true); |
| 960 | assert.equal(state.userInputs.has("input-1"), true); |
| 961 | |
| 962 | applyRuntimeEvent( |
| 963 | state, |
| 964 | runtimeEvent(10, "approval.decided", { approval_id: "approval-1", decision: "allow" }), |
| 965 | ); |
| 966 | assert.equal(state.approvals.has("approval-1"), false); |
| 967 | assert.equal(state.userInputs.has("input-1"), true); |
| 968 | |
| 969 | applyRuntimeEvent( |
| 970 | state, |
| 971 | runtimeEvent(11, "user_input.answered", { input_id: "input-1" }), |
| 972 | ); |
| 973 | assert.equal(state.userInputs.has("input-1"), false); |
| 974 | }); |
| 975 | |
| 976 | test("hydrates pending attention from a reload snapshot and clears cancellation events", () => { |
| 977 | const state = createThreadState("thread-a"); |
| 978 | const detail = { |
| 979 | ...snapshot(), |
| 980 | pending_approvals: [{ |
| 981 | id: "approval-reload", |
| 982 | turn_id: "turn-1", |
| 983 | tool_name: "exec_command", |
| 984 | description: "Run a local check", |
| 985 | }], |
| 986 | pending_user_inputs: [{ |
| 987 | id: "input-reload", |
| 988 | turn_id: "turn-1", |
| 989 | request: { questions: [{ id: "choice", question: "Continue?", options: [] }] }, |
| 990 | }], |
| 991 | }; |
| 992 | |
| 993 | assert.equal(applySnapshot(state, detail), true); |
| 994 | assert.equal(state.approvals.get("approval-reload").tool_name, "exec_command"); |
| 995 | assert.equal(state.userInputs.get("input-reload").turn_id, "turn-1"); |
| 996 | |
| 997 | applyRuntimeEvent( |
| 998 | state, |
| 999 | runtimeEvent(8, "user_input.canceled", { id: "input-reload", terminal: true }), |
| 1000 | ); |
| 1001 | assert.equal(state.userInputs.has("input-reload"), false); |
| 1002 | }); |
| 1003 | |
| 1004 | test("turn completion defensively clears attention owned by that turn", () => { |
| 1005 | const state = createThreadState("thread-a"); |
| 1006 | assert.equal(applySnapshot(state, { |
| 1007 | ...snapshot(), |
| 1008 | pending_approvals: [{ id: "approval-terminal", turn_id: "turn-1" }], |
| 1009 | pending_user_inputs: [{ id: "input-terminal", turn_id: "turn-1", request: { questions: [] } }], |
| 1010 | pending_dynamic_tool_calls: [{ call_id: "call-terminal", turn_id: "turn-1", tool: "lookup" }], |
| 1011 | }), true); |
| 1012 | state.approvals.set("approval-other", { id: "approval-other", turn_id: "turn-other" }); |
| 1013 | state.userInputs.set("input-other", { id: "input-other", turn_id: "turn-other" }); |
| 1014 | state.dynamicToolCalls.set("call-other", { call_id: "call-other", turn_id: "turn-other" }); |
| 1015 | |
| 1016 | assert.equal(applyRuntimeEvent( |
| 1017 | state, |
| 1018 | runtimeEvent(8, "turn.completed", { turn: { id: "turn-1", status: "completed" } }), |
| 1019 | ), true); |
| 1020 | assert.equal(state.approvals.has("approval-terminal"), false); |
| 1021 | assert.equal(state.userInputs.has("input-terminal"), false); |
| 1022 | assert.equal(state.dynamicToolCalls.has("call-terminal"), false); |
| 1023 | assert.equal(state.approvals.has("approval-other"), true); |
| 1024 | assert.equal(state.userInputs.has("input-other"), true); |
| 1025 | assert.equal(state.dynamicToolCalls.has("call-other"), true); |
| 1026 | }); |
| 1027 | |
| 1028 | test("dynamic tool calls hydrate and disappear exactly once across terminal variants", () => { |
| 1029 | const state = createThreadState("thread-a"); |
| 1030 | assert.equal(applySnapshot(state, { |
| 1031 | ...snapshot(), |
| 1032 | pending_dynamic_tool_calls: [{ |
| 1033 | thread_id: "thread-a", |
| 1034 | turn_id: "turn-1", |
| 1035 | call_id: "call-snapshot", |
| 1036 | tool: "snapshot_lookup", |
| 1037 | arguments: { id: "snapshot" }, |
| 1038 | }], |
| 1039 | }), true); |
| 1040 | assert.equal(state.dynamicToolCalls.get("call-snapshot").tool, "snapshot_lookup"); |
| 1041 | |
| 1042 | assert.equal(applyRuntimeEvent( |
| 1043 | state, |
| 1044 | runtimeEvent(8, "tool_call.requested", { |
| 1045 | thread_id: "thread-a", |
| 1046 | turn_id: "turn-1", |
| 1047 | call_id: "call-live", |
| 1048 | tool: "live_lookup", |
| 1049 | arguments: { id: "live" }, |
| 1050 | }), |
| 1051 | ), true); |
| 1052 | assert.equal(state.dynamicToolCalls.size, 2); |
| 1053 | |
| 1054 | assert.equal(applyRuntimeEvent( |
| 1055 | state, |
| 1056 | runtimeEvent(9, "tool_call.resolved", { call_id: "call-snapshot", status: "resolved" }), |
| 1057 | ), true); |
| 1058 | assert.equal(state.dynamicToolCalls.has("call-snapshot"), false); |
| 1059 | assert.equal(applyRuntimeEvent( |
| 1060 | state, |
| 1061 | runtimeEvent(9, "tool_call.resolved", { call_id: "call-snapshot", status: "resolved" }), |
| 1062 | ), false); |
| 1063 | assert.equal(state.dynamicToolCalls.size, 1); |
| 1064 | |
| 1065 | assert.equal(applyRuntimeEvent( |
| 1066 | state, |
| 1067 | runtimeEvent(10, "tool_call.canceled", { call_id: "call-live", status: "canceled" }), |
| 1068 | ), true); |
| 1069 | assert.equal(state.dynamicToolCalls.size, 0); |
| 1070 | |
| 1071 | assert.equal(applyRuntimeEvent( |
| 1072 | state, |
| 1073 | runtimeEvent(11, "tool_call.requested", { |
| 1074 | call_id: "call-timeout", |
| 1075 | tool: "slow_lookup", |
| 1076 | arguments: {}, |
| 1077 | }), |
| 1078 | ), true); |
| 1079 | assert.equal(state.dynamicToolCalls.has("call-timeout"), true); |
| 1080 | assert.equal(applyRuntimeEvent( |
| 1081 | state, |
| 1082 | runtimeEvent(12, "tool_call.timeout", { call_id: "call-timeout", status: "timeout" }), |
| 1083 | ), true); |
| 1084 | assert.equal(state.dynamicToolCalls.size, 0); |
| 1085 | }); |
| 1086 | |
| 1087 | test("preserves drafts per thread without browser storage", () => { |
| 1088 | const drafts = new Map(); |
| 1089 | saveDraft(drafts, "thread-a", "draft A"); |
| 1090 | saveDraft(drafts, "thread-b", "draft B"); |
| 1091 | assert.equal(restoreDraft(drafts, "thread-a"), "draft A"); |
| 1092 | assert.equal(restoreDraft(drafts, "thread-b"), "draft B"); |
| 1093 | saveDraft(drafts, "thread-a", ""); |
| 1094 | assert.equal(restoreDraft(drafts, "thread-a"), ""); |
| 1095 | }); |
| 1096 | |
| 1097 | test("renders hostile Runtime text only through the textContent sink", async () => { |
| 1098 | const hostile = `<img src=x onerror=alert(1)><script>alert(2)</script>`; |
| 1099 | const fakeElement = { textContent: "" }; |
| 1100 | setSafeText(fakeElement, hostile); |
| 1101 | assert.equal(fakeElement.textContent, hostile); |
| 1102 | |
| 1103 | const source = await readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"); |
| 1104 | assert.equal(source.includes("inner" + "HTML"), false); |
| 1105 | assert.equal(source.includes("insertAdjacent" + "HTML"), false); |
| 1106 | assert.equal(source.includes("local" + "Storage"), false); |
| 1107 | assert.equal(source.includes("codewhale_runtime_token"), false); |
| 1108 | }); |
| 1109 | |
| 1110 | test("web session fetch keeps request proof outside cookies and strips bootstrap fragments", async () => { |
| 1111 | const stored = new Map(); |
| 1112 | const storage = () => ({ setItem: (key, value) => stored.set(key, value), getItem: (key) => stored.get(key) }); |
| 1113 | const paths = []; |
| 1114 | const calls = []; |
| 1115 | const history = { replaceState: (_state, _title, path) => paths.push(path) }; |
| 1116 | const fetch = async (path, options) => { calls.push({ path, options }); return { ok: true }; }; |
| 1117 | const request = createWebSessionFetch({ |
| 1118 | location: { hash: "#p=proof-one", pathname: "/", search: "?view=threads" }, history, storage, fetch, |
| 1119 | }); |
| 1120 | assert.deepEqual(paths, ["/?view=threads"]); |
| 1121 | await request("/v1/threads", { method: "POST", body: "{}" }); |
| 1122 | await request("/__codewhale/web/stream-ticket", { method: "POST" }); |
| 1123 | const reloaded = createWebSessionFetch({ location: { hash: "" }, history, storage, fetch }); |
| 1124 | await reloaded("/v1/threads"); |
| 1125 | for (const { options } of calls) { |
| 1126 | assert.equal(options.headers.get("x-codewhale-web-request"), "proof-one"); |
| 1127 | assert.equal(options.headers.has("cookie"), false); |
| 1128 | assert.equal(options.credentials, "same-origin"); |
| 1129 | assert.equal(options.cache, "no-store"); |
| 1130 | } |
| 1131 | assert.equal(calls[0].options.headers.get("content-type"), "application/json"); |
| 1132 | assert.equal(eventStreamUrl("thread-a", 4, "ticket-one"), "/v1/threads/thread-a/events?since_seq=4&web_stream_ticket=ticket-one"); |
| 1133 | |
| 1134 | const memoryOnly = createWebSessionFetch({ |
| 1135 | location: { hash: "#p=memory-proof", pathname: "/", search: "" }, history, |
| 1136 | storage: () => { throw new Error("storage unavailable"); }, fetch, |
| 1137 | }); |
| 1138 | await memoryOnly("/v1/threads"); |
| 1139 | assert.equal(calls.at(-1).options.headers.get("x-codewhale-web-request"), "memory-proof"); |
| 1140 | }); |
| 1141 | |
| 1142 | test("web session uses only its fragment or this tab's stored proof", async () => { |
| 1143 | for (const storedProof of [null, "this-tab-proof", "unavailable"]) { |
| 1144 | const stored = new Map([["codewhale_web_request_proof", storedProof]]); |
| 1145 | const calls = []; |
| 1146 | const request = createWebSessionFetch({ |
| 1147 | location: { hash: "" }, |
| 1148 | history: { replaceState: () => assert.fail("no fragment to clear") }, |
| 1149 | storage: () => { |
| 1150 | if (storedProof === "unavailable") throw new Error("storage unavailable"); |
| 1151 | return { getItem: (key) => stored.get(key), setItem: (key, value) => stored.set(key, value) }; |
| 1152 | }, |
| 1153 | fetch: async (_path, options) => { calls.push(options); return { ok: true }; }, |
| 1154 | }); |
| 1155 | await request("/v1/threads"); |
| 1156 | await request("/__codewhale/web/stream-ticket", { method: "POST" }); |
| 1157 | assert.equal(calls.length, 2); |
| 1158 | const expected = storedProof === "this-tab-proof" ? "this-tab-proof" : ""; |
| 1159 | for (const options of calls) { |
| 1160 | assert.equal(options.headers.get("x-codewhale-web-request"), expected); |
| 1161 | } |
| 1162 | } |
| 1163 | }); |
| 1164 | |
| 1165 | function streamHarness(api) { |
| 1166 | const app = { |
| 1167 | generation: 1, selectedThreadId: "thread-a", threadState: { latestSeq: 4 }, |
| 1168 | stream: null, streamOpenCancel: null, reconnectTimer: null, |
| 1169 | }; |
| 1170 | const streams = []; |
| 1171 | const timers = new Map(); |
| 1172 | const statuses = []; |
| 1173 | let nextTimer = 0; |
| 1174 | class EventSource { |
| 1175 | constructor(url) { this.url = url; this.closed = false; streams.push(this); } |
| 1176 | close() { this.closed = true; } |
| 1177 | addEventListener() {} |
| 1178 | } |
| 1179 | const connector = createStreamConnector({ |
| 1180 | app, api, EventSource, receive: () => {}, setConnection: () => {}, |
| 1181 | showStatus: (message) => statuses.push(message), |
| 1182 | setTimeout: (callback, delay) => { timers.set(++nextTimer, { callback, delay }); return nextTimer; }, |
| 1183 | clearTimeout: (id) => timers.delete(id), |
| 1184 | }); |
| 1185 | return { |
| 1186 | ...connector, app, streams, timers, statuses, |
| 1187 | tick: async () => { |
| 1188 | assert.equal(timers.size, 1, "exactly one reconnect should be pending"); |
| 1189 | const [id, { callback, delay }] = timers.entries().next().value; |
| 1190 | timers.delete(id); |
| 1191 | callback(); |
| 1192 | await new Promise((resolve) => setImmediate(resolve)); |
| 1193 | return delay; |
| 1194 | }, |
| 1195 | }; |
| 1196 | } |
| 1197 | |
| 1198 | test("stream retries ticket network and 5xx failures with capped backoff and resumes the latest cursor", async () => { |
| 1199 | let requests = 0; |
| 1200 | const h = streamHarness(async () => { |
| 1201 | requests += 1; |
| 1202 | if (requests === 2) throw new TypeError("network unavailable"); |
| 1203 | if (requests > 2 && requests < 10) throw Object.assign(new Error("temporarily unavailable"), { status: 503 }); |
| 1204 | return { stream_ticket: `ticket-${requests}` }; |
| 1205 | }); |
| 1206 | await h.connectStream("thread-a", 4, 1); |
| 1207 | h.streams[0].onopen(); |
| 1208 | h.streams[0].onerror(); |
| 1209 | assert.equal(h.streams[0].closed, true); |
| 1210 | h.app.threadState.latestSeq = 9; |
| 1211 | const delays = []; |
| 1212 | while (h.streams.length === 1) delays.push(await h.tick()); |
| 1213 | assert.deepEqual(delays, [900, 1800, 3600, 7200, 14400, 28800, 30000, 30000, 30000]); |
| 1214 | assert.match(h.streams[1].url, /since_seq=9&web_stream_ticket=ticket-10$/); |
| 1215 | h.streams[1].onopen(); |
| 1216 | h.streams[1].onerror(); |
| 1217 | assert.equal(await h.tick(), 900, "opening a stream resets backoff"); |
| 1218 | h.stopStream(); |
| 1219 | assert.equal(h.timers.size, 0); |
| 1220 | }); |
| 1221 | |
| 1222 | test("stream stops ticket retries on 401 and 403", async () => { |
| 1223 | for (const status of [401, 403]) { |
| 1224 | let requests = 0; |
| 1225 | const h = streamHarness(async () => { |
| 1226 | if (++requests === 1) return { stream_ticket: "first" }; |
| 1227 | throw Object.assign(new Error("session ended"), { status }); |
| 1228 | }); |
| 1229 | await h.connectStream("thread-a", 4, 1); |
| 1230 | h.app.stream.onerror(); |
| 1231 | await h.tick(); |
| 1232 | assert.equal(h.timers.size, 0); |
| 1233 | assert.equal(h.app.stream, null); |
| 1234 | assert.deepEqual(h.statuses, ["session ended"]); |
| 1235 | } |
| 1236 | }); |
| 1237 | |
| 1238 | test("stream ignores superseded ticket completions and failures, including stopped connections", async () => { |
| 1239 | const pending = []; |
| 1240 | const h = streamHarness(() => new Promise((resolve, reject) => pending.push({ resolve, reject }))); |
| 1241 | const first = h.connectStream("thread-a", 4, 1); |
| 1242 | const second = h.connectStream("thread-a", 4, 1); |
| 1243 | pending[1].resolve({ stream_ticket: "current" }); |
| 1244 | await second; |
| 1245 | pending[0].resolve({ stream_ticket: "stale" }); |
| 1246 | await first; |
| 1247 | assert.equal(h.streams.length, 1, "a late ticket cannot create an orphan stream"); |
| 1248 | assert.match(h.app.stream.url, /current$/); |
| 1249 | const third = h.connectStream("thread-a", 4, 1); |
| 1250 | assert.equal(h.streams[0].closed, true); |
| 1251 | h.stopStream(); |
| 1252 | pending[2].resolve({ stream_ticket: "stopped" }); |
| 1253 | await third; |
| 1254 | assert.equal(h.streams.length, 1); |
| 1255 | assert.equal(h.app.stream, null); |
| 1256 | const fourth = h.connectStream("thread-a", 4, 1); |
| 1257 | h.app.generation += 1; |
| 1258 | pending[3].reject(new Error("old selection failed")); |
| 1259 | await fourth; |
| 1260 | assert.equal(h.timers.size, 0); |
| 1261 | assert.deepEqual(h.statuses, []); |
| 1262 | }); |
| 1263 | |
| 1264 | test("stream recovery handshake leaves retries to snapshot recovery until open", async () => { |
| 1265 | const h = streamHarness(async () => ({ stream_ticket: "recovery" })); |
| 1266 | const opened = h.connectStream("thread-a", 4, 1, true); |
| 1267 | await new Promise((resolve) => setImmediate(resolve)); |
| 1268 | h.app.stream.onerror(); |
| 1269 | await assert.rejects(opened, /did not reopen/); |
| 1270 | assert.equal(h.timers.size, 0); |
| 1271 | const replacement = h.connectStream("thread-a", 4, 1, true); |
| 1272 | await new Promise((resolve) => setImmediate(resolve)); |
| 1273 | h.app.stream.onopen(); |
| 1274 | await replacement; |
| 1275 | h.app.stream.onerror(); |
| 1276 | assert.equal(h.timers.size, 1, "normal reconnect resumes after the handshake"); |
| 1277 | h.stopStream(); |
| 1278 | }); |
| 1279 | |
| 1280 | test("records workspace restore-point receipts on their turn in order", () => { |
| 1281 | const state = createThreadState("thread-a"); |
| 1282 | applySnapshot(state, snapshot("thread-a", 7)); |
| 1283 | const pre = { kind: "pre_turn", snapshot_id: "c1", tree_id: "t1", session_id: "thread-a" }; |
| 1284 | const post = { kind: "post_turn", snapshot_id: "c2", tree_id: "t2", session_id: "thread-a" }; |
| 1285 | assert.equal(applyRuntimeEvent(state, runtimeEvent(8, "turn.workspace_snapshot", pre)), true); |
| 1286 | assert.equal(applyRuntimeEvent(state, runtimeEvent(9, "turn.workspace_snapshot", post)), true); |
| 1287 | assert.deepEqual(state.turns.get("turn-1").workspace_snapshots, [pre, post]); |
| 1288 | // A receipt for a turn the client has not seen still advances continuity. |
| 1289 | const orphan = runtimeEvent(10, "turn.workspace_snapshot", pre, { turn_id: "turn-9" }); |
| 1290 | assert.equal(applyRuntimeEvent(state, orphan), true); |
| 1291 | assert.equal(state.latestSeq, 10); |
| 1292 | assert.equal(state.turns.has("turn-9"), false); |
| 1293 | }); |
| 1294 | |
| 1295 | test("approval card leads with the summary and keeps tool instructions out of the lead", () => { |
| 1296 | const instructions = "Run a shell command. Call task_shell_wait with that task_id and do not sleep-poll with bash."; |
| 1297 | assert.deepEqual(approvalCardCopy({ summary: "Run cargo test", description: instructions }), { |
| 1298 | lead: "Run cargo test", |
| 1299 | detail: instructions, |
| 1300 | }); |
| 1301 | const fallback = approvalCardCopy({ description: instructions }); |
| 1302 | assert.equal(fallback.lead, "Run a shell command."); |
| 1303 | assert.equal(fallback.detail, instructions); |
| 1304 | assert.ok(approvalCardCopy({ description: "x".repeat(400) }).lead.length <= 160); |
| 1305 | assert.equal(approvalCardCopy({}).detail, ""); |
| 1306 | }); |
| 1307 | |
| 1308 | test("approval card puts Allow and Deny before the request text", async () => { |
| 1309 | const source = await readFile(new URL("../src/runtime_web/app.mjs", import.meta.url), "utf8"); |
| 1310 | const body = source.slice(source.indexOf("function renderApproval(")); |
| 1311 | assert.ok(body.indexOf("card.append(actions)") < body.indexOf('element("pre", "approval-request"')); |
| 1312 | }); |
| 1313 | |
| 1314 | test("saved session view explains itself and says how many messages it shows", () => { |
| 1315 | assert.match(savedSessionNotice(), /read-only/); |
| 1316 | const peek = { omitted_before: 30, entries: new Array(12).fill({}) }; |
| 1317 | assert.equal(peekOmittedLabel(peek), "Showing the last 12 of 42 messages"); |
| 1318 | assert.equal(peekOmittedLabel({ omitted_before: 0, entries: [] }), ""); |
| 1319 | assert.equal(peekCanShowEarlier(peek, PEEK_DEFAULT_ENTRIES), true); |
| 1320 | assert.equal(peekCanShowEarlier(peek, PEEK_EXPANDED_ENTRIES), false); |
| 1321 | assert.match(composerPlaceholderFor(sessionTarget("s1"), "Ask"), /Resume/); |
| 1322 | assert.equal(composerPlaceholderFor(NO_TARGET, "Ask"), "Ask"); |
| 1323 | }); |
| 1324 | |
| 1325 | test("header and thread rail stop contradicting an open saved session", () => { |
| 1326 | assert.equal( |
| 1327 | headerTitleFor({ thread: null, summary: null, target: sessionTarget("s1"), peek: { title: "Prime numbers" } }), |
| 1328 | "Prime numbers", |
| 1329 | ); |
| 1330 | assert.equal(headerTitleFor({ thread: null, summary: null, target: NO_TARGET, peek: null }), "Choose a thread"); |
| 1331 | assert.equal(showNoMatchingThreads([], []), true); |
| 1332 | assert.equal(showNoMatchingThreads([], [{ id: "s1" }]), false); |
| 1333 | }); |
| 1334 |