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