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