Open History to see the last commit
1import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
2import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
3import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
4import {
5 collectAssistantCitations,
6 expandAssistantCitationsForProvider,
7 serializeAssistantCitation,
8} from "@t3tools/shared/assistantCitations";
9import {
10 DEFAULT_RESOLVED_KEYBINDINGS,
11 compileResolvedKeybindingsConfig,
12 mergeWithDefaultKeybindings,
13} from "@t3tools/shared/keybindings";
14import { describe, expect, it } from "vite-plus/test";
15
16import {
17 clampCollapsedComposerCursor,
18 collapseExpandedComposerCursor,
19 composerSubmissionIntentForKey,
20 composerStateAtPromptEnd,
21 detectComposerTrigger,
22 expandCollapsedComposerCursor,
23 formatAssistantCitationForComposer,
24 isCollapsedCursorAdjacentToInlineToken,
25 isPathSuggestionCurrent,
26 parseStandaloneComposerSlashCommand,
27 replaceTextRange,
28} from "./composer-logic";
29import { carryDisplacedCustomAnswerIntoPrompt } from "./pendingUserInput";
30import { formatTerminalContextReference } from "./lib/terminalContext";
31
32const terminalReference = formatTerminalContextReference({
33 id: "ctx-1",
34 terminalLabel: "Terminal 1",
35 lineStart: 3,
36 lineEnd: 4,
37});
38
39const citation: AssistantCitation = {
40 version: 1,
41 environmentId: EnvironmentId.make("environment-1"),
42 threadId: ThreadId.make("thread-1"),
43 messageId: MessageId.make("message-1"),
44 text: "Keep Unicode 👋 and punctuation (here).",
45 start: 3,
46 end: 40,
47 prefix: "前: ",
48 suffix: " 後",
49};
50const citationSource = serializeAssistantCitation(citation).replaceAll("+", "%20");
51
52describe("isPathSuggestionCurrent", () => {
53 const searchedTarget = {
54 environmentId: EnvironmentId.make("local"),
55 cwd: "/repo",
56 query: "alpha",
57 };
58
59 it("allows a file suggestion matching the live search", () => {
60 expect(
61 isPathSuggestionCurrent(
62 searchedTarget,
63 detectComposerTrigger("@alpha", 6),
64 searchedTarget.environmentId,
65 searchedTarget.cwd,
66 ),
67 ).toBe(true);
68 });
69
70 it.each([
71 ["query", { ...searchedTarget, query: "beta" }],
72 ["cwd", { ...searchedTarget, cwd: "/other-repo" }],
73 ["environment", { ...searchedTarget, environmentId: EnvironmentId.make("remote") }],
74 ] as const)("rejects a visible file suggestion after the live %s changes", (_change, current) => {
75 const prompt = `@${current.query}`;
76 expect(
77 isPathSuggestionCurrent(
78 searchedTarget,
79 detectComposerTrigger(prompt, prompt.length),
80 current.environmentId,
81 current.cwd,
82 ),
83 ).toBe(false);
84 });
85});
86
87describe("formatAssistantCitationForComposer", () => {
88 it.each([undefined, "", " \n\t "])(
89 "keeps citation-only insertion for a blank comment %j",
90 (comment) => {
91 expect(formatAssistantCitationForComposer(citation, comment)).toBe(
92 `${serializeAssistantCitation(citation)} `,
93 );
94 },
95 );
96
97 it("binds a multiline comment to its citation without adding standalone prompt text", () => {
98 const comment = 'What does "keep" mean? 👋\n Please show an example.';
99 const text = formatAssistantCitationForComposer(citation, ` ${comment}\n`);
100 const boundCitation = { ...citation, comment };
101 expect(text).toBe(`${serializeAssistantCitation(boundCitation)} `);
102 expect(collectAssistantCitations(text).map((entry) => entry.citation)).toEqual([boundCitation]);
103 expect(expandAssistantCitationsForProvider(text)).toMatch(/^\[assistant-quote-1\] \n\n/);
104 });
105});
106
107describe("composerSubmissionIntentForKey", () => {
108 const input = {
109 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
110 platform: "Linux",
111 isSoftwareKeyboardOpen: false,
112 isDraftThread: false,
113 };
114 const enter = { key: "Enter", metaKey: false, ctrlKey: false, altKey: false, shiftKey: false };
115
116 it.each([
117 ["enter", "one line", false, "foreground"],
118 ["enter", "two\nlines", false, "foreground"],
119 ["mod-enter-multiline", "one line", false, "foreground"],
120 ["mod-enter-multiline", "two\nlines", false, null],
121 ["mod-enter-multiline", "two\nlines", true, "foreground"],
122 ["mod-enter", "one line", false, null],
123 ["mod-enter", "one line", true, "foreground"],
124 ] as const)("honors %s for %j", (sendShortcut, prompt, ctrlKey, expected) => {
125 expect(
126 composerSubmissionIntentForKey({
127 ...input,
128 event: { ...enter, ctrlKey },
129 sendShortcut,
130 prompt,
131 }),
132 ).toBe(expected);
133 });
134
135 it.each(["MacIntel", "Win32", "Linux"])("uses the configured actions on %s", (platform) => {
136 const modEnter = {
137 ...enter,
138 metaKey: platform === "MacIntel",
139 ctrlKey: platform !== "MacIntel",
140 };
141 for (const [sendShortcut, prompt, requiresModifier] of [
142 ["enter", "one line", false],
143 ["enter", "two\nlines", false],
144 ["mod-enter", "one line", true],
145 ["mod-enter", "two\nlines", true],
146 ["mod-enter-multiline", "one line", false],
147 ["mod-enter-multiline", "two\nlines", true],
148 ] as const) {
149 const running = { ...input, platform, sendShortcut, prompt, isRunning: true };
150 const intent = composerSubmissionIntentForKey({ ...running, event: modEnter });
151 expect(intent).toBe(requiresModifier ? "foreground" : "alternate");
152 const alternateIntent = composerSubmissionIntentForKey({
153 ...running,
154 event: { ...modEnter, shiftKey: requiresModifier },
155 });
156 expect(alternateIntent).toBe("alternate");
157 expect(composerSubmissionIntentForKey({ ...running, event: enter })).toBe(
158 requiresModifier ? null : "foreground",
159 );
160 for (const activeTurnDefault of ["queue", "steer"] as const) {
161 expect(
162 resolveComposerDispatchMode({
163 running: true,
164 alternateModifier: intent === "alternate",
165 activeTurnDefault,
166 }),
167 ).toBe(
168 requiresModifier ? activeTurnDefault : activeTurnDefault === "queue" ? "steer" : "queue",
169 );
170 expect(
171 resolveComposerDispatchMode({
172 running: true,
173 alternateModifier: alternateIntent === "alternate",
174 activeTurnDefault,
175 }),
176 ).toBe(activeTurnDefault === "queue" ? "steer" : "queue");
177 }
178 expect(
179 composerSubmissionIntentForKey({
180 ...input,
181 platform,
182 sendShortcut,
183 isDraftThread: true,
184 event: { ...modEnter, altKey: true },
185 }),
186 ).toBe("background");
187 expect(
188 composerSubmissionIntentForKey({
189 ...input,
190 platform,
191 sendShortcut,
192 event: { ...modEnter, altKey: true },
193 }),
194 ).toBe("background");
195 expect(
196 composerSubmissionIntentForKey({
197 ...input,
198 platform,
199 sendShortcut,
200 prompt,
201 isDraftThread: true,
202 event: modEnter,
203 }),
204 ).toBe("background");
205 expect(
206 composerSubmissionIntentForKey({ ...running, event: { ...enter, shiftKey: true } }),
207 ).toBeNull();
208 }
209 });
210
211 it("leaves queued-message steering on Mod+Shift+Enter outside a draft", () => {
212 expect(
213 composerSubmissionIntentForKey({
214 ...input,
215 isRunning: true,
216 event: { ...enter, ctrlKey: true, shiftKey: true },
217 }),
218 ).toBeNull();
219 });
220
221 it("honors the send preference with an existing install's saved alternate binding", () => {
222 const keybindings = mergeWithDefaultKeybindings(
223 compileResolvedKeybindingsConfig([
224 {
225 key: "mod+enter",
226 command: "composer.sendAlternate",
227 when: "composerFocus && turnRunning",
228 },
229 ]),
230 );
231 const running = { ...input, keybindings, isRunning: true, sendShortcut: "mod-enter" as const };
232 expect(composerSubmissionIntentForKey({ ...running, event: { ...enter, ctrlKey: true } })).toBe(
233 "foreground",
234 );
235 expect(
236 composerSubmissionIntentForKey({
237 ...running,
238 event: { ...enter, ctrlKey: true, shiftKey: true },
239 }),
240 ).toBe("alternate");
241 });
242
243 it("does not start a background thread with the queued-message shortcut", () => {
244 expect(
245 composerSubmissionIntentForKey({
246 ...input,
247 isDraftThread: true,
248 event: { ...enter, ctrlKey: true, shiftKey: true },
249 }),
250 ).toBeNull();
251 });
252
253 it.each([
254 ["mod+arrowup", { key: "ArrowUp", ctrlKey: true }],
255 ["shift+tab", { key: "Tab", shiftKey: true }],
256 ] as const)("accepts a remapped %s action", (key, event) => {
257 const keybindings = mergeWithDefaultKeybindings(
258 compileResolvedKeybindingsConfig([
259 { key, command: "composer.sendBackground", when: "composerFocus && draftThreadRoute" },
260 ]),
261 );
262 expect(
263 composerSubmissionIntentForKey({
264 ...input,
265 keybindings,
266 isDraftThread: true,
267 event: { ...enter, ...event },
268 }),
269 ).toBe("background");
270 });
271
272 it.each(["enter", "mod-enter", "mod-enter-multiline"] as const)(
273 "uses remapped keys and removes the old action bindings with %s",
274 (sendShortcut) => {
275 const keybindings = mergeWithDefaultKeybindings(
276 compileResolvedKeybindingsConfig([
277 {
278 key: "alt+q",
279 command: "composer.sendAlternate",
280 when: "composerFocus && turnRunning",
281 },
282 {
283 key: "alt+b",
284 command: "composer.sendBackground",
285 when: "composerFocus && draftThreadRoute",
286 },
287 ]),
288 );
289 const custom = { ...input, keybindings, sendShortcut, prompt: "two\nlines" };
290 expect(
291 composerSubmissionIntentForKey({
292 ...custom,
293 isRunning: true,
294 event: { ...enter, key: "q", altKey: true },
295 }),
296 ).toBe("alternate");
297 expect(
298 composerSubmissionIntentForKey({
299 ...custom,
300 isDraftThread: true,
301 event: { ...enter, key: "b", altKey: true },
302 }),
303 ).toBe("background");
304 expect(
305 composerSubmissionIntentForKey({
306 ...custom,
307 isRunning: true,
308 event: { ...enter, ctrlKey: true },
309 }),
310 ).toBe("foreground");
311 expect(
312 composerSubmissionIntentForKey({
313 ...custom,
314 isDraftThread: true,
315 event: { ...enter, ctrlKey: true, shiftKey: true },
316 }),
317 ).toBeNull();
318 expect(
319 composerSubmissionIntentForKey({
320 ...custom,
321 isRunning: true,
322 event: { ...enter, ctrlKey: true, shiftKey: true },
323 }),
324 ).toBeNull();
325 expect(
326 composerSubmissionIntentForKey({ ...custom, event: { ...enter, key: "b", altKey: true } }),
327 ).toBeNull();
328 },
329 );
330
331 it.each(["MacIntel", "Win32", "Linux"])(
332 "keeps modifier submission available with the software keyboard open on %s",
333 (platform) => {
334 const modEnter = {
335 ...enter,
336 metaKey: platform === "MacIntel",
337 ctrlKey: platform !== "MacIntel",
338 };
339 const keyboardOpen = { ...input, platform, isSoftwareKeyboardOpen: true };
340 expect(composerSubmissionIntentForKey({ ...keyboardOpen, event: modEnter })).toBe(
341 "foreground",
342 );
343 expect(
344 composerSubmissionIntentForKey({ ...keyboardOpen, isRunning: true, event: modEnter }),
345 ).toBe("alternate");
346 expect(
347 composerSubmissionIntentForKey({ ...keyboardOpen, isDraftThread: true, event: modEnter }),
348 ).toBe("background");
349 },
350 );
351
352 it.each([
353 { isSoftwareKeyboardOpen: true },
354 { event: { ...enter, isComposing: true } },
355 { event: { ...enter, keyCode: 229 } },
356 { event: { ...enter, repeat: true } },
357 ])("does not submit with %j", (override) => {
358 expect(composerSubmissionIntentForKey({ ...input, event: enter, ...override })).toBeNull();
359 });
360});
361
362describe("detectComposerTrigger", () => {
363 it.each([
364 ["Run /tmp/build.sh", "Run /tmp/build.sh".length],
365 ["/etc/hosts", "/etc/hosts".length],
366 ["Use /etc/hosts now", "Use /et".length],
367 ])("keeps the path in %j out of the slash menu", (text, cursor) => {
368 expect(detectComposerTrigger(text, cursor)).toBeNull();
369 });
370
371 it.each(["Use ", "Use\t", "Use\n "])("detects inline slash skills after %j", (prefix) => {
372 const text = `${prefix}/skill:review later`;
373 const cursor = `${prefix}/skill:review`.length;
374 expect(detectComposerTrigger(text, cursor)).toEqual({
375 kind: "slash-command",
376 query: "skill:review",
377 rangeStart: prefix.length,
378 rangeEnd: cursor,
379 });
380 });
381
382 it.each(["Use /", "Use /review"])("detects the inline slash token in %j", (text) => {
383 expect(detectComposerTrigger(text, text.length)).toEqual({
384 kind: "slash-command",
385 query: text.slice(5),
386 rangeStart: 4,
387 rangeEnd: text.length,
388 });
389 });
390
391 it.each(["Use/review", "https://example.com/review", "Use /review "])(
392 "does not trigger for %j",
393 (text) => expect(detectComposerTrigger(text, text.length)).toBeNull(),
394 );
395
396 it("detects @path trigger at cursor", () => {
397 const text = "Please check @src/com";
398 const trigger = detectComposerTrigger(text, text.length);
399
400 expect(trigger).toEqual({
401 kind: "path",
402 query: "src/com",
403 rangeStart: "Please check ".length,
404 rangeEnd: text.length,
405 });
406 });
407
408 it("detects slash command token while typing command name", () => {
409 const text = "/mo";
410 const trigger = detectComposerTrigger(text, text.length);
411
412 expect(trigger).toEqual({
413 kind: "slash-command",
414 query: "mo",
415 rangeStart: 0,
416 rangeEnd: text.length,
417 });
418 });
419
420 it("keeps /model as a slash command item", () => {
421 const text = "/model";
422 const trigger = detectComposerTrigger(text, text.length);
423
424 expect(trigger).toEqual({
425 kind: "slash-command",
426 query: "model",
427 rangeStart: 0,
428 rangeEnd: text.length,
429 });
430 });
431
432 it("does not keep a subcommand trigger active after /model arguments", () => {
433 const text = "/model spark";
434 const trigger = detectComposerTrigger(text, text.length);
435
436 expect(trigger).toBeNull();
437 });
438
439 it("detects non-model slash commands while typing", () => {
440 const text = "/pl";
441 const trigger = detectComposerTrigger(text, text.length);
442
443 expect(trigger).toEqual({
444 kind: "slash-command",
445 query: "pl",
446 rangeStart: 0,
447 rangeEnd: text.length,
448 });
449 });
450
451 it("keeps slash command detection active for provider commands", () => {
452 const text = "/rev";
453 const trigger = detectComposerTrigger(text, text.length);
454
455 expect(trigger).toEqual({
456 kind: "slash-command",
457 query: "rev",
458 rangeStart: 0,
459 rangeEnd: text.length,
460 });
461 });
462
463 it.each(["$", "€", "£", "¥", "₹", "₩", "₿", "𑿝"])(
464 "detects %sskill trigger at cursor",
465 (prefix) => {
466 const text = `Use ${prefix}gh-fi`;
467 const trigger = detectComposerTrigger(text, text.length);
468
469 expect(trigger).toEqual({
470 kind: "skill",
471 query: "gh-fi",
472 rangeStart: "Use ".length,
473 rangeEnd: text.length,
474 });
475 },
476 );
477
478 it("detects a pull request number at a token boundary", () => {
479 const text = "Compare this with #8737";
480
481 expect(detectComposerTrigger(text, text.length)).toEqual({
482 kind: "pull-request",
483 query: "8737",
484 rangeStart: "Compare this with ".length,
485 rangeEnd: text.length,
486 });
487 });
488
489 it("opens pull request completion from a bare hash", () => {
490 const text = "Compare with #";
491
492 expect(detectComposerTrigger(text, text.length)).toEqual({
493 kind: "pull-request",
494 query: "",
495 rangeStart: "Compare with ".length,
496 rangeEnd: text.length,
497 });
498 });
499
500 it("detects a one-word pull request search", () => {
501 const text = "Compare with #composer";
502
503 expect(detectComposerTrigger(text, text.length)).toEqual({
504 kind: "pull-request",
505 query: "composer",
506 rangeStart: "Compare with ".length,
507 rangeEnd: text.length,
508 });
509 });
510
511 it("supports hyphenated pull request search terms", () => {
512 const text = "Find #inline-context";
513
514 expect(detectComposerTrigger(text, text.length)).toEqual({
515 kind: "pull-request",
516 query: "inline-context",
517 rangeStart: "Find ".length,
518 rangeEnd: text.length,
519 });
520 });
521
522 it("does not keep pull request completion active for headings or embedded hashes", () => {
523 expect(detectComposerTrigger("# Heading", "# Heading".length)).toBeNull();
524 expect(detectComposerTrigger("issue#123", "issue#123".length)).toBeNull();
525 });
526
527 it("detects @path trigger in the middle of existing text", () => {
528 const text = "Please inspect @in this sentence";
529 const cursorAfterAt = "Please inspect @".length;
530
531 const trigger = detectComposerTrigger(text, cursorAfterAt);
532 expect(trigger).toEqual({
533 kind: "path",
534 query: "",
535 rangeStart: "Please inspect ".length,
536 rangeEnd: cursorAfterAt,
537 });
538 });
539
540 it("detects @path trigger with query typed mid-text", () => {
541 const text = "Please inspect @srin this sentence";
542 const cursorAfterQuery = "Please inspect @sr".length;
543
544 const trigger = detectComposerTrigger(text, cursorAfterQuery);
545 expect(trigger).toEqual({
546 kind: "path",
547 query: "sr",
548 rangeStart: "Please inspect ".length,
549 rangeEnd: cursorAfterQuery,
550 });
551 });
552
553 it("detects trigger with true cursor even when regex-based mention detection would false-match", () => {
554 const text = "Please inspect @in this sentence";
555 const cursorAfterAt = "Please inspect @".length;
556
557 const trigger = detectComposerTrigger(text, cursorAfterAt);
558 expect(trigger).not.toBeNull();
559 expect(trigger?.kind).toBe("path");
560 expect(trigger?.query).toBe("");
561 });
562});
563
564describe("filterComposerPullRequestMatches", () => {
565 const entries = [
566 {
567 number: 7,
568 projectId: "project-1",
569 repository: "t3tools/t3code",
570 updatedAt: "2026-09-01T12:00:00.000Z",
571 },
572 {
573 number: 8987,
574 projectId: "project-1",
575 repository: "T3Tools/T3Code",
576 updatedAt: "2026-09-03T12:00:00.000Z",
577 },
578 {
579 number: 27,
580 projectId: "project-1",
581 repository: "t3tools/t3code",
582 updatedAt: "2026-09-02T12:00:00.000Z",
583 },
584 {
585 number: 27,
586 projectId: "project-1",
587 repository: "t3tools/t3code",
588 updatedAt: "2026-09-01T13:00:00.000Z",
589 },
590 {
591 number: 70,
592 projectId: "project-2",
593 repository: "t3tools/other",
594 updatedAt: "2026-09-04T12:00:00.000Z",
595 },
596 ];
597
598 it("matches and de-duplicates number fragments within one repository, exact match first", () => {
599 expect(
600 filterComposerPullRequestMatches({
601 entries,
602 projectId: "project-1",
603 repository: "t3tools/t3code",
604 query: "7",
605 limit: 10,
606 }).map((entry) => entry.number),
607 ).toEqual([7, 8987, 27]);
608 });
609
610 it("keeps an older exact match when newer substring matches would fill the limit", () => {
611 const exact = {
612 number: 7,
613 projectId: "project-1",
614 repository: "t3tools/t3code",
615 updatedAt: "2020-01-01T00:00:00.000Z",
616 };
617 const newerSubstringMatches = Array.from({ length: 12 }, (_unused, index) => ({
618 number: 700 + index,
619 projectId: "project-1",
620 repository: "t3tools/t3code",
621 updatedAt: `2026-09-${String(index + 1).padStart(2, "0")}T12:00:00.000Z`,
622 }));
623 const matches = filterComposerPullRequestMatches({
624 entries: [...newerSubstringMatches, exact],
625 projectId: "project-1",
626 repository: "t3tools/t3code",
627 query: "7",
628 limit: 10,
629 });
630 expect(matches[0]?.number).toBe(7);
631 expect(matches).toHaveLength(10);
632 });
633
634 it("uses an empty query for a capped recent list", () => {
635 expect(
636 filterComposerPullRequestMatches({
637 entries,
638 projectId: "project-1",
639 repository: "t3tools/t3code",
640 query: "",
641 limit: 2,
642 }).map((entry) => entry.number),
643 ).toEqual([8987, 27]);
644 });
645});
646
647describe("replaceTextRange", () => {
648 it("replaces a text range and returns new cursor", () => {
649 const replaced = replaceTextRange("hello @src", 6, 10, "");
650 expect(replaced).toEqual({
651 text: "hello ",
652 cursor: 6,
653 });
654 });
655});
656
657describe("expandCollapsedComposerCursor", () => {
658 it("keeps cursor unchanged when no mention segment is present", () => {
659 expect(expandCollapsedComposerCursor("plain text", 5)).toBe(5);
660 });
661
662 it("maps collapsed mention cursor to expanded text cursor", () => {
663 const text = "what's in my @AGENTS.md fsfdas";
664 const collapsedCursorAfterMention = "what's in my ".length + 2;
665 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
666
667 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
668 expandedCursorAfterMention,
669 );
670 });
671
672 it("maps collapsed quoted mention cursor to expanded text cursor", () => {
673 const text = 'what is in @"My File.md" please';
674 const collapsedCursorAfterMention = "what is in ".length + 2;
675 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
676
677 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
678 expandedCursorAfterMention,
679 );
680 });
681
682 it("maps collapsed markdown file links to their expanded source offsets", () => {
683 const text = "what's in [AGENTS.md](AGENTS.md) please";
684 const collapsedCursorAfterMention = "what's in ".length + 2;
685 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
686
687 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
688 expandedCursorAfterMention,
689 );
690 });
691
692 it("allows path trigger detection to close after selecting a mention", () => {
693 const text = "what's in my @AGENTS.md ";
694 const collapsedCursorAfterMention = "what's in my ".length + 2;
695 const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
696
697 expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
698 });
699
700 it.each(["$", "€", "𑿝"])("maps collapsed %s skill cursor to expanded text cursor", (prefix) => {
701 const text = `run ${prefix}review-follow-up then`;
702 const collapsedCursorAfterSkill = "run ".length + 2;
703 const expandedCursorAfterSkill = `run ${prefix}review-follow-up `.length;
704
705 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterSkill)).toBe(
706 expandedCursorAfterSkill,
707 );
708 });
709});
710
711describe("composerStateAtPromptEnd", () => {
712 it("puts the caret at the end of a restored parked draft", () => {
713 const prompt = carryDisplacedCustomAnswerIntoPrompt("first half\n", "second half");
714
715 expect(composerStateAtPromptEnd(prompt)).toEqual({
716 cursor: prompt.length,
717 trigger: null,
718 });
719 });
720
721 it("collapses mention chips so the next keystroke lands after the draft", () => {
722 const prompt = carryDisplacedCustomAnswerIntoPrompt("", "see @AGENTS.md please");
723
724 expect(composerStateAtPromptEnd(prompt).cursor).toBe("see ".length + 1 + " please".length);
725 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(0);
726 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(prompt.length);
727 });
728
729 it("keeps a trailing mention trigger when the restored draft ends with @", () => {
730 const prompt = "look at @";
731
732 expect(composerStateAtPromptEnd(prompt)).toEqual({
733 cursor: prompt.length,
734 trigger: { kind: "path", query: "", rangeStart: "look at ".length, rangeEnd: prompt.length },
735 });
736 });
737});
738
739describe("collapseExpandedComposerCursor", () => {
740 it("keeps cursor unchanged when no mention segment is present", () => {
741 expect(collapseExpandedComposerCursor("plain text", 5)).toBe(5);
742 });
743
744 it("maps expanded mention cursor back to collapsed cursor", () => {
745 const text = "what's in my @AGENTS.md fsfdas";
746 const collapsedCursorAfterMention = "what's in my ".length + 2;
747 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
748
749 expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
750 collapsedCursorAfterMention,
751 );
752 });
753
754 it("maps expanded quoted mention cursor back to collapsed cursor", () => {
755 const text = 'what is in @"My File.md" please';
756 const collapsedCursorAfterMention = "what is in ".length + 2;
757 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
758
759 expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
760 collapsedCursorAfterMention,
761 );
762 });
763
764 it("maps expanded markdown file link cursors back to collapsed offsets", () => {
765 const text = "what's in [AGENTS.md](AGENTS.md) please";
766 const collapsedCursorAfterMention = "what's in ".length + 2;
767 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
768
769 expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
770 collapsedCursorAfterMention,
771 );
772 });
773
774 it("keeps package-like text expanded when another mention already exists earlier", () => {
775 const text = "open @AGENTS.md then @src/index.ts ";
776 const expandedCursor = text.length;
777 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
778
779 expect(collapsedCursor).toBe("open ".length + 1 + " then @src/index.ts ".length);
780 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
781 });
782
783 it("collapses only genuine mentions when package-like text exists earlier", () => {
784 const text = "install @scope/pkg then @README.md ";
785 const expandedCursor = text.length;
786 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
787
788 expect(collapsedCursor).toBe("install @scope/pkg then ".length + 1 + " ".length);
789 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
790 });
791
792 it.each(["$", "€", "𑿝"])("maps expanded %s skill cursor back to collapsed cursor", (prefix) => {
793 const text = `run ${prefix}review-follow-up then`;
794 const collapsedCursorAfterSkill = "run ".length + 2;
795 const expandedCursorAfterSkill = `run ${prefix}review-follow-up `.length;
796
797 expect(collapseExpandedComposerCursor(text, expandedCursorAfterSkill)).toBe(
798 collapsedCursorAfterSkill,
799 );
800 });
801});
802
803it("preserves the caret before trailing text after mixed-width skill chips", () => {
804 const text = "𑿝ui a $review tail";
805 const expanded = "𑿝ui a $review ".length;
806 expect(collapseExpandedComposerCursor(text, expanded)).toBe(6);
807 expect(expandCollapsedComposerCursor(text, 6)).toBe(expanded);
808});
809
810describe("clampCollapsedComposerCursor", () => {
811 it("clamps to collapsed prompt length when mentions are present", () => {
812 const text = "open @AGENTS.md then ";
813
814 expect(clampCollapsedComposerCursor(text, text.length)).toBe(
815 "open ".length + 1 + " then ".length,
816 );
817 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(
818 "open ".length + 1 + " then ".length,
819 );
820 });
821});
822
823describe("assistant citation cursor offsets", () => {
824 it("roundtrips every collapsed offset across citations, mentions, skills, and Unicode", () => {
825 const prefix = "👋(";
826 const between = "),雪";
827 const after = " @AGENTS.md $review ";
828 const text = `${prefix}${citationSource}${between}${citationSource}${after}${terminalReference}!`;
829 const collapsedLength = `${prefix}□${between}□ □ □ □!`.length;
830 const boundaries = [
831 [prefix.length, prefix.length],
832 [prefix.length + 1, prefix.length + citationSource.length],
833 [prefix.length + 1 + between.length, prefix.length + citationSource.length + between.length],
834 [
835 prefix.length + 2 + between.length,
836 prefix.length + citationSource.length * 2 + between.length,
837 ],
838 [collapsedLength, text.length],
839 ] as const;
840
841 for (const [collapsed, expanded] of boundaries) {
842 expect(expandCollapsedComposerCursor(text, collapsed)).toBe(expanded);
843 expect(collapseExpandedComposerCursor(text, expanded)).toBe(collapsed);
844 }
845 for (let cursor = 0; cursor <= collapsedLength; cursor += 1) {
846 expect(
847 collapseExpandedComposerCursor(text, expandCollapsedComposerCursor(text, cursor)),
848 ).toBe(cursor);
849 }
850 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(collapsedLength);
851 });
852
853 it("snaps serialized offsets inside a citation to the end of its chip", () => {
854 const prefix = "前👋";
855 const text = `${prefix}${citationSource}.`;
856
857 for (const offset of [1, citationSource.length - 1, citationSource.length]) {
858 expect(collapseExpandedComposerCursor(text, prefix.length + offset)).toBe(prefix.length + 1);
859 }
860 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length, "right")).toBe(true);
861 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length + 1, "left")).toBe(true);
862 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length + 2, "left")).toBe(false);
863 });
864
865 it("deletes one collapsed citation without changing its neighbor or surrounding punctuation", () => {
866 const text = `(${citationSource}),${citationSource}!`;
867 const result = replaceTextRange(
868 text,
869 expandCollapsedComposerCursor(text, 1),
870 expandCollapsedComposerCursor(text, 2),
871 "",
872 );
873
874 expect(result).toEqual({ text: `(),${citationSource}!`, cursor: 1 });
875 expect(collapseExpandedComposerCursor(result.text, result.text.length)).toBe("(),□!".length);
876 });
877});
878
879describe("isCollapsedCursorAdjacentToInlineToken", () => {
880 it("returns false when no mention exists", () => {
881 expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "left")).toBe(false);
882 expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "right")).toBe(false);
883 });
884
885 it("keeps @query typing non-adjacent while no mention pill exists", () => {
886 const text = "hello @pac";
887 expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "left")).toBe(false);
888 expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "right")).toBe(false);
889 });
890
891 it("detects left adjacency only when cursor is directly after a mention", () => {
892 const text = "open @AGENTS.md next";
893 const mentionStart = "open ".length;
894 const mentionEnd = mentionStart + 1;
895
896 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
897 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
898 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
899 });
900
901 it("detects right adjacency only when cursor is directly before a mention", () => {
902 const text = "open @AGENTS.md next";
903 const mentionStart = "open ".length;
904 const mentionEnd = mentionStart + 1;
905
906 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "right")).toBe(true);
907 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "right")).toBe(false);
908 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart - 1, "right")).toBe(false);
909 });
910
911 it("treats context reference pills as inline tokens for adjacency checks", () => {
912 const text = `open ${terminalReference} next`;
913 const tokenStart = "open ".length;
914 const tokenEnd = tokenStart + 1;
915
916 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
917 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
918 });
919
920 it("treats skill pills as inline tokens for adjacency checks", () => {
921 const text = "run $review-follow-up next";
922 const tokenStart = "run ".length;
923 const tokenEnd = tokenStart + 1;
924
925 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
926 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
927 });
928});
929
930describe("parseStandaloneComposerSlashCommand", () => {
931 it("parses standalone /plan command", () => {
932 expect(parseStandaloneComposerSlashCommand(" /plan ")).toBe("plan");
933 });
934
935 it("parses standalone /default command", () => {
936 expect(parseStandaloneComposerSlashCommand("/default")).toBe("default");
937 });
938
939 it("ignores slash commands with extra message text", () => {
940 expect(parseStandaloneComposerSlashCommand("/plan explain this")).toBeNull();
941 });
942});
943
944describe("literal editor answer cursor state", () => {
945 const prefill = "- [X] done $my-skill ";
946
947 it("keeps character positions after token-like text for inserted lines and replacements", () => {
948 for (const replacement of ["\n", "\t", "edited\n "]) {
949 const next = replaceTextRange(prefill, prefill.length, prefill.length, replacement);
950 const cursor = collapseExpandedComposerCursor(next.text, next.cursor, true);
951 expect(next.text).toBe(prefill + replacement);
952 expect(cursor).toBe(next.text.length);
953 expect(expandCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
954 expect(clampCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
955 }
956 const replaced = replaceTextRange(prefill, 11, 20, "$another-skill");
957 const cursor = collapseExpandedComposerCursor(replaced.text, replaced.cursor, true);
958 expect(replaced.text).toBe("- [X] done $another-skill ");
959 expect(cursor).toBe(25);
960 expect(expandCollapsedComposerCursor(replaced.text, cursor, true)).toBe(25);
961 });
962
963 it("does not open a skill or path menu when restoring an editor answer", () => {
964 for (const value of ["- [X] done $my-skill", "Use @README", ""]) {
965 expect(composerStateAtPromptEnd(value, true)).toEqual({
966 cursor: value.length,
967 trigger: null,
968 });
969 }
970 expect(composerStateAtPromptEnd("Use $my").trigger?.kind).toBe("skill");
971 });
972});