The best way to control Claude Code, Codex and more from any computer or phone

main
ts 609 lines 21.3 KB
Raw
1 import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests";
2 import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
3 import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
4 import {
5 collectAssistantCitations,
6 expandAssistantCitationsForProvider,
7 serializeAssistantCitation,
8 } from "@t3tools/shared/assistantCitations";
9 import {
10 DEFAULT_RESOLVED_KEYBINDINGS,
11 compileResolvedKeybindingsConfig,
12 mergeWithDefaultKeybindings,
13 } from "@t3tools/shared/keybindings";
14 import { describe, expect, it } from "vite-plus/test";
15
16 import {
17 clampCollapsedComposerCursor,
18 collapseExpandedComposerCursor,
19 composerSubmissionIntentForKey,
20 composerStateAtPromptEnd,
21 detectComposerTrigger,
22 expandCollapsedComposerCursor,
23 extendReplacementRangeForTrailingSpace,
24 formatAssistantCitationForComposer,
25 isPathSuggestionCurrent,
26 replaceTextRange,
27 } from "./composer-logic";
28 import { slashCommandItemsForPromptPosition } from "./components/chat/composerSlashCommandSearch";
29 import { carryDisplacedCustomAnswerIntoPrompt } from "./pendingUserInput";
30 import { formatTerminalContextReference } from "./lib/terminalContext";
31
32 const terminalReference = formatTerminalContextReference({
33 id: "ctx-1",
34 terminalLabel: "Terminal 1",
35 lineStart: 3,
36 lineEnd: 4,
37 });
38
39 const 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 };
50 const citationSource = serializeAssistantCitation(citation).replaceAll("+", "%20");
51
52 describe("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
87 describe("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
98 describe("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
271 describe("detectComposerTrigger", () => {
272 it.each([
273 ["Run /tmp/build.sh", "Run /tmp/build.sh".length],
274 ["/etc/hosts", "/etc/hosts".length],
275 ["Use /etc/hosts now", "Use /et".length],
276 ])("keeps the path in %j out of the slash menu", (text, cursor) => {
277 expect(detectComposerTrigger(text, cursor)).toBeNull();
278 });
279
280 it.each(["Use ", "Use\t", "Use\n "])("detects inline slash skills after %j", (prefix) => {
281 const text = `${prefix}/skill:review later`;
282 const cursor = `${prefix}/skill:review`.length;
283 expect(detectComposerTrigger(text, cursor)).toEqual({
284 kind: "slash-command",
285 query: "skill:review",
286 rangeStart: prefix.length,
287 rangeEnd: cursor,
288 });
289 });
290
291 it.each(["Use/review", "https://example.com/review", "Use /review "])(
292 "does not trigger for %j",
293 (text) => expect(detectComposerTrigger(text, text.length)).toBeNull(),
294 );
295
296 it("does not keep a subcommand trigger active after /model arguments", () => {
297 const text = "/model spark";
298 const trigger = detectComposerTrigger(text, text.length);
299
300 expect(trigger).toBeNull();
301 });
302
303 it.each([
304 "It costs $5",
305 "budget $9.99",
306 "only $.99",
307 "about €20",
308 "raise $10k",
309 "raise $10k.",
310 "is it $5?",
311 ])("does not detect a skill trigger for the amount in %j", (text) => {
312 expect(detectComposerTrigger(text, text.length)).toBeNull();
313 });
314
315 it("detects a pull request number at a token boundary", () => {
316 const text = "Compare this with #8737";
317
318 expect(detectComposerTrigger(text, text.length)).toEqual({
319 kind: "pull-request",
320 query: "8737",
321 rangeStart: "Compare this with ".length,
322 rangeEnd: text.length,
323 });
324 });
325
326 it("does not keep pull request completion active for headings or embedded hashes", () => {
327 expect(detectComposerTrigger("# Heading", "# Heading".length)).toBeNull();
328 expect(detectComposerTrigger("issue#123", "issue#123".length)).toBeNull();
329 });
330
331 // regression: #936 @file autocomplete used the wrong cursor when typing mid-text
332 it("detects @path trigger in the middle of existing text", () => {
333 const text = "Please inspect @in this sentence";
334 const cursorAfterAt = "Please inspect @".length;
335
336 const trigger = detectComposerTrigger(text, cursorAfterAt);
337 expect(trigger).toEqual({
338 kind: "path",
339 query: "",
340 rangeStart: "Please inspect ".length,
341 rangeEnd: cursorAfterAt,
342 });
343 });
344 });
345
346 describe("filterComposerPullRequestMatches", () => {
347 const entries = [
348 {
349 host: "github.com",
350 number: 7,
351 projectId: "project-1",
352 repository: "t3tools/t3code",
353 updatedAt: "2026-09-01T12:00:00.000Z",
354 },
355 {
356 host: "github.com",
357 number: 8987,
358 projectId: "project-1",
359 repository: "T3Tools/T3Code",
360 updatedAt: "2026-09-03T12:00:00.000Z",
361 },
362 {
363 host: "github.com",
364 number: 27,
365 projectId: "project-1",
366 repository: "t3tools/t3code",
367 updatedAt: "2026-09-02T12:00:00.000Z",
368 },
369 {
370 host: "github.com",
371 number: 27,
372 projectId: "project-1",
373 repository: "t3tools/t3code",
374 updatedAt: "2026-09-01T13:00:00.000Z",
375 },
376 {
377 host: "github.com",
378 number: 70,
379 projectId: "project-2",
380 repository: "t3tools/other",
381 updatedAt: "2026-09-04T12:00:00.000Z",
382 },
383 ];
384
385 it("matches and de-duplicates number fragments within one repository, exact match first", () => {
386 expect(
387 filterComposerPullRequestMatches({
388 keyOf: threadPullRequestKeyOf,
389 entries,
390 projectId: "project-1",
391 repository: "t3tools/t3code",
392 query: "7",
393 limit: 10,
394 }).map((entry) => entry.number),
395 ).toEqual([7, 8987, 27]);
396 });
397
398 it("keeps an older exact match when newer substring matches would fill the limit", () => {
399 const exact = {
400 host: "github.com",
401 number: 7,
402 projectId: "project-1",
403 repository: "t3tools/t3code",
404 updatedAt: "2020-01-01T00:00:00.000Z",
405 };
406 const newerSubstringMatches = Array.from({ length: 12 }, (_unused, index) => ({
407 host: "github.com",
408 number: 700 + index,
409 projectId: "project-1",
410 repository: "t3tools/t3code",
411 updatedAt: `2026-09-${String(index + 1).padStart(2, "0")}T12:00:00.000Z`,
412 }));
413 const matches = filterComposerPullRequestMatches({
414 keyOf: threadPullRequestKeyOf,
415 entries: [...newerSubstringMatches, exact],
416 projectId: "project-1",
417 repository: "t3tools/t3code",
418 query: "7",
419 limit: 10,
420 });
421 expect(matches[0]?.number).toBe(7);
422 expect(matches).toHaveLength(10);
423 });
424 });
425
426 describe("expandCollapsedComposerCursor", () => {
427 it("maps collapsed mention cursor to expanded text cursor", () => {
428 const text = "what's in my @AGENTS.md fsfdas";
429 const collapsedCursorAfterMention = "what's in my ".length + 2;
430 const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
431
432 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
433 expandedCursorAfterMention,
434 );
435 });
436
437 // regression: #2625 cursor mapping broke for quoted mentions containing spaces
438 it("maps collapsed quoted mention cursor to expanded text cursor", () => {
439 const text = 'what is in @"My File.md" please';
440 const collapsedCursorAfterMention = "what is in ".length + 2;
441 const expandedCursorAfterMention = 'what is in @"My File.md" '.length;
442
443 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
444 expandedCursorAfterMention,
445 );
446 });
447
448 it("maps collapsed markdown file links to their expanded source offsets", () => {
449 const text = "what's in [AGENTS.md](AGENTS.md) please";
450 const collapsedCursorAfterMention = "what's in ".length + 2;
451 const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
452
453 expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
454 expandedCursorAfterMention,
455 );
456 });
457
458 it("allows path trigger detection to close after selecting a mention", () => {
459 const text = "what's in my @AGENTS.md ";
460 const collapsedCursorAfterMention = "what's in my ".length + 2;
461 const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
462
463 expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
464 });
465 });
466
467 describe("composerStateAtPromptEnd", () => {
468 it("collapses mention chips so the next keystroke lands after the draft", () => {
469 const prompt = carryDisplacedCustomAnswerIntoPrompt("", "see @AGENTS.md please");
470
471 expect(composerStateAtPromptEnd(prompt).cursor).toBe("see ".length + 1 + " please".length);
472 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(0);
473 expect(composerStateAtPromptEnd(prompt).cursor).not.toBe(prompt.length);
474 });
475
476 it("keeps a trailing mention trigger when the restored draft ends with @", () => {
477 const prompt = "look at @";
478
479 expect(composerStateAtPromptEnd(prompt)).toEqual({
480 cursor: prompt.length,
481 trigger: { kind: "path", query: "", rangeStart: "look at ".length, rangeEnd: prompt.length },
482 });
483 });
484 });
485
486 describe("collapseExpandedComposerCursor", () => {
487 it("keeps package-like text expanded when another mention already exists earlier", () => {
488 const text = "open @AGENTS.md then @src/index.ts ";
489 const expandedCursor = text.length;
490 const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor);
491
492 expect(collapsedCursor).toBe("open ".length + 1 + " then @src/index.ts ".length);
493 expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor);
494 });
495 });
496
497 it("preserves the caret before trailing text after mixed-width skill chips", () => {
498 const text = "𑿝ui a $review tail";
499 const expanded = "𑿝ui a $review ".length;
500 expect(collapseExpandedComposerCursor(text, expanded)).toBe(6);
501 expect(expandCollapsedComposerCursor(text, 6)).toBe(expanded);
502 });
503
504 describe("assistant citation cursor offsets", () => {
505 it("roundtrips every collapsed offset across citations, mentions, skills, and Unicode", () => {
506 const prefix = "👋(";
507 const between = "),雪";
508 const after = " @AGENTS.md $review ";
509 const text = `${prefix}${citationSource}${between}${citationSource}${after}${terminalReference}!`;
510 const collapsedLength = `${prefix}□${between}□ □ □ □!`.length;
511 const boundaries = [
512 [prefix.length, prefix.length],
513 [prefix.length + 1, prefix.length + citationSource.length],
514 [prefix.length + 1 + between.length, prefix.length + citationSource.length + between.length],
515 [
516 prefix.length + 2 + between.length,
517 prefix.length + citationSource.length * 2 + between.length,
518 ],
519 [collapsedLength, text.length],
520 ] as const;
521
522 for (const [collapsed, expanded] of boundaries) {
523 expect(expandCollapsedComposerCursor(text, collapsed)).toBe(expanded);
524 expect(collapseExpandedComposerCursor(text, expanded)).toBe(collapsed);
525 }
526 for (let cursor = 0; cursor <= collapsedLength; cursor += 1) {
527 expect(
528 collapseExpandedComposerCursor(text, expandCollapsedComposerCursor(text, cursor)),
529 ).toBe(cursor);
530 }
531 expect(clampCollapsedComposerCursor(text, Number.POSITIVE_INFINITY)).toBe(collapsedLength);
532 });
533
534 it("snaps serialized offsets inside a citation to the end of its chip", () => {
535 const prefix = "前👋";
536 const text = `${prefix}${citationSource}.`;
537
538 for (const offset of [1, citationSource.length - 1, citationSource.length]) {
539 expect(collapseExpandedComposerCursor(text, prefix.length + offset)).toBe(prefix.length + 1);
540 }
541 });
542
543 it("deletes one collapsed citation without changing its neighbor or surrounding punctuation", () => {
544 const text = `(${citationSource}),${citationSource}!`;
545 const result = replaceTextRange(
546 text,
547 expandCollapsedComposerCursor(text, 1),
548 expandCollapsedComposerCursor(text, 2),
549 "",
550 );
551
552 expect(result).toEqual({ text: `(),${citationSource}!`, cursor: 1 });
553 expect(collapseExpandedComposerCursor(result.text, result.text.length)).toBe("(),□!".length);
554 });
555 });
556
557 describe("literal editor answer cursor state", () => {
558 const prefill = "- [X] done $my-skill ";
559
560 it("keeps character positions after token-like text for inserted lines and replacements", () => {
561 for (const replacement of ["\n", "\t", "edited\n "]) {
562 const next = replaceTextRange(prefill, prefill.length, prefill.length, replacement);
563 const cursor = collapseExpandedComposerCursor(next.text, next.cursor, true);
564 expect(next.text).toBe(prefill + replacement);
565 expect(cursor).toBe(next.text.length);
566 expect(expandCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
567 expect(clampCollapsedComposerCursor(next.text, cursor, true)).toBe(next.cursor);
568 }
569 const replaced = replaceTextRange(prefill, 11, 20, "$another-skill");
570 const cursor = collapseExpandedComposerCursor(replaced.text, replaced.cursor, true);
571 expect(replaced.text).toBe("- [X] done $another-skill ");
572 expect(cursor).toBe(25);
573 expect(expandCollapsedComposerCursor(replaced.text, cursor, true)).toBe(25);
574 });
575
576 it("does not open a skill or path menu when restoring an editor answer", () => {
577 for (const value of ["- [X] done $my-skill", "Use @README", ""]) {
578 expect(composerStateAtPromptEnd(value, true)).toEqual({
579 cursor: value.length,
580 trigger: null,
581 });
582 }
583 expect(composerStateAtPromptEnd("Use $my").trigger?.kind).toBe("skill");
584 });
585 });
586
587 describe("extendReplacementRangeForTrailingSpace", () => {
588 it("swallows one existing space after the range when the replacement ends with one", () => {
589 expect(extendReplacementRangeForTrailingSpace("@fi rest", 3, "@file ")).toBe(4);
590 expect(extendReplacementRangeForTrailingSpace("@firest", 3, "@file ")).toBe(3);
591 expect(extendReplacementRangeForTrailingSpace("@fi rest", 3, "@file")).toBe(3);
592 expect(extendReplacementRangeForTrailingSpace("@fi", 3, "@file ")).toBe(3);
593 });
594 });
595
596 describe("side chat slash commands", () => {
597 it("are not offered after the start of a message", () => {
598 const items = (["side", "btw", "clear", "model"] as const).map((command) => ({
599 id: `slash:${command}`,
600 type: "slash-command" as const,
601 command,
602 label: `/${command}`,
603 description: "",
604 }));
605 expect(slashCommandItemsForPromptPosition(items, false).map((item) => item.id)).toEqual([
606 "slash:model",
607 ]);
608 });
609 });