Open History to see the last commit
1import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
2import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
3import {
4 collectAssistantCitations,
5 expandAssistantCitationsForProvider,
6 serializeAssistantCitation,
7} from "@t3tools/shared/assistantCitations";
8import {
9 DEFAULT_RESOLVED_KEYBINDINGS,
10 compileResolvedKeybindingsConfig,
11 mergeWithDefaultKeybindings,
12} from "@t3tools/shared/keybindings";
13import { describe, expect, it } from "vite-plus/test";
14β
15import {
16 clampCollapsedComposerCursor,
17 collapseExpandedComposerCursor,
18 composerSubmissionIntentForKey,
19 composerStateAtPromptEnd,
20 detectComposerTrigger,
21 expandCollapsedComposerCursor,
22 extendReplacementRangeForTrailingSpace,
23 formatAssistantCitationForComposer,
24 isCollapsedCursorAdjacentToInlineToken,
25 isPathSuggestionCurrent,
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("isPathSuggestionCurrent", () => {
52 const searchedTarget = {
53 environmentId: EnvironmentId.make("local"),
54 cwd: "/repo",
55 query: "alpha",
56 };
57β
58 it("allows a file suggestion matching the live search", () => {
59 expect(
60 isPathSuggestionCurrent(
61 searchedTarget,
62 detectComposerTrigger("@alpha", 6),
63 searchedTarget.environmentId,
64 searchedTarget.cwd,
65 ),
66 ).toBe(true);
67 });
68β
69 it.each([
70 ["query", { ...searchedTarget, query: "beta" }],
71 ["cwd", { ...searchedTarget, cwd: "/other-repo" }],
72 ["environment", { ...searchedTarget, environmentId: EnvironmentId.make("remote") }],
73 ] as const)("rejects a visible file suggestion after the live %s changes", (_change, current) => {
74 const prompt = `@${current.query}`;
75 expect(
76 isPathSuggestionCurrent(
77 searchedTarget,
78 detectComposerTrigger(prompt, prompt.length),
79 current.environmentId,
80 current.cwd,
81 ),
82 ).toBe(false);
83 });
84});
85β
86describe("formatAssistantCitationForComposer", () => {
87 it("binds a multiline comment to its citation without adding standalone prompt text", () => {
88 const comment = 'What does "keep" mean? π\n Please show an example.';
89 const text = formatAssistantCitationForComposer(citation, ` ${comment}\n`);
90 const boundCitation = { ...citation, comment };
91 expect(text).toBe(`${serializeAssistantCitation(boundCitation)} `);
92 expect(collectAssistantCitations(text).map((entry) => entry.citation)).toEqual([boundCitation]);
93 expect(expandAssistantCitationsForProvider(text)).toMatch(/^\[assistant-quote-1\] \n\n/);
94 });
95});
96β
97describe("composerSubmissionIntentForKey", () => {
98 const input = {
99 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
100 platform: "Linux",
101 isSoftwareKeyboardOpen: false,
102 isDraftThread: false,
103 };
104 const enter = { key: "Enter", metaKey: false, ctrlKey: false, altKey: false, shiftKey: false };
105β
106 it.each([
107 ["enter", "one line", false, "foreground"],
108 ["enter", "two\nlines", false, "foreground"],
109 ["mod-enter-multiline", "one line", false, "foreground"],
110 ["mod-enter-multiline", "two\nlines", false, null],
111 ["mod-enter-multiline", "two\nlines", true, "foreground"],
112 ["mod-enter", "one line", false, null],
113 ["mod-enter", "one line", true, "foreground"],
114 ] as const)("honors %s for %j", (sendShortcut, prompt, ctrlKey, expected) => {
115 expect(
116 composerSubmissionIntentForKey({
117 ...input,
118 event: { ...enter, ctrlKey },
119 sendShortcut,
120 prompt,
121 }),
122 ).toBe(expected);
123 });
124β
125 it("honors the send preference with an existing install's saved alternate binding", () => {
126 const keybindings = mergeWithDefaultKeybindings(
127 compileResolvedKeybindingsConfig([
128 {
129 key: "mod+enter",
130 command: "composer.sendAlternate",
131 when: "composerFocus && turnRunning",
132 },
133 ]),
134 );
135 const running = { ...input, keybindings, isRunning: true, sendShortcut: "mod-enter" as const };
136 expect(composerSubmissionIntentForKey({ ...running, event: { ...enter, ctrlKey: true } })).toBe(
137 "foreground",
138 );
139 expect(
140 composerSubmissionIntentForKey({
141 ...running,
142 event: { ...enter, ctrlKey: true, shiftKey: true },
143 }),
144 ).toBe("alternate");
145 });
146β
147 it.each(["enter", "mod-enter", "mod-enter-multiline"] as const)(
148 "uses remapped keys and removes the old action bindings with %s",
149 (sendShortcut) => {
150 const keybindings = mergeWithDefaultKeybindings(
151 compileResolvedKeybindingsConfig([
152 {
153 key: "alt+q",
154 command: "composer.sendAlternate",
155 when: "composerFocus && turnRunning",
156 },
157 {
158 key: "alt+b",
159 command: "composer.sendBackground",
160 when: "composerFocus && draftThreadRoute",
161 },
162 ]),
163 );
164 const custom = { ...input, keybindings, sendShortcut, prompt: "two\nlines" };
165 expect(
166 composerSubmissionIntentForKey({
167 ...custom,
168 isRunning: true,
169 event: { ...enter, key: "q", altKey: true },
170 }),
171 ).toBe("alternate");
172 expect(
173 composerSubmissionIntentForKey({
174 ...custom,
175 isDraftThread: true,
176 event: { ...enter, key: "b", altKey: true },
177 }),
178 ).toBe("background");
179 expect(
180 composerSubmissionIntentForKey({
181 ...custom,
182 isRunning: true,
183 event: { ...enter, ctrlKey: true },
184 }),
185 ).toBe("foreground");
186 expect(
187 composerSubmissionIntentForKey({
188 ...custom,
189 isDraftThread: true,
190 event: { ...enter, ctrlKey: true, shiftKey: true },
191 }),
192 ).toBeNull();
193 expect(
194 composerSubmissionIntentForKey({
195 ...custom,
196 isRunning: true,
197 event: { ...enter, ctrlKey: true, shiftKey: true },
198 }),
199 ).toBeNull();
200 expect(
201 composerSubmissionIntentForKey({ ...custom, event: { ...enter, key: "b", altKey: true } }),
202 ).toBeNull();
203 },
204 );
205β
206 it.each(["MacIntel", "Win32", "Linux"])(
207 "keeps modifier submission available with the software keyboard open on %s",
208 (platform) => {
209 const modEnter = {
210 ...enter,
211 metaKey: platform === "MacIntel",
212 ctrlKey: platform !== "MacIntel",
213 };
214 const keyboardOpen = { ...input, platform, isSoftwareKeyboardOpen: true };
215 expect(composerSubmissionIntentForKey({ ...keyboardOpen, event: modEnter })).toBe(
216 "foreground",
217 );
218 expect(
219 composerSubmissionIntentForKey({ ...keyboardOpen, isRunning: true, event: modEnter }),
220 ).toBe("alternate");
221 expect(
222 composerSubmissionIntentForKey({ ...keyboardOpen, isDraftThread: true, event: modEnter }),
223 ).toBe("background");
224 },
225 );
226β
227 it.each([
228 { isSoftwareKeyboardOpen: true },
229 { event: { ...enter, isComposing: true } },
230 { event: { ...enter, keyCode: 229 } },
231 { event: { ...enter, repeat: true } },
232 ])("does not submit with %j", (override) => {
233 expect(composerSubmissionIntentForKey({ ...input, event: enter, ...override })).toBeNull();
234 });
235});
236β
237describe("detectComposerTrigger", () => {
238 it.each([
239 ["Run /tmp/build.sh", "Run /tmp/build.sh".length],
240 ["/etc/hosts", "/etc/hosts".length],
241 ["Use /etc/hosts now", "Use /et".length],
242 ])("keeps the path in %j out of the slash menu", (text, cursor) => {
243 expect(detectComposerTrigger(text, cursor)).toBeNull();
244 });
245β
246 it.each(["Use ", "Use\t", "Use\n "])("detects inline slash skills after %j", (prefix) => {
247 const text = `${prefix}/skill:review later`;
248 const cursor = `${prefix}/skill:review`.length;
249 expect(detectComposerTrigger(text, cursor)).toEqual({
250 kind: "slash-command",
251 query: "skill:review",
252 rangeStart: prefix.length,
253 rangeEnd: cursor,
254 });
255 });
256β
257 it.each(["Use/review", "https://example.com/review", "Use /review "])(
258 "does not trigger for %j",
259 (text) => expect(detectComposerTrigger(text, text.length)).toBeNull(),
260 );
261β
262 it("does not keep a subcommand trigger active after /model arguments", () => {
263 const text = "/model spark";
264 const trigger = detectComposerTrigger(text, text.length);
265β
266 expect(trigger).toBeNull();
267 });
268β
269 it.each([
270 "It costs $5",
271 "budget $9.99",
272 "only $.99",
273 "about β¬20",
274 "raise $10k",
275 "raise $10k.",
276 "is it $5?",
277 ])("does not detect a skill trigger for the amount in %j", (text) => {
278 expect(detectComposerTrigger(text, text.length)).toBeNull();
279 });
280β
281 it("detects a pull request number at a token boundary", () => {
282 const text = "Compare this with #8737";
283β
284 expect(detectComposerTrigger(text, text.length)).toEqual({
285 kind: "pull-request",
286 query: "8737",
287 rangeStart: "Compare this with ".length,
288 rangeEnd: text.length,
289 });
290 });
291β
292 it("does not keep pull request completion active for headings or embedded hashes", () => {
293 expect(detectComposerTrigger("# Heading", "# Heading".length)).toBeNull();
294 expect(detectComposerTrigger("issue#123", "issue#123".length)).toBeNull();
295 });
296β
297 // regression: #936 @file autocomplete used the wrong cursor when typing mid-text
298 it("detects @path trigger in the middle of existing text", () => {
299 const text = "Please inspect @in this sentence";
300 const cursorAfterAt = "Please inspect @".length;
301β
302 const trigger = detectComposerTrigger(text, cursorAfterAt);
303 expect(trigger).toEqual({
304 kind: "path",
305 query: "",
306 rangeStart: "Please inspect ".length,
307 rangeEnd: cursorAfterAt,
308 });
309 });
310});
311β
312describe("filterComposerPullRequestMatches", () => {
313 const entries = [
314 {
315 number: 7,
316 projectId: "project-1",
317 repository: "t3tools/t3code",
318 updatedAt: "2026-09-01T12:00:00.000Z",
319 },
320 {
321 number: 8987,
322 projectId: "project-1",
323 repository: "T3Tools/T3Code",
324 updatedAt: "2026-09-03T12:00:00.000Z",
325 },
326 {
327 number: 27,
328 projectId: "project-1",
329 repository: "t3tools/t3code",
330 updatedAt: "2026-09-02T12:00:00.000Z",
331 },
332 {
333 number: 27,
334 projectId: "project-1",
335 repository: "t3tools/t3code",
336 updatedAt: "2026-09-01T13:00:00.000Z",
337 },
338 {
339 number: 70,
340 projectId: "project-2",
341 repository: "t3tools/other",
342 updatedAt: "2026-09-04T12:00:00.000Z",
343 },
344 ];
345β
346 it("matches and de-duplicates number fragments within one repository, exact match first", () => {
347 expect(
348 filterComposerPullRequestMatches({
349 entries,
350 projectId: "project-1",
351 repository: "t3tools/t3code",
352 query: "7",
353 limit: 10,
354 }).map((entry) => entry.number),
355 ).toEqual([7, 8987, 27]);
356 });
357β
358 it("keeps an older exact match when newer substring matches would fill the limit", () => {
359 const exact = {
360 number: 7,
361 projectId: "project-1",
362 repository: "t3tools/t3code",
363 updatedAt: "2020-01-01T00:00:00.000Z",
364 };
365 const newerSubstringMatches = Array.from({ length: 12 }, (_unused, index) => ({
366 number: 700 + index,
367 projectId: "project-1",
368 repository: "t3tools/t3code",
369 updatedAt: `2026-09-${String(index + 1).padStart(2, "0")}T12:00:00.000Z`,
370 }));
371 const matches = filterComposerPullRequestMatches({
372 entries: [...newerSubstringMatches, exact],
373 projectId: "project-1",
374 repository: "t3tools/t3code",
375 query: "7",
376 limit: 10,
377 });
378 expect(matches[0]?.number).toBe(7);
379 expect(matches).toHaveLength(10);
380 });
381});
382β
383describe("expandCollapsedComposerCursor", () => {
384 it("maps collapsed mention cursor to expanded text cursor", () => {
385 const text = "what's in my @AGENTS.md fsfdas";
386 const collapsedCursorAfterMention = "what's in my ".length + 2;
387 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
388β
389 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
390 expandedCursorAfterMention,
391 );
392 });
393β
394 // regression: #2625 cursor mapping broke for quoted mentions containing spaces
395 it("maps collapsed quoted mention cursor to expanded text cursor", () => {
396 const text = 'what is in @"My File.md" please';
397 const collapsedCursorAfterMention = "what is in ".length + 2;
398 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
399β
400 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
401 expandedCursorAfterMention,
402 );
403 });
404β
405 it("maps collapsed markdown file links to their expanded source offsets", () => {
406 const text = "what's in [AGENTS.md](AGENTS.md) please";
407 const collapsedCursorAfterMention = "what's in ".length + 2;
408 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
409β
410 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
411 expandedCursorAfterMention,
412 );
413 });
414β
415 it("allows path trigger detection to close after selecting a mention", () => {
416 const text = "what's in my @AGENTS.md ";
417 const collapsedCursorAfterMention = "what's in my ".length + 2;
418 const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
419β
420 expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
421 });
422});
423β
424describe("composerStateAtPromptEnd", () => {
425 it("collapses mention chips so the next keystroke lands after the draft", () => {
426 const prompt = carryDisplacedCustomAnswerIntoPrompt("", "see @AGENTS.md please");
427β
428 expect(composerStateAtPromptEnd(prompt).cursor).toBe("see ".length + 1 + " please".length);
429 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(0);
430 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(prompt.length);
431 });
432β
433 it("keeps a trailing mention trigger when the restored draft ends with @", () => {
434 const prompt = "look at @";
435β
436 expect(composerStateAtPromptEnd(prompt)).toEqual({
437 cursor: prompt.length,
438 trigger: { kind: "path", query: "", rangeStart: "look at ".length, rangeEnd: prompt.length },
439 });
440 });
441});
442β
443describe("collapseExpandedComposerCursor", () => {
444 it("keeps package-like text expanded when another mention already exists earlier", () => {
445 const text = "open @AGENTS.md then @src/index.ts ";
446 const expandedCursor = text.length;
447 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
448β
449 expect(collapsedCursor).toBe("open ".length + 1 + " then @src/index.ts ".length);
450 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
451 });
452});
453β
454it("preserves the caret before trailing text after mixed-width skill chips", () => {
455 const text = "πΏui a $review tail";
456 const expanded = "πΏui a $review ".length;
457 expect(collapseExpandedComposerCursor(text, expanded)).toBe(6);
458 expect(expandCollapsedComposerCursor(text, 6)).toBe(expanded);
459});
460β
461describe("assistant citation cursor offsets", () => {
462 it("roundtrips every collapsed offset across citations, mentions, skills, and Unicode", () => {
463 const prefix = "π(";
464 const between = "),ιͺ";
465 const after = " @AGENTS.md $review ";
466 const text = `${prefix}${citationSource}${between}${citationSource}${after}${terminalReference}!`;
467 const collapsedLength = `${prefix}β‘${between}β‘ β‘ β‘ β‘!`.length;
468 const boundaries = [
469 [prefix.length, prefix.length],
470 [prefix.length + 1, prefix.length + citationSource.length],
471 [prefix.length + 1 + between.length, prefix.length + citationSource.length + between.length],
472 [
473 prefix.length + 2 + between.length,
474 prefix.length + citationSource.length * 2 + between.length,
475 ],
476 [collapsedLength, text.length],
477 ] as const;
478β
479 for (const [collapsed, expanded] of boundaries) {
480 expect(expandCollapsedComposerCursor(text, collapsed)).toBe(expanded);
481 expect(collapseExpandedComposerCursor(text, expanded)).toBe(collapsed);
482 }
483 for (let cursor = 0; cursor <= collapsedLength; cursor += 1) {
484 expect(
485 collapseExpandedComposerCursor(text, expandCollapsedComposerCursor(text, cursor)),
486 ).toBe(cursor);
487 }
488 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(collapsedLength);
489 });
490β
491 it("snaps serialized offsets inside a citation to the end of its chip", () => {
492 const prefix = "επ";
493 const text = `${prefix}${citationSource}.`;
494β
495 for (const offset of [1, citationSource.length - 1, citationSource.length]) {
496 expect(collapseExpandedComposerCursor(text, prefix.length + offset)).toBe(prefix.length + 1);
497 }
498 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length, "right")).toBe(true);
499 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length + 1, "left")).toBe(true);
500 expect(isCollapsedCursorAdjacentToInlineToken(text, prefix.length + 2, "left")).toBe(false);
501 });
502β
503 it("deletes one collapsed citation without changing its neighbor or surrounding punctuation", () => {
504 const text = `(${citationSource}),${citationSource}!`;
505 const result = replaceTextRange(
506 text,
507 expandCollapsedComposerCursor(text, 1),
508 expandCollapsedComposerCursor(text, 2),
509 "",
510 );
511β
512 expect(result).toEqual({ text: `(),${citationSource}!`, cursor: 1 });
513 expect(collapseExpandedComposerCursor(result.text, result.text.length)).toBe("(),β‘!".length);
514 });
515});
516β
517describe("isCollapsedCursorAdjacentToInlineToken", () => {
518 it("detects left adjacency only when cursor is directly after a mention", () => {
519 const text = "open @AGENTS.md next";
520 const mentionStart = "open ".length;
521 const mentionEnd = mentionStart + 1;
522β
523 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
524 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
525 expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
526 });
527β
528 it("treats context reference pills as inline tokens for adjacency checks", () => {
529 const text = `open ${terminalReference} next`;
530 const tokenStart = "open ".length;
531 const tokenEnd = tokenStart + 1;
532β
533 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
534 expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
535 });
536});
537β
538describe("literal editor answer cursor state", () => {
539 const prefill = "- [X] done $my-skill ";
540β
541 it("keeps character positions after token-like text for inserted lines and replacements", () => {
542 for (const replacement of ["\n", "\t", "edited\n "]) {
543 const next = replaceTextRange(prefill, prefill.length, prefill.length, replacement);
544 const cursor = collapseExpandedComposerCursor(next.text, next.cursor, true);
545 expect(next.text).toBe(prefill + replacement);
546 expect(cursor).toBe(next.text.length);
547 expect(expandCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
548 expect(clampCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
549 }
550 const replaced = replaceTextRange(prefill, 11, 20, "$another-skill");
551 const cursor = collapseExpandedComposerCursor(replaced.text, replaced.cursor, true);
552 expect(replaced.text).toBe("- [X] done $another-skill ");
553 expect(cursor).toBe(25);
554 expect(expandCollapsedComposerCursor(replaced.text, cursor, true)).toBe(25);
555 });
556β
557 it("does not open a skill or path menu when restoring an editor answer", () => {
558 for (const value of ["- [X] done $my-skill", "Use @README", ""]) {
559 expect(composerStateAtPromptEnd(value, true)).toEqual({
560 cursor: value.length,
561 trigger: null,
562 });
563 }
564 expect(composerStateAtPromptEnd("Use $my").trigger?.kind).toBe("skill");
565 });
566});
567β
568describe("extendReplacementRangeForTrailingSpace", () => {
569 it("swallows one existing space after the range when the replacement ends with one", () => {
570 expect(extendReplacementRangeForTrailingSpace("@fi rest", 3, "@file ")).toBe(4);
571 expect(extendReplacementRangeForTrailingSpace("@firest", 3, "@file ")).toBe(3);
572 expect(extendReplacementRangeForTrailingSpace("@fi rest", 3, "@file")).toBe(3);
573 expect(extendReplacementRangeForTrailingSpace("@fi", 3, "@file ")).toBe(3);
574 });
575});