Open History to see the last commit
1import type { ClientSettings } from "@t3tools/contracts/settings";
2import type {
3 AssistantCitation,
4 EnvironmentId,
5 ResolvedKeybindingsConfig,
6} from "@t3tools/contracts";
7import type { ComposerPathSearchTarget } from "@t3tools/client-runtime/state/threads";
8import {
9 serializeAssistantCitation,
10 withAssistantCitationComment,
11} from "@t3tools/shared/assistantCitations";
12import { isPathWord } from "@t3tools/shared/composerTrigger";
13import {
14 splitPromptIntoComposerSegments,
15 type ComposerPromptSegment,
16} from "./composer-editor-mentions";
17
18import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings";
19
20export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
21export type ComposerSlashCommand = "model" | "plan" | "default";
22export type ComposerSubmissionIntent = "foreground" | "background" | "alternate";
23
24export interface ComposerTrigger {
25 kind: ComposerTriggerKind;
26 query: string;
27 rangeStart: number;
28 rangeEnd: number;
29}
30
31export function isPathSuggestionCurrent(
32 searchTarget: ComposerPathSearchTarget,
33 trigger: ComposerTrigger | null,
34 environmentId: EnvironmentId | null,
35 cwd: string | null,
36) {
37 return (
38 trigger?.kind === "path" &&
39 searchTarget.environmentId === environmentId &&
40 searchTarget.cwd === cwd &&
41 searchTarget.query === trigger.query.trim()
42 );
43}
44
45export function formatAssistantCitationForComposer(citation: AssistantCitation, comment = "") {
46 return `${serializeAssistantCitation(withAssistantCitationComment(citation, comment))} `;
47}
48
49export function composerRequiresModifier(
50 sendShortcut: ClientSettings["sendShortcut"] | undefined,
51 prompt: string,
52) {
53 return (
54 sendShortcut === "mod-enter" ||
55 (sendShortcut === "mod-enter-multiline" && /[\r\n]/.test(prompt))
56 );
57}
58
59export function composerSubmissionIntentForKey(input: {
60 event: ShortcutEventLike & { isComposing?: boolean; keyCode?: number; repeat?: boolean };
61 keybindings: ResolvedKeybindingsConfig;
62 platform?: string;
63 isSoftwareKeyboardOpen: boolean;
64 isDraftThread: boolean;
65 isRunning?: boolean;
66 sendShortcut?: ClientSettings["sendShortcut"];
67 prompt?: string;
68}): ComposerSubmissionIntent | null {
69 const { event } = input;
70 if (event.isComposing || event.keyCode === 229 || event.repeat) return null;
71 if (input.isSoftwareKeyboardOpen && event.key === "Enter" && !event.metaKey && !event.ctrlKey)
72 return null;
73 const command = resolveShortcutCommand(event, input.keybindings, {
74 ...(input.platform === undefined ? {} : { platform: input.platform }),
75 context: {
76 composerFocus: true,
77 draftThreadRoute: input.isDraftThread,
78 turnRunning: input.isRunning === true,
79 composerRequiresModifier: composerRequiresModifier(input.sendShortcut, input.prompt ?? ""),
80 },
81 });
82 if (command === "composer.sendAlternate" && input.isRunning) return "alternate";
83 if (command === "composer.sendBackground" && input.isDraftThread) return "background";
84 if (command === "composer.sendAndNewThread" && !input.isDraftThread) return "background";
85 if (command !== null || event.key !== "Enter" || event.shiftKey || event.altKey) return null;
86 if (
87 composerRequiresModifier(input.sendShortcut, input.prompt ?? "") &&
88 !event.metaKey &&
89 !event.ctrlKey
90 )
91 return null;
92 return "foreground";
93}
94
95const isInlineTokenSegment = (segment: ComposerPromptSegment): boolean => segment.type !== "text";
96
97function clampCursor(text: string, cursor: number): number {
98 if (!Number.isFinite(cursor)) return text.length;
99 return Math.max(0, Math.min(text.length, Math.floor(cursor)));
100}
101
102function isWhitespace(char: string): boolean {
103 return char === " " || char === "\n" || char === "\t" || char === "\r";
104}
105
106function tokenStartForCursor(text: string, cursor: number): number {
107 let index = cursor - 1;
108 while (index >= 0 && !isWhitespace(text[index] ?? "")) {
109 index -= 1;
110 }
111 return index + 1;
112}
113
114export function expandCollapsedComposerCursor(
115 text: string,
116 cursorInput: number,
117 literalText = false,
118): number {
119 if (literalText) return clampCursor(text, cursorInput);
120 const collapsedCursor = clampCursor(text, cursorInput);
121 const segments = splitPromptIntoComposerSegments(text);
122 if (segments.length === 0) {
123 return collapsedCursor;
124 }
125
126 let remaining = collapsedCursor;
127 let expandedCursor = 0;
128
129 for (const segment of segments) {
130 if (
131 segment.type === "mention" ||
132 segment.type === "citation" ||
133 segment.type === "context-reference"
134 ) {
135 const expandedLength = segment.source.length;
136 if (remaining <= 1) {
137 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
138 }
139 remaining -= 1;
140 expandedCursor += expandedLength;
141 continue;
142 }
143 if (segment.type === "skill") {
144 const expandedLength = segment.source.length;
145 if (remaining <= 1) {
146 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
147 }
148 remaining -= 1;
149 expandedCursor += expandedLength;
150 continue;
151 }
152
153 const segmentLength = segment.text.length;
154 if (remaining <= segmentLength) {
155 return expandedCursor + remaining;
156 }
157 remaining -= segmentLength;
158 expandedCursor += segmentLength;
159 }
160
161 return expandedCursor;
162}
163
164function collapsedSegmentLength(segment: ComposerPromptSegment): number {
165 if (segment.type === "text") {
166 return segment.text.length;
167 }
168 return 1;
169}
170
171function clampCollapsedComposerCursorForSegments(
172 segments: ReadonlyArray<ComposerPromptSegment>,
173 cursorInput: number,
174): number {
175 const collapsedLength = segments.reduce(
176 (total, segment) => total + collapsedSegmentLength(segment),
177 0,
178 );
179 if (!Number.isFinite(cursorInput)) {
180 return collapsedLength;
181 }
182 return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
183}
184
185export function clampCollapsedComposerCursor(
186 text: string,
187 cursorInput: number,
188 literalText = false,
189): number {
190 if (literalText) return clampCursor(text, cursorInput);
191 return clampCollapsedComposerCursorForSegments(
192 splitPromptIntoComposerSegments(text),
193 cursorInput,
194 );
195}
196
197export function collapseExpandedComposerCursor(
198 text: string,
199 cursorInput: number,
200 literalText = false,
201): number {
202 if (literalText) return clampCursor(text, cursorInput);
203 const expandedCursor = clampCursor(text, cursorInput);
204 const segments = splitPromptIntoComposerSegments(text);
205 if (segments.length === 0) {
206 return expandedCursor;
207 }
208
209 let remaining = expandedCursor;
210 let collapsedCursor = 0;
211
212 for (const segment of segments) {
213 if (
214 segment.type === "mention" ||
215 segment.type === "citation" ||
216 segment.type === "context-reference"
217 ) {
218 const expandedLength = segment.source.length;
219 if (remaining === 0) {
220 return collapsedCursor;
221 }
222 if (remaining <= expandedLength) {
223 return collapsedCursor + 1;
224 }
225 remaining -= expandedLength;
226 collapsedCursor += 1;
227 continue;
228 }
229 if (segment.type === "skill") {
230 const expandedLength = segment.source.length;
231 if (remaining === 0) {
232 return collapsedCursor;
233 }
234 if (remaining <= expandedLength) {
235 return collapsedCursor + 1;
236 }
237 remaining -= expandedLength;
238 collapsedCursor += 1;
239 continue;
240 }
241
242 const segmentLength = segment.text.length;
243 if (remaining <= segmentLength) {
244 return collapsedCursor + remaining;
245 }
246 remaining -= segmentLength;
247 collapsedCursor += segmentLength;
248 }
249
250 return collapsedCursor;
251}
252
253export function isCollapsedCursorAdjacentToInlineToken(
254 text: string,
255 cursorInput: number,
256 direction: "left" | "right",
257): boolean {
258 const segments = splitPromptIntoComposerSegments(text);
259 if (!segments.some(isInlineTokenSegment)) {
260 return false;
261 }
262
263 const cursor = clampCollapsedComposerCursorForSegments(segments, cursorInput);
264 let collapsedOffset = 0;
265
266 for (const segment of segments) {
267 if (isInlineTokenSegment(segment)) {
268 if (direction === "left" && cursor === collapsedOffset + 1) {
269 return true;
270 }
271 if (direction === "right" && cursor === collapsedOffset) {
272 return true;
273 }
274 }
275 collapsedOffset += collapsedSegmentLength(segment);
276 }
277
278 return false;
279}
280
281export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
282 const cursor = clampCursor(text, cursorInput);
283 const tokenStart = tokenStartForCursor(text, cursor);
284 const token = text.slice(tokenStart, cursor);
285 if (token.startsWith("/")) {
286 if (isPathWord(text, tokenStart, cursor, isWhitespace)) return null;
287 return {
288 kind: "slash-command",
289 query: token.slice(1),
290 rangeStart: tokenStart,
291 rangeEnd: cursor,
292 };
293 }
294 const pullRequestMatch = /^#([\p{L}\p{N}][\p{L}\p{N}_-]*)?$/u.exec(token);
295 if (pullRequestMatch) {
296 return {
297 kind: "pull-request",
298 query: pullRequestMatch[1] ?? "",
299 rangeStart: tokenStart,
300 rangeEnd: cursor,
301 };
302 }
303 const skillPrefix = /^\p{Sc}/u.exec(token);
304 if (skillPrefix) {
305 return {
306 kind: "skill",
307 query: token.slice(skillPrefix[0].length),
308 rangeStart: tokenStart,
309 rangeEnd: cursor,
310 };
311 }
312 if (!token.startsWith("@")) {
313 return null;
314 }
315
316 return {
317 kind: "path",
318 query: token.slice(1),
319 rangeStart: tokenStart,
320 rangeEnd: cursor,
321 };
322}
323
324export function pastedPathQueryLength(
325 lineBefore: string,
326 pasted: string,
327 pathQueryActive = true,
328): number {
329 if (!pathQueryActive) return 0;
330 if (detectComposerTrigger(lineBefore, lineBefore.length)?.kind !== "path") return 0;
331 return /^\S*/.exec(pasted)![0].length;
332}
333
334export function composerStateAtPromptEnd(
335 text: string,
336 literalText = false,
337): {
338 cursor: number;
339 trigger: ComposerTrigger | null;
340} {
341 const cursor = collapseExpandedComposerCursor(text, text.length, literalText);
342 return {
343 cursor,
344 trigger: literalText
345 ? null
346 : detectComposerTrigger(text, expandCollapsedComposerCursor(text, cursor)),
347 };
348}
349
350export function parseStandaloneComposerSlashCommand(
351 text: string,
352): Exclude<ComposerSlashCommand, "model"> | null {
353 const match = /^\/(plan|default)\s*$/i.exec(text.trim());
354 if (!match) {
355 return null;
356 }
357 const command = match[1]?.toLowerCase();
358 if (command === "plan") return "plan";
359 return "default";
360}
361
362export function replaceTextRange(
363 text: string,
364 rangeStart: number,
365 rangeEnd: number,
366 replacement: string,
367): { text: string; cursor: number } {
368 const safeStart = Math.max(0, Math.min(text.length, rangeStart));
369 const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
370 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
371 return { text: nextText, cursor: safeStart + replacement.length };
372}