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