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

composer-logic.test.ts

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