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