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