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

composer-logic.test.ts

627 lines21.9 KB

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