Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composer-logic.test.ts

811 lines27.9 KB

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