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

composer-logic.test.ts

550 lines19.3 KB

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 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.each([
269 "It costs $5",
270 "budget $9.99",
271 "only $.99",
272 "about €20",
273 "raise $10k",
274 "raise $10k.",
275 "is it $5?",
276 ])("does not detect a skill trigger for the amount in %j", (text) => {
277 expect(detectComposerTrigger(text, text.length)).toBeNull();
278 });
279​
280 it("detects a pull request number at a token boundary", () => {
281 const text = "Compare this with #8737";
282​
283 expect(detectComposerTrigger(text, text.length)).toEqual({
284 kind: "pull-request",
285 query: "8737",
286 rangeStart: "Compare this with ".length,
287 rangeEnd: text.length,
288 });
289 });
290​
291 it("does not keep pull request completion active for headings or embedded hashes", () => {
292 expect(detectComposerTrigger("# Heading", "# Heading".length)).toBeNull();
293 expect(detectComposerTrigger("issue#123", "issue#123".length)).toBeNull();
294 });
295​
296 // regression: #936 @file autocomplete used the wrong cursor when typing mid-text
297 it("detects @path trigger in the middle of existing text", () => {
298 const text = "Please inspect @in this sentence";
299 const cursorAfterAt = "Please inspect @".length;
300​
301 const trigger = detectComposerTrigger(text, cursorAfterAt);
302 expect(trigger).toEqual({
303 kind: "path",
304 query: "",
305 rangeStart: "Please inspect ".length,
306 rangeEnd: cursorAfterAt,
307 });
308 });
309});
310​
311describe("filterComposerPullRequestMatches", () => {
312 const entries = [
313 {
314 number: 7,
315 projectId: "project-1",
316 repository: "t3tools/t3code",
317 updatedAt: "2026-09-01T12:00:00.000Z",
318 },
319 {
320 number: 8987,
321 projectId: "project-1",
322 repository: "T3Tools/T3Code",
323 updatedAt: "2026-09-03T12:00:00.000Z",
324 },
325 {
326 number: 27,
327 projectId: "project-1",
328 repository: "t3tools/t3code",
329 updatedAt: "2026-09-02T12:00:00.000Z",
330 },
331 {
332 number: 27,
333 projectId: "project-1",
334 repository: "t3tools/t3code",
335 updatedAt: "2026-09-01T13:00:00.000Z",
336 },
337 {
338 number: 70,
339 projectId: "project-2",
340 repository: "t3tools/other",
341 updatedAt: "2026-09-04T12:00:00.000Z",
342 },
343 ];
344​
345 it("matches and de-duplicates number fragments within one repository, exact match first", () => {
346 expect(
347 filterComposerPullRequestMatches({
348 entries,
349 projectId: "project-1",
350 repository: "t3tools/t3code",
351 query: "7",
352 limit: 10,
353 }).map((entry) => entry.number),
354 ).toEqual([7, 8987, 27]);
355 });
356​
357 it("keeps an older exact match when newer substring matches would fill the limit", () => {
358 const exact = {
359 number: 7,
360 projectId: "project-1",
361 repository: "t3tools/t3code",
362 updatedAt: "2020-01-01T00:00:00.000Z",
363 };
364 const newerSubstringMatches = Array.from({ length: 12 }, (_unused, index) => ({
365 number: 700 + index,
366 projectId: "project-1",
367 repository: "t3tools/t3code",
368 updatedAt: `2026-09-${String(index + 1).padStart(2, "0")}T12:00:00.000Z`,
369 }));
370 const matches = filterComposerPullRequestMatches({
371 entries: [...newerSubstringMatches, exact],
372 projectId: "project-1",
373 repository: "t3tools/t3code",
374 query: "7",
375 limit: 10,
376 });
377 expect(matches[0]?.number).toBe(7);
378 expect(matches).toHaveLength(10);
379 });
380});
381​
382describe("expandCollapsedComposerCursor", () => {
383 it("maps collapsed mention cursor to expanded text cursor", () => {
384 const text = "what's in my @AGENTS.md fsfdas";
385 const collapsedCursorAfterMention = "what's in my ".length + 2;
386 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
387​
388 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
389 expandedCursorAfterMention,
390 );
391 });
392​
393 // regression: #2625 cursor mapping broke for quoted mentions containing spaces
394 it("maps collapsed quoted mention cursor to expanded text cursor", () => {
395 const text = 'what is in @"My File.md" please';
396 const collapsedCursorAfterMention = "what is in ".length + 2;
397 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
398​
399 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
400 expandedCursorAfterMention,
401 );
402 });
403​
404 it("maps collapsed markdown file links to their expanded source offsets", () => {
405 const text = "what's in [AGENTS.md](AGENTS.md) please";
406 const collapsedCursorAfterMention = "what's in ".length + 2;
407 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
408​
409 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
410 expandedCursorAfterMention,
411 );
412 });
413​
414 it("allows path trigger detection to close after selecting a mention", () => {
415 const text = "what's in my @AGENTS.md ";
416 const collapsedCursorAfterMention = "what's in my ".length + 2;
417 const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
418​
419 expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
420 });
421});
422​
423describe("composerStateAtPromptEnd", () => {
424 it("collapses mention chips so the next keystroke lands after the draft", () => {
425 const prompt = carryDisplacedCustomAnswerIntoPrompt("", "see @AGENTS.md please");
426​
427 expect(composerStateAtPromptEnd(prompt).cursor).toBe("see ".length + 1 + " please".length);
428 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(0);
429 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(prompt.length);
430 });
431​
432 it("keeps a trailing mention trigger when the restored draft ends with @", () => {
433 const prompt = "look at @";
434​
435 expect(composerStateAtPromptEnd(prompt)).toEqual({
436 cursor: prompt.length,
437 trigger: { kind: "path", query: "", rangeStart: "look at ".length, rangeEnd: prompt.length },
438 });
439 });
440});
441​
442describe("collapseExpandedComposerCursor", () => {
443 it("keeps package-like text expanded when another mention already exists earlier", () => {
444 const text = "open @AGENTS.md then @src/index.ts ";
445 const expandedCursor = text.length;
446 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
447​
448 expect(collapsedCursor).toBe("open ".length + 1 + " then @src/index.ts ".length);
449 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
450 });
451});
452​
453it("preserves the caret before trailing text after mixed-width skill chips", () => {
454 const text = "𑿝ui a $review tail";
455 const expanded = "𑿝ui a $review ".length;
456 expect(collapseExpandedComposerCursor(text, expanded)).toBe(6);
457 expect(expandCollapsedComposerCursor(text, 6)).toBe(expanded);
458});
459​
460describe("assistant citation cursor offsets", () => {
461 it("roundtrips every collapsed offset across citations, mentions, skills, and Unicode", () => {
462 const prefix = "πŸ‘‹(";
463 const between = "),ι›ͺ";
464 const after = " @AGENTS.md $review ";
465 const text = `${prefix}${citationSource}${between}${citationSource}${after}${terminalReference}!`;
466 const collapsedLength = `${prefix}β–‘${between}β–‘ β–‘ β–‘ β–‘!`.length;
467 const boundaries = [
468 [prefix.length, prefix.length],
469 [prefix.length + 1, prefix.length + citationSource.length],
470 [prefix.length + 1 + between.length, prefix.length + citationSource.length + between.length],
471 [
472 prefix.length + 2 + between.length,
473 prefix.length + citationSource.length * 2 + between.length,
474 ],
475 [collapsedLength, text.length],
476 ] as const;
477​
478 for (const [collapsed, expanded] of boundaries) {
479 expect(expandCollapsedComposerCursor(text, collapsed)).toBe(expanded);
480 expect(collapseExpandedComposerCursor(text, expanded)).toBe(collapsed);
481 }
482 for (let cursor = 0; cursor <= collapsedLength; cursor += 1) {
483 expect(
484 collapseExpandedComposerCursor(text, expandCollapsedComposerCursor(text, cursor)),
485 ).toBe(cursor);
486 }
487 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(collapsedLength);
488 });
489​
490 it("snaps serialized offsets inside a citation to the end of its chip", () => {
491 const prefix = "ε‰πŸ‘‹";
492 const text = `${prefix}${citationSource}.`;
493​
494 for (const offset of [1, citationSource.length - 1, citationSource.length]) {
495 expect(collapseExpandedComposerCursor(text, prefix.length + offset)).toBe(prefix.length + 1);
496 }
497 });
498​
499 it("deletes one collapsed citation without changing its neighbor or surrounding punctuation", () => {
500 const text = `(${citationSource}),${citationSource}!`;
501 const result = replaceTextRange(
502 text,
503 expandCollapsedComposerCursor(text, 1),
504 expandCollapsedComposerCursor(text, 2),
505 "",
506 );
507​
508 expect(result).toEqual({ text: `(),${citationSource}!`, cursor: 1 });
509 expect(collapseExpandedComposerCursor(result.text, result.text.length)).toBe("(),β–‘!".length);
510 });
511});
512​
513describe("literal editor answer cursor state", () => {
514 const prefill = "- [X] done $my-skill ";
515​
516 it("keeps character positions after token-like text for inserted lines and replacements", () => {
517 for (const replacement of ["\n", "\t", "edited\n "]) {
518 const next = replaceTextRange(prefill, prefill.length, prefill.length, replacement);
519 const cursor = collapseExpandedComposerCursor(next.text, next.cursor, true);
520 expect(next.text).toBe(prefill + replacement);
521 expect(cursor).toBe(next.text.length);
522 expect(expandCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
523 expect(clampCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
524 }
525 const replaced = replaceTextRange(prefill, 11, 20, "$another-skill");
526 const cursor = collapseExpandedComposerCursor(replaced.text, replaced.cursor, true);
527 expect(replaced.text).toBe("- [X] done $another-skill ");
528 expect(cursor).toBe(25);
529 expect(expandCollapsedComposerCursor(replaced.text, cursor, true)).toBe(25);
530 });
531​
532 it("does not open a skill or path menu when restoring an editor answer", () => {
533 for (const value of ["- [X] done $my-skill", "Use @README", ""]) {
534 expect(composerStateAtPromptEnd(value, true)).toEqual({
535 cursor: value.length,
536 trigger: null,
537 });
538 }
539 expect(composerStateAtPromptEnd("Use $my").trigger?.kind).toBe("skill");
540 });
541});
542​
543describe("extendReplacementRangeForTrailingSpace", () => {
544 it("swallows one existing space after the range when the replacement ends with one", () => {
545 expect(extendReplacementRangeForTrailingSpace("@fi rest", 3, "@file ")).toBe(4);
546 expect(extendReplacementRangeForTrailingSpace("@firest", 3, "@file ")).toBe(3);
547 expect(extendReplacementRangeForTrailingSpace("@fi rest", 3, "@file")).toBe(3);
548 expect(extendReplacementRangeForTrailingSpace("@fi", 3, "@file ")).toBe(3);
549 });
550});