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

composer-logic.test.ts

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