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