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