@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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