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("detects @path trigger at cursor", () => {
250 const text = "Please check @src/com";
251 const trigger = detectComposerTrigger(text, text.length);
252
253 expect(trigger).toEqual({
254 kind: "path",
255 query: "src/com",
256 rangeStart: "Please check ".length,
257 rangeEnd: text.length,
258 });
259 });
260
261 it("detects slash command token while typing command name", () => {
262 const text = "/mo";
263 const trigger = detectComposerTrigger(text, text.length);
264
265 expect(trigger).toEqual({
266 kind: "slash-command",
267 query: "mo",
268 rangeStart: 0,
269 rangeEnd: text.length,
270 });
271 });
272
273 it("keeps /model as a slash command item", () => {
274 const text = "/model";
275 const trigger = detectComposerTrigger(text, text.length);
276
277 expect(trigger).toEqual({
278 kind: "slash-command",
279 query: "model",
280 rangeStart: 0,
281 rangeEnd: text.length,
282 });
283 });
284
285 it("does not keep a subcommand trigger active after /model arguments", () => {
286 const text = "/model spark";
287 const trigger = detectComposerTrigger(text, text.length);
288
289 expect(trigger).toBeNull();
290 });
291
292 it("detects non-model slash commands while typing", () => {
293 const text = "/pl";
294 const trigger = detectComposerTrigger(text, text.length);
295
296 expect(trigger).toEqual({
297 kind: "slash-command",
298 query: "pl",
299 rangeStart: 0,
300 rangeEnd: text.length,
301 });
302 });
303
304 it("keeps slash command detection active for provider commands", () => {
305 const text = "/rev";
306 const trigger = detectComposerTrigger(text, text.length);
307
308 expect(trigger).toEqual({
309 kind: "slash-command",
310 query: "rev",
311 rangeStart: 0,
312 rangeEnd: text.length,
313 });
314 });
315
316 it.each(["$", "€", "£", "¥", "₹", "₩", "₿", "𑿝"])(
317 "detects %sskill trigger at cursor",
318 (prefix) => {
319 const text = `Use ${prefix}gh-fi`;
320 const trigger = detectComposerTrigger(text, text.length);
321
322 expect(trigger).toEqual({
323 kind: "skill",
324 query: "gh-fi",
325 rangeStart: "Use ".length,
326 rangeEnd: text.length,
327 });
328 },
329 );
330
331 it("detects a pull request number at a token boundary", () => {
332 const text = "Compare this with #8737";
333
334 expect(detectComposerTrigger(text, text.length)).toEqual({
335 kind: "pull-request",
336 query: "8737",
337 rangeStart: "Compare this with ".length,
338 rangeEnd: text.length,
339 });
340 });
341
342 it("opens pull request completion from a bare hash", () => {
343 const text = "Compare with #";
344
345 expect(detectComposerTrigger(text, text.length)).toEqual({
346 kind: "pull-request",
347 query: "",
348 rangeStart: "Compare with ".length,
349 rangeEnd: text.length,
350 });
351 });
352
353 it("detects a one-word pull request search", () => {
354 const text = "Compare with #composer";
355
356 expect(detectComposerTrigger(text, text.length)).toEqual({
357 kind: "pull-request",
358 query: "composer",
359 rangeStart: "Compare with ".length,
360 rangeEnd: text.length,
361 });
362 });
363
364 it("supports hyphenated pull request search terms", () => {
365 const text = "Find #inline-context";
366
367 expect(detectComposerTrigger(text, text.length)).toEqual({
368 kind: "pull-request",
369 query: "inline-context",
370 rangeStart: "Find ".length,
371 rangeEnd: text.length,
372 });
373 });
374
375 it("does not keep pull request completion active for headings or embedded hashes", () => {
376 expect(detectComposerTrigger("# Heading", "# Heading".length)).toBeNull();
377 expect(detectComposerTrigger("issue#123", "issue#123".length)).toBeNull();
378 });
379
380 it("detects @path trigger in the middle of existing text", () => {
381 // User typed @ between "inspect " and "in this sentence"
382 const text = "Please inspect @in this sentence";
383 const cursorAfterAt = "Please inspect @".length;
384
385 const trigger = detectComposerTrigger(text, cursorAfterAt);
386 expect(trigger).toEqual({
387 kind: "path",
388 query: "",
389 rangeStart: "Please inspect ".length,
390 rangeEnd: cursorAfterAt,
391 });
392 });
393
394 it("detects @path trigger with query typed mid-text", () => {
395 // User typed @sr between "inspect " and "in this sentence"
396 const text = "Please inspect @srin this sentence";
397 const cursorAfterQuery = "Please inspect @sr".length;
398
399 const trigger = detectComposerTrigger(text, cursorAfterQuery);
400 expect(trigger).toEqual({
401 kind: "path",
402 query: "sr",
403 rangeStart: "Please inspect ".length,
404 rangeEnd: cursorAfterQuery,
405 });
406 });
407
408 it("detects trigger with true cursor even when regex-based mention detection would false-match", () => {
409 // MENTION_TOKEN_REGEX can false-match plain text like "@in" as a mention.
410 // The fix bypasses it by computing the expanded cursor from the Lexical node tree.
411 const text = "Please inspect @in this sentence";
412 const cursorAfterAt = "Please inspect @".length;
413
414 const trigger = detectComposerTrigger(text, cursorAfterAt);
415 expect(trigger).not.toBeNull();
416 expect(trigger?.kind).toBe("path");
417 expect(trigger?.query).toBe("");
418 });
419});
420
421describe("filterComposerPullRequestMatches", () => {
422 const entries = [
423 {
424 number: 7,
425 projectId: "project-1",
426 repository: "t3tools/t3code",
427 updatedAt: "2026-09-01T12:00:00.000Z",
428 },
429 {
430 number: 8987,
431 projectId: "project-1",
432 repository: "T3Tools/T3Code",
433 updatedAt: "2026-09-03T12:00:00.000Z",
434 },
435 {
436 number: 27,
437 projectId: "project-1",
438 repository: "t3tools/t3code",
439 updatedAt: "2026-09-02T12:00:00.000Z",
440 },
441 {
442 number: 27,
443 projectId: "project-1",
444 repository: "t3tools/t3code",
445 updatedAt: "2026-09-01T13:00:00.000Z",
446 },
447 {
448 number: 70,
449 projectId: "project-2",
450 repository: "t3tools/other",
451 updatedAt: "2026-09-04T12:00:00.000Z",
452 },
453 ];
454
455 it("matches and de-duplicates number fragments within one repository, exact match first", () => {
456 expect(
457 filterComposerPullRequestMatches({
458 entries,
459 projectId: "project-1",
460 repository: "t3tools/t3code",
461 query: "7",
462 limit: 10,
463 }).map((entry) => entry.number),
464 ).toEqual([7, 8987, 27]);
465 });
466
467 it("keeps an older exact match when newer substring matches would fill the limit", () => {
468 const exact = {
469 number: 7,
470 projectId: "project-1",
471 repository: "t3tools/t3code",
472 updatedAt: "2020-01-01T00:00:00.000Z",
473 };
474 const newerSubstringMatches = Array.from({ length: 12 }, (_unused, index) => ({
475 number: 700 + index,
476 projectId: "project-1",
477 repository: "t3tools/t3code",
478 updatedAt: `2026-09-${String(index + 1).padStart(2, "0")}T12:00:00.000Z`,
479 }));
480 const matches = filterComposerPullRequestMatches({
481 entries: [...newerSubstringMatches, exact],
482 projectId: "project-1",
483 repository: "t3tools/t3code",
484 query: "7",
485 limit: 10,
486 });
487 expect(matches[0]?.number).toBe(7);
488 expect(matches).toHaveLength(10);
489 });
490
491 it("uses an empty query for a capped recent list", () => {
492 expect(
493 filterComposerPullRequestMatches({
494 entries,
495 projectId: "project-1",
496 repository: "t3tools/t3code",
497 query: "",
498 limit: 2,
499 }).map((entry) => entry.number),
500 ).toEqual([8987, 27]);
501 });
502});
503
504describe("replaceTextRange", () => {
505 it("replaces a text range and returns new cursor", () => {
506 const replaced = replaceTextRange("hello @src", 6, 10, "");
507 expect(replaced).toEqual({
508 text: "hello ",
509 cursor: 6,
510 });
511 });
512});
513
514describe("expandCollapsedComposerCursor", () => {
515 it("keeps cursor unchanged when no mention segment is present", () => {
516 expect(expandCollapsedComposerCursor("plain text", 5)).toBe(5);
517 });
518
519 it("maps collapsed mention cursor to expanded text cursor", () => {
520 const text = "what's in my @AGENTS.md fsfdas";
521 const collapsedCursorAfterMention = "what's in my ".length + 2;
522 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
523
524 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
525 expandedCursorAfterMention,
526 );
527 });
528
529 it("maps collapsed quoted mention cursor to expanded text cursor", () => {
530 const text = 'what is in @"My File.md" please';
531 const collapsedCursorAfterMention = "what is in ".length + 2;
532 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
533
534 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
535 expandedCursorAfterMention,
536 );
537 });
538
539 it("maps collapsed markdown file links to their expanded source offsets", () => {
540 const text = "what's in [AGENTS.md](AGENTS.md) please";
541 const collapsedCursorAfterMention = "what's in ".length + 2;
542 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
543
544 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
545 expandedCursorAfterMention,
546 );
547 });
548
549 it("allows path trigger detection to close after selecting a mention", () => {
550 const text = "what's in my @AGENTS.md ";
551 const collapsedCursorAfterMention = "what's in my ".length + 2;
552 const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
553
554 expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
555 });
556
557 it.each(["$", "€", "𑿝"])("maps collapsed %s skill cursor to expanded text cursor", (prefix) => {
558 const text = `run ${prefix}review-follow-up then`;
559 const collapsedCursorAfterSkill = "run ".length + 2;
560 const expandedCursorAfterSkill = `run ${prefix}review-follow-up `.length;
561
562 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterSkill)).toBe(
563 expandedCursorAfterSkill,
564 );
565 });
566});
567
568describe("composerStateAtPromptEnd", () => {
569 it("puts the caret at the end of a restored parked draft", () => {
570 const prompt = carryDisplacedCustomAnswerIntoPrompt("first half\n", "second half");
571
572 expect(composerStateAtPromptEnd(prompt)).toEqual({
573 cursor: prompt.length,
574 trigger: null,
575 });
576 });
577
578 it("collapses mention chips so the next keystroke lands after the draft", () => {
579 const prompt = carryDisplacedCustomAnswerIntoPrompt("", "see @AGENTS.md please");
580
581 expect(composerStateAtPromptEnd(prompt).cursor).toBe("see ".length + 1 + " please".length);
582 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(0);
583 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(prompt.length);
584 });
585
586 it("keeps a trailing mention trigger when the restored draft ends with @", () => {
587 const prompt = "look at @";
588
589 expect(composerStateAtPromptEnd(prompt)).toEqual({
590 cursor: prompt.length,
591 trigger: { kind: "path", query: "", rangeStart: "look at ".length, rangeEnd: prompt.length },
592 });
593 });
594});
595
596describe("collapseExpandedComposerCursor", () => {
597 it("keeps cursor unchanged when no mention segment is present", () => {
598 expect(collapseExpandedComposerCursor("plain text", 5)).toBe(5);
599 });
600
601 it("maps expanded mention cursor back to collapsed cursor", () => {
602 const text = "what's in my @AGENTS.md fsfdas";
603 const collapsedCursorAfterMention = "what's in my ".length + 2;
604 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
605
606 expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
607 collapsedCursorAfterMention,
608 );
609 });
610
611 it("maps expanded quoted mention cursor back to collapsed cursor", () => {
612 const text = 'what is in @"My File.md" please';
613 const collapsedCursorAfterMention = "what is in ".length + 2;
614 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
615
616 expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
617 collapsedCursorAfterMention,
618 );
619 });
620
621 it("maps expanded markdown file link cursors back to collapsed offsets", () => {
622 const text = "what's in [AGENTS.md](AGENTS.md) please";
623 const collapsedCursorAfterMention = "what's in ".length + 2;
624 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
625
626 expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
627 collapsedCursorAfterMention,
628 );
629 });
630
631 it("keeps package-like text expanded when another mention already exists earlier", () => {
632 const text = "open @AGENTS.md then @src/index.ts ";
633 const expandedCursor = text.length;
634 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
635
636 expect(collapsedCursor).toBe("open ".length + 1 + " then @src/index.ts ".length);
637 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
638 });
639
640 it("collapses only genuine mentions when package-like text exists earlier", () => {
641 const text = "install @scope/pkg then @README.md ";
642 const expandedCursor = text.length;
643 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
644
645 expect(collapsedCursor).toBe("install @scope/pkg then ".length + 1 + " ".length);
646 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
647 });
648
649 it.each(["$", "€", "𑿝"])("maps expanded %s skill cursor back to collapsed cursor", (prefix) => {
650 const text = `run ${prefix}review-follow-up then`;
651 const collapsedCursorAfterSkill = "run ".length + 2;
652 const expandedCursorAfterSkill = `run ${prefix}review-follow-up `.length;
653
654 expect(collapseExpandedComposerCursor(text, expandedCursorAfterSkill)).toBe(
655 collapsedCursorAfterSkill,
656 );
657 });
658});
659
660it("preserves the caret before trailing text after mixed-width skill chips", () => {
661 const text = "𑿝ui a $review tail";
662 const expanded = "𑿝ui a $review ".length;
663 expect(collapseExpandedComposerCursor(text, expanded)).toBe(6);
664 expect(expandCollapsedComposerCursor(text, 6)).toBe(expanded);
665});
666
667describe("clampCollapsedComposerCursor", () => {
668 it("clamps to collapsed prompt length when mentions are present", () => {
669 const text = "open @AGENTS.md then ";
670
671 expect(clampCollapsedComposerCursor(text, text.length)).toBe(
672 "open ".length + 1 + " then ".length,
673 );
674 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(
675 "open ".length + 1 + " then ".length,
676 );
677 });
678});
679
680describe("assistant citation cursor offsets", () => {
681 it("roundtrips every collapsed offset across citations, mentions, skills, and Unicode", () => {
682 const prefix = "👋(";
683 const between = "),雪";
684 const after = " @AGENTS.md $review ";
685 const text = `${prefix}${citationSource}${between}${citationSource}${after}${terminalReference}!`;
686 const collapsedLength = `${prefix}□${between}□ □ □ □!`.length;
687 const boundaries = [
688 [prefix.length, prefix.length],
689 [prefix.length + 1, prefix.length + citationSource.length],
690 [prefix.length + 1 + between.length, prefix.length + citationSource.length + between.length],
691 [
692 prefix.length + 2 + between.length,
693 prefix.length + citationSource.length * 2 + between.length,
694 ],
695 [collapsedLength, text.length],
696 ] as const;
697
698 for (const [collapsed, expanded] of boundaries) {
699 expect(expandCollapsedComposerCursor(text, collapsed)).toBe(expanded);
700 expect(collapseExpandedComposerCursor(text, expanded)).toBe(collapsed);
701 }
702 for (let cursor = 0; cursor <= collapsedLength; cursor += 1) {
703 expect(
704 collapseExpandedComposerCursor(text, expandCollapsedComposerCursor(text, cursor)),
705 ).toBe(cursor);
706 }
707 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(collapsedLength);
708 });
709
710 it("snaps serialized offsets inside a citation to the end of its chip", () => {
711 const prefix = "前👋";
712 const text = `${prefix}${citationSource}.`;
713
714 for (const offset of [1, citationSource.length - 1, citationSource.length]) {
715 expect(collapseExpandedComposerCursor(text, prefix.length + offset)).toBe(prefix.length + 1);
716 }
717 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length, "right")).toBe(true);
718 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length + 1, "left")).toBe(true);
719 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length + 2, "left")).toBe(false);
720 });
721
722 it("deletes one collapsed citation without changing its neighbor or surrounding punctuation", () => {
723 const text = `(${citationSource}),${citationSource}!`;
724 const result = replaceTextRange(
725 text,
726 expandCollapsedComposerCursor(text, 1),
727 expandCollapsedComposerCursor(text, 2),
728 "",
729 );
730
731 expect(result).toEqual({ text: `(),${citationSource}!`, cursor: 1 });
732 expect(collapseExpandedComposerCursor(result.text, result.text.length)).toBe("(),□!".length);
733 });
734});
735
736describe("replaceTextRange trailing space consumption", () => {
737 it("double space after insertion when replacement ends with space", () => {
738 // Simulates: "and then |@AG| summarize" where | marks replacement range
739 // The replacement is "@AGENTS.md " (with trailing space)
740 // But if we don't extend rangeEnd, the existing space stays
741 const text = "and then @AG summarize";
742 const rangeStart = "and then ".length;
743 const rangeEnd = "and then @AG".length;
744
745 // Without consuming trailing space: double space
746 const withoutConsume = replaceTextRange(text, rangeStart, rangeEnd, "@AGENTS.md ");
747 expect(withoutConsume.text).toBe("and then @AGENTS.md summarize");
748
749 // With consuming trailing space: single space
750 const extendedEnd = text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd;
751 const withConsume = replaceTextRange(text, rangeStart, extendedEnd, "@AGENTS.md ");
752 expect(withConsume.text).toBe("and then @AGENTS.md summarize");
753 });
754});
755
756describe("isCollapsedCursorAdjacentToInlineToken", () => {
757 it("returns false when no mention exists", () => {
758 expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "left")).toBe(false);
759 expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "right")).toBe(false);
760 });
761
762 it("keeps @query typing non-adjacent while no mention pill exists", () => {
763 const text = "hello @pac";
764 expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "left")).toBe(false);
765 expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "right")).toBe(false);
766 });
767
768 it("detects left adjacency only when cursor is directly after a mention", () => {
769 const text = "open @AGENTS.md next";
770 const mentionStart = "open ".length;
771 const mentionEnd = mentionStart + 1;
772
773 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
774 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
775 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
776 });
777
778 it("detects right adjacency only when cursor is directly before a mention", () => {
779 const text = "open @AGENTS.md next";
780 const mentionStart = "open ".length;
781 const mentionEnd = mentionStart + 1;
782
783 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "right")).toBe(true);
784 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "right")).toBe(false);
785 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart - 1, "right")).toBe(false);
786 });
787
788 it("treats context reference pills as inline tokens for adjacency checks", () => {
789 const text = `open ${terminalReference} next`;
790 const tokenStart = "open ".length;
791 const tokenEnd = tokenStart + 1;
792
793 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
794 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
795 });
796
797 it("treats skill pills as inline tokens for adjacency checks", () => {
798 const text = "run $review-follow-up next";
799 const tokenStart = "run ".length;
800 const tokenEnd = tokenStart + 1;
801
802 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
803 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
804 });
805});
806
807describe("parseStandaloneComposerSlashCommand", () => {
808 it("parses standalone /plan command", () => {
809 expect(parseStandaloneComposerSlashCommand(" /plan ")).toBe("plan");
810 });
811
812 it("parses standalone /default command", () => {
813 expect(parseStandaloneComposerSlashCommand("/default")).toBe("default");
814 });
815
816 it("ignores slash commands with extra message text", () => {
817 expect(parseStandaloneComposerSlashCommand("/plan explain this")).toBeNull();
818 });
819});
820
821describe("literal editor answer cursor state", () => {
822 const prefill = "- [X] done $my-skill ";
823
824 it("keeps character positions after token-like text for inserted lines and replacements", () => {
825 for (const replacement of ["\n", "\t", "edited\n "]) {
826 const next = replaceTextRange(prefill, prefill.length, prefill.length, replacement);
827 const cursor = collapseExpandedComposerCursor(next.text, next.cursor, true);
828 expect(next.text).toBe(prefill + replacement);
829 expect(cursor).toBe(next.text.length);
830 expect(expandCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
831 expect(clampCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
832 }
833 const replaced = replaceTextRange(prefill, 11, 20, "$another-skill");
834 const cursor = collapseExpandedComposerCursor(replaced.text, replaced.cursor, true);
835 expect(replaced.text).toBe("- [X] done $another-skill ");
836 expect(cursor).toBe(25);
837 expect(expandCollapsedComposerCursor(replaced.text, cursor, true)).toBe(25);
838 });
839
840 it("does not open a skill or path menu when restoring an editor answer", () => {
841 for (const value of ["- [X] done $my-skill", "Use @README", ""]) {
842 expect(composerStateAtPromptEnd(value, true)).toEqual({
843 cursor: value.length,
844 trigger: null,
845 });
846 }
847 expect(composerStateAtPromptEnd("Use $my").trigger?.kind).toBe("skill");
848 });
849});