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 "@v12/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 = "v12: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 contextTaskCount?: number;
223}): {
224 trimmedPrompt: string;
225 sendableTerminalContexts: TerminalContextDraft[];
226 expiredTerminalContextCount: number;
227 hasSendableContent: boolean;
228} {
229 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
230 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
231 const expiredTerminalContextCount =
232 options.terminalContexts.length - sendableTerminalContexts.length;
233 const elementContextCount = options.elementContextCount ?? 0;
234 const contextTaskCount = options.contextTaskCount ?? 0;
235 return {
236 trimmedPrompt,
237 sendableTerminalContexts,
238 expiredTerminalContextCount,
239 hasSendableContent:
240 trimmedPrompt.length > 0 ||
241 options.imageCount > 0 ||
242 sendableTerminalContexts.length > 0 ||
243 elementContextCount > 0 ||
244 contextTaskCount > 0,
245 };
246}
247
248export function buildExpiredTerminalContextToastCopy(
249 expiredTerminalContextCount: number,
250 variant: "omitted" | "empty",
251): { title: string; description: string } {
252 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
253 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
254 if (variant === "empty") {
255 return {
256 title: `${noun} won't be sent`,
257 description: "Remove it or re-add it to include terminal output.",
258 };
259 }
260 return {
261 title: `${noun} omitted from message`,
262 description: "Re-add it if you want that terminal output included.",
263 };
264}
265
266export function threadHasStarted(thread: Thread | null | undefined): boolean {
267 return Boolean(
268 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
269 );
270}
271
272// `threadProvider` is the open branded driver kind carried by the session.
273// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe
274// rollback / fork behavior — the routing layer is the right place to surface
275// "driver not installed" errors, not the lock state.
276//
277// `selectedProvider` takes the same open-string shape because the composer
278// now tracks the picker selection as a `ProviderInstanceId` (e.g.
279// `codex_personal`). Custom instance ids that don't directly match a
280// registered driver resolve to `null` here, which matches the existing
281// "unknown driver -> unlocked" semantics. Callers that want the lock to track
282// a custom instance's underlying driver kind should resolve the instance id
283// upstream and pass the correlated kind.
284export function deriveLockedProvider(input: {
285 thread: Thread | null | undefined;
286 selectedProvider: string | null;
287 threadProvider: string | null;
288}): ProviderDriverKind | null {
289 if (!threadHasStarted(input.thread)) {
290 return null;
291 }
292 const sessionProvider = input.thread?.session?.providerName ?? null;
293 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
294 return sessionProvider;
295 }
296 const narrowedThreadProvider =
297 input.threadProvider && isProviderDriverKind(input.threadProvider)
298 ? input.threadProvider
299 : null;
300 const narrowedSelectedProvider =
301 input.selectedProvider && isProviderDriverKind(input.selectedProvider)
302 ? input.selectedProvider
303 : null;
304 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
305}
306
307export function getStartedThreadModelChangeBlockReason(input: {
308 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
309 hasStartedSession: boolean;
310 currentModelSelection: ModelSelection;
311 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
312 nextModelSelection: ModelSelection;
313}): { title: string; description: string } | null {
314 if (!input.hasStartedSession) {
315 return null;
316 }
317 const currentModelSelection = {
318 ...input.currentModelSelection,
319 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
320 };
321 if (
322 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
323 currentModelSelection.model === input.nextModelSelection.model
324 ) {
325 return null;
326 }
327 const currentProvider = input.providers.find(
328 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
329 );
330 const nextProvider = input.providers.find(
331 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
332 );
333 if (
334 currentProvider?.requiresNewThreadForModelChange !== true &&
335 nextProvider?.requiresNewThreadForModelChange !== true
336 ) {
337 return null;
338 }
339 return {
340 title: "Start a new chat to change models",
341 description: "This provider does not allow switching models after a conversation has started.",
342 };
343}
344
345export async function waitForStartedServerThread(
346 threadRef: ScopedThreadRef,
347 timeoutMs = 1_000,
348 minimumMessageCount = 0,
349): Promise<boolean> {
350 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
351 const getThread = () => appAtomRegistry.get(threadAtom);
352 const thread = getThread();
353
354 const isReady = (candidate: ReturnType<typeof getThread>) =>
355 isServerThreadReadyForFork(candidate, minimumMessageCount);
356
357 if (isReady(thread)) {
358 return true;
359 }
360
361 return await new Promise<boolean>((resolve) => {
362 let settled = false;
363 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
364 const finish = (result: boolean) => {
365 if (settled) {
366 return;
367 }
368 settled = true;
369 if (timeoutId !== null) {
370 globalThis.clearTimeout(timeoutId);
371 }
372 unsubscribe();
373 resolve(result);
374 };
375
376 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
377 if (!isReady(thread)) {
378 return;
379 }
380 finish(true);
381 });
382
383 if (isReady(getThread())) {
384 finish(true);
385 return;
386 }
387
388 timeoutId = globalThis.setTimeout(() => {
389 finish(false);
390 }, timeoutMs);
391 });
392}
393
394export function isServerThreadReadyForFork(
395 thread: Thread | null | undefined,
396 minimumMessageCount: number,
397): boolean {
398 return Boolean(
399 threadHasStarted(thread) &&
400 (thread?.messages.length ?? 0) >= minimumMessageCount &&
401 thread?.messages.every((message) => !message.streaming),
402 );
403}
404
405export function isServerThreadSettled(thread: Thread | null | undefined): thread is Thread {
406 return Boolean(
407 thread &&
408 thread.session?.status !== "running" &&
409 thread.session?.status !== "starting" &&
410 thread.messages.every((message) => !message.streaming),
411 );
412}
413
414export async function waitForSettledServerThread(
415 threadRef: ScopedThreadRef,
416 timeoutMs = 5_000,
417): Promise<Thread | null> {
418 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
419 const getThread = () => appAtomRegistry.get(threadAtom);
420 const current = getThread();
421 if (isServerThreadSettled(current)) return current;
422
423 return await new Promise<Thread | null>((resolve) => {
424 let settled = false;
425 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
426 const finish = (result: Thread | null) => {
427 if (settled) return;
428 settled = true;
429 if (timeoutId !== null) globalThis.clearTimeout(timeoutId);
430 unsubscribe();
431 resolve(result);
432 };
433 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
434 if (isServerThreadSettled(thread)) finish(thread);
435 });
436 const refreshed = getThread();
437 if (isServerThreadSettled(refreshed)) {
438 finish(refreshed);
439 return;
440 }
441 timeoutId = globalThis.setTimeout(() => finish(null), timeoutMs);
442 });
443}
444
445export interface LocalDispatchSnapshot {
446 startedAt: string;
447 preparingWorktree: boolean;
448 latestTurnTurnId: TurnId | null;
449 latestTurnRequestedAt: string | null;
450 latestTurnStartedAt: string | null;
451 latestTurnCompletedAt: string | null;
452 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
453 sessionUpdatedAt: string | null;
454}
455
456export function createLocalDispatchSnapshot(
457 activeThread: Thread | undefined,
458 options?: { preparingWorktree?: boolean },
459): LocalDispatchSnapshot {
460 const latestTurn = activeThread?.latestTurn ?? null;
461 const session = activeThread?.session ?? null;
462 return {
463 startedAt: new Date().toISOString(),
464 preparingWorktree: Boolean(options?.preparingWorktree),
465 latestTurnTurnId: latestTurn?.turnId ?? null,
466 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
467 latestTurnStartedAt: latestTurn?.startedAt ?? null,
468 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
469 sessionStatus: session?.status ?? null,
470 sessionUpdatedAt: session?.updatedAt ?? null,
471 };
472}
473
474export function hasServerAcknowledgedLocalDispatch(input: {
475 localDispatch: LocalDispatchSnapshot | null;
476 phase: SessionPhase;
477 latestTurn: Thread["latestTurn"] | null;
478 session: Thread["session"] | null;
479 hasPendingApproval: boolean;
480 hasPendingUserInput: boolean;
481 threadError: string | null | undefined;
482}): boolean {
483 if (!input.localDispatch) {
484 return false;
485 }
486 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
487 return true;
488 }
489
490 const latestTurn = input.latestTurn ?? null;
491 const session = input.session ?? null;
492 const latestTurnChanged =
493 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
494 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
495 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
496 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
497
498 if (input.phase === "running") {
499 if (!latestTurnChanged) {
500 return false;
501 }
502 if (latestTurn?.startedAt === null || latestTurn === null) {
503 return false;
504 }
505 if (
506 session?.activeTurnId !== null &&
507 session?.activeTurnId !== undefined &&
508 latestTurn?.turnId !== session.activeTurnId
509 ) {
510 return false;
511 }
512 return true;
513 }
514
515 return (
516 latestTurnChanged ||
517 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
518 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
519 );
520}