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