Open History to see the last commit
1import {
2 type EnvironmentId,
3 isProviderDriverKind,
4 ProjectId,
5 type ModelSelection,
6 type ProviderDriverKind,
7 type ServerProvider,
8 type ScopedThreadRef,
9 type ThreadId,
10 type TurnId,
11} from "@t3tools/contracts";
12import { type ChatMessage, type SessionPhase, type Thread } from "../types";
13import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
14import * as Schema from "effect/Schema";
15import { appAtomRegistry } from "../rpc/atomRegistry";
16import { environmentThreadDetails } from "../state/threads";
17import {
18 filterTerminalContextsWithText,
19 stripInlineTerminalContextPlaceholders,
20 type TerminalContextDraft,
21} from "../lib/terminalContext";
22import type { DraftThreadEnvMode } from "../composerDraftStore";
23
24export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
25export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
26export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
27
28export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
29
30export function buildLocalDraftThread(
31 threadId: ThreadId,
32 draftThread: DraftThreadState,
33 fallbackModelSelection: ModelSelection,
34): Thread {
35 return {
36 id: threadId,
37 environmentId: draftThread.environmentId,
38 projectId: draftThread.projectId,
39 title: "New thread",
40 modelSelection: fallbackModelSelection,
41 runtimeMode: draftThread.runtimeMode,
42 interactionMode: draftThread.interactionMode,
43 session: null,
44 messages: [],
45 createdAt: draftThread.createdAt,
46 updatedAt: draftThread.createdAt,
47 archivedAt: null,
48 deletedAt: null,
49 latestTurn: null,
50 branch: draftThread.branch,
51 worktreePath: draftThread.worktreePath,
52 checkpoints: [],
53 activities: [],
54 proposedPlans: [],
55 };
56}
57
58export function shouldWriteThreadErrorToCurrentServerThread(input: {
59 serverThread:
60 | {
61 environmentId: EnvironmentId;
62 id: ThreadId;
63 }
64 | null
65 | undefined;
66 routeThreadRef: ScopedThreadRef;
67 targetThreadId: ThreadId;
68}): boolean {
69 return Boolean(
70 input.serverThread &&
71 input.targetThreadId === input.routeThreadRef.threadId &&
72 input.serverThread.environmentId === input.routeThreadRef.environmentId &&
73 input.serverThread.id === input.targetThreadId,
74 );
75}
76
77export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
78 threadId: ThreadId;
79 turnId?: TurnId;
80} {
81 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
82 return {
83 threadId: thread.id,
84 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
85 };
86}
87
88export function reconcileMountedTerminalThreadIds(input: {
89 currentThreadIds: ReadonlyArray<string>;
90 openThreadIds: ReadonlyArray<string>;
91 activeThreadId: string | null;
92 activeThreadTerminalOpen: boolean;
93 maxHiddenThreadCount?: number;
94}): string[] {
95 return reconcileRetainedMountedThreadIds({
96 currentThreadIds: input.currentThreadIds,
97 openThreadIds: input.openThreadIds,
98 activeThreadId: input.activeThreadId,
99 activeThreadOpen: input.activeThreadTerminalOpen,
100 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
101 });
102}
103
104export function reconcileRetainedMountedThreadIds(input: {
105 currentThreadIds: ReadonlyArray<string>;
106 openThreadIds: ReadonlyArray<string>;
107 activeThreadId: string | null;
108 activeThreadOpen: boolean;
109 maxHiddenThreadCount: number;
110 retainInactiveActiveThread?: boolean;
111}): string[] {
112 const openThreadIdSet = new Set(input.openThreadIds);
113 const hiddenThreadIds = input.currentThreadIds.filter(
114 (threadId) =>
115 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
116 openThreadIdSet.has(threadId),
117 );
118 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
119 const nextThreadIds =
120 hiddenThreadIds.length > maxHiddenThreadCount
121 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
122 : hiddenThreadIds;
123
124 if (
125 input.activeThreadId &&
126 input.activeThreadOpen &&
127 !nextThreadIds.includes(input.activeThreadId)
128 ) {
129 nextThreadIds.push(input.activeThreadId);
130 }
131
132 return nextThreadIds;
133}
134
135export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
136 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
137 return;
138 }
139 URL.revokeObjectURL(previewUrl);
140}
141
142export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
143 if (message.role !== "user" || !message.attachments) {
144 return;
145 }
146 for (const attachment of message.attachments) {
147 if (attachment.type !== "image") {
148 continue;
149 }
150 revokeBlobPreviewUrl(attachment.previewUrl);
151 }
152}
153
154export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
155 if (message.role !== "user" || !message.attachments) {
156 return [];
157 }
158 const previewUrls: string[] = [];
159 for (const attachment of message.attachments) {
160 if (attachment.type !== "image") continue;
161 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
162 previewUrls.push(attachment.previewUrl);
163 }
164 return previewUrls;
165}
166
167export interface PullRequestDialogState {
168 initialReference: string | null;
169 key: number;
170}
171
172export function readFileAsDataUrl(file: File): Promise<string> {
173 return new Promise((resolve, reject) => {
174 const reader = new FileReader();
175 reader.addEventListener("load", () => {
176 if (typeof reader.result === "string") {
177 resolve(reader.result);
178 return;
179 }
180 reject(new Error("Could not read image data."));
181 });
182 reader.addEventListener("error", () => {
183 reject(reader.error ?? new Error("Failed to read image."));
184 });
185 reader.readAsDataURL(file);
186 });
187}
188
189export function resolveSendEnvMode(input: {
190 requestedEnvMode: DraftThreadEnvMode;
191 isGitRepo: boolean;
192}): DraftThreadEnvMode {
193 return input.isGitRepo ? input.requestedEnvMode : "local";
194}
195
196export function cloneComposerImageForRetry(
197 image: ComposerImageAttachment,
198): ComposerImageAttachment {
199 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
200 return image;
201 }
202 try {
203 return {
204 ...image,
205 previewUrl: URL.createObjectURL(image.file),
206 };
207 } catch {
208 return image;
209 }
210}
211
212export function deriveComposerSendState(options: {
213 prompt: string;
214 imageCount: number;
215 terminalContexts: ReadonlyArray<TerminalContextDraft>;
216 /**
217 * Optional element-pick attachment count. Element contexts contribute to
218 * "sendable content" exactly like images and (text-bearing) terminal
219 * contexts do: a prompt of just element chips is still a valid send.
220 */
221 elementContextCount?: number;
222}): {
223 trimmedPrompt: string;
224 sendableTerminalContexts: TerminalContextDraft[];
225 expiredTerminalContextCount: number;
226 hasSendableContent: boolean;
227} {
228 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
229 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
230 const expiredTerminalContextCount =
231 options.terminalContexts.length - sendableTerminalContexts.length;
232 const elementContextCount = options.elementContextCount ?? 0;
233 return {
234 trimmedPrompt,
235 sendableTerminalContexts,
236 expiredTerminalContextCount,
237 hasSendableContent:
238 trimmedPrompt.length > 0 ||
239 options.imageCount > 0 ||
240 sendableTerminalContexts.length > 0 ||
241 elementContextCount > 0,
242 };
243}
244
245export function buildExpiredTerminalContextToastCopy(
246 expiredTerminalContextCount: number,
247 variant: "omitted" | "empty",
248): { title: string; description: string } {
249 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
250 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
251 if (variant === "empty") {
252 return {
253 title: `${noun} won't be sent`,
254 description: "Remove it or re-add it to include terminal output.",
255 };
256 }
257 return {
258 title: `${noun} omitted from message`,
259 description: "Re-add it if you want that terminal output included.",
260 };
261}
262
263export function threadHasStarted(thread: Thread | null | undefined): boolean {
264 return Boolean(
265 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
266 );
267}
268
269// `threadProvider` is the open branded driver kind carried by the session.
270// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe
271// rollback / fork behavior — the routing layer is the right place to surface
272// "driver not installed" errors, not the lock state.
273//
274// `selectedProvider` takes the same open-string shape because the composer
275// now tracks the picker selection as a `ProviderInstanceId` (e.g.
276// `codex_personal`). Custom instance ids that don't directly match a
277// registered driver resolve to `null` here, which matches the existing
278// "unknown driver -> unlocked" semantics. Callers that want the lock to track
279// a custom instance's underlying driver kind should resolve the instance id
280// upstream and pass the correlated kind.
281export function deriveLockedProvider(input: {
282 thread: Thread | null | undefined;
283 selectedProvider: string | null;
284 threadProvider: string | null;
285}): ProviderDriverKind | null {
286 if (!threadHasStarted(input.thread)) {
287 return null;
288 }
289 const sessionProvider = input.thread?.session?.providerName ?? null;
290 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
291 return sessionProvider;
292 }
293 const narrowedThreadProvider =
294 input.threadProvider && isProviderDriverKind(input.threadProvider)
295 ? input.threadProvider
296 : null;
297 const narrowedSelectedProvider =
298 input.selectedProvider && isProviderDriverKind(input.selectedProvider)
299 ? input.selectedProvider
300 : null;
301 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
302}
303
304export function getStartedThreadModelChangeBlockReason(input: {
305 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
306 hasStartedSession: boolean;
307 currentModelSelection: ModelSelection;
308 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
309 nextModelSelection: ModelSelection;
310}): { title: string; description: string } | null {
311 if (!input.hasStartedSession) {
312 return null;
313 }
314 const currentModelSelection = {
315 ...input.currentModelSelection,
316 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
317 };
318 if (
319 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
320 currentModelSelection.model === input.nextModelSelection.model
321 ) {
322 return null;
323 }
324 const currentProvider = input.providers.find(
325 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
326 );
327 const nextProvider = input.providers.find(
328 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
329 );
330 if (
331 currentProvider?.requiresNewThreadForModelChange !== true &&
332 nextProvider?.requiresNewThreadForModelChange !== true
333 ) {
334 return null;
335 }
336 return {
337 title: "Start a new chat to change models",
338 description: "This provider does not allow switching models after a conversation has started.",
339 };
340}
341
342export async function waitForStartedServerThread(
343 threadRef: ScopedThreadRef,
344 timeoutMs = 1_000,
345): Promise<boolean> {
346 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
347 const getThread = () => appAtomRegistry.get(threadAtom);
348 const thread = getThread();
349
350 if (threadHasStarted(thread)) {
351 return true;
352 }
353
354 return await new Promise<boolean>((resolve) => {
355 let settled = false;
356 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
357 const finish = (result: boolean) => {
358 if (settled) {
359 return;
360 }
361 settled = true;
362 if (timeoutId !== null) {
363 globalThis.clearTimeout(timeoutId);
364 }
365 unsubscribe();
366 resolve(result);
367 };
368
369 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
370 if (!threadHasStarted(thread)) {
371 return;
372 }
373 finish(true);
374 });
375
376 if (threadHasStarted(getThread())) {
377 finish(true);
378 return;
379 }
380
381 timeoutId = globalThis.setTimeout(() => {
382 finish(false);
383 }, timeoutMs);
384 });
385}
386
387export interface LocalDispatchSnapshot {
388 startedAt: string;
389 preparingWorktree: boolean;
390 latestTurnTurnId: TurnId | null;
391 latestTurnRequestedAt: string | null;
392 latestTurnStartedAt: string | null;
393 latestTurnCompletedAt: string | null;
394 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
395 sessionUpdatedAt: string | null;
396}
397
398export function createLocalDispatchSnapshot(
399 activeThread: Thread | undefined,
400 options?: { preparingWorktree?: boolean },
401): LocalDispatchSnapshot {
402 const latestTurn = activeThread?.latestTurn ?? null;
403 const session = activeThread?.session ?? null;
404 return {
405 startedAt: new Date().toISOString(),
406 preparingWorktree: Boolean(options?.preparingWorktree),
407 latestTurnTurnId: latestTurn?.turnId ?? null,
408 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
409 latestTurnStartedAt: latestTurn?.startedAt ?? null,
410 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
411 sessionStatus: session?.status ?? null,
412 sessionUpdatedAt: session?.updatedAt ?? null,
413 };
414}
415
416export function hasServerAcknowledgedLocalDispatch(input: {
417 localDispatch: LocalDispatchSnapshot | null;
418 phase: SessionPhase;
419 latestTurn: Thread["latestTurn"] | null;
420 session: Thread["session"] | null;
421 hasPendingApproval: boolean;
422 hasPendingUserInput: boolean;
423 threadError: string | null | undefined;
424}): boolean {
425 if (!input.localDispatch) {
426 return false;
427 }
428 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
429 return true;
430 }
431
432 const latestTurn = input.latestTurn ?? null;
433 const session = input.session ?? null;
434 const latestTurnChanged =
435 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
436 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
437 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
438 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
439
440 if (input.phase === "running") {
441 if (!latestTurnChanged) {
442 return false;
443 }
444 if (latestTurn?.startedAt === null || latestTurn === null) {
445 return false;
446 }
447 if (
448 session?.activeTurnId !== null &&
449 session?.activeTurnId !== undefined &&
450 latestTurn?.turnId !== session.activeTurnId
451 ) {
452 return false;
453 }
454 return true;
455 }
456
457 return (
458 latestTurnChanged ||
459 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
460 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
461 );
462}