Open History to see the last commit
1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 type AssetCreateUrlInput,
4 type AssetCreateUrlResult,
5 type ChatFileAttachment,
6 type EnvironmentId,
7 isProviderDriverKind,
8 ProjectId,
9 type MessageId,
10 type ModelSelection,
11 type ProviderInteractionMode,
12 ProviderDriverKind,
13 type ProviderInstanceId,
14 type ServerProvider,
15 type ScopedProjectRef,
16 type ScopedThreadRef,
17 type ThreadId,
18 type TurnId,
19} from "@t3tools/contracts";
20import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
21import {
22 squashAtomCommandFailure,
23 type AtomCommandResult,
24} from "@t3tools/client-runtime/state/runtime";
25import { videoMimeType } from "@t3tools/shared/video";
26import {
27 appendCodexArtifactTemplateUsePrompt,
28 codexArtifactTemplateUsePrompt,
29 type CodexArtifactTemplate,
30} from "@t3tools/client-runtime/codex-artifact-templates";
31import {
32 type ChatMessage,
33 isImageAttachment,
34 type SessionPhase,
35 type Thread,
36 type ThreadShell,
37 type TurnDiffSummary,
38} from "../types";
39import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
40import * as Schema from "effect/Schema";
41import { shallow } from "zustand/vanilla/shallow";
42import { appAtomRegistry } from "../rpc/atomRegistry";
43import { environmentThreadDetails } from "../state/threads";
44import {
45 filterTerminalContextsWithText,
46 stripInlineTerminalContextPlaceholders,
47 type TerminalContextDraft,
48} from "../lib/terminalContext";
49import type { DraftThreadEnvMode } from "../composerDraftStore";
50import type { ComposerSubmissionIntent } from "../composer-logic";
51import type { TimelineEntry } from "../session-logic";
52import type { DesktopPreviewOverlay } from "../previewStateStore";
53import type { RightPanelSurface } from "../rightPanelStore";
54import {
55 NO_PROVIDER_MODEL_SELECTION,
56 resolveSelectableProviderInstanceEntry,
57 type ProviderInstanceEntry,
58} from "../providerInstances";
59
60export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
61export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
62export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
63export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
64
65export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
66
67export function agentControlledBrowserCloseConfirmation(
68 surfaces: readonly RightPanelSurface[],
69 desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
70): string | null {
71 const activeBrowserCount = surfaces.filter(
72 (surface) =>
73 surface.kind === "preview" &&
74 surface.resourceId !== null &&
75 desktopByTabId[surface.resourceId]?.controller === "agent",
76 ).length;
77 if (activeBrowserCount === 0) return null;
78 if (activeBrowserCount === 1) {
79 return [
80 "Close browser while the agent is using it?",
81 "The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
82 ].join("\n");
83 }
84 return [
85 `Close ${activeBrowserCount} browsers while the agent is using them?`,
86 "The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
87 ].join("\n");
88}
89
90export function shouldRenderPreviewMiniPlayer(
91 miniPlayerTabId: string | null,
92 renderedRightPanelSurface: RightPanelSurface | null,
93): boolean {
94 return (
95 miniPlayerTabId !== null &&
96 !(
97 renderedRightPanelSurface?.kind === "preview" &&
98 renderedRightPanelSurface.resourceId === miniPlayerTabId
99 )
100 );
101}
102
103export function shouldOpenProactivePullRequest(
104 previousTargetKey: string | null | undefined,
105 targetKey: string | null,
106): boolean {
107 return previousTargetKey !== undefined && targetKey !== null && targetKey !== previousTargetKey;
108}
109
110export function shouldOpenProactiveTurnDiff(input: {
111 previousRunningTurnId: TurnId | null | undefined;
112 runningTurnId: TurnId | null;
113 settledTurnId: TurnId | null;
114 turnCompleted: boolean;
115}): boolean {
116 return (
117 input.previousRunningTurnId !== undefined &&
118 input.previousRunningTurnId !== null &&
119 input.runningTurnId === null &&
120 input.turnCompleted &&
121 input.settledTurnId === input.previousRunningTurnId
122 );
123}
124
125export function resolveProactiveTurnDiffAction(input: {
126 checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;
127 isGitRepo: boolean | undefined;
128 activeSurfaceKind: RightPanelSurface["kind"] | null;
129}): "defer" | "ignore" | "open" {
130 if (input.activeSurfaceKind === "pull-request") return "ignore";
131 if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
132 if (input.isGitRepo === undefined) return "defer";
133 if (
134 !input.isGitRepo ||
135 input.checkpoint.status !== "ready" ||
136 input.checkpoint.files.length === 0
137 ) {
138 return "ignore";
139 }
140 return "open";
141}
142
143export function codexArtifactTemplatePromptToAppend(
144 currentDraft: string,
145 template: CodexArtifactTemplate,
146): string | null {
147 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
148 ? null
149 : codexArtifactTemplateUsePrompt(template);
150}
151
152export function shouldDockDraftHeroForSubmission(input: {
153 isDraftHeroState: boolean;
154 activeThreadKey: string | null;
155 submissionIntent: ComposerSubmissionIntent;
156}): boolean {
157 return (
158 input.submissionIntent === "foreground" &&
159 input.isDraftHeroState &&
160 input.activeThreadKey !== null
161 );
162}
163
164export function shouldReleaseTimelineAnchorForToolActivity(input: {
165 anchorMessageId: MessageId | null;
166 liveFollowEnabled: boolean;
167 runningTurnId: TurnId | null;
168 timelineEntries: ReadonlyArray<TimelineEntry>;
169}): boolean {
170 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
171 return false;
172 }
173
174 return input.timelineEntries.some((timelineEntry) => {
175 if (timelineEntry.kind !== "work" || timelineEntry.entry.turnId !== input.runningTurnId) {
176 return false;
177 }
178
179 const entry = timelineEntry.entry;
180 return (
181 entry.tone === "tool" ||
182 entry.itemType !== undefined ||
183 entry.requestKind !== undefined ||
184 (entry.command?.trim().length ?? 0) > 0
185 );
186 });
187}
188
189export function toolGroupConsumesUpwardNavigation(target: EventTarget | null): boolean {
190 const elementTarget = target instanceof Element ? target : null;
191 const group = elementTarget?.closest<HTMLElement>("[data-tool-group-scroll]");
192 if (!group) return false;
193
194 // A nested result or the group itself can consume an upward scroll.
195 for (let element = elementTarget; element; element = element.parentElement) {
196 if (element.scrollTop > 0) {
197 const overflowY = getComputedStyle(element).overflowY;
198 if (overflowY === "auto" || overflowY === "scroll") return true;
199 }
200 if (element === group) break;
201 }
202 return false;
203}
204
205export function resolveDraftHeroState(input: {
206 isLocalDraftThread: boolean;
207 hasTimelineEntries: boolean;
208 isWorking: boolean;
209 draftHeroDockRequested: boolean;
210 backgroundSubmissionPending: boolean;
211}): boolean {
212 if (input.backgroundSubmissionPending) {
213 return true;
214 }
215 return (
216 input.isLocalDraftThread &&
217 !input.hasTimelineEntries &&
218 !input.isWorking &&
219 !input.draftHeroDockRequested
220 );
221}
222
223export function resolveDraftPromotionNavigationTarget(input: {
224 serverThreadRef: ScopedThreadRef | null;
225 serverThread: Pick<Thread, "latestTurn" | "session"> | null | undefined;
226 backgroundSubmissionPending: boolean;
227}): ScopedThreadRef | null {
228 if (input.backgroundSubmissionPending) {
229 return null;
230 }
231 const sessionStatus = input.serverThread?.session?.status;
232 const turnStarted = input.serverThread?.latestTurn?.startedAt != null;
233 const startupStopped =
234 sessionStatus === "error" || sessionStatus === "stopped" || sessionStatus === "interrupted";
235 // Keep local preparation feedback mounted until the server can render the
236 // running turn or its startup error on the canonical thread route.
237 return turnStarted || startupStopped ? input.serverThreadRef : null;
238}
239
240export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
241 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
242 return () => globalThis.clearTimeout(timeoutId);
243}
244
245export function hasEnvironmentReconnectWarningGraceElapsed(
246 activeEnvironmentId: EnvironmentId | null,
247 elapsedEnvironmentId: EnvironmentId | null,
248): boolean {
249 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
250}
251
252export function startNewThreadForProject(
253 projectRef: ScopedProjectRef | null,
254 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
255): boolean {
256 if (projectRef === null) return false;
257 void handleNewThread(projectRef);
258
259 return true;
260}
261
262export function resolveThreadMetadataUpdateForNextTurn(input: {
263 currentModelSelection: ModelSelection;
264 nextModelSelection?: ModelSelection;
265 currentBranch: string | null;
266 nextBranch?: string;
267}): {
268 modelSelection?: ModelSelection;
269 branch?: string;
270 worktreePath?: null;
271} | null {
272 const nextModelSelection = input.nextModelSelection;
273 const modelSelectionChanged =
274 nextModelSelection !== undefined &&
275 (nextModelSelection.model !== input.currentModelSelection.model ||
276 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
277 JSON.stringify(nextModelSelection.options ?? null) !==
278 JSON.stringify(input.currentModelSelection.options ?? null));
279 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
280 if (!modelSelectionChanged && !branchChanged) {
281 return null;
282 }
283 return {
284 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
285 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
286 };
287}
288
289export function buildLocalDraftThread(
290 threadId: ThreadId,
291 draftThread: DraftThreadState,
292 fallbackModelSelection: ModelSelection,
293): Thread {
294 return {
295 id: threadId,
296 environmentId: draftThread.environmentId,
297 projectId: draftThread.projectId,
298 title: "New thread",
299 modelSelection: fallbackModelSelection,
300 runtimeMode: draftThread.runtimeMode,
301 interactionMode: draftThread.interactionMode,
302 session: null,
303 messages: [],
304 createdAt: draftThread.createdAt,
305 updatedAt: draftThread.createdAt,
306 archivedAt: null,
307 settledOverride: null,
308 settledAt: null,
309 deletedAt: null,
310 latestTurn: null,
311 branch: draftThread.branch,
312 worktreePath: draftThread.worktreePath,
313 checkpoints: [],
314 activities: [],
315 proposedPlans: [],
316 };
317}
318
319export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
320 return {
321 ...shell,
322 messages: [],
323 proposedPlans: [],
324 activities: [],
325 checkpoints: [],
326 deletedAt: null,
327 };
328}
329
330export function shouldWriteThreadErrorToCurrentServerThread(input: {
331 activeServerThread:
332 | {
333 environmentId: EnvironmentId;
334 id: ThreadId;
335 }
336 | null
337 | undefined;
338 routeThreadRef: ScopedThreadRef;
339 targetThreadId: ThreadId;
340}): boolean {
341 return Boolean(
342 input.activeServerThread &&
343 input.targetThreadId === input.routeThreadRef.threadId &&
344 input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
345 input.activeServerThread.id === input.targetThreadId,
346 );
347}
348
349export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
350 threadId: ThreadId;
351 turnId?: TurnId;
352} {
353 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
354 return {
355 threadId: thread.id,
356 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
357 };
358}
359
360/** Use the same enabled instance for the composer, provider status, and chat actions. */
361export function resolveComposerProviderSelection(input: {
362 entries: ReadonlyArray<ProviderInstanceEntry>;
363 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
364 lockedProvider: ProviderDriverKind | null;
365 lockedInstanceId: ProviderInstanceId | null | undefined;
366}) {
367 const requestedInstanceId = input.candidateInstanceIds.find(
368 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
369 );
370 const requestedDriverKind =
371 input.lockedProvider ??
372 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
373 input.entries[0]?.driverKind ??
374 ProviderDriverKind.make("unconfigured");
375 const lockedContinuationGroupKey = input.lockedProvider
376 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
377 ?.continuationGroupKey ?? null)
378 : null;
379 // Missing metadata must not move Antigravity history into another Google profile.
380 const requiresExactInstance =
381 input.lockedProvider === "antigravity" &&
382 input.lockedInstanceId != null &&
383 lockedContinuationGroupKey === null;
384 const compatibleEntries = input.entries.filter(
385 (entry) =>
386 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
387 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
388 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
389 );
390 const selectedProviderEntry =
391 input.candidateInstanceIds
392 .map((candidate) =>
393 compatibleEntries.find(
394 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
395 ),
396 )
397 .find((entry) => entry !== undefined) ??
398 resolveSelectableProviderInstanceEntry(
399 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
400 undefined,
401 ) ??
402 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
403 const unavailableProviderInstanceId = selectedProviderEntry
404 ? undefined
405 : input.lockedProvider
406 ? (input.lockedInstanceId ?? requestedInstanceId)
407 : requestedInstanceId;
408 return {
409 selectedProviderEntry,
410 requestedDriverKind,
411 lockedContinuationGroupKey,
412 unavailableProviderInstanceId,
413 };
414}
415
416/** Keep restored drafts and every plan control on the selected instance's supported mode. */
417export function resolveComposerInteractionMode(input: {
418 planModeEnabled: boolean;
419 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
420 interactionMode: ProviderInteractionMode;
421}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
422 const enabled =
423 input.planModeEnabled &&
424 input.provider != null &&
425 input.provider.showInteractionModeToggle !== false;
426 return {
427 enabled,
428 interactionMode: enabled ? input.interactionMode : "default",
429 };
430}
431
432export function getAntigravitySendBlockReason(
433 provider:
434 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
435 | null
436 | undefined,
437 model: string,
438): string | null {
439 if (provider?.driver !== "antigravity") return null;
440 if (!provider.installed) {
441 return "Install Antigravity in provider settings before sending.";
442 }
443 if (provider.auth.status === "unauthenticated") {
444 return "Sign in to Antigravity in provider settings before sending.";
445 }
446 const slug = model.trim();
447 if (slug.length === 0) return "Choose an Antigravity model before sending.";
448 // A restart clears the account status and catalog. Session startup checks
449 // saved credentials and validates the model before sending the prompt.
450 if (provider.auth.status === "unknown") return null;
451 if (provider.models.length === 0) {
452 return "Refresh Antigravity models in provider settings before sending.";
453 }
454 // A saved model that left the catalog is kept in the picker as unavailable
455 // so the user sees what the thread used. The server rejects it at turn
456 // start, so block here unless the provider is in an error state, where a
457 // retry with the same model is the right move.
458 if (
459 provider.status === "ready" &&
460 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
461 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
462 ) {
463 return "That Antigravity model is no longer available. Choose another model.";
464 }
465 return null;
466}
467
468/**
469 * Maps each user message to the checkpoint turn count a revert should target.
470 * Returns `previous` when the result is unchanged: streaming text deltas
471 * rebuild `timelineEntries` per token, and the timeline row projection only
472 * reuses rows while this Map keeps its identity.
473 */
474export function buildRevertTurnCountByUserMessageId(
475 input: {
476 supportsConversationRollback: boolean;
477 timelineEntries: ReadonlyArray<TimelineEntry>;
478 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
479 inferredCheckpointTurnCountByTurnId: Readonly<Record<string, number | undefined>>;
480 },
481 previous: Map<MessageId, number> | null = null,
482): Map<MessageId, number> {
483 const byUserMessageId = new Map<MessageId, number>();
484 const entryCount = input.supportsConversationRollback ? input.timelineEntries.length : 0;
485 for (let index = 0; index < entryCount; index += 1) {
486 const entry = input.timelineEntries[index];
487 if (!entry || entry.kind !== "message" || entry.message.role !== "user") {
488 continue;
489 }
490
491 for (let nextIndex = index + 1; nextIndex < input.timelineEntries.length; nextIndex += 1) {
492 const nextEntry = input.timelineEntries[nextIndex];
493 if (!nextEntry || nextEntry.kind !== "message") {
494 continue;
495 }
496 if (nextEntry.message.role === "user") {
497 break;
498 }
499 const summary = input.turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id);
500 if (!summary) {
501 continue;
502 }
503 const turnCount =
504 summary.checkpointTurnCount ?? input.inferredCheckpointTurnCountByTurnId[summary.turnId];
505 if (typeof turnCount !== "number") {
506 break;
507 }
508 byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1));
509 break;
510 }
511 }
512 return previous !== null && shallow(previous, byUserMessageId) ? previous : byUserMessageId;
513}
514
515export function reconcileMountedTerminalThreadIds(input: {
516 currentThreadIds: ReadonlyArray<string>;
517 openThreadIds: ReadonlyArray<string>;
518 activeThreadId: string | null;
519 activeThreadTerminalOpen: boolean;
520 maxHiddenThreadCount?: number;
521}): string[] {
522 return reconcileRetainedMountedThreadIds({
523 currentThreadIds: input.currentThreadIds,
524 openThreadIds: input.openThreadIds,
525 activeThreadId: input.activeThreadId,
526 activeThreadOpen: input.activeThreadTerminalOpen,
527 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
528 });
529}
530
531export function reconcileRetainedMountedThreadIds(input: {
532 currentThreadIds: ReadonlyArray<string>;
533 openThreadIds: ReadonlyArray<string>;
534 activeThreadId: string | null;
535 activeThreadOpen: boolean;
536 maxHiddenThreadCount: number;
537 retainInactiveActiveThread?: boolean;
538}): string[] {
539 const openThreadIdSet = new Set(input.openThreadIds);
540 const hiddenThreadIds = input.currentThreadIds.filter(
541 (threadId) =>
542 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
543 openThreadIdSet.has(threadId),
544 );
545 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
546 const nextThreadIds =
547 hiddenThreadIds.length > maxHiddenThreadCount
548 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
549 : hiddenThreadIds;
550
551 if (
552 input.activeThreadId &&
553 input.activeThreadOpen &&
554 !nextThreadIds.includes(input.activeThreadId)
555 ) {
556 nextThreadIds.push(input.activeThreadId);
557 }
558
559 return nextThreadIds;
560}
561
562export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
563 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
564 return;
565 }
566 URL.revokeObjectURL(previewUrl);
567}
568
569/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
570export async function resolveFileAttachmentUrl(input: {
571 attachment: ChatFileAttachment;
572 environmentId: EnvironmentId;
573 httpBaseUrl: string;
574 createAssetUrl: (input: {
575 environmentId: EnvironmentId;
576 input: AssetCreateUrlInput;
577 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
578}): Promise<string> {
579 const { attachment } = input;
580 const result = await input.createAssetUrl({
581 environmentId: input.environmentId,
582 input: {
583 resource: {
584 _tag: "attachment",
585 attachmentId: attachment.id,
586 fileName: attachment.name,
587 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
588 },
589 },
590 });
591 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
592 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
593 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
594 return url;
595}
596
597export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
598 if (message.role !== "user" || !message.attachments) {
599 return;
600 }
601 for (const attachment of message.attachments) {
602 if (!isImageAttachment(attachment)) {
603 continue;
604 }
605 revokeBlobPreviewUrl(attachment.previewUrl);
606 }
607}
608
609export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
610 if (message.role !== "user" || !message.attachments) {
611 return [];
612 }
613 const previewUrls: string[] = [];
614 for (const attachment of message.attachments) {
615 if (!isImageAttachment(attachment)) continue;
616 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
617 previewUrls.push(attachment.previewUrl);
618 }
619 return previewUrls;
620}
621
622export interface PullRequestDialogState {
623 initialReference: string | null;
624 key: number;
625}
626
627export function readFileAsDataUrl(file: File): Promise<string> {
628 return new Promise((resolve, reject) => {
629 const reader = new FileReader();
630 reader.addEventListener("load", () => {
631 if (typeof reader.result === "string") {
632 resolve(reader.result);
633 return;
634 }
635 reject(new Error("Could not read image data."));
636 });
637 reader.addEventListener("error", () => {
638 reject(reader.error ?? new Error("Failed to read image."));
639 });
640 reader.readAsDataURL(file);
641 });
642}
643
644export function resolveSendEnvMode(input: {
645 requestedEnvMode: DraftThreadEnvMode;
646 isGitRepo: boolean;
647}): DraftThreadEnvMode {
648 return input.isGitRepo ? input.requestedEnvMode : "local";
649}
650
651export function resolveBackgroundDraftWorkspaceOptions(input: {
652 envMode: DraftThreadEnvMode;
653 branch: string | null;
654 startFromOrigin: boolean;
655}): {
656 envMode: DraftThreadEnvMode;
657 branch: string | null;
658 worktreePath: null;
659 startFromOrigin: boolean;
660} {
661 return {
662 envMode: input.envMode,
663 branch: input.branch,
664 worktreePath: null,
665 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
666 };
667}
668
669export function cloneComposerImageForRetry(
670 image: ComposerImageAttachment,
671): ComposerImageAttachment {
672 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
673 return image;
674 }
675 try {
676 return {
677 ...image,
678 previewUrl: URL.createObjectURL(image.file),
679 };
680 } catch {
681 return image;
682 }
683}
684
685export function deriveComposerSendState(options: {
686 prompt: string;
687 imageCount: number;
688 terminalContexts: ReadonlyArray<TerminalContextDraft>;
689 /**
690 * Optional element-pick attachment count. Element contexts contribute to
691 * "sendable content" exactly like images and (text-bearing) terminal
692 * contexts do: a prompt of just element chips is still a valid send.
693 */
694 elementContextCount?: number;
695}): {
696 trimmedPrompt: string;
697 sendableTerminalContexts: TerminalContextDraft[];
698 expiredTerminalContextCount: number;
699 hasSendableContent: boolean;
700} {
701 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
702 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
703 const expiredTerminalContextCount =
704 options.terminalContexts.length - sendableTerminalContexts.length;
705 const elementContextCount = options.elementContextCount ?? 0;
706 return {
707 trimmedPrompt,
708 sendableTerminalContexts,
709 expiredTerminalContextCount,
710 hasSendableContent:
711 trimmedPrompt.length > 0 ||
712 options.imageCount > 0 ||
713 sendableTerminalContexts.length > 0 ||
714 elementContextCount > 0,
715 };
716}
717
718export function buildExpiredTerminalContextToastCopy(
719 expiredTerminalContextCount: number,
720 variant: "omitted" | "empty",
721): { title: string; description: string } {
722 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
723 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
724 if (variant === "empty") {
725 return {
726 title: `${noun} won't be sent`,
727 description: "Remove it or re-add it to include terminal output.",
728 };
729 }
730 return {
731 title: `${noun} omitted from message`,
732 description: "Re-add it if you want that terminal output included.",
733 };
734}
735
736export function branchMismatchKey(
737 threadId: string | null,
738 mismatch: { threadBranch: string; currentBranch: string } | null,
739): string | null {
740 if (!threadId || !mismatch) {
741 return null;
742 }
743 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
744}
745
746// The mismatch banner only matters when the user is about to send: passive
747// reading of an old thread carries no risk (the branch picker tint already
748// covers ambient awareness). Draft content is the intent signal — composer
749// focus is useless here because ChatView autofocuses the composer on every
750// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
751// revealed so it doesn't flicker away when the draft is cleared.
752export function shouldShowBranchMismatchBanner(input: {
753 hasMismatch: boolean;
754 isDismissed: boolean;
755 composerHasContent: boolean;
756 wasShownForCurrentMismatch: boolean;
757}): boolean {
758 if (!input.hasMismatch || input.isDismissed) {
759 return false;
760 }
761 return input.composerHasContent || input.wasShownForCurrentMismatch;
762}
763
764export function shouldShowPlanFollowUpPrompt(input: {
765 pendingUserInputCount: number;
766 interactionMode: ProviderInteractionMode;
767 latestTurnSettled: boolean;
768 hasActionableProposedPlan: boolean;
769 hasComposerAttachments: boolean;
770}): boolean {
771 return (
772 input.pendingUserInputCount === 0 &&
773 input.interactionMode === "plan" &&
774 input.latestTurnSettled &&
775 input.hasActionableProposedPlan &&
776 !input.hasComposerAttachments
777 );
778}
779
780// Session-scoped (module-level so it survives ChatView remounts, e.g. route
781// changes). Durable cross-device dismissal is planned as a server-side ack.
782const sessionDismissedBranchMismatchKeys = new Set<string>();
783
784export function dismissBranchMismatchForSession(key: string): void {
785 sessionDismissedBranchMismatchKeys.add(key);
786}
787
788export function isBranchMismatchDismissedForSession(key: string | null): boolean {
789 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
790}
791
792export function threadHasStarted(thread: Thread | null | undefined): boolean {
793 return Boolean(
794 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
795 );
796}
797
798// Imported history has no session until its first prompt. Resolve its instance
799// through the environment's provider catalog before locking to a driver.
800export function deriveLockedProvider(input: {
801 thread: Thread | null | undefined;
802 selectedProvider: string | null;
803 threadProvider: string | null;
804 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
805}): ProviderDriverKind | null {
806 if (!threadHasStarted(input.thread)) {
807 return null;
808 }
809 const sessionProvider = input.thread?.session?.providerName ?? null;
810 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
811 return sessionProvider;
812 }
813 // Preserve the existing lock while an instance is missing from the catalog;
814 // a started thread must not silently fall back to a different driver.
815 const threadProvider =
816 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
817 input.threadProvider;
818 const selectedProvider =
819 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
820 input.selectedProvider;
821 const narrowedThreadProvider =
822 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
823 const narrowedSelectedProvider =
824 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
825 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
826}
827
828export function getStartedThreadModelChangeBlockReason(input: {
829 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
830 hasStartedSession: boolean;
831 currentModelSelection: ModelSelection;
832 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
833 nextModelSelection: ModelSelection;
834}): { title: string; description: string } | null {
835 if (!input.hasStartedSession) {
836 return null;
837 }
838 const currentModelSelection = {
839 ...input.currentModelSelection,
840 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
841 };
842 if (
843 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
844 currentModelSelection.model === input.nextModelSelection.model
845 ) {
846 return null;
847 }
848 const currentProvider = input.providers.find(
849 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
850 );
851 const nextProvider = input.providers.find(
852 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
853 );
854 if (
855 currentProvider?.requiresNewThreadForModelChange !== true &&
856 nextProvider?.requiresNewThreadForModelChange !== true
857 ) {
858 return null;
859 }
860 return {
861 title: "Start a new chat to change models",
862 description: "This provider does not allow switching models after a conversation has started.",
863 };
864}
865
866export async function waitForStartedServerThread(
867 threadRef: ScopedThreadRef,
868 timeoutMs = 1_000,
869): Promise<boolean> {
870 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
871 const getThread = () => appAtomRegistry.get(threadAtom);
872 const thread = getThread();
873
874 if (threadHasStarted(thread)) {
875 return true;
876 }
877
878 return await new Promise<boolean>((resolve) => {
879 let settled = false;
880 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
881 const finish = (result: boolean) => {
882 if (settled) {
883 return;
884 }
885 settled = true;
886 if (timeoutId !== null) {
887 globalThis.clearTimeout(timeoutId);
888 }
889 unsubscribe();
890 resolve(result);
891 };
892
893 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
894 if (!threadHasStarted(thread)) {
895 return;
896 }
897 finish(true);
898 });
899
900 if (threadHasStarted(getThread())) {
901 finish(true);
902 return;
903 }
904
905 timeoutId = globalThis.setTimeout(() => {
906 finish(false);
907 }, timeoutMs);
908 });
909}
910
911export interface LocalDispatchSnapshot {
912 startedAt: string;
913 preparingWorktree: boolean;
914 submissionIntent: ComposerSubmissionIntent;
915 latestUserMessageId: ChatMessage["id"] | null;
916 latestTurnTurnId: TurnId | null;
917 latestTurnRequestedAt: string | null;
918 latestTurnStartedAt: string | null;
919 latestTurnCompletedAt: string | null;
920 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
921 sessionUpdatedAt: string | null;
922 latestTurnStartFailureId: string | null;
923}
924
925export function latestTurnStartFailureId(
926 activeThread: Thread | undefined,
927 latestUserMessageId: ChatMessage["id"] | null,
928): string | null {
929 if (latestUserMessageId === null) return null;
930 return (
931 activeThread?.activities.findLast((activity) => {
932 if (activity.kind !== "provider.turn.start.failed") return false;
933 const payload =
934 typeof activity.payload === "object" && activity.payload !== null
935 ? (activity.payload as { readonly requestId?: unknown })
936 : null;
937 return payload?.requestId === latestUserMessageId;
938 })?.id ?? null
939 );
940}
941
942export function createLocalDispatchSnapshot(
943 activeThread: Thread | undefined,
944 options?: {
945 preparingWorktree?: boolean;
946 submissionIntent?: ComposerSubmissionIntent;
947 },
948): LocalDispatchSnapshot {
949 const latestTurn = activeThread?.latestTurn ?? null;
950 const session = activeThread?.session ?? null;
951 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
952 return {
953 startedAt: new Date().toISOString(),
954 preparingWorktree: Boolean(options?.preparingWorktree),
955 submissionIntent: options?.submissionIntent ?? "foreground",
956 latestUserMessageId: latestUserMessage?.id ?? null,
957 latestTurnTurnId: latestTurn?.turnId ?? null,
958 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
959 latestTurnStartedAt: latestTurn?.startedAt ?? null,
960 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
961 sessionStatus: session?.status ?? null,
962 sessionUpdatedAt: session?.updatedAt ?? null,
963 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
964 };
965}
966
967export function hasServerAcknowledgedLocalDispatch(input: {
968 localDispatch: LocalDispatchSnapshot | null;
969 phase: SessionPhase;
970 latestTurn: Thread["latestTurn"] | null;
971 latestUserMessageId: ChatMessage["id"] | null;
972 session: Thread["session"] | null;
973 hasPendingApproval: boolean;
974 hasPendingUserInput: boolean;
975 latestTurnStartFailureId?: string | null;
976 threadError: string | null | undefined;
977}): boolean {
978 if (!input.localDispatch) {
979 return false;
980 }
981 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
982 return true;
983 }
984 if (
985 input.latestTurnStartFailureId !== undefined &&
986 input.latestTurnStartFailureId !== null &&
987 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
988 ) {
989 return true;
990 }
991 if (input.phase === "connecting") {
992 return false;
993 }
994
995 const latestTurn = input.latestTurn ?? null;
996 const session = input.session ?? null;
997 const latestUserMessageChanged =
998 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
999 const latestTurnChanged =
1000 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
1001 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
1002 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
1003 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
1004
1005 if (input.phase === "running") {
1006 // Steering adds a user message to the current running turn without
1007 // necessarily changing any of the turn timestamps. Treat that projected
1008 // message as the server acknowledgment so the composer does not remain
1009 // stuck in its local "Sending" state until the turn settles.
1010 if (latestUserMessageChanged) {
1011 return true;
1012 }
1013 if (!latestTurnChanged) {
1014 return false;
1015 }
1016 if (latestTurn?.startedAt === null || latestTurn === null) {
1017 return false;
1018 }
1019 if (
1020 session?.activeTurnId !== null &&
1021 session?.activeTurnId !== undefined &&
1022 latestTurn?.turnId !== session.activeTurnId
1023 ) {
1024 return false;
1025 }
1026 return true;
1027 }
1028
1029 return (
1030 latestTurnChanged ||
1031 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1032 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1033 );
1034}