返回 DeepSeek-Reasonix
composer-goal-toggle.test.tsx
根目录 / desktop / frontend / src / __tests__ / composer-goal-toggle.test.tsx
1 import { JSDOM } from "jsdom";
2 import React from "react";
3 import { act } from "react";
4 import { createRoot } from "react-dom/client";
5 import { Composer, composerPickFileEntry } from "../components/Composer";
6 import { InvocationMetadataContext, UserMessage } from "../components/Message";
7 import { selectionFromDom } from "../components/RichComposerInput";
8 import { LocaleProvider } from "../lib/i18n";
9 import { ToastProvider } from "../lib/toast";
10 import type { AppBindings } from "../lib/bridge";
11 import type { ComposerInvocation, StructuredInvocationSubmit } from "../lib/invocationDisplay";
12 import type { CollaborationMode, CommandInfo, DirEntry, ToolApprovalMode } from "../lib/types";
13 import { dispatchNativeFileDrop, installDesktopHostStub, type DesktopHostStubOptions } from "./desktopHostStub";
14 import { createFileUploadMock, dispatchPasteFile } from "./fileUploadStub";
15
16 let passed = 0;
17 let failed = 0;
18
19 function ok(value: boolean, label: string) {
20 if (value) {
21 process.stdout.write(` PASS ${label}\n`);
22 passed += 1;
23 } else {
24 process.stdout.write(` FAIL ${label}\n`);
25 failed += 1;
26 }
27 }
28
29 function eq(actual: unknown, expected: unknown, label: string) {
30 if (actual === expected) ok(true, label);
31 else ok(false, `${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
32 }
33
34 function flushTimers(ms = 0): Promise<void> {
35 return new Promise((resolve) => setTimeout(resolve, ms));
36 }
37
38 class TestResizeObserver {
39 observe() {}
40 unobserve() {}
41 disconnect() {}
42 }
43
44 function installDom() {
45 const dom = new JSDOM("<!doctype html><html><body><div id=\"root\"></div></body></html>", {
46 pretendToBeVisual: true,
47 url: "http://localhost/",
48 });
49 (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
50 globalThis.window = dom.window as unknown as Window & typeof globalThis;
51 globalThis.document = dom.window.document;
52 Object.defineProperty(globalThis, "navigator", { configurable: true, value: dom.window.navigator });
53 globalThis.Node = dom.window.Node;
54 globalThis.HTMLElement = dom.window.HTMLElement;
55 globalThis.HTMLTextAreaElement = dom.window.HTMLTextAreaElement;
56 globalThis.Event = dom.window.Event;
57 globalThis.CustomEvent = dom.window.CustomEvent;
58 globalThis.KeyboardEvent = dom.window.KeyboardEvent;
59 globalThis.InputEvent = dom.window.InputEvent;
60 globalThis.MouseEvent = dom.window.MouseEvent;
61 globalThis.PointerEvent = dom.window.MouseEvent as unknown as typeof PointerEvent;
62 globalThis.MutationObserver = dom.window.MutationObserver;
63 globalThis.File = dom.window.File;
64 globalThis.FileReader = dom.window.FileReader;
65 globalThis.localStorage = dom.window.localStorage;
66 globalThis.requestAnimationFrame = dom.window.requestAnimationFrame.bind(dom.window);
67 globalThis.cancelAnimationFrame = dom.window.cancelAnimationFrame.bind(dom.window);
68 globalThis.ResizeObserver = TestResizeObserver;
69 Object.defineProperty(dom.window.HTMLElement.prototype, "attachEvent", { configurable: true, value: () => {} });
70 Object.defineProperty(dom.window.HTMLElement.prototype, "detachEvent", { configurable: true, value: () => {} });
71 Object.defineProperty(dom.window.HTMLElement.prototype, "scrollIntoView", { configurable: true, value: () => {} });
72 Object.defineProperty(window, "matchMedia", {
73 configurable: true,
74 value: () => ({
75 matches: true,
76 media: "(prefers-reduced-motion: reduce)",
77 onchange: null,
78 addEventListener() {},
79 removeEventListener() {},
80 addListener() {},
81 removeListener() {},
82 dispatchEvent: () => false,
83 }),
84 });
85 return dom;
86 }
87
88 async function renderComposer(props: Partial<Parameters<typeof Composer>[0]> = {}) {
89 const rootEl = document.getElementById("root");
90 if (!rootEl) throw new Error("missing root");
91 const root = createRoot(rootEl);
92 const calls: {
93 send: string[];
94 submit: (string | undefined)[];
95 structured: (StructuredInvocationSubmit | undefined)[];
96 cancel: number;
97 clearGoal: number;
98 setCollaborationMode: CollaborationMode[];
99 } = {
100 send: [],
101 submit: [],
102 structured: [],
103 cancel: 0,
104 clearGoal: 0,
105 setCollaborationMode: [],
106 };
107 let currentProps: Parameters<typeof Composer>[0] = {
108 running: false,
109 collaborationMode: "normal",
110 toolApprovalMode: "ask" as ToolApprovalMode,
111
112 goal: "",
113 cwd: "/repo",
114 tabId: "tab-a",
115 modelLabel: "DeepSeek-R1",
116 onSend: (displayText, submitText, _tabId, structured) => {
117 calls.send.push(displayText);
118 calls.submit.push(submitText);
119 calls.structured.push(structured);
120 },
121 onCancel: async () => {
122 calls.cancel += 1;
123 return { discardedItemIds: [] };
124 },
125 onCycleMode: () => {},
126 onSetMode: () => {},
127 onSetCollaborationMode: (mode) => calls.setCollaborationMode.push(mode),
128 onSetToolApprovalMode: () => {},
129 onClearGoal: () => { calls.clearGoal += 1; },
130 onEditGoal: () => {}, onPauseGoal: () => {}, onResumeGoal: () => {},
131 onSwitchModel: () => {},
132 onSetEffort: () => {},
133
134 ready: true,
135 ...props,
136 };
137 const paint = async (nextProps: Partial<Parameters<typeof Composer>[0]> = {}) => {
138 currentProps = { ...currentProps, ...nextProps };
139 await act(async () => {
140 root.render(
141 <LocaleProvider>
142 <ToastProvider>
143 <Composer {...currentProps} />
144 </ToastProvider>
145 </LocaleProvider>,
146 );
147 await flushTimers();
148 });
149 };
150 await paint();
151 return { root, calls, rerender: paint };
152 }
153
154 function mockApp(methods: Partial<AppBindings>, stubOptions?: DesktopHostStubOptions) {
155 installDesktopHostStub(({
156 main: {
157 App: {
158 Commands: async () => [],
159 Models: async () => [],
160 ModelsForTab: async () => [],
161 SlashArgs: async () => ({ items: [], from: 0 }),
162 CaptureAttachmentTarget: async () => ({ token: "goal-attachment-target", capabilities: ["attachments-v2"] }), ReleaseAttachmentTarget: async () => {},
163 ...methods,
164 } as Partial<AppBindings> as AppBindings,
165 },
166 }).main.App, stubOptions ?? { getPathForFile: (file) => file.name });
167 }
168
169 const mockFileUpload = createFileUploadMock("goal-attachment-target", { ok, eq });
170
171 function dispatchPasteText(input: HTMLElement, text: string) {
172 const event = new Event("paste", { bubbles: true, cancelable: true });
173 Object.defineProperty(event, "clipboardData", {
174 configurable: true,
175 value: {
176 files: [],
177 items: [],
178 types: ["text/plain"],
179 getData: (kind: string) => (kind === "text" || kind === "text/plain" ? text : ""),
180 },
181 });
182 input.dispatchEvent(event);
183 }
184
185 function nativeFileDropEvent(): Event {
186 const drop = new window.Event("drop", { bubbles: true, cancelable: true });
187 Object.defineProperty(drop, "dataTransfer", {
188 configurable: true,
189 value: {
190 types: ["Files"],
191 files: [{}],
192 items: [
193 {
194 kind: "file",
195 webkitGetAsEntry: () => ({ isFile: true }),
196 },
197 ],
198 },
199 });
200 return drop;
201 }
202
203 async function waitFor(label: string, predicate: () => boolean) {
204 for (let attempt = 0; attempt < 20; attempt += 1) {
205 await act(async () => {
206 await flushTimers();
207 });
208 if (predicate()) return;
209 }
210 throw new Error(`timed out waiting for ${label}`);
211 }
212
213 type RenderedComposer = Awaited<ReturnType<typeof renderComposer>>;
214
215 function fileEntry(name: string): DirEntry {
216 return { name, isDir: false };
217 }
218
219 function richComposerTaskText(input: HTMLElement): string {
220 const clone = input.cloneNode(true) as HTMLElement;
221 clone.querySelectorAll("[data-invocation-id], [data-composer-caret-anchor]").forEach((node) => node.remove());
222 return clone.textContent ?? "";
223 }
224
225 function richTextBeforeInvocation(input: HTMLElement, invocation: Element): string {
226 const range = document.createRange();
227 range.setStart(input, 0);
228 range.setEndBefore(invocation);
229 const shell = document.createElement("div");
230 shell.appendChild(range.cloneContents());
231 return richComposerTaskText(shell);
232 }
233
234 async function appendRichComposerInput(input: HTMLElement, text: string, composing = false) {
235 await act(async () => {
236 if (composing) input.dispatchEvent(new Event("compositionstart", { bubbles: true }));
237 input.appendChild(document.createTextNode(text));
238 input.dispatchEvent(new window.InputEvent("input", {
239 bubbles: true,
240 data: text,
241 inputType: composing ? "insertCompositionText" : "insertText",
242 isComposing: composing,
243 }));
244 if (composing) input.dispatchEvent(new Event("compositionend", { bubbles: true }));
245 await flushTimers();
246 });
247 }
248
249 async function replaceComposerDraft(rerender: RenderedComposer["rerender"], id: number, text: string) {
250 await rerender({ insertRequest: { id, text, mode: "replace" } });
251 }
252
253 console.log("\ncomposer goal toggle");
254
255 {
256 const dom = installDom();
257 const { root, calls, rerender } = await renderComposer();
258 let textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
259 if (!textarea) throw new Error("composer textarea did not render");
260 eq(["spellcheck", "autocorrect", "autocapitalize"].map((name) => textarea.getAttribute(name)).join("/"), "false/off/off", "plain composer disables browser text assistance");
261 await rerender({ insertRequest: { id: 1, text: "ship the release notes", mode: "replace" } });
262 eq(textarea.value, "ship the release notes", "insert request populates the composer draft");
263 // The insert queues a rAF that refocuses the textarea; drain that frame
264 // before focusing the trigger, or the late refocus blurs the tooltip away.
265 await act(async () => {
266 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
267 await flushTimers();
268 });
269
270 await rerender({ insertRequest: { id: 2, text: "/reviewer ", mode: "prefix" } });
271 eq(textarea.value, "/reviewer ship the release notes", "prefix insert preserves the draft as a subagent task");
272 eq(calls.send.length, 0, "prefix insert does not send the subagent task");
273
274 eq(document.querySelector(".composer-task-mode-trigger"), null, "default execution has no mode chip");
275 const intentButton = document.querySelector(".composer-content-trigger") as HTMLButtonElement;
276 await act(async () => {
277 intentButton.click();
278 await flushTimers();
279 });
280
281 const taskModeItems = document.querySelectorAll(".composer-intent-menu__item");
282 eq(taskModeItems.length, 2, "task method menu exposes only Plan and Goal");
283 eq(document.querySelectorAll(".composer-intent-switch").length, 0, "task method menu does not present independent switches");
284 const planButton = taskModeItems[0] as HTMLButtonElement | undefined;
285 if (!planButton) throw new Error("composer Plan menu item did not render");
286 eq(planButton.querySelector(".composer-access-menu__desc"), null, "Plan menu keeps a single-line label");
287 ok(planButton.textContent?.toLowerCase().includes("read-only") === false, "Plan menu does not present Plan as a read-only permission mode");
288 const goalButton = taskModeItems[1] as HTMLButtonElement | undefined;
289 if (!goalButton) throw new Error("composer goal menu item did not render");
290
291 await act(async () => {
292 goalButton.click();
293 await flushTimers();
294 });
295
296 eq(calls.send.length, 0, "enabling goal mode with a draft does not send");
297 eq(calls.setCollaborationMode.join(","), "goal", "enabling goal mode switches only the collaboration axis");
298 eq(textarea.value, "/reviewer ship the release notes", "enabling goal mode preserves the prefixed draft text");
299
300 await rerender({ collaborationMode: "plan" });
301 ok(document.querySelector(".composer-task-mode-trigger") !== null, "Plan exposes its active mode chip");
302 await act(async () => {
303 document.querySelector<HTMLButtonElement>(".composer-content-trigger")?.click();
304 await flushTimers();
305 });
306 await act(async () => {
307 document.querySelector<HTMLButtonElement>(".composer-intent-menu__item")?.click();
308 await flushTimers();
309 });
310 eq(calls.setCollaborationMode.at(-1), "normal", "selecting active Plan exits to the implicit default");
311 eq(textarea.value, "/reviewer ship the release notes", "exiting Plan preserves the draft");
312 await act(async () => {
313 document.querySelector<HTMLButtonElement>(".composer-task-mode-trigger")?.click();
314 await flushTimers();
315 });
316 eq(calls.setCollaborationMode.at(-1), "normal", "clicking the mode chip exits Plan directly");
317 eq(textarea.value, "/reviewer ship the release notes", "dismissing the chip preserves the draft");
318
319 await act(async () => {
320 root.unmount();
321 });
322 dom.window.close();
323 }
324
325 {
326 const dom = installDom();
327 mockApp({
328 Commands: async () => [
329 { name: "ui-ux-pro-max", description: "Review the interface", kind: "skill" },
330 ],
331 ListDirForTarget: async () => [],
332 SearchFileRefsForTarget: async () => [],
333 });
334 const { root, calls, rerender } = await renderComposer({ collaborationMode: "goal", goal: "" });
335 await replaceComposerDraft(rerender, 4199, "/ui-ux-pro-max");
336 await waitFor("skill menu for the initial goal", () => Boolean(document.querySelector(".slashmenu")));
337 let textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
338 if (!textarea) throw new Error("composer textarea did not render for the initial goal skill");
339 await act(async () => {
340 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
341 await flushTimers();
342 });
343
344 let sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
345 if (!sendButton) throw new Error("composer send button did not render for the initial goal skill");
346 await act(async () => {
347 sendButton.click();
348 await flushTimers();
349 });
350 eq(calls.send.length, 0, "a skill alone cannot become the initial goal");
351 ok(document.body.textContent?.includes("Enter a goal") === true, "a skill-only initial goal asks for task text");
352
353 await replaceComposerDraft(rerender, 4200, "List the existing notes");
354 sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
355 if (!sendButton) throw new Error("composer send button disappeared after entering the goal");
356 await act(async () => {
357 sendButton.click();
358 await flushTimers();
359 });
360 eq(calls.send[0], "List the existing notes", "the initial goal keeps its visible task text");
361 eq(calls.submit[0], "/ui-ux-pro-max List the existing notes", "the initial goal preserves the selected skill");
362 eq(calls.structured[0]?.input, "List the existing notes", "the initial goal sends structured skill input");
363 eq(calls.structured[0]?.invocations[0]?.name, "ui-ux-pro-max", "the initial goal submits the selected skill entity");
364
365 await replaceComposerDraft(rerender, 4201, "/ui-ux-pro-max List the notes again");
366 sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
367 if (!sendButton) throw new Error("composer send button did not render for a pasted skill invocation");
368 await act(async () => {
369 sendButton.click();
370 await flushTimers();
371 });
372 eq(calls.send[1], "List the notes again", "a pasted skill invocation keeps its task as the visible goal");
373 eq(calls.submit[1], "/ui-ux-pro-max List the notes again", "a pasted skill invocation keeps its slash display");
374 eq(calls.structured[1]?.input, "List the notes again", "a pasted skill invocation uses structured input");
375 eq(calls.structured[1]?.invocations[0]?.name, "ui-ux-pro-max", "a pasted skill invocation resolves the selected command");
376
377 await act(async () => {
378 root.unmount();
379 });
380 dom.window.close();
381 }
382
383 {
384 // Attachment-only first Goal: no text, no skill — attachment refs are valid task context.
385 const dom = installDom();
386 mockApp({}, { getPathForFile: () => "" });
387 const restoreUpload = mockFileUpload(async () => ".reasonix/attachments/notes.txt");
388 const { root, calls } = await renderComposer({ collaborationMode: "goal", goal: "" });
389 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
390 if (!textarea) throw new Error("composer textarea did not render for attachment-only goal");
391 await act(async () => {
392 dispatchPasteFile(textarea, new File(["hello"], "notes.txt", { type: "text/plain" }));
393 await flushTimers();
394 });
395 await waitFor("attachment-only initial goal card", () => document.body.textContent?.includes("notes.txt") === true);
396
397 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
398 if (!sendButton) throw new Error("send button missing for attachment-only initial goal");
399 await act(async () => {
400 sendButton.click();
401 await flushTimers();
402 });
403 eq(calls.send.length, 1, "attachment-only input can become the initial Goal");
404 ok(
405 calls.submit[0]?.includes("@.reasonix/attachments/notes.txt") === true,
406 "attachment-only initial Goal submits the attachment ref",
407 );
408 eq(calls.structured[0], undefined, "attachment-only initial Goal is not a structured skill submit");
409
410 await act(async () => {
411 root.unmount();
412 });
413 dom.window.close();
414 restoreUpload();
415 }
416
417 {
418 // Workspace-ref-only first Goal: no text, no skill — workspace refs remain valid task context.
419 const dom = installDom();
420 mockApp({
421 AttachDroppedForTarget: async () => ({
422 kind: "workspace",
423 path: "src/App.tsx",
424 isDir: false,
425 displayPath: "src/App.tsx",
426 }),
427 });
428 const { root, calls } = await renderComposer({ collaborationMode: "goal", goal: "" });
429 const wrap = document.querySelector(".composer-wrap");
430 if (!wrap) throw new Error("composer drop target did not render for workspace-ref goal");
431 await act(async () => {
432 dispatchNativeFileDrop(wrap, [new File([""], "/repo/src/App.tsx")]);
433 await flushTimers();
434 });
435 await waitFor("workspace-ref-only initial goal card", () => document.body.textContent?.includes("App.tsx") === true);
436
437 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
438 if (!sendButton) throw new Error("send button missing for workspace-ref-only initial goal");
439 await act(async () => {
440 sendButton.click();
441 await flushTimers();
442 });
443 eq(calls.send.length, 1, "workspace-ref-only input can become the initial Goal");
444 eq(calls.submit[0], "@src/App.tsx", "workspace-ref-only initial Goal submits the workspace ref");
445 eq(calls.structured[0], undefined, "workspace-ref-only initial Goal is not a structured skill submit");
446
447 await act(async () => {
448 root.unmount();
449 });
450 dom.window.close();
451 }
452
453 {
454 const dom = installDom();
455 mockApp({
456 Commands: async () => [
457 { name: "writing-plans", description: "Write a plan", kind: "skill" },
458 { name: "review", description: "Review the result", kind: "skill" },
459 ],
460 ListDirForTarget: async () => [],
461 SearchFileRefsForTarget: async () => [],
462 });
463 const { root, calls, rerender } = await renderComposer();
464 await replaceComposerDraft(rerender, 4200, "/writing-plans");
465 await waitFor("skill menu for pasted-block offsets", () => Boolean(document.querySelector(".slashmenu")));
466 let textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
467 if (!textarea) throw new Error("composer textarea did not render for pasted-block offsets");
468 await act(async () => {
469 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
470 await flushTimers();
471 });
472
473 let richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
474 let firstToken = richInput?.querySelector(".composer-invocation-token");
475 if (!richInput || !firstToken) throw new Error("initial rich invocation did not render for pasted-block offsets");
476 const afterFirst = document.createRange();
477 afterFirst.setStartAfter(firstToken);
478 afterFirst.collapse(true);
479 document.getSelection()?.removeAllRanges();
480 document.getSelection()?.addRange(afterFirst);
481 const expandedText = Array.from({ length: 20 }, (_, index) => `expanded line ${index + 1}`).join("\n");
482 await act(async () => {
483 dispatchPasteText(richInput!, expandedText);
484 await flushTimers();
485 });
486 const firstLabel = document.querySelector(".composer__pasted-label")?.textContent ?? "";
487 ok(firstLabel !== "", "long rich-composer paste folds into a pasted block");
488
489 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
490 if (!richInput) throw new Error("rich input disappeared after folded paste");
491 await appendRichComposerInput(richInput, " /review");
492 const afterReviewQuery = document.createRange();
493 afterReviewQuery.selectNodeContents(richInput);
494 afterReviewQuery.collapse(false);
495 document.getSelection()?.removeAllRanges();
496 document.getSelection()?.addRange(afterReviewQuery);
497 await act(async () => {
498 richInput!.dispatchEvent(new window.KeyboardEvent("keyup", { key: "w", bubbles: true }));
499 await flushTimers();
500 });
501 await waitFor("second skill menu after folded paste", () => Boolean(document.querySelector(".slashmenu")));
502 await act(async () => {
503 richInput!.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
504 await flushTimers();
505 });
506
507 const expandButton = document.querySelectorAll<HTMLButtonElement>(".composer__pasted-actions button")[1];
508 if (!expandButton) throw new Error("pasted-block expand button did not render");
509 await act(async () => {
510 expandButton.click();
511 await flushTimers();
512 });
513 ok(document.querySelector(".composer__pasted-block") === null, "expanding a pasted block removes its folded control");
514
515 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
516 const tokensAfterExpand = richInput?.querySelectorAll(".composer-invocation-token");
517 const secondToken = tokensAfterExpand?.[1];
518 if (!richInput || !secondToken) throw new Error("second rich invocation disappeared after pasted-block expansion");
519 eq(richTextBeforeInvocation(richInput, secondToken), `${expandedText} `, "expanding folded text shifts the following invocation to the end of the expanded content");
520 const beforeSecond = document.createRange();
521 beforeSecond.setStartBefore(secondToken);
522 beforeSecond.collapse(true);
523 document.getSelection()?.removeAllRanges();
524 document.getSelection()?.addRange(beforeSecond);
525 const removedText = Array.from({ length: 20 }, (_, index) => `removed line ${index + 1}`).join("\n");
526 await act(async () => {
527 dispatchPasteText(richInput!, removedText);
528 await flushTimers();
529 });
530 const removeButton = document.querySelectorAll<HTMLButtonElement>(".composer__pasted-actions button")[2];
531 if (!removeButton) throw new Error("pasted-block remove button did not render");
532 await act(async () => {
533 removeButton.click();
534 await flushTimers();
535 });
536
537 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
538 const secondTokenAfterRemove = richInput?.querySelectorAll(".composer-invocation-token")[1];
539 if (!richInput || !secondTokenAfterRemove) throw new Error("second rich invocation disappeared after pasted-block removal");
540 eq(richTextBeforeInvocation(richInput, secondTokenAfterRemove), `${expandedText} `, "removing folded text restores the following invocation offset");
541
542 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
543 if (!sendButton) throw new Error("send button did not render after pasted-block replacement");
544 await act(async () => {
545 sendButton.click();
546 await flushTimers();
547 });
548 eq(calls.structured[0]?.invocations[1]?.offset, expandedText.length, "trimmed structured submission keeps the normalized following invocation offset");
549
550 await act(async () => {
551 root.unmount();
552 });
553 dom.window.close();
554 }
555
556 {
557 const dom = installDom();
558 const command: CommandInfo = {
559 name: "writing-plans",
560 description: "Write a plan",
561 kind: "skill",
562 };
563 mockApp({
564 Commands: async () => [command],
565 ListDirForTarget: async () => [],
566 SearchFileRefsForTarget: async () => [],
567 });
568 const { root, rerender } = await renderComposer();
569 await replaceComposerDraft(rerender, 4201, "/writing-plans");
570 await waitFor("skill menu for paste undo selection", () => Boolean(document.querySelector(".slashmenu")));
571 const initialTextarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
572 if (!initialTextarea) throw new Error("composer textarea did not render for paste undo selection");
573 await act(async () => {
574 initialTextarea.dispatchEvent(new window.KeyboardEvent("keydown", {
575 key: "Enter",
576 bubbles: true,
577 cancelable: true,
578 }));
579 await flushTimers();
580 });
581
582 let richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
583 let token = richInput?.querySelector<HTMLElement>(".composer-invocation-token");
584 const invocationId = token?.dataset.invocationId;
585 if (!richInput || !token || !invocationId) throw new Error("rich invocation did not render for paste undo selection");
586 eq(["spellcheck", "autocorrect", "autocapitalize"].map((name) => richInput.getAttribute(name)).join("/"), "false/off/off", "rich composer disables browser text assistance");
587 const afterToken = document.createRange();
588 afterToken.setStartAfter(token);
589 afterToken.collapse(true);
590 document.getSelection()?.removeAllRanges();
591 document.getSelection()?.addRange(afterToken);
592 await act(async () => {
593 dispatchPasteText(richInput!, "pasted");
594 await flushTimers();
595 });
596 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
597 if (!richInput) throw new Error("rich input disappeared after paste");
598 eq(richComposerTaskText(richInput), "pasted", "paste after an invocation inserts on the token's right side");
599
600 await act(async () => {
601 richInput!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
602 await flushTimers();
603 });
604 let richMenuItems = Array.from(document.querySelectorAll<HTMLButtonElement>(".context-menu__item"));
605 eq(richMenuItems.length, 6, "rich composer exposes the shared edit context menu");
606 ok(richMenuItems[0]?.disabled === false, "rich composer context-menu undo is enabled after paste");
607 ok(richMenuItems[1]?.disabled === true, "rich composer context-menu redo is disabled before undo");
608 await act(async () => {
609 richMenuItems[0]?.click();
610 await flushTimers();
611 });
612 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
613 if (!richInput) throw new Error("rich input disappeared after context-menu undo");
614 eq(richComposerTaskText(richInput), "", "rich composer context-menu undo removes the pasted text");
615
616 await act(async () => {
617 richInput!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
618 await flushTimers();
619 });
620 richMenuItems = Array.from(document.querySelectorAll<HTMLButtonElement>(".context-menu__item"));
621 ok(richMenuItems[1]?.disabled === false, "rich composer context-menu redo is enabled after undo");
622 await act(async () => {
623 richMenuItems[1]?.click();
624 await flushTimers();
625 });
626 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
627 if (!richInput) throw new Error("rich input disappeared after context-menu redo");
628 eq(richComposerTaskText(richInput), "pasted", "rich composer context-menu redo restores the pasted text");
629
630 const undoPaste = new window.KeyboardEvent("keydown", {
631 key: "z",
632 ctrlKey: true,
633 bubbles: true,
634 cancelable: true,
635 });
636 await act(async () => {
637 richInput!.dispatchEvent(undoPaste);
638 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
639 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
640 await flushTimers();
641 });
642 eq(undoPaste.defaultPrevented, true, "Ctrl+Z restores the rich-composer paste transaction");
643
644 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
645 token = richInput?.querySelector<HTMLElement>(".composer-invocation-token");
646 if (!richInput || !token) throw new Error("rich invocation disappeared after paste undo");
647 const restoredInvocation: ComposerInvocation = { id: invocationId, offset: 0, command };
648 const restoredSelection = selectionFromDom(
649 richInput,
650 new Map([[invocationId, restoredInvocation]]),
651 );
652 eq(
653 restoredSelection.ok ? restoredSelection.selection.afterInvocationId : undefined,
654 invocationId,
655 "paste undo restores the caret after the invocation token",
656 );
657
658 await act(async () => {
659 richInput!.dispatchEvent(new window.KeyboardEvent("keydown", {
660 key: "Backspace",
661 bubbles: true,
662 cancelable: true,
663 }));
664 await flushTimers();
665 });
666 ok(
667 document.querySelector(".composer-invocation-token") === null,
668 "Backspace after paste undo removes the invocation on the caret's left",
669 );
670
671 await act(async () => {
672 root.unmount();
673 });
674 dom.window.close();
675 }
676
677 {
678 const dom = installDom();
679 const { root, calls } = await renderComposer({
680 collaborationMode: "goal",
681 goal: "finish the migration",
682 });
683
684 const intentButton = document.querySelector(".composer-task-mode-trigger") as HTMLButtonElement | null;
685 if (!intentButton) throw new Error("active goal task method trigger did not render");
686 ok(intentButton.textContent?.includes("Goal") === true, "task method trigger exposes an active goal");
687
688 await act(async () => {
689 (document.querySelector(".composer-content-trigger") as HTMLButtonElement).click();
690 await flushTimers();
691 });
692
693 const goalActions = Array.from(document.querySelectorAll(".composer-intent-menu__stop")) as HTMLButtonElement[];
694 const stopGoal = goalActions.find((b) => b.textContent === "End goal");
695 if (!stopGoal) throw new Error("explicit end-goal action did not render");
696 await act(async () => {
697 stopGoal.click();
698 await flushTimers();
699 });
700 eq(calls.clearGoal, 1, "explicit stop action clears the active goal");
701 eq(calls.setCollaborationMode.length, 0, "stopping a goal does not race a second mode update");
702 await act(async () => {
703 intentButton.click();
704 await flushTimers();
705 });
706 eq(calls.clearGoal, 2, "dismissing an active goal chip uses the existing clear-goal action");
707
708 await act(async () => {
709 root.unmount();
710 });
711 dom.window.close();
712 }
713
714 {
715 const dom = installDom();
716 const { root, calls } = await renderComposer({
717 running: true,
718 collaborationMode: "goal",
719 goal: "finish the migration",
720 turnStartAt: Date.now(),
721 });
722
723 const stopButton = document.querySelector(".composer__btn--stop") as HTMLButtonElement | null;
724 if (!stopButton) throw new Error("composer stop button did not render");
725
726 await act(async () => {
727 stopButton.click();
728 await flushTimers();
729 });
730
731 eq(calls.cancel, 1, "goal-mode stop cancels the running turn");
732 eq(calls.clearGoal, 1, "goal-mode stop clears the active goal");
733
734 await act(async () => {
735 root.unmount();
736 });
737 dom.window.close();
738 }
739
740 {
741 const dom = installDom();
742 mockApp({}, { getPathForFile: () => "" });
743 const restoreUpload = mockFileUpload(async () => {
744 throw new Error("/Users/example/private.pdf: permission denied");
745 });
746 const { root, rerender } = await renderComposer();
747 await rerender({ insertRequest: { id: 2, text: "keep this draft", mode: "replace" } });
748
749 let textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
750 if (!textarea) throw new Error("composer textarea did not render");
751 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
752 if (!sendButton) throw new Error("composer send button did not render");
753
754 await act(async () => {
755 dispatchPasteFile(textarea, new File(["hello"], "notes.txt", { type: "text/plain" }));
756 await flushTimers();
757 });
758 await waitFor("pasted file failure toast", () => document.body.textContent?.includes("File attach failed") === true);
759
760 ok(document.body.textContent?.includes("File attach failed") === true, "raw upload rejection shows a visible error");
761 eq(textarea.value, "keep this draft", "failed pasted file attach preserves composer text");
762 ok(sendButton.disabled === false, "failed pasted file attach clears the pending state");
763 ok(document.body.textContent?.includes("/Users/example") === false, "pasted file failure toast does not expose the local path");
764
765 await act(async () => {
766 root.unmount();
767 });
768 dom.window.close();
769 restoreUpload();
770 }
771
772 {
773 const dom = installDom();
774 mockApp({}, { getPathForFile: () => "" });
775 const restoreUpload = mockFileUpload(async () => ".reasonix/attachments/notes.txt");
776 const { root } = await renderComposer();
777
778 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
779 if (!textarea) throw new Error("composer textarea did not render");
780
781 await act(async () => {
782 dispatchPasteFile(textarea, new File(["hello"], "notes.txt", { type: "text/plain" }));
783 await flushTimers();
784 });
785 await waitFor("pasted file attachment", () => document.body.textContent?.includes("notes.txt") === true);
786
787 ok(document.body.textContent?.includes("notes.txt") === true, "successful pasted file attach still renders the attachment");
788
789 await act(async () => {
790 root.unmount();
791 });
792 dom.window.close();
793 restoreUpload();
794 }
795
796 {
797 const dom = installDom();
798 mockApp({
799 AttachDroppedForTarget: async () => {
800 throw new Error("/Users/example/secret.pdf: permission denied");
801 },
802 });
803 const { root, rerender } = await renderComposer();
804 await rerender({ insertRequest: { id: 3, text: "drop draft", mode: "replace" } });
805
806 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
807 if (!textarea) throw new Error("composer textarea did not render");
808 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
809 if (!sendButton) throw new Error("composer send button did not render");
810 const wrapSecret = document.querySelector(".composer-wrap");
811 if (!wrapSecret) throw new Error("composer drop target did not render");
812
813 await act(async () => {
814 dispatchNativeFileDrop(wrapSecret, [new File([""], "/Users/example/secret.pdf")]);
815 await flushTimers();
816 });
817 await waitFor("dropped file failure toast", () => document.body.textContent?.includes("Dropped file attach failed") === true);
818
819 ok(document.body.textContent?.includes("Dropped file attach failed") === true, "AttachDropped rejection shows a visible error");
820 eq(textarea.value, "drop draft", "failed dropped file attach preserves composer text");
821 ok(sendButton.disabled === false, "failed dropped file attach clears the pending state");
822 ok(document.body.textContent?.includes("/Users/example") === false, "dropped file failure toast does not expose the local path");
823
824 await act(async () => {
825 root.unmount();
826 });
827 dom.window.close();
828 }
829
830 {
831 const dom = installDom();
832 mockApp({
833 AttachDroppedForTarget: async () => ({
834 kind: "attachment",
835 path: ".reasonix/attachments/report.pdf",
836 }),
837 });
838 const { root } = await renderComposer();
839 const wrapReport = document.querySelector(".composer-wrap");
840 if (!wrapReport) throw new Error("composer drop target did not render");
841
842 await act(async () => {
843 dispatchNativeFileDrop(wrapReport, [new File([""], "/Users/example/report.pdf")]);
844 await flushTimers();
845 });
846 await waitFor("dropped file attachment", () => document.body.textContent?.includes("report.pdf") === true);
847
848 ok(document.body.textContent?.includes("report.pdf") === true, "successful dropped file attach still renders the attachment");
849
850 await act(async () => {
851 root.unmount();
852 });
853 dom.window.close();
854 }
855
856 {
857 const dom = installDom();
858 mockApp({
859 AttachDroppedForTarget: async () => ({
860 kind: "workspace",
861 path: "__reasonix_external_folder/mock/Folder-With-Spaces",
862 isDir: true,
863 displayPath: "/Users/example/Folder With Spaces",
864 }),
865 });
866 const { root, calls, rerender } = await renderComposer();
867 await rerender({ insertRequest: { id: 4, text: "inspect", mode: "replace" } });
868 const wrapFolderwithspaces = document.querySelector(".composer-wrap");
869 if (!wrapFolderwithspaces) throw new Error("composer drop target did not render");
870
871 await act(async () => {
872 dispatchNativeFileDrop(wrapFolderwithspaces, [new File([""], "/Users/example/Folder With Spaces")]);
873 await flushTimers();
874 });
875 await waitFor("dropped external folder chip", () => document.body.textContent?.includes("Folder With Spaces/") === true);
876
877 ok(document.body.textContent?.includes("Folder With Spaces/") === true, "dropped external folder renders as a folder context chip");
878
879 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
880 if (!sendButton) throw new Error("composer send button did not render");
881 await act(async () => {
882 sendButton.click();
883 await flushTimers();
884 });
885
886 eq(calls.send.join(","), "inspect @/Users/example/Folder\\ With\\ Spaces/", "external folder display text preserves the real folder path as one escaped reference");
887 eq(calls.submit.join(","), "inspect @__reasonix_external_folder/mock/Folder-With-Spaces/", "external folder submit text uses the session ref token");
888
889 await act(async () => {
890 root.unmount();
891 });
892 dom.window.close();
893 }
894
895 {
896 const externalToken = "__reasonix_external_folder/mock/Folder-With-Spaces/src/outside.txt";
897 const externalDisplayPath = "/Users/example/Folder With Spaces/src/outside.txt";
898 const picked = composerPickFileEntry("ask @outside", "outside", "", {
899 name: "src/outside.txt",
900 path: externalToken,
901 isDir: false,
902 displayName: "Folder With Spaces/src/outside.txt",
903 displayPath: externalDisplayPath,
904 });
905 eq(picked.text, "ask ", "external search selection removes the token fragment from the draft");
906 eq(picked.workspaceRef?.path, externalToken, "external search selection submits the session ref token");
907 eq(picked.workspaceRef?.displayPath, externalDisplayPath, "external search selection keeps the real display path");
908
909 const localFile = composerPickFileEntry("ask @src/mai", "src/mai", "src/", { name: "main.go", isDir: false });
910 eq(localFile.text, "ask @src/main.go ", "local file selection still completes inline text");
911
912 const localDir = composerPickFileEntry("ask @sr", "sr", "", { name: "src", isDir: true });
913 eq(localDir.text, "ask @src/", "local dir selection still keeps the menu-open slash");
914
915 const trailingNewline = composerPickFileEntry("ask @src/mai\n", "src/mai", "src/", { name: "main.go", isDir: false });
916 eq(trailingNewline.text, "ask @src/main.go ", "file selection ignores an invisible trailing newline");
917 }
918
919 {
920 const dom = installDom();
921 const { root: dropNavRoot } = await renderComposer();
922 const composer = document.querySelector(".composer") as HTMLElement | null;
923 if (!composer) throw new Error("composer did not render");
924
925 const drop = nativeFileDropEvent();
926 await act(async () => {
927 composer.dispatchEvent(drop);
928 await flushTimers();
929 });
930 ok(drop.defaultPrevented, "native file drop prevents browser image navigation");
931
932 await act(async () => {
933 dropNavRoot.unmount();
934 });
935 dom.window.close();
936 }
937
938 {
939 const dom = installDom();
940 const { root: dropWrapRoot } = await renderComposer();
941 const wrap = document.querySelector(".composer-wrap") as HTMLElement | null;
942 if (!wrap) throw new Error("composer wrap did not render");
943
944 const drop = nativeFileDropEvent();
945 await act(async () => {
946 wrap.dispatchEvent(drop);
947 await flushTimers();
948 });
949 ok(drop.defaultPrevented, "outer native file drop target prevents browser image navigation");
950
951 await act(async () => {
952 dropWrapRoot.unmount();
953 });
954 dom.window.close();
955 }
956
957 {
958 const dom = installDom();
959 let rejectSubmit: (err: Error) => void = () => {};
960 const rejectedSubmit = new Promise<void>((_, reject) => {
961 rejectSubmit = reject;
962 });
963 rejectedSubmit.catch(() => {});
964 const { root, calls, rerender } = await renderComposer({
965 onSend: (displayText) => {
966 calls.send.push(displayText);
967 return rejectedSubmit;
968 },
969 });
970
971 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
972 if (!textarea) throw new Error("composer textarea did not render");
973
974 await rerender({ insertRequest: { id: 2, text: "keep this draft", mode: "replace" } });
975 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
976 if (!sendButton) throw new Error("composer send button did not render");
977
978 await act(async () => {
979 sendButton.click();
980 rejectSubmit(new Error("workspace is still starting"));
981 await flushTimers();
982 });
983
984 eq(calls.send.join(","), "keep this draft", "rejected submit attempts the send once");
985 eq(textarea.value, "keep this draft", "rejected submit preserves the composer draft");
986
987 await act(async () => {
988 root.unmount();
989 });
990 dom.window.close();
991 }
992
993 {
994 const dom = installDom();
995 const { root, calls, rerender } = await renderComposer({
996 onSend: (displayText) => {
997 calls.send.push(displayText);
998 return Promise.resolve();
999 },
1000 });
1001
1002 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1003 if (!textarea) throw new Error("composer textarea did not render");
1004
1005 await rerender({ insertRequest: { id: 3, text: "send this draft", mode: "replace" } });
1006 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1007 if (!sendButton) throw new Error("composer send button did not render");
1008
1009 await act(async () => {
1010 sendButton.click();
1011 await flushTimers();
1012 });
1013
1014 eq(calls.send.join(","), "send this draft", "successful submit attempts the send once");
1015 eq(textarea.value, "", "successful submit clears the composer draft");
1016
1017 await act(async () => {
1018 root.unmount();
1019 });
1020 dom.window.close();
1021 }
1022
1023 {
1024 const dom = installDom();
1025 const { root, rerender } = await renderComposer({
1026 running: true,
1027 guidanceQueuePreviewItems: ["confirm the send lifecycle", "keep steer protocol unchanged", "add a hanging submit regression"],
1028 });
1029
1030 let guidanceItems = Array.from(document.querySelectorAll(".composer-guidance-item"));
1031 eq(guidanceItems.length, 2, "running guidance preview shows a compact queue preview");
1032 ok(guidanceItems[0]?.textContent?.includes("confirm the send lifecycle") === true, "guidance preview shows the first seeded item");
1033 ok(guidanceItems[1]?.textContent?.includes("keep steer protocol unchanged") === true, "guidance preview shows the second seeded item");
1034 eq(document.querySelectorAll(".composer-guidance-item__guide").length, 2, "guidance preview exposes a guide action for each visible item");
1035 let guidanceMore = document.querySelector(".composer-guidance-more") as HTMLButtonElement | null;
1036 ok(guidanceMore?.textContent?.includes("1 more queued") === true, "guidance preview summarizes overflow items");
1037 eq(guidanceMore?.getAttribute("aria-expanded"), "false", "guidance overflow starts collapsed");
1038
1039 if (!guidanceMore) throw new Error("guidance overflow button did not render");
1040 await act(async () => {
1041 guidanceMore.click();
1042 await flushTimers();
1043 });
1044 guidanceItems = Array.from(document.querySelectorAll(".composer-guidance-item"));
1045 eq(guidanceItems.length, 3, "guidance overflow expands the remaining queued items");
1046 ok(guidanceItems[2]?.textContent?.includes("add a hanging submit regression") === true, "expanded guidance preview shows the hidden item");
1047 guidanceMore = document.querySelector(".composer-guidance-more") as HTMLButtonElement | null;
1048 ok(guidanceMore?.textContent?.includes("Collapse") === true, "expanded guidance overflow can be collapsed");
1049 eq(guidanceMore?.getAttribute("aria-expanded"), "true", "guidance overflow reports expanded state");
1050
1051 if (!guidanceMore) throw new Error("guidance collapse button did not render");
1052 await act(async () => {
1053 guidanceMore.click();
1054 await flushTimers();
1055 });
1056 guidanceItems = Array.from(document.querySelectorAll(".composer-guidance-item"));
1057 eq(guidanceItems.length, 2, "guidance overflow collapses back to the compact preview");
1058
1059 await rerender({ guidanceQueuePreviewItems: ["only the latest preview seed"] });
1060 guidanceItems = Array.from(document.querySelectorAll(".composer-guidance-item"));
1061 eq(guidanceItems.length, 1, "guidance preview refreshes when the seed changes");
1062 ok(guidanceItems[0]?.textContent?.includes("only the latest preview seed") === true, "guidance preview renders the refreshed seed");
1063
1064 await rerender({ running: false });
1065 ok(document.querySelector(".composer-guidance-item") === null, "guidance preview clears when the mock turn stops");
1066
1067 await act(async () => {
1068 root.unmount();
1069 });
1070 dom.window.close();
1071 }
1072
1073 {
1074 const dom = installDom();
1075 let nextInboxID = 0, revision = 0;
1076 let queued: { id: string; preview: string; state: string; intent: string; byteSize: number; position: number }[] = [];
1077 const steerItemIDs: string[] = [], deletedItemIDs: string[] = [];
1078 mockApp({
1079 InboxSnapshot: async () => ({ revision, paused: false, recovered: false, items: queued,
1080 itemsCount: queued.length, bytes: 0, maxItems: 64, maxBytes: 64 * 1024 * 1024 }),
1081 EnqueueInboxFollowup: async (_tabID, display) => {
1082 const id = `durable-${++nextInboxID}`;
1083 queued.push({ id, preview: display, state: "queued", intent: "followup", byteSize: display.length, position: queued.length + 1 }); revision++;
1084 return { itemId: id, disposition: "queued_followup", position: queued.length, paused: false };
1085 },
1086 SteerInboxItem: async (_tabID, itemID) => {
1087 steerItemIDs.push(itemID);
1088 queued = queued.filter(item => item.id !== itemID); revision++;
1089 return { itemId: itemID, disposition: "steer_accepted", position: 1, paused: false };
1090 },
1091 DeleteInboxItem: async (_tabID, itemID) => {
1092 deletedItemIDs.push(itemID);
1093 queued = queued.filter(item => item.id !== itemID); revision++;
1094 },
1095 });
1096 const { root, calls, rerender } = await renderComposer({
1097 running: true, inboxSessionPath: "/repo/session.jsonl",
1098 onSend: (displayText, submitText) => {
1099 calls.send.push(displayText);
1100 calls.submit.push(submitText);
1101 },
1102 });
1103
1104 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1105 if (!textarea) throw new Error("composer textarea did not render");
1106 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1107 if (!sendButton) throw new Error("running composer send button did not render");
1108
1109 eq(textarea.placeholder, "Running — type guidance, Enter adds it to the queue", "running composer explains queued guidance input");
1110 ok(sendButton.classList.contains("composer__btn--steer"), "running composer marks send button as steer");
1111 ok(sendButton.disabled === true, "running steer button stays disabled without input");
1112
1113 await rerender({ insertRequest: { id: 4, text: "keep the files small", mode: "replace" } });
1114 ok(sendButton.disabled === false, "running steer button enables after text input");
1115
1116 await act(async () => {
1117 sendButton.click();
1118 await flushTimers();
1119 });
1120
1121 eq(calls.send.join(","), "", "running composer queues guidance without sending it immediately");
1122 eq(textarea.value, "", "queued running guidance clears the composer draft");
1123 const guidanceItem = document.querySelector(".composer-guidance-item") as HTMLElement | null;
1124 if (!guidanceItem) throw new Error("running guidance chip did not render");
1125 ok(guidanceItem.textContent?.includes("keep the files small") === true, "running guidance chip shows queued text");
1126 ok(document.querySelector(".composer-guidance-head")?.textContent?.includes("Queued guidance 1") === true, "running guidance shelf shows queued count");
1127
1128 const guideButton = guidanceItem.querySelector(".composer-guidance-item__guide") as HTMLButtonElement | null;
1129 if (!guideButton) throw new Error("running guidance guide button did not render");
1130 await act(async () => {
1131 guideButton.click();
1132 await flushTimers();
1133 });
1134 eq(steerItemIDs.join(","), "durable-1", "guide attempts admission with the existing durable item ID");
1135 eq(calls.send.join(","), "", "guide never opens a duplicate frontend submit");
1136 ok(document.querySelector(".composer-guidance-item") === null, "accepted durable steer clears after backend admission");
1137
1138 await rerender({ insertRequest: { id: 5, text: "prefer the smaller diff", mode: "replace" } });
1139 await act(async () => {
1140 sendButton.click();
1141 await flushTimers();
1142 });
1143 const dismissibleGuidanceItem = document.querySelector(".composer-guidance-item") as HTMLElement | null;
1144 if (!dismissibleGuidanceItem) throw new Error("dismissible guidance chip did not render");
1145 const dismissButton = Array.from(dismissibleGuidanceItem.querySelectorAll<HTMLButtonElement>(".composer-guidance-item__action")).at(-1) ?? null;
1146 if (!dismissButton) throw new Error("running guidance dismiss button did not render");
1147 await act(async () => {
1148 dismissButton.click();
1149 await flushTimers();
1150 });
1151 eq(deletedItemIDs.join(","), "durable-2", "dismiss deletes the durable backend item before clearing the shelf");
1152 ok(document.querySelector(".composer-guidance-item") === null, "running guidance chip can be dismissed");
1153
1154 await rerender({ insertRequest: { id: 6, text: "prefer the smaller diff", mode: "replace" } });
1155 await act(async () => {
1156 sendButton.click();
1157 await flushTimers();
1158 });
1159 ok(document.querySelector(".composer-guidance-item") !== null, "running guidance chip renders again after another queued item");
1160
1161 queued = []; revision++; // The controller consumed and acknowledged the item.
1162 await rerender({ guidanceConsumedKey: "s1", guidanceConsumedText: "prefer the smaller diff" });
1163 ok(document.querySelector(".composer-guidance-item") === null, "running guidance chip clears when steer is consumed");
1164
1165 await rerender({ insertRequest: { id: 7, text: "then stop showing the chip", mode: "replace" } });
1166 await act(async () => {
1167 sendButton.click();
1168 await flushTimers();
1169 });
1170 ok(document.querySelector(".composer-guidance-item") !== null, "running guidance chip renders before turn stop");
1171
1172 await rerender({ running: false });
1173 ok(document.querySelector(".composer-guidance-item") !== null, "pending guidance remains after the current turn stops");
1174
1175 await act(async () => {
1176 root.unmount();
1177 });
1178 dom.window.close();
1179 }
1180
1181 {
1182 const dom = installDom();
1183 const steerItemIDs: string[] = [];
1184 let queued = false, revision = 0;
1185 mockApp({
1186 InboxSnapshot: async () => ({ revision, paused: false, recovered: false,
1187 items: queued ? [{ id: "durable-activating", preview: "steer while activating", state: "queued", intent: "followup", byteSize: 22, position: 1 }] : [], itemsCount: queued ? 1 : 0,
1188 bytes: 0, maxItems: 64, maxBytes: 64 * 1024 * 1024,
1189 }),
1190 EnqueueInboxFollowup: async () => { queued = true; revision++; return { itemId: "durable-activating", disposition: "queued_followup", position: 1, paused: false }; },
1191 SteerInboxItem: async (_tabID, itemID) => {
1192 steerItemIDs.push(itemID);
1193 queued = false; revision++;
1194 return { itemId: itemID, disposition: "steer_accepted", position: 1, paused: false };
1195 },
1196 });
1197 const { root, calls, rerender } = await renderComposer({
1198 running: true, inboxSessionPath: "/repo/activating.jsonl",
1199 submitDisabled: true,
1200 onSend: (displayText) => {
1201 calls.send.push(displayText);
1202 },
1203 });
1204
1205 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1206 if (!sendButton) throw new Error("running composer send button did not render");
1207
1208 await rerender({ insertRequest: { id: 7, text: "steer while activating", mode: "replace" } });
1209 ok(sendButton.disabled === false, "running guidance queue ignores controller submitDisabled");
1210
1211 await act(async () => {
1212 sendButton.click();
1213 await flushTimers();
1214 });
1215
1216 eq(calls.send.join(","), "", "running guidance queues while controllerReady is false");
1217 const guideButton = document.querySelector(".composer-guidance-item__guide") as HTMLButtonElement | null;
1218 if (!guideButton) throw new Error("running guidance guide button did not render");
1219 await act(async () => {
1220 guideButton.click();
1221 await flushTimers();
1222 });
1223
1224 eq(steerItemIDs.join(","), "durable-activating", "queued durable item can be guided while controllerReady is false");
1225 eq(calls.send.join(","), "", "controllerReady gap does not create a duplicate submit");
1226
1227 await act(async () => {
1228 root.unmount();
1229 });
1230 dom.window.close();
1231 }
1232
1233 {
1234 // A backend steer rejection means the turn crossed its final admission
1235 // boundary. The same durable item becomes a follow-up; the Controller, not
1236 // the browser, owns its later FIFO dispatch and ack.
1237 const dom = installDom();
1238 let steerAttempts = 0;
1239 let backendQueued = false, backendRevision = 0;
1240 mockApp({
1241 InboxSnapshot: async () => ({
1242 revision: backendRevision,
1243 paused: false,
1244 recovered: false,
1245 items: backendQueued ? [{
1246 id: "durable-late", intent: "followup", state: "queued", preview: "preserve this late guidance", byteSize: 27, position: 1,
1247 }] : [],
1248 itemsCount: backendQueued ? 1 : 0,
1249 bytes: backendQueued ? 27 : 0,
1250 maxItems: 64,
1251 maxBytes: 64 * 1024 * 1024,
1252 }),
1253 EnqueueInboxFollowup: async () => { backendQueued = true; backendRevision++;
1254 return { itemId: "durable-late", disposition: "queued_followup", position: 1, paused: false }; },
1255 SteerInboxItem: async (_tabID, itemID) => {
1256 steerAttempts += 1;
1257 return { itemId: itemID, disposition: "queued_followup", position: 1, paused: false };
1258 },
1259 });
1260 const { root, calls, rerender } = await renderComposer({
1261 running: true, inboxSessionPath: "/repo/late.jsonl",
1262 onSend: (displayText, submitText) => {
1263 calls.send.push(displayText);
1264 calls.submit.push(submitText);
1265 return Promise.resolve();
1266 },
1267 });
1268
1269 await rerender({ insertRequest: { id: 71, text: "preserve this late guidance", mode: "replace" } });
1270 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1271 if (!sendButton) throw new Error("running composer send button did not render");
1272 await act(async () => {
1273 sendButton.click();
1274 await flushTimers();
1275 });
1276 const guidanceItem = document.querySelector(".composer-guidance-item") as HTMLElement | null;
1277 const guideButton = guidanceItem?.querySelector(".composer-guidance-item__guide") as HTMLButtonElement | null;
1278 if (!guideButton) throw new Error("late guidance guide button did not render");
1279 await act(async () => {
1280 guideButton.click();
1281 await flushTimers();
1282 });
1283
1284 eq(steerAttempts, 1, "late guidance attempts one strict steer admission");
1285 eq(calls.send.length, 0, "rejected steer does not open a provider turn");
1286 ok(document.querySelector(".composer-guidance-item") !== null, "rejected steer remains queued");
1287
1288 backendQueued = false; backendRevision++; // Controller dispatched and durably acked after TurnDone.
1289 await rerender({ running: false });
1290 await waitFor("acked durable follow-up removed from shelf", () => document.querySelector(".composer-guidance-item") === null);
1291 eq(calls.send.length, 0, "late durable follow-up is never resubmitted by the frontend");
1292
1293 await act(async () => {
1294 root.unmount();
1295 });
1296 dom.window.close();
1297 }
1298
1299 {
1300 // A message queued while a turn is running remains durable. Natural
1301 // completion is dispatched by the Controller, so the frontend must only
1302 // reconcile the eventual durable ack and never call onSend itself.
1303 const dom = installDom();
1304 let backendQueued = false, backendRevision = 0;
1305 mockApp({
1306 InboxSnapshot: async () => ({
1307 revision: backendRevision,
1308 paused: false,
1309 recovered: false,
1310 items: backendQueued ? [{
1311 id: "durable-natural", intent: "followup", state: "queued", preview: "keep going after this finishes", byteSize: 30, position: 1,
1312 }] : [],
1313 itemsCount: backendQueued ? 1 : 0,
1314 bytes: backendQueued ? 30 : 0,
1315 maxItems: 64,
1316 maxBytes: 64 * 1024 * 1024,
1317 }),
1318 EnqueueInboxFollowup: async () => { backendQueued = true; backendRevision++;
1319 return { itemId: "durable-natural", disposition: "queued_followup", position: 1, paused: false }; },
1320 });
1321 const { root, calls, rerender } = await renderComposer({
1322 running: true, inboxSessionPath: "/repo/natural.jsonl",
1323 onSend: (displayText, submitText) => {
1324 calls.send.push(displayText);
1325 calls.submit.push(submitText);
1326 return Promise.resolve();
1327 },
1328 });
1329
1330 await rerender({ insertRequest: { id: 8, text: "keep going after this finishes", mode: "replace" } });
1331 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1332 if (!sendButton) throw new Error("running composer send button did not render");
1333
1334 await act(async () => {
1335 sendButton.click();
1336 await flushTimers();
1337 });
1338
1339 eq(calls.send.length, 0, "queuing while running does not send immediately");
1340 ok(document.querySelector(".composer-guidance-item") !== null, "queued message shows in the guidance shelf");
1341
1342 backendQueued = false; backendRevision++; // Controller completed and acked the next FIFO turn.
1343 await rerender({ running: false });
1344 await waitFor("durable guidance ack reconciled", () => document.querySelector(".composer-guidance-item") === null);
1345
1346 eq(calls.send.length, 0, "natural completion never triggers a duplicate frontend submit");
1347 eq(calls.submit.length, 0, "durable body remains backend-owned through dispatch");
1348
1349 await act(async () => {
1350 root.unmount();
1351 });
1352 dom.window.close();
1353 }
1354
1355 {
1356 // Stop passes only this Composer's durable IDs to the controller, then folds
1357 // their visible text back into the draft instead of leaving a hidden turn
1358 // that could run after cancellation.
1359 const dom = installDom();
1360 let cancelledItemIDs: string[] = [];
1361 let queued = false;
1362 mockApp({
1363 InboxSnapshot: async () => ({
1364 revision: queued ? 1 : 0, paused: false, recovered: false,
1365 items: queued ? [{ id: "durable-cancel", preview: "keep cancelled follow-up", state: "queued", intent: "followup", source: "desktop", byteSize: 24, position: 1 }] : [], itemsCount: queued ? 1 : 0,
1366 bytes: 0, maxItems: 64, maxBytes: 64 * 1024 * 1024,
1367 }),
1368 EnqueueInboxFollowup: async () => { queued = true; return { itemId: "durable-cancel", disposition: "queued_followup", position: 1, paused: false }; },
1369 });
1370 const { root, rerender } = await renderComposer({
1371 running: true, inboxSessionPath: "/repo/cancel.jsonl",
1372 onCancel: async (itemIDs = []) => {
1373 cancelledItemIDs = itemIDs;
1374 return { discardedItemIds: [...itemIDs] };
1375 },
1376 });
1377
1378 await rerender({ insertRequest: { id: 81, text: "keep cancelled follow-up", mode: "replace" } });
1379 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1380 if (!sendButton) throw new Error("running composer send button did not render");
1381 await act(async () => {
1382 sendButton.click();
1383 await flushTimers();
1384 });
1385
1386 const stopButton = document.querySelector(".composer__btn--stop") as HTMLButtonElement | null;
1387 if (!stopButton) throw new Error("running composer stop button did not render");
1388 await act(async () => {
1389 stopButton.click();
1390 await flushTimers();
1391 });
1392 eq(cancelledItemIDs.join(","), "durable-cancel", "stop scopes backend discard to the Composer-owned durable ID");
1393 ok(document.querySelector(".composer-guidance-item") === null, "stop clears the local shelf after handing off durable IDs");
1394 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1395 ok(textarea?.value.includes("keep cancelled follow-up") === true, "stop restores queued guidance to the editable draft");
1396
1397 await act(async () => {
1398 root.unmount();
1399 });
1400 dom.window.close();
1401 }
1402
1403 {
1404 // Controller activation state is irrelevant to browser-side dispatch now:
1405 // the durable item remains visible until an authoritative consume/ack event.
1406 const dom = installDom();
1407 let backendReadyQueued = false, backendRevision = 0;
1408 mockApp({
1409 InboxSnapshot: async () => ({
1410 revision: backendRevision,
1411 paused: false,
1412 recovered: false,
1413 items: backendReadyQueued ? [{
1414 id: "durable-ready", intent: "followup", state: "queued", preview: "keep going once ready", byteSize: 21, position: 1,
1415 }] : [],
1416 itemsCount: backendReadyQueued ? 1 : 0,
1417 bytes: backendReadyQueued ? 21 : 0,
1418 maxItems: 64,
1419 maxBytes: 64 * 1024 * 1024,
1420 }),
1421 EnqueueInboxFollowup: async () => { backendReadyQueued = true; backendRevision++;
1422 return { itemId: "durable-ready", disposition: "queued_followup", position: 1, paused: false }; },
1423 });
1424 const { root, calls, rerender } = await renderComposer({
1425 running: true, inboxSessionPath: "/repo/ready.jsonl",
1426 submitDisabled: false,
1427 onSend: (displayText, submitText) => {
1428 calls.send.push(displayText);
1429 calls.submit.push(submitText);
1430 return Promise.resolve();
1431 },
1432 });
1433
1434 await rerender({ insertRequest: { id: 9, text: "keep going once ready", mode: "replace" } });
1435 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1436 if (!sendButton) throw new Error("running composer send button did not render");
1437
1438 await act(async () => {
1439 sendButton.click();
1440 await flushTimers();
1441 });
1442 ok(document.querySelector(".composer-guidance-item") !== null, "queued message shows in the guidance shelf");
1443
1444 // Turn ends, but the controller is still not ready to accept a submit —
1445 // matches a rebuild/hydration window right after the turn finishes.
1446 await rerender({ running: false, submitDisabled: true });
1447 await act(async () => {
1448 await flushTimers();
1449 });
1450 eq(calls.send.length, 0, "auto-send does not fire while the controller is still activating");
1451 ok(document.querySelector(".composer-guidance-item") !== null, "queued message stays on the shelf while not ready");
1452
1453 await rerender({ submitDisabled: false });
1454 await act(async () => {
1455 await flushTimers();
1456 });
1457 eq(calls.send.length, 0, "controller readiness never triggers frontend auto-submit");
1458 ok(document.querySelector(".composer-guidance-item") !== null, "durable item remains until backend consume/ack");
1459
1460 backendReadyQueued = false; backendRevision++;
1461 await rerender({ guidanceConsumedKey: "durable-ready-acked", guidanceConsumedText: "keep going once ready" });
1462 ok(document.querySelector(".composer-guidance-item") === null, "backend consume event clears the acknowledged item");
1463
1464 await act(async () => {
1465 root.unmount();
1466 });
1467 dom.window.close();
1468 }
1469
1470 {
1471 const dom = installDom();
1472 let listDirCalls = 0;
1473 const listDirTabs: string[] = [];
1474 mockApp({
1475 ListDirForTarget: async (target) => {
1476 listDirTabs.push(target.tabId);
1477 listDirCalls += 1;
1478 return listDirCalls === 1 ? [fileEntry("cached-dir.txt")] : [fileEntry("fresh-dir.txt")];
1479 },
1480 SearchFileRefsForTarget: async () => [],
1481 });
1482 const { root, rerender } = await renderComposer();
1483
1484 await replaceComposerDraft(rerender, 101, "@");
1485 await waitFor("initial @ directory load", () => listDirCalls === 1);
1486
1487 await replaceComposerDraft(rerender, 102, "");
1488 await replaceComposerDraft(rerender, 103, "@");
1489 await waitFor("@ directory revalidation call", () => listDirCalls === 2);
1490
1491 eq(listDirCalls, 2, "@ directory cache hit still revalidates ListDir");
1492 ok(listDirTabs.every((tabId) => tabId === "tab-a"), "@ directory requests stay scoped to the composer tab");
1493
1494 await act(async () => {
1495 root.unmount();
1496 });
1497 dom.window.close();
1498 }
1499
1500 {
1501 const dom = installDom();
1502 let listDirCalls = 0;
1503 mockApp({
1504 ListDirForTarget: async () => {
1505 listDirCalls += 1;
1506 return listDirCalls === 1 ? [fileEntry("manual-refresh-stale.txt")] : [fileEntry("manual-refresh-fresh.txt")];
1507 },
1508 SearchFileRefsForTarget: async () => [],
1509 });
1510 const { root, rerender } = await renderComposer({ fileRefRefreshKey: "0" });
1511
1512 await replaceComposerDraft(rerender, 201, "@");
1513 await waitFor("initial @ directory load before refresh key", () => listDirCalls === 1);
1514
1515 await rerender({ fileRefRefreshKey: "1" });
1516 await waitFor("@ directory reload after refresh key", () => listDirCalls === 2);
1517
1518 eq(listDirCalls, 2, "fileRefRefreshKey refreshes @ directory cache while the menu is open");
1519
1520 await act(async () => {
1521 root.unmount();
1522 });
1523 dom.window.close();
1524 }
1525
1526 {
1527 const dom = installDom();
1528 const realDateNow = Date.now;
1529 let now = 1000;
1530 let searchCalls = 0;
1531 Date.now = () => now;
1532 mockApp({
1533 ListDirForTarget: async () => [],
1534 SearchFileRefsForTarget: async () => {
1535 searchCalls += 1;
1536 return searchCalls === 1 ? [fileEntry("alpha-old.ts")] : [fileEntry("alpha-new.ts")];
1537 },
1538 });
1539 const { root, rerender } = await renderComposer();
1540
1541 try {
1542 await replaceComposerDraft(rerender, 301, "@alpha");
1543 await waitFor("initial @ search request", () => searchCalls === 1);
1544 eq(searchCalls, 1, "@ search fetches the first query");
1545
1546 await replaceComposerDraft(rerender, 302, "");
1547 now = 2000;
1548 await replaceComposerDraft(rerender, 303, "@alpha");
1549 await act(async () => {
1550 await flushTimers();
1551 });
1552 eq(searchCalls, 1, "@ search cache is reused inside the TTL");
1553
1554 await replaceComposerDraft(rerender, 304, "");
1555 now = 7001;
1556 await replaceComposerDraft(rerender, 305, "@alpha");
1557 await waitFor("expired @ search cache refresh", () => searchCalls === 2);
1558 eq(searchCalls, 2, "@ search cache revalidates after the TTL");
1559 } finally {
1560 Date.now = realDateNow;
1561 }
1562
1563 await act(async () => {
1564 root.unmount();
1565 });
1566 dom.window.close();
1567 }
1568
1569 {
1570 const dom = installDom();
1571 let staleListDirResolve: ((entries: DirEntry[]) => void) | undefined;
1572 let thirdListDirResolve: ((entries: DirEntry[]) => void) | undefined;
1573 let listDirCalls = 0;
1574 mockApp({
1575 ListDirForTarget: async () => {
1576 listDirCalls += 1;
1577 if (listDirCalls === 1) {
1578 return new Promise<DirEntry[]>((resolve) => {
1579 staleListDirResolve = resolve;
1580 });
1581 }
1582 if (listDirCalls === 2) return [fileEntry("cache-live.txt")];
1583 return new Promise<DirEntry[]>((resolve) => {
1584 thirdListDirResolve = resolve;
1585 });
1586 },
1587 SearchFileRefsForTarget: async () => [],
1588 });
1589 const { root, rerender } = await renderComposer({ fileRefRefreshKey: "0" });
1590
1591 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1592 if (!textarea) throw new Error("composer textarea did not render");
1593
1594 await replaceComposerDraft(rerender, 401, "@cache");
1595 await waitFor("initial stale @ directory request", () => listDirCalls === 1);
1596
1597 await rerender({ fileRefRefreshKey: "1" });
1598 await waitFor("fresh @ directory request after refresh key", () => listDirCalls === 2);
1599 await act(async () => {
1600 await flushTimers();
1601 });
1602
1603 staleListDirResolve?.([fileEntry("cache-stale.txt")]);
1604 await act(async () => {
1605 await flushTimers();
1606 });
1607
1608 await replaceComposerDraft(rerender, 402, "");
1609 await replaceComposerDraft(rerender, 403, "@cache");
1610 await waitFor("second fresh @ directory request", () => listDirCalls === 3);
1611 await act(async () => {
1612 textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1613 await flushTimers();
1614 });
1615 eq(textarea.value, "@cache-live.txt ", "stale @ directory request cannot repopulate cache after refresh");
1616 thirdListDirResolve?.([fileEntry("cache-later.txt")]);
1617
1618 await act(async () => {
1619 root.unmount();
1620 });
1621 dom.window.close();
1622 }
1623
1624 {
1625 const dom = installDom();
1626 const pending: Array<(entries: DirEntry[]) => void> = [];
1627 mockApp({
1628 ListDirForTarget: async () => [],
1629 SearchFileRefsForTarget: async () => new Promise<DirEntry[]>((resolve) => pending.push(resolve)),
1630 });
1631 const { root, rerender } = await renderComposer({ workspaceScopeKey: "session-a" });
1632 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1633 if (!textarea) throw new Error("composer textarea did not render");
1634
1635 await replaceComposerDraft(rerender, 501, "@current");
1636 await waitFor("initial composer session scope request", () => pending.length === 1);
1637 await rerender({ workspaceScopeKey: "session-b" });
1638 await waitFor("next composer session scope request", () => pending.length === 2);
1639 await rerender({ workspaceScopeKey: "session-a" });
1640 await waitFor("revisited composer session scope request", () => pending.length === 3);
1641
1642 await act(async () => {
1643 pending[2]([fileEntry("current-session-a.txt")]);
1644 await flushTimers();
1645 });
1646
1647 await act(async () => {
1648 pending[0]([fileEntry("stale-initial-a.txt")]);
1649 pending[1]([fileEntry("stale-session-b.txt")]);
1650 await flushTimers();
1651 textarea.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1652 await flushTimers();
1653 });
1654
1655 eq(textarea.value, "@current-session-a.txt ", "same-tab A→B→A keeps the current composer file-ref search cache");
1656
1657 await act(async () => {
1658 root.unmount();
1659 });
1660 dom.window.close();
1661 }
1662
1663 {
1664 const dom = installDom();
1665 mockApp({
1666 Commands: async () => [
1667 { name: "writing-plans", description: "Write a plan", kind: "skill", color: "amber" },
1668 { name: "review", description: "Review the result", kind: "skill" },
1669 { name: "mcp", description: "Manage MCP servers", kind: "builtin", group: "integrations" },
1670 ],
1671 ListDirForTarget: async () => [],
1672 SearchFileRefsForTarget: async () => [],
1673 });
1674 const { root, calls, rerender } = await renderComposer();
1675
1676 const initialText = "请用/writing-plans检查";
1677 await replaceComposerDraft(rerender, 1900, initialText);
1678 let textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1679 if (!textarea) throw new Error("composer textarea did not render for middle slash completion");
1680 const slashCaret = "请用/writ".length;
1681 await act(async () => {
1682 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
1683 await flushTimers();
1684 });
1685 await act(async () => {
1686 textarea!.focus();
1687 textarea!.setSelectionRange(slashCaret, slashCaret);
1688 textarea!.dispatchEvent(new window.Event("select", { bubbles: true }));
1689 textarea!.dispatchEvent(new window.KeyboardEvent("keyup", { key: "/", bubbles: true }));
1690 await flushTimers();
1691 });
1692 await waitFor("middle slash command menu", () => Boolean(document.querySelector(".slashmenu")));
1693
1694 await act(async () => {
1695 textarea!.dispatchEvent(new window.KeyboardEvent("keydown", {
1696 key: "Enter",
1697 bubbles: true,
1698 cancelable: true,
1699 }));
1700 await flushTimers();
1701 });
1702
1703 let richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1704 let tokens = richInput?.querySelectorAll<HTMLElement>(".composer-invocation-token");
1705 if (!richInput || !tokens?.[0]) throw new Error("middle skill invocation did not render");
1706 eq(richComposerTaskText(richInput), "请用检查", "first middle skill selection preserves surrounding text");
1707 eq(
1708 document.querySelector<HTMLElement>(".invocation-display--composer")?.style.getPropertyValue("--invocation-color"),
1709 "#d59a2f",
1710 "middle skill selection keeps its configured color",
1711 );
1712
1713 const afterFirstToken = document.createRange();
1714 afterFirstToken.setStartAfter(tokens[0]);
1715 afterFirstToken.collapse(true);
1716 document.getSelection()?.removeAllRanges();
1717 document.getSelection()?.addRange(afterFirstToken);
1718 await act(async () => {
1719 dispatchPasteText(richInput!, "更多");
1720 await flushTimers();
1721 });
1722 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1723 if (!richInput) throw new Error("rich input disappeared after middle-skill paste");
1724 eq(richComposerTaskText(richInput), "请用更多检查", "paste after a middle skill preserves the entity and suffix");
1725 eq(
1726 richInput.querySelectorAll(".composer-invocation-token").length,
1727 1,
1728 "paste after a middle skill keeps the selected entity",
1729 );
1730
1731 await appendRichComposerInput(richInput, " /review");
1732 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1733 if (!richInput) throw new Error("rich input disappeared before the second skill selection");
1734 const queryAtEnd = document.createRange();
1735 queryAtEnd.selectNodeContents(richInput);
1736 queryAtEnd.collapse(false);
1737 document.getSelection()?.removeAllRanges();
1738 document.getSelection()?.addRange(queryAtEnd);
1739 await act(async () => {
1740 richInput!.dispatchEvent(new window.KeyboardEvent("keyup", { key: "w", bubbles: true }));
1741 await flushTimers();
1742 });
1743 await waitFor("second skill menu at the end", () => Boolean(document.querySelector(".slashmenu")));
1744 await act(async () => {
1745 richInput!.dispatchEvent(new window.KeyboardEvent("keydown", {
1746 key: "Enter",
1747 bubbles: true,
1748 cancelable: true,
1749 }));
1750 await flushTimers();
1751 });
1752
1753 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1754 tokens = richInput?.querySelectorAll<HTMLElement>(".composer-invocation-token");
1755 eq(tokens?.length, 2, "a second skill can be inserted after existing text and an entity");
1756 const sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1757 if (!sendButton) throw new Error("send button did not render for middle skill submission");
1758 await act(async () => {
1759 sendButton.click();
1760 await flushTimers();
1761 });
1762 eq(calls.structured[0]?.input, "请用更多检查", "middle skills submit the surrounding task text without slash tokens");
1763 eq(
1764 calls.structured[0]?.invocations.map((item) => item.name).join(","),
1765 "writing-plans,review",
1766 "multiple middle/end skills submit in visual order",
1767 );
1768 eq(calls.structured[0]?.invocations[0]?.offset, 2, "first middle skill keeps its text offset");
1769
1770 await act(async () => {
1771 root.unmount();
1772 });
1773 dom.window.close();
1774 }
1775
1776 {
1777 const dom = installDom();
1778 let commandsCalls = 0;
1779 const slashArgInputs: string[] = [];
1780 let availableCommands: CommandInfo[] = [
1781 { name: "mcp", description: "Manage MCP servers", kind: "builtin", group: "integrations" },
1782 { name: "explore", description: "Investigate the codebase", kind: "subagent" },
1783 { name: "superpowers:writing-plans", description: "Write a plan", kind: "skill", plugin: "superpowers" },
1784 { name: "toolbox:writing-plans", description: "Write another plan", kind: "skill", plugin: "toolbox" },
1785 { name: "superpowers:brainstorming", description: "Explore an idea", kind: "skill", plugin: "superpowers" },
1786 ];
1787 mockApp({
1788 Commands: async () => {
1789 commandsCalls += 1;
1790 return availableCommands;
1791 },
1792 ListDirForTarget: async () => [],
1793 SearchFileRefsForTarget: async () => [],
1794 SlashArgs: async (input) => {
1795 slashArgInputs.push(input);
1796 return input === "/mcp "
1797 ? { items: [{ label: "show", insert: "show", hint: "Show an MCP server", descend: false }], from: 5 }
1798 : { items: [], from: 0 };
1799 },
1800 });
1801 const { root, calls, rerender } = await renderComposer({ workspaceScopeKey: "runtime-0" });
1802
1803 await waitFor("plugin commands loaded", () => commandsCalls > 0);
1804 await replaceComposerDraft(rerender, 1999, "/\n");
1805 await waitFor("slash menu before trailing newline", () => Boolean(document.querySelector(".slashmenu")));
1806 ok(document.querySelector(".slashmenu") !== null, "slash menu ignores an invisible trailing newline");
1807
1808 await replaceComposerDraft(rerender, 1998, "@\n");
1809 await waitFor("file menu before trailing newline", () => Boolean(document.querySelector(".slashmenu")));
1810 ok(document.querySelector(".slashmenu") !== null, "file menu ignores an invisible trailing newline");
1811
1812 await replaceComposerDraft(rerender, 1997, "/mcp \n");
1813 await act(async () => {
1814 await flushTimers(150);
1815 });
1816 await waitFor("slash argument menu before trailing newline", () => document.querySelector(".slashmenu")?.textContent?.includes("show") === true);
1817 ok(slashArgInputs.includes("/mcp "), "slash argument completion removes an invisible trailing newline before lookup");
1818
1819 await replaceComposerDraft(rerender, 2000, "/m");
1820 await waitFor("initial skill command menu", () => Boolean(document.querySelector(".slashmenu")));
1821 ok(
1822 document.querySelector(".slashmenu")?.textContent?.includes("/my-formatter") === false,
1823 "new subagent command is absent before runtime refresh",
1824 );
1825
1826 availableCommands = [
1827 ...availableCommands,
1828 { name: "my-formatter", description: "Formats code the way I like it", kind: "subagent", color: "amber" },
1829 ];
1830 const initialCommandsCalls = commandsCalls;
1831 await rerender({ workspaceScopeKey: "runtime-1" });
1832 await waitFor("commands refreshed after runtime rebuild", () => commandsCalls > initialCommandsCalls);
1833 ok(commandsCalls > initialCommandsCalls, "runtime rebuild refetches subagent slash commands");
1834
1835 await replaceComposerDraft(rerender, 2001, "/writing-plans");
1836 await waitFor("qualified plugin skill menu", () => Boolean(document.querySelector(".slashmenu")));
1837
1838 const menuSizer = document.querySelector<HTMLElement>(".slashmenu__sizer");
1839 eq(menuSizer?.style.height, "94px", "short skill query keeps one group heading and both matching plugin names");
1840 let textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1841 if (!textarea) throw new Error("composer textarea did not render");
1842 await act(async () => {
1843 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1844 await flushTimers();
1845 });
1846 ok(document.querySelector(".composer__rich-input") !== null, "selecting a plugin skill switches to the rich task input");
1847 ok(document.querySelector(".invocation-display--composer")?.textContent?.includes("Writing Plans") === true, "selected skill renders as composer context");
1848 ok(document.querySelector(".invocation-display--composer")?.textContent?.includes("superpowers") === true, "selected plugin skill keeps its source visible");
1849 ok(document.querySelector(".composer__rich-input .composer-invocation-token") !== null, "selected skill is an inline task entity");
1850 ok(document.querySelector(".composer__rich-input .composer-invocation-caret-anchor")?.textContent === "\u00A0", "selected skill keeps a caret anchor after the inline entity");
1851
1852 const richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1853 if (!richInput) throw new Error("rich composer did not render");
1854 const richContent = document.querySelector(".composer__content") as HTMLDivElement | null;
1855 if (!richContent) throw new Error("rich composer content area did not render");
1856 richInput.blur();
1857 await act(async () => {
1858 richContent.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
1859 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
1860 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
1861 await flushTimers();
1862 });
1863 ok(document.activeElement === richInput, "clicking blank rich-composer space focuses the editable task input");
1864
1865 const invocationToken = richInput.querySelector(".composer-invocation-token");
1866 if (!invocationToken) throw new Error("rich invocation token did not render");
1867 const richRange = document.createRange();
1868 richRange.setStartAfter(invocationToken);
1869 richRange.collapse(true);
1870 document.getSelection()?.removeAllRanges();
1871 document.getSelection()?.addRange(richRange);
1872 await act(async () => {
1873 richInput.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Backspace", bubbles: true, cancelable: true }));
1874 await flushTimers();
1875 });
1876 ok(document.querySelector(".invocation-display--composer") === null, "Backspace removes a selected skill from an empty task input");
1877 await act(async () => {
1878 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
1879 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
1880 await flushTimers();
1881 });
1882 const textareaAfterEntityRemoval = document.querySelector("textarea") as HTMLTextAreaElement | null;
1883 if (!textareaAfterEntityRemoval) throw new Error("textarea did not return after removing the last entity");
1884 ok(
1885 document.activeElement === textareaAfterEntityRemoval,
1886 "removing the last entity hands focus to the textarea that replaces the rich input",
1887 );
1888 const undoEntityRemoval = new window.KeyboardEvent("keydown", {
1889 key: "z",
1890 ctrlKey: true,
1891 bubbles: true,
1892 cancelable: true,
1893 });
1894 await act(async () => {
1895 textareaAfterEntityRemoval.dispatchEvent(undoEntityRemoval);
1896 await flushTimers();
1897 });
1898 eq(undoEntityRemoval.defaultPrevented, true, "Ctrl+Z restores a token removed by the rich composer");
1899 ok(
1900 document.querySelector(".invocation-display--composer") !== null,
1901 "undoing the programmatic Backspace restores the selected skill",
1902 );
1903 const restoredRichInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1904 if (!restoredRichInput) throw new Error("rich composer did not return after undoing token removal");
1905 const redoEntityRemoval = new window.KeyboardEvent("keydown", {
1906 key: "Z",
1907 ctrlKey: true,
1908 shiftKey: true,
1909 bubbles: true,
1910 cancelable: true,
1911 });
1912 await act(async () => {
1913 restoredRichInput.dispatchEvent(redoEntityRemoval);
1914 await flushTimers();
1915 });
1916 eq(redoEntityRemoval.defaultPrevented, true, "Ctrl+Shift+Z redoes rich token removal");
1917 ok(
1918 document.querySelector(".invocation-display--composer") === null,
1919 "redoing the programmatic Backspace removes the selected skill again",
1920 );
1921
1922 await replaceComposerDraft(rerender, 2002, "/writing-plans");
1923 await waitFor("plain composer after replacing the restored skill", () => Boolean(document.querySelector("textarea")));
1924 await waitFor("skill menu after removal", () => Boolean(document.querySelector(".slashmenu")));
1925 textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1926 if (!textarea) throw new Error("composer textarea did not return after removing the skill");
1927 await act(async () => {
1928 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1929 await flushTimers();
1930 });
1931
1932 let sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1933 if (!sendButton) throw new Error("composer send button did not render for skill-only invocation");
1934 ok(sendButton.disabled === false, "inline skill-only invocation enables submit");
1935 await act(async () => {
1936 sendButton?.click();
1937 await flushTimers();
1938 });
1939 eq(calls.submit[0], "/superpowers:writing-plans", "inline skill-only submission retains display metadata");
1940 eq(calls.structured[0]?.input, "", "inline skill-only submission sends an empty explicit task");
1941 eq(calls.structured[0]?.display, "/superpowers:writing-plans", "inline skill-only submission preserves reloadable invocation display metadata");
1942 eq(calls.structured[0]?.invocations[0]?.name, "superpowers:writing-plans", "inline skill-only submission sends a structured skill entity");
1943
1944 await replaceComposerDraft(rerender, 20021, "/writing-plans");
1945 await waitFor("skill menu for task submission", () => Boolean(document.querySelector(".slashmenu")));
1946 textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1947 if (!textarea) throw new Error("composer textarea did not return after skill-only send");
1948 await act(async () => {
1949 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1950 await flushTimers();
1951 });
1952
1953 await replaceComposerDraft(rerender, 2003, "Draft the release plan");
1954 sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1955 if (!sendButton) throw new Error("composer send button did not render");
1956 await act(async () => {
1957 sendButton.click();
1958 await flushTimers();
1959 });
1960 eq(calls.send[1], "Draft the release plan", "selected skill keeps the visible transcript text clean");
1961 eq(calls.submit[1], "/superpowers:writing-plans Draft the release plan", "selected skill preserves invocation display metadata");
1962 eq(calls.structured[1]?.input, "Draft the release plan", "selected skill sends task text separately from invocation metadata");
1963 ok(document.querySelector(".invocation-display--composer") === null, "selected skill clears after send");
1964
1965 await replaceComposerDraft(rerender, 2004, "/mcp");
1966 await waitFor("builtin command menu", () => Boolean(document.querySelector(".slashmenu")));
1967 textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1968 if (!textarea) throw new Error("composer textarea did not render for management command");
1969 await act(async () => {
1970 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1971 await flushTimers();
1972 });
1973 eq(textarea.value, "/mcp ", "management commands keep the existing inline argument flow");
1974 ok(document.querySelector(".invocation-display--composer") === null, "management commands do not become selected abilities");
1975
1976 await replaceComposerDraft(rerender, 2005, "/my-formatter");
1977 await waitFor("colored subagent command menu", () => Boolean(document.querySelector(".slashmenu")));
1978 textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
1979 if (!textarea) throw new Error("composer textarea did not render for colored subagent");
1980 await act(async () => {
1981 textarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
1982 await flushTimers();
1983 });
1984 ok(document.querySelector<HTMLElement>(".invocation-display--composer")?.style.getPropertyValue("--invocation-color") === "#d59a2f", "selected custom subagent uses its configured color");
1985 sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
1986 ok(sendButton?.disabled === true, "subagent-only invocation remains blocked until a task is entered");
1987
1988 const subagentInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1989 if (!subagentInput) throw new Error("rich composer did not render for colored subagent");
1990 await appendRichComposerInput(subagentInput, "Inspect ");
1991 eq(richComposerTaskText(subagentInput), "Inspect ", "rich composer does not duplicate ordinary browser input");
1992 await appendRichComposerInput(subagentInput, "仓库做了什么?", true);
1993 eq(richComposerTaskText(subagentInput), "Inspect 仓库做了什么?", "rich composer does not duplicate committed IME input");
1994
1995 await replaceComposerDraft(rerender, 2006, "");
1996 const resetSubagentInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
1997 if (!resetSubagentInput) throw new Error("rich composer disappeared after external text replacement");
1998 eq(richComposerTaskText(resetSubagentInput), "", "external replacement can restore the initially rendered rich-composer text");
1999 await appendRichComposerInput(resetSubagentInput, "Inspect ");
2000 await appendRichComposerInput(resetSubagentInput, "仓库做了什么?", true);
2001
2002 sendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
2003 if (!sendButton) throw new Error("composer send button did not render after subagent task input");
2004 await act(async () => {
2005 sendButton.click();
2006 await flushTimers();
2007 });
2008 eq(calls.send[2], "Inspect 仓库做了什么?", "subagent task is sent exactly once after rich input");
2009 eq(calls.structured[2]?.input, "Inspect 仓库做了什么?", "structured subagent input contains one task copy");
2010
2011 await act(async () => {
2012 root.unmount();
2013 });
2014 dom.window.close();
2015 }
2016
2017 {
2018 const dom = installDom();
2019 const rootEl = document.getElementById("root");
2020 if (!rootEl) throw new Error("missing root");
2021 const root = createRoot(rootEl);
2022 await act(async () => {
2023 root.render(
2024 <LocaleProvider>
2025 <UserMessage
2026 id="h1"
2027 text="Draft the release plan"
2028 submitText="/superpowers:writing-plans Draft the release plan"
2029 />
2030 </LocaleProvider>,
2031 );
2032 await flushTimers();
2033 });
2034 ok(document.querySelector(".invocation-display--message")?.textContent?.includes("Writing Plans") === true, "restored history renders the selected skill header");
2035 ok(document.querySelector(".invocation-display--message")?.textContent?.includes("superpowers") === true, "restored history retains plugin source from the qualified command");
2036 ok(document.querySelector(".msg__rich-text")?.textContent?.endsWith("Draft the release plan") === true, "history message keeps slash syntax out of the task body");
2037
2038 await act(async () => {
2039 root.render(
2040 <LocaleProvider>
2041 <InvocationMetadataContext.Provider value={{ "my-formatter": { kind: "subagent", color: "amber" } }}>
2042 <UserMessage
2043 id="h2"
2044 text="Format this file"
2045 submitText={"以下是用户引用的历史会话上下文:\n\n[会话:Earlier]\n...\n\n---\n\n当前用户问题:\n/my-formatter Format this file"}
2046 />
2047 </InvocationMetadataContext.Provider>
2048 </LocaleProvider>,
2049 );
2050 await flushTimers();
2051 });
2052 ok(document.querySelector(".invocation-display--message")?.textContent?.includes("My Formatter") === true, "history and trash previews recover selected abilities after referenced-session context");
2053 ok(document.querySelector(".invocation-display--subagent") !== null, "restored custom subagents keep their command type styling");
2054 ok(document.querySelector<HTMLElement>(".invocation-display--subagent")?.style.getPropertyValue("--invocation-color") === "#d59a2f", "restored custom subagents keep their configured color");
2055
2056 await act(async () => {
2057 root.render(
2058 <LocaleProvider>
2059 <UserMessage
2060 id="h3"
2061 text={"Compare these commands\n/other-command"}
2062 submitText={"/reasonix-develop Compare these commands\n/other-command"}
2063 />
2064 </LocaleProvider>,
2065 );
2066 await flushTimers();
2067 });
2068 ok(document.querySelector(".invocation-display--message")?.textContent?.includes("Reasonix Develop") === true, "history recovery ignores slash-prefixed lines inside the task body");
2069
2070 await act(async () => {
2071 root.render(
2072 <LocaleProvider>
2073 <UserMessage
2074 id="h4"
2075 text={"Compare these commands\n/other-command"}
2076 submitText={"以下是用户引用的历史会话上下文:\n\n[会话:Earlier]\n...\n\n---\n\n当前用户问题:\nCompare these commands\n/other-command"}
2077 />
2078 </LocaleProvider>,
2079 );
2080 await flushTimers();
2081 });
2082 ok(document.querySelector(".invocation-display--message") === null, "ordinary referenced-session text does not turn task slash lines into a skill header");
2083
2084 await act(async () => root.unmount());
2085 dom.window.close();
2086 }
2087
2088 {
2089 const dom = installDom();
2090 let savedFiles = 0;
2091 const restoreUpload = mockFileUpload(async () => {
2092 savedFiles += 1;
2093 return ".reasonix/attachments/notes.txt";
2094 });
2095 mockApp({
2096 Commands: async () => [{ name: "skill", description: "Manage skills", kind: "builtin" }],
2097 ListDirForTarget: async () => [fileEntry("README.md")],
2098 SearchFileRefsForTarget: async () => [],
2099 ListSessions: async () => [{ path: "/sessions/recent.jsonl", title: "Recent session", current: false }],
2100 }, { getPathForFile: () => "" });
2101 const { root, rerender } = await renderComposer();
2102 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
2103 if (!textarea) throw new Error("composer textarea did not render");
2104
2105 await replaceComposerDraft(rerender, 3000, "Follow up #recent\n");
2106 await waitFor("typed hash recent-session picker", () => Boolean(document.querySelector(".slashmenu__search")));
2107 const typedSessionSearch = document.querySelector(".slashmenu__search") as HTMLInputElement | null;
2108 eq(typedSessionSearch?.value, "recent", "typing # opens recent sessions and carries the query across an invisible trailing newline");
2109 ok(document.activeElement !== typedSessionSearch, "the typed # flow leaves focus in the composer instead of the panel search box");
2110 await act(async () => {
2111 typedSessionSearch?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
2112 await flushTimers();
2113 });
2114 eq(textarea.value, "Follow up #recent\n", "Escape closes the typed recent-session picker and keeps the literal # text");
2115 ok(!document.querySelector(".slashmenu__search"), "Escape dismisses the typed recent-session panel until the query changes");
2116
2117 await replaceComposerDraft(rerender, 3005, "issue#6310");
2118 await act(async () => {
2119 await flushTimers();
2120 });
2121 ok(!document.querySelector(".slashmenu__search"), "an embedded hash remains ordinary composer text");
2122
2123 await replaceComposerDraft(rerender, 3006, "#\n");
2124 await waitFor("typed hash picker before session selection", () => Boolean(document.querySelector(".slashmenu__search")));
2125 const typedSessionButton = Array.from(document.querySelectorAll<HTMLButtonElement>(".slashmenu button"))
2126 .find((button) => button.textContent?.includes("Recent session"));
2127 if (!typedSessionButton) throw new Error("typed recent-session option did not render");
2128 await act(async () => {
2129 typedSessionButton.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
2130 await flushTimers();
2131 });
2132 eq(textarea.value, "", "selecting a typed recent-session reference removes the # token");
2133 ok(document.querySelector(".composer-context__item--session")?.textContent?.includes("Recent session") === true, "selecting a typed recent-session reference adds its context card");
2134 const removeTypedSession = document.querySelector<HTMLButtonElement>(".composer-context__item--session button");
2135 await act(async () => {
2136 removeTypedSession?.click();
2137 await flushTimers();
2138 });
2139
2140 const contentTrigger = document.querySelector(".composer-content-trigger") as HTMLButtonElement | null;
2141 if (!contentTrigger) throw new Error("content menu trigger did not render");
2142 await act(async () => {
2143 contentTrigger.click();
2144 await flushTimers();
2145 });
2146 ok(Boolean(document.querySelector(".composer-content-menu")), "plus trigger opens the add-content menu");
2147 const initialContentItems = Array.from(document.querySelectorAll<HTMLButtonElement>(".composer-content-menu__item"));
2148 eq(initialContentItems.length, 4, "add-content menu exposes four focused actions");
2149 const contentItemIcons = initialContentItems.map((item) => item.querySelector("svg")?.getAttribute("class") ?? "");
2150 ok(contentItemIcons[0]?.includes("lucide-file-plus"), "attachment action uses the file attachment icon");
2151 ok(contentItemIcons[1]?.includes("lucide-at-sign"), "workspace action uses the mention icon");
2152 ok(contentItemIcons[2]?.includes("lucide-hash"), "recent-session action uses the history reference icon");
2153 eq(initialContentItems[3]?.querySelector(".composer-content-menu__trigger-icon")?.textContent, "/", "command action uses the literal slash trigger icon");
2154 ok(!document.querySelector(".composer-content-menu__divider"), "add-content actions remain one unified group without a divider");
2155 ok(initialContentItems.every((item) => !item.querySelector("kbd")), "add-content actions do not duplicate their trigger icons on the right");
2156
2157 const attachmentButton = initialContentItems[0];
2158 const fileInput = document.querySelector(".composer-content-file-input") as HTMLInputElement | null;
2159 if (!attachmentButton || !fileInput) throw new Error("attachment picker controls did not render");
2160 await act(async () => {
2161 attachmentButton.click();
2162 Object.defineProperty(fileInput, "files", { configurable: true, value: [new File(["notes"], "notes.txt", { type: "text/plain" })] });
2163 fileInput.dispatchEvent(new Event("change", { bubbles: true }));
2164 await flushTimers();
2165 });
2166 await waitFor("attachment chosen from add-content menu", () => savedFiles === 1);
2167 eq(savedFiles, 1, "attachment action streams the chosen File exactly once");
2168
2169 await replaceComposerDraft(rerender, 3001, "@");
2170 await waitFor("workspace menu before plus toggle", () => Boolean(document.querySelector(".slashmenu")));
2171 await act(async () => {
2172 contentTrigger.click();
2173 await flushTimers();
2174 });
2175 ok(!document.querySelector(".slashmenu"), "opening add-content closes the active suggestion panel");
2176 ok(Boolean(document.querySelector(".composer-content-menu")), "add-content remains the only open composer surface");
2177
2178 const sessionButton = document.querySelectorAll<HTMLButtonElement>(".composer-content-menu__item")[2];
2179 if (!sessionButton) throw new Error("recent-session action did not render");
2180 await act(async () => {
2181 sessionButton.click();
2182 await flushTimers();
2183 });
2184 await waitFor("direct recent-session picker", () => Boolean(document.querySelector(".slashmenu__search")));
2185 eq(textarea.value, "@ #", "recent-session action inserts # at the remembered caret");
2186 ok(!document.querySelector(".composer-content-menu"), "recent-session picker replaces the add-content menu");
2187 const sessionSearch = document.querySelector(".slashmenu__search") as HTMLInputElement | null;
2188 if (!sessionSearch) throw new Error("recent-session search did not render");
2189 await act(async () => {
2190 sessionSearch.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
2191 await flushTimers();
2192 });
2193 eq(textarea.value, "@ #", "Escape closes the direct recent-session picker and keeps the inserted # trigger");
2194
2195 await replaceComposerDraft(rerender, 3002, "");
2196 await act(async () => {
2197 contentTrigger.click();
2198 await flushTimers();
2199 });
2200 const commandButton = document.querySelectorAll<HTMLButtonElement>(".composer-content-menu__item")[3];
2201 if (!commandButton) throw new Error("command action did not render");
2202 await act(async () => {
2203 commandButton.click();
2204 await flushTimers();
2205 });
2206 eq(textarea.value, "/", "command action inserts / at the caret");
2207 await waitFor("slash menu from add-content action", () => Boolean(document.querySelector(".slashmenu")));
2208
2209 await replaceComposerDraft(rerender, 3003, "existing text");
2210 await act(async () => {
2211 contentTrigger.click();
2212 await flushTimers();
2213 });
2214 const disabledCommandButton = document.querySelectorAll<HTMLButtonElement>(".composer-content-menu__item")[3];
2215 if (!disabledCommandButton) throw new Error("command action did not render for non-empty input");
2216 ok(disabledCommandButton.disabled, "command action is disabled while the composer has text");
2217 await act(async () => {
2218 disabledCommandButton.click();
2219 await flushTimers();
2220 });
2221 eq(textarea.value, "existing text", "disabled command action does not insert / into existing text");
2222
2223 await rerender({ running: true });
2224 await waitFor("content menu closes when a run starts", () => !document.querySelector(".composer-content-menu"));
2225 await rerender({ running: false });
2226 ok(!document.querySelector(".composer-content-menu"), "content menu stays closed after the run ends");
2227
2228 await replaceComposerDraft(rerender, 3004, "");
2229 await act(async () => {
2230 contentTrigger.click();
2231 await flushTimers();
2232 });
2233 const runningSessionButton = document.querySelectorAll<HTMLButtonElement>(".composer-content-menu__item")[2];
2234 if (!runningSessionButton) throw new Error("recent-session action did not render before running");
2235 await act(async () => {
2236 runningSessionButton.click();
2237 await flushTimers();
2238 });
2239 await waitFor("recent-session picker before running", () => Boolean(document.querySelector(".slashmenu__search")));
2240 await rerender({ running: true });
2241 await waitFor("recent-session picker closes when a run starts", () => !document.querySelector(".slashmenu__search"));
2242 await rerender({ running: false });
2243 ok(!document.querySelector(".slashmenu__search"), "recent-session picker stays closed after the run ends");
2244
2245 await act(async () => {
2246 root.unmount();
2247 });
2248 dom.window.close();
2249 restoreUpload();
2250 }
2251
2252 {
2253 // Entity-only input must remain structured while queued during a run.
2254 const dom = installDom();
2255 let queued: { submit?: string; invocations?: StructuredInvocationSubmit["invocations"] } = {};
2256 let queuedDisplay = "";
2257 mockApp({
2258 Commands: async () => [
2259 { name: "superpowers:writing-plans", description: "Write a plan", kind: "skill", plugin: "superpowers" },
2260 ],
2261 ListDirForTarget: async () => [],
2262 SearchFileRefsForTarget: async () => [],
2263 InboxSnapshot: async () => ({
2264 revision: queuedDisplay ? 1 : 0, paused: false, recovered: false,
2265 items: queuedDisplay ? [{ id: "durable-entity", preview: queuedDisplay, state: "queued", intent: "followup", source: "desktop", byteSize: queuedDisplay.length, position: 1 }] : [], itemsCount: queuedDisplay ? 1 : 0,
2266 bytes: 0, maxItems: 64, maxBytes: 64 * 1024 * 1024,
2267 }),
2268 EnqueueInboxFollowupWithInvocations: async (_tabId, display, input, invocations) => {
2269 queued = { submit: input, invocations };
2270 queuedDisplay = display;
2271 return { itemId: "durable-entity", disposition: "queued_followup", position: 1, paused: false };
2272 },
2273 });
2274 const { root, calls, rerender } = await renderComposer({ inboxSessionPath: "/repo/entity.jsonl" });
2275 await replaceComposerDraft(rerender, 4000, "/writing-plans");
2276 await waitFor("skill menu for the running-queue entity", () => Boolean(document.querySelector(".slashmenu")));
2277 const queueTextarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
2278 if (!queueTextarea) throw new Error("composer textarea did not render");
2279 await act(async () => {
2280 queueTextarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
2281 await flushTimers();
2282 });
2283 const queueRichInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
2284 if (!queueRichInput) throw new Error("rich composer did not render for the running-queue entity");
2285 await rerender({ running: true });
2286 await act(async () => {
2287 queueRichInput.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
2288 await flushTimers();
2289 });
2290 eq(calls.send.length, 0, "an entity-only submit while running queues instead of sending");
2291 ok(
2292 document.querySelector(".composer-guidance-item__text")?.textContent?.includes("/superpowers:writing-plans") === true,
2293 "the queued guidance shows the entity's slash form instead of dropping it silently",
2294 );
2295 eq(`${queued.invocations?.[0]?.name}:${queued.invocations?.[0]?.kind}`, "superpowers:writing-plans:skill", "queued guidance preserves the selected skill invocation");
2296 eq(queued.submit, "", "entity-only guidance keeps an empty explicit task instead of degrading to slash text");
2297 ok(document.querySelector(".composer__rich-input") === null, "queueing an entity-only submit clears the draft");
2298 await act(async () => {
2299 root.unmount();
2300 });
2301 dom.window.close();
2302 }
2303
2304 {
2305 // While an IME is composing, the rich input must neither resync the model
2306 // nor restore the DOM selection (removeAllRanges cancels or commits an
2307 // in-progress composition); compositionend performs the one authoritative
2308 // sync.
2309 const dom = installDom();
2310 mockApp({
2311 Commands: async () => [
2312 { name: "superpowers:writing-plans", description: "Write a plan", kind: "skill", plugin: "superpowers" },
2313 ],
2314 ListDirForTarget: async () => [],
2315 SearchFileRefsForTarget: async () => [],
2316 });
2317 const { root, calls, rerender } = await renderComposer();
2318 await replaceComposerDraft(rerender, 4100, "/writing-plans");
2319 await waitFor("skill menu for the composition guard", () => Boolean(document.querySelector(".slashmenu")));
2320 const compositionTextarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
2321 if (!compositionTextarea) throw new Error("composer textarea did not render");
2322 await act(async () => {
2323 compositionTextarea.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
2324 await flushTimers();
2325 });
2326 const compositionRichInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
2327 if (!compositionRichInput) throw new Error("rich composer did not render for the composition guard");
2328
2329 // Drain the entity-pick flow's pending animation frames (imperative caret
2330 // restore) so the spy below counts only composition-window work.
2331 await act(async () => {
2332 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
2333 await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
2334 await flushTimers();
2335 });
2336 const domSelection = document.getSelection();
2337 if (!domSelection) throw new Error("document selection unavailable");
2338 let selectionStomps = 0;
2339 const originalRemoveAllRanges = domSelection.removeAllRanges.bind(domSelection);
2340 (domSelection as { removeAllRanges: () => void }).removeAllRanges = () => {
2341 selectionStomps += 1;
2342 originalRemoveAllRanges();
2343 };
2344 await act(async () => {
2345 compositionRichInput.dispatchEvent(new window.Event("compositionstart", { bubbles: true }));
2346 compositionRichInput.appendChild(document.createTextNode("拼"));
2347 compositionRichInput.dispatchEvent(new window.Event("input", { bubbles: true }));
2348 await flushTimers();
2349 });
2350 eq(selectionStomps, 0, "composition input neither resyncs the model nor restores the selection");
2351 await act(async () => {
2352 compositionRichInput.dispatchEvent(new window.Event("compositionend", { bubbles: true }));
2353 await flushTimers();
2354 });
2355 (domSelection as { removeAllRanges: () => void }).removeAllRanges = originalRemoveAllRanges;
2356
2357 const compositionSendButton = document.querySelector(".composer__btn--send") as HTMLButtonElement | null;
2358 if (!compositionSendButton) throw new Error("send button did not render after composition");
2359 await act(async () => {
2360 compositionSendButton.click();
2361 await flushTimers();
2362 });
2363 eq(calls.structured[0]?.input, "拼", "compositionend commits the composed text to the model exactly once");
2364
2365 await act(async () => {
2366 root.unmount();
2367 });
2368 dom.window.close();
2369 }
2370
2371 {
2372 const dom = installDom();
2373 mockApp({
2374 Commands: async () => [
2375 { name: "review", description: "Review the current task", kind: "skill" },
2376 ],
2377 ListDirForTarget: async () => [],
2378 SearchFileRefsForTarget: async () => [],
2379 });
2380 const sessionA = "session:project:/repo:topic-a:session-a";
2381 const sessionB = "session:project:/repo:topic-b:session-b";
2382 const { root, rerender } = await renderComposer({ sessionKey: sessionA });
2383
2384 await replaceComposerDraft(rerender, 5000, "x/review");
2385 await waitFor("session A slash menu", () => Boolean(document.querySelector(".slashmenu")));
2386
2387 await rerender({ sessionKey: sessionB, insertRequest: null });
2388 await replaceComposerDraft(rerender, 5001, "b");
2389 const sessionBInput = document.querySelector("textarea") as HTMLTextAreaElement | null;
2390 if (!sessionBInput) throw new Error("session B textarea did not render");
2391 await act(async () => {
2392 sessionBInput.focus();
2393 sessionBInput.setSelectionRange(1, 1);
2394 sessionBInput.dispatchEvent(new window.KeyboardEvent("keyup", { key: "b", bubbles: true }));
2395 await flushTimers();
2396 });
2397
2398 await rerender({ sessionKey: sessionA, insertRequest: null });
2399 eq(
2400 (document.querySelector("textarea") as HTMLTextAreaElement | null)?.value,
2401 "x/review",
2402 "switching back restores session A slash draft",
2403 );
2404 await waitFor(
2405 "restored session A slash menu",
2406 () => Boolean(document.querySelector(".slashmenu")),
2407 );
2408 ok(
2409 document.querySelector(".slashmenu") !== null,
2410 "restoring a draft recomputes slash completion from its end caret",
2411 );
2412
2413 await act(async () => {
2414 root.unmount();
2415 });
2416 dom.window.close();
2417 }
2418
2419 {
2420 const dom = installDom();
2421 mockApp({
2422 Commands: async () => [
2423 { name: "review", description: "Review the current task", kind: "skill" },
2424 ],
2425 ListDirForTarget: async () => [],
2426 SearchFileRefsForTarget: async () => [],
2427 });
2428 const sessionA = "session:project:/repo:rich-topic-a:rich-session-a";
2429 const sessionB = "session:project:/repo:rich-topic-b:rich-session-b";
2430 const realRequestAnimationFrame = globalThis.requestAnimationFrame;
2431 const queuedComposerFrames: FrameRequestCallback[] = [];
2432 globalThis.requestAnimationFrame = (callback) => {
2433 queuedComposerFrames.push(callback);
2434 return queuedComposerFrames.length;
2435 };
2436 const { root, rerender } = await renderComposer({ sessionKey: sessionA });
2437
2438 await replaceComposerDraft(rerender, 6000, "/review");
2439 await waitFor("session A first skill menu", () => Boolean(document.querySelector(".slashmenu")));
2440 const textarea = document.querySelector("textarea") as HTMLTextAreaElement | null;
2441 if (!textarea) throw new Error("session A textarea did not render");
2442 await act(async () => {
2443 textarea.dispatchEvent(new window.KeyboardEvent("keydown", {
2444 key: "Enter",
2445 bubbles: true,
2446 cancelable: true,
2447 }));
2448 await flushTimers();
2449 });
2450
2451 let richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
2452 if (!richInput) throw new Error("session A rich input did not render");
2453 await appendRichComposerInput(richInput, " /review");
2454 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
2455 if (!richInput) throw new Error("session A rich input disappeared");
2456 const queryAtEnd = document.createRange();
2457 queryAtEnd.selectNodeContents(richInput);
2458 queryAtEnd.collapse(false);
2459 document.getSelection()?.removeAllRanges();
2460 document.getSelection()?.addRange(queryAtEnd);
2461 await act(async () => {
2462 richInput.dispatchEvent(new window.KeyboardEvent("keyup", { key: "w", bubbles: true }));
2463 await flushTimers();
2464 });
2465 await waitFor("session A second skill menu", () => Boolean(document.querySelector(".slashmenu")));
2466
2467 await rerender({ sessionKey: sessionB, insertRequest: null });
2468 await replaceComposerDraft(rerender, 6001, "b");
2469 await rerender({ sessionKey: sessionA, insertRequest: null });
2470 await act(async () => {
2471 let frameTime = 0;
2472 while (queuedComposerFrames.length > 0) {
2473 queuedComposerFrames.shift()?.(frameTime += 16);
2474 }
2475 await flushTimers();
2476 });
2477 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
2478 if (!richInput) throw new Error("session A rich input was not restored");
2479 eq(richComposerTaskText(richInput), " /review", "switching back restores the rich invocation draft");
2480 await waitFor(
2481 "restored session A rich slash menu",
2482 () => Boolean(document.querySelector(".slashmenu")),
2483 );
2484 ok(
2485 document.querySelector(".slashmenu") !== null,
2486 "restoring a rich invocation draft recomputes slash completion from its end caret",
2487 );
2488
2489 await act(async () => {
2490 richInput.dispatchEvent(new window.KeyboardEvent("keydown", {
2491 key: "Enter",
2492 bubbles: true,
2493 cancelable: true,
2494 }));
2495 await flushTimers();
2496 });
2497 richInput = document.querySelector(".composer__rich-input") as HTMLDivElement | null;
2498 eq(
2499 richInput?.querySelectorAll(".composer-invocation-token").length,
2500 2,
2501 "the restored rich slash query can select a second skill",
2502 );
2503 eq(richInput ? richComposerTaskText(richInput) : "", " ", "selecting the restored query replaces its slash token");
2504
2505 await rerender({ sessionKey: sessionB, insertRequest: null });
2506 eq(
2507 (document.querySelector("textarea") as HTMLTextAreaElement | null)?.value,
2508 "b",
2509 "switching away again preserves the other session draft",
2510 );
2511
2512 await act(async () => {
2513 root.unmount();
2514 });
2515 globalThis.requestAnimationFrame = realRequestAnimationFrame;
2516 dom.window.close();
2517 }
2518
2519 console.log(`\n${passed} passed, ${failed} failed, ${passed + failed} total`);
2520 if (failed > 0) process.exit(1);
2521
2521 lines Plain Text