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