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 PreviewAnnotationPayload,
12 type ProviderInteractionMode,
13 ProviderDriverKind,
14 type ProviderInstanceId,
15 type ServerProvider,
16 type ScopedProjectRef,
17 type ScopedThreadRef,
18 type ThreadId,
19 type ThreadLinkedPullRequest,
20 type TurnId,
21 WORKTREE_SETUP_ACTIVITY_KIND,
22 WorktreeSetupSnapshot,
23} from "@t3tools/contracts";
24import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
25import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
26import {
27 squashAtomCommandFailure,
28 type AtomCommandResult,
29} from "@t3tools/client-runtime/state/runtime";
30import { videoMimeType } from "@t3tools/shared/video";
31import {
32 appendCodexArtifactTemplateUsePrompt,
33 codexArtifactTemplateUsePrompt,
34 type CodexArtifactTemplate,
35} from "@t3tools/client-runtime/codex-artifact-templates";
36import {
37 type ChatMessage,
38 isImageAttachment,
39 type SessionPhase,
40 type Thread,
41 type ThreadShell,
42 type TurnDiffSummary,
43} from "../types";
44import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
45import * as Option from "effect/Option";
46import * as Schema from "effect/Schema";
47import { appAtomRegistry } from "../rpc/atomRegistry";
48import { environmentThreadDetails } from "../state/threads";
49import { stripInlineContextReferences } from "~/lib/composerContextReferences";
50import { filterTerminalContextsWithText, type TerminalContextDraft } from "../lib/terminalContext";
51import type { DraftThreadEnvMode } from "../composerDraftStore";
52import { collapseExpandedComposerCursor, type ComposerSubmissionIntent } from "../composer-logic";
53import type { ReviewCommentContext } from "../reviewCommentContext";
54import type { TimelineEntry } from "../session-logic";
55import type { PreviewMiniPlayerSource } from "../previewMiniPlayerStore";
56import type { DesktopPreviewOverlay } from "../previewStateStore";
57import type { RightPanelSurface } from "../rightPanelStore";
58import {
59 NO_PROVIDER_MODEL_SELECTION,
60 resolveSelectableProviderInstanceEntry,
61 type ProviderInstanceEntry,
62} from "../providerInstances";
63
64export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
65export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
66export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
67export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
68
69export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
70
71export function agentControlledBrowserCloseConfirmation(
72 surfaces: readonly RightPanelSurface[],
73 desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
74): string | null {
75 const activeBrowserCount = surfaces.filter(
76 (surface) =>
77 surface.kind === "preview" &&
78 surface.resourceId !== null &&
79 desktopByTabId[surface.resourceId]?.controller === "agent",
80 ).length;
81 if (activeBrowserCount === 0) return null;
82 if (activeBrowserCount === 1) {
83 return [
84 "Close browser while the agent is using it?",
85 "The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
86 ].join("\n");
87 }
88 return [
89 `Close ${activeBrowserCount} browsers while the agent is using them?`,
90 "The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
91 ].join("\n");
92}
93
94/** The floating player hides only while the same source is rendered in the panel. */
95export function shouldRenderPreviewMiniPlayer(
96 source: PreviewMiniPlayerSource | null,
97 renderedRightPanelSurface: RightPanelSurface | null,
98): boolean {
99 if (source === null) return false;
100 if (source.kind === "browser") {
101 return !(
102 renderedRightPanelSurface?.kind === "preview" &&
103 renderedRightPanelSurface.resourceId === source.tabId
104 );
105 }
106 return !(
107 renderedRightPanelSurface?.kind === "device" &&
108 renderedRightPanelSurface.target?.hostId === source.hostId &&
109 renderedRightPanelSurface.target.deviceId === source.deviceId
110 );
111}
112
113export function shouldOpenProactivePullRequest(
114 previousTargetKey: string | null | undefined,
115 targetKey: string | null,
116): boolean {
117 return targetKey !== null && targetKey !== previousTargetKey;
118}
119
120interface ProactivePanelObservation {
121 threadKey: string;
122 runningTurnId: TurnId | null | undefined;
123 targetKey: string | null | undefined;
124 userActionTurnId: TurnId | null;
125 userActionRevision: number;
126}
127
128/** Capture user intent before loading or metadata writes can defer panel activation. */
129export function observeProactivePanelUserChoice(
130 previous: ProactivePanelObservation | null,
131 input: { threadKey: string; runningTurnId: TurnId | null; userActionRevision: number },
132): ProactivePanelObservation {
133 const sameThread = previous?.threadKey === input.threadKey;
134 const newTurn =
135 sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;
136 return {
137 threadKey: input.threadKey,
138 runningTurnId: sameThread ? previous.runningTurnId : undefined,
139 targetKey: sameThread ? previous.targetKey : undefined,
140 userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),
141 userActionRevision:
142 !sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,
143 };
144}
145
146/** Follow a changed server link only when the panel still shows the previous linked PR. */
147export function shouldRetargetThreadPullRequestPanel(
148 previous: ThreadLinkedPullRequest | null,
149 current: ThreadLinkedPullRequest | null,
150 surface: RightPanelSurface | null,
151): boolean {
152 if (previous === null || current === null || surface?.kind !== "pull-request") return false;
153 const previousRepository = previous.repository.toLowerCase();
154 return (
155 (previous.projectId !== current.projectId ||
156 previousRepository !== current.repository.toLowerCase() ||
157 previous.number !== current.number) &&
158 surface.projectId === previous.projectId &&
159 surface.repository.toLowerCase() === previousRepository &&
160 surface.number === previous.number
161 );
162}
163
164export function shouldOpenProactiveTurnDiff(input: {
165 previousRunningTurnId: TurnId | null | undefined;
166 runningTurnId: TurnId | null;
167 settledTurnId: TurnId | null;
168 turnCompleted: boolean;
169}): boolean {
170 return (
171 input.runningTurnId === null &&
172 input.turnCompleted &&
173 input.settledTurnId !== null &&
174 (input.previousRunningTurnId === undefined ||
175 input.settledTurnId === input.previousRunningTurnId)
176 );
177}
178
179export function resolveProactiveTurnDiffAction(input: {
180 checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;
181 isGitRepo: boolean | undefined;
182}): "defer" | "ignore" | "open" {
183 if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
184 if (input.isGitRepo === undefined) return "defer";
185 if (
186 !input.isGitRepo ||
187 input.checkpoint.status !== "ready" ||
188 input.checkpoint.files.length === 0
189 ) {
190 return "ignore";
191 }
192 return "open";
193}
194
195export function codexArtifactTemplatePromptToAppend(
196 currentDraft: string,
197 template: CodexArtifactTemplate,
198): string | null {
199 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
200 ? null
201 : codexArtifactTemplateUsePrompt(template);
202}
203
204export function shouldDockDraftHeroForSubmission(input: {
205 isDraftHeroState: boolean;
206 activeThreadKey: string | null;
207 submissionIntent: ComposerSubmissionIntent;
208}): boolean {
209 return (
210 input.submissionIntent === "foreground" &&
211 input.isDraftHeroState &&
212 input.activeThreadKey !== null
213 );
214}
215
216export function shouldReleaseTimelineAnchorForToolActivity(input: {
217 anchorMessageId: MessageId | null;
218 liveFollowEnabled: boolean;
219 runningTurnId: TurnId | null;
220 timelineEntries: ReadonlyArray<TimelineEntry>;
221}): boolean {
222 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
223 return false;
224 }
225
226 return input.timelineEntries.some((timelineEntry) => {
227 if (timelineEntry.kind !== "work" || timelineEntry.entry.turnId !== input.runningTurnId) {
228 return false;
229 }
230
231 const entry = timelineEntry.entry;
232 return (
233 entry.tone === "tool" ||
234 entry.itemType !== undefined ||
235 entry.requestKind !== undefined ||
236 (entry.command?.trim().length ?? 0) > 0
237 );
238 });
239}
240
241export function toolGroupConsumesUpwardNavigation(target: EventTarget | null): boolean {
242 const elementTarget = target instanceof Element ? target : null;
243 const group = elementTarget?.closest<HTMLElement>("[data-tool-group-scroll]");
244 if (!group) return false;
245
246 // A nested result or the group itself can consume an upward scroll.
247 for (let element = elementTarget; element; element = element.parentElement) {
248 if (element.scrollTop > 0) {
249 const overflowY = getComputedStyle(element).overflowY;
250 if (overflowY === "auto" || overflowY === "scroll") return true;
251 }
252 if (element === group) break;
253 }
254 return false;
255}
256
257const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);
258
259/**
260 * The worktree setup the server recorded on the thread, if any: running once
261 * the bootstrap created the thread, then the settled outcome. It is what a
262 * reload or a second client renders, and what tells them to attach the live
263 * stream while it still says running.
264 */
265export function findRecordedWorktreeSetup(
266 activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>,
267 threadId: ThreadId,
268): WorktreeSetupSnapshot | null {
269 for (let index = activities.length - 1; index >= 0; index -= 1) {
270 const activity = activities[index]!;
271 if (activity.kind !== WORKTREE_SETUP_ACTIVITY_KIND) continue;
272 const decoded = decodeWorktreeSetupSnapshot(activity.payload);
273 if (Option.isSome(decoded) && decoded.value.threadId === threadId) return decoded.value;
274 }
275 return null;
276}
277
278/**
279 * Which setup snapshot the timeline shows, if any. The live stream wins while
280 * it has a newer sequence; the recorded activity covers everything else. A
281 * running setup always shows. The setup belongs to the thread's first turn:
282 * once the user has sent a follow-up it is history and nothing about it is
283 * shown again, whatever its outcome. Within that first turn, a clean finish
284 * leaves no trace once the turn is live (the setup is a means to the reply,
285 * not part of the conversation), while a failed script, a failed setup, or a
286 * cancelled one stays so the outcome, exit code, and terminal are reachable.
287 * Before the turn is live everything stays so nothing collapses in the
288 * handoff gap. Visibility never depends on whether a turn happens to be
289 * running, which would make the row come and go.
290 */
291export function resolveVisibleWorktreeSetup(input: {
292 live: WorktreeSetupSnapshot | null;
293 recorded: WorktreeSetupSnapshot | null;
294 turnStarted: boolean;
295 /** The user sent a message after the one that created the worktree. */
296 followUpSent: boolean;
297}): WorktreeSetupSnapshot | null {
298 const snapshot =
299 input.live && (!input.recorded || input.live.sequence >= input.recorded.sequence)
300 ? input.live
301 : input.recorded;
302 if (!snapshot) return null;
303 if (snapshot.phase === "running") return snapshot;
304 if (input.followUpSent) return null;
305 if (snapshot.phase !== "done") return snapshot;
306 if (!input.turnStarted) return snapshot;
307 return snapshot.stages.some((stage) => stage.status === "failed") ? snapshot : null;
308}
309
310export function resolveDraftHeroState(input: {
311 isLocalDraftThread: boolean;
312 hasTimelineEntries: boolean;
313 isWorking: boolean;
314 draftHeroDockRequested: boolean;
315 backgroundSubmissionPending: boolean;
316 /** A worktree setup card is on the timeline, so the timeline must stay visible. */
317 hasWorktreeSetupCard?: boolean;
318}): boolean {
319 if (input.hasWorktreeSetupCard) {
320 return false;
321 }
322 if (input.backgroundSubmissionPending) {
323 return true;
324 }
325 return (
326 input.isLocalDraftThread &&
327 !input.hasTimelineEntries &&
328 !input.isWorking &&
329 !input.draftHeroDockRequested
330 );
331}
332
333/**
334 * Keep painted timelines on screen across thread jumps. Remounting LegendList
335 * (or handing it an empty first paint) punches a hole through the chat pane —
336 * white in light mode — so cmd+1/2/3 spam flashes even when the destination
337 * is already cached.
338 *
339 * Stored at module scope because ChatView remounts when the thread route
340 * changes (same pattern as the thread-error banner session dismissals).
341 * Remember more than the last thread so jumping back to cmd+1 does not show
342 * cmd+3's messages, and so a cached destination can paint on the first frame.
343 */
344export type HeldThreadTimeline<T extends readonly unknown[]> = {
345 threadKey: string | null;
346 entries: T;
347 markdownCwd?: string | null;
348 workspaceRoot?: string | null;
349};
350
351const MAX_REMEMBERED_THREAD_TIMELINES = 16;
352
353let rememberedThreadTimelines = new Map<string, HeldThreadTimeline<readonly unknown[]>>();
354let rememberedThreadTimelineOrder: string[] = [];
355let lastReadyThreadKey: string | null = null;
356
357function rememberThreadTimelineEntries(held: HeldThreadTimeline<readonly unknown[]>): void {
358 if (held.threadKey === null) {
359 return;
360 }
361 rememberedThreadTimelines.set(held.threadKey, held);
362 rememberedThreadTimelineOrder = [
363 ...rememberedThreadTimelineOrder.filter((key) => key !== held.threadKey),
364 held.threadKey,
365 ];
366 while (rememberedThreadTimelineOrder.length > MAX_REMEMBERED_THREAD_TIMELINES) {
367 const evicted = rememberedThreadTimelineOrder.shift();
368 if (evicted !== undefined) {
369 rememberedThreadTimelines.delete(evicted);
370 }
371 }
372 lastReadyThreadKey = held.threadKey;
373}
374
375export function rememberReadyThreadTimeline<T extends readonly unknown[]>(
376 held: HeldThreadTimeline<T>,
377): void {
378 if (held.threadKey === null || held.entries.length === 0) {
379 return;
380 }
381 rememberThreadTimelineEntries(held);
382}
383
384export function peekRememberedThreadTimeline<T extends readonly unknown[]>(
385 threadKey: string | null,
386): T | null {
387 if (threadKey === null) {
388 return null;
389 }
390 return (rememberedThreadTimelines.get(threadKey)?.entries as T | undefined) ?? null;
391}
392
393export function peekHeldThreadTimeline<
394 T extends readonly unknown[],
395>(): HeldThreadTimeline<T> | null {
396 if (lastReadyThreadKey === null) {
397 return null;
398 }
399 const held = rememberedThreadTimelines.get(lastReadyThreadKey);
400 if (held === undefined || held.entries.length === 0) {
401 return null;
402 }
403 return held as HeldThreadTimeline<T>;
404}
405
406export function resetHeldThreadTimeline(): void {
407 rememberedThreadTimelines = new Map();
408 rememberedThreadTimelineOrder = [];
409 lastReadyThreadKey = null;
410}
411
412export function threadKeysShareEnvironment(left: string | null, right: string | null): boolean {
413 if (left === null || right === null) {
414 return false;
415 }
416 const leftRef = parseScopedThreadKey(left);
417 const rightRef = parseScopedThreadKey(right);
418 return leftRef !== null && rightRef !== null && leftRef.environmentId === rightRef.environmentId;
419}
420
421/** True while we still paint another thread's last snapshot. */
422export function isPaintOnlyThreadTimeline(
423 displayThreadKey: string | null,
424 activeThreadKey: string | null,
425): boolean {
426 return (
427 displayThreadKey !== null && activeThreadKey !== null && displayThreadKey !== activeThreadKey
428 );
429}
430
431export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input: {
432 loading: boolean;
433 activeThreadKey: string | null;
434 nextEntries: T;
435 rememberedForActive?: T | null;
436 lastReady?: HeldThreadTimeline<T> | null;
437}): { entries: T; displayThreadKey: string | null } {
438 if (input.nextEntries.length > 0) {
439 return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
440 }
441
442 const rememberedForActive =
443 input.rememberedForActive ?? peekRememberedThreadTimeline<T>(input.activeThreadKey);
444 if (input.loading && rememberedForActive !== null && rememberedForActive.length > 0) {
445 return { entries: rememberedForActive, displayThreadKey: input.activeThreadKey };
446 }
447
448 const lastReady = input.lastReady ?? peekHeldThreadTimeline<T>();
449 if (
450 input.loading &&
451 lastReady !== null &&
452 lastReady.threadKey !== null &&
453 lastReady.threadKey !== input.activeThreadKey &&
454 lastReady.entries.length > 0 &&
455 threadKeysShareEnvironment(lastReady.threadKey, input.activeThreadKey)
456 ) {
457 return { entries: lastReady.entries, displayThreadKey: lastReady.threadKey };
458 }
459 return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
460}
461
462export function resolveDraftPromotionNavigationTarget(input: {
463 serverThreadRef: ScopedThreadRef | null;
464 serverThread: Pick<Thread, "latestTurn" | "session" | "messages"> | null | undefined;
465 backgroundSubmissionPending: boolean;
466}): ScopedThreadRef | null {
467 if (input.backgroundSubmissionPending) {
468 return null;
469 }
470 const sessionStatus = input.serverThread?.session?.status;
471 const turnStarted = input.serverThread?.latestTurn?.startedAt != null;
472 const startupStopped =
473 sessionStatus === "error" || sessionStatus === "stopped" || sessionStatus === "interrupted";
474 // A worktree bootstrap persists the user message before the turn, so the
475 // thread route can render the send and the live setup by itself. Otherwise
476 // keep the draft mounted until the server can render the running turn or
477 // its startup error.
478 const messagePersisted =
479 input.serverThread?.messages.some((message) => message.role === "user") ?? false;
480 return turnStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;
481}
482
483export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
484 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
485 return () => globalThis.clearTimeout(timeoutId);
486}
487
488export function hasEnvironmentReconnectWarningGraceElapsed(
489 activeEnvironmentId: EnvironmentId | null,
490 elapsedEnvironmentId: EnvironmentId | null,
491): boolean {
492 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
493}
494
495export function startNewThreadForProject(
496 projectRef: ScopedProjectRef | null,
497 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
498): boolean {
499 if (projectRef === null) return false;
500 void handleNewThread(projectRef);
501
502 return true;
503}
504
505export function resolveThreadMetadataUpdateForNextTurn(input: {
506 currentModelSelection: ModelSelection;
507 nextModelSelection?: ModelSelection;
508 currentBranch: string | null;
509 nextBranch?: string;
510}): {
511 modelSelection?: ModelSelection;
512 branch?: string;
513 worktreePath?: null;
514} | null {
515 const nextModelSelection = input.nextModelSelection;
516 const modelSelectionChanged =
517 nextModelSelection !== undefined &&
518 (nextModelSelection.model !== input.currentModelSelection.model ||
519 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
520 JSON.stringify(nextModelSelection.options ?? null) !==
521 JSON.stringify(input.currentModelSelection.options ?? null));
522 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
523 if (!modelSelectionChanged && !branchChanged) {
524 return null;
525 }
526 return {
527 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
528 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
529 };
530}
531
532export function buildLocalDraftThread(
533 threadId: ThreadId,
534 draftThread: DraftThreadState,
535 fallbackModelSelection: ModelSelection,
536): Thread {
537 return {
538 id: threadId,
539 environmentId: draftThread.environmentId,
540 projectId: draftThread.projectId,
541 title: "New thread",
542 modelSelection: fallbackModelSelection,
543 runtimeMode: draftThread.runtimeMode,
544 interactionMode: draftThread.interactionMode,
545 session: null,
546 messages: [],
547 createdAt: draftThread.createdAt,
548 updatedAt: draftThread.createdAt,
549 archivedAt: null,
550 settledOverride: null,
551 settledAt: null,
552 deletedAt: null,
553 latestTurn: null,
554 branch: draftThread.branch,
555 worktreePath: draftThread.worktreePath,
556 checkpoints: [],
557 pullRequests: [],
558 activities: [],
559 proposedPlans: [],
560 };
561}
562
563export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
564 return {
565 ...shell,
566 messages: [],
567 proposedPlans: [],
568 activities: [],
569 checkpoints: [],
570 deletedAt: null,
571 };
572}
573
574export function shouldWriteThreadErrorToCurrentServerThread(input: {
575 activeServerThread:
576 | {
577 environmentId: EnvironmentId;
578 id: ThreadId;
579 }
580 | null
581 | undefined;
582 routeThreadRef: ScopedThreadRef;
583 targetThreadId: ThreadId;
584}): boolean {
585 return Boolean(
586 input.activeServerThread &&
587 input.targetThreadId === input.routeThreadRef.threadId &&
588 input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
589 input.activeServerThread.id === input.targetThreadId,
590 );
591}
592
593export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
594 threadId: ThreadId;
595 turnId?: TurnId;
596} {
597 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
598 return {
599 threadId: thread.id,
600 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
601 };
602}
603
604/** Use the same enabled instance for the composer, provider status, and chat actions. */
605export function resolveComposerProviderSelection(input: {
606 entries: ReadonlyArray<ProviderInstanceEntry>;
607 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
608 lockedProvider: ProviderDriverKind | null;
609 lockedInstanceId: ProviderInstanceId | null | undefined;
610}) {
611 const requestedInstanceId = input.candidateInstanceIds.find(
612 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
613 );
614 const requestedDriverKind =
615 input.lockedProvider ??
616 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
617 input.entries[0]?.driverKind ??
618 ProviderDriverKind.make("unconfigured");
619 const lockedContinuationGroupKey = input.lockedProvider
620 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
621 ?.continuationGroupKey ?? null)
622 : null;
623 // Missing metadata must not move Antigravity history into another Google profile.
624 const requiresExactInstance =
625 input.lockedProvider === "antigravity" &&
626 input.lockedInstanceId != null &&
627 lockedContinuationGroupKey === null;
628 const compatibleEntries = input.entries.filter(
629 (entry) =>
630 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
631 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
632 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
633 );
634 const selectedProviderEntry =
635 input.candidateInstanceIds
636 .map((candidate) =>
637 compatibleEntries.find(
638 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
639 ),
640 )
641 .find((entry) => entry !== undefined) ??
642 resolveSelectableProviderInstanceEntry(
643 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
644 undefined,
645 ) ??
646 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
647 const unavailableProviderInstanceId = selectedProviderEntry
648 ? undefined
649 : input.lockedProvider
650 ? (input.lockedInstanceId ?? requestedInstanceId)
651 : requestedInstanceId;
652 return {
653 selectedProviderEntry,
654 requestedDriverKind,
655 lockedContinuationGroupKey,
656 unavailableProviderInstanceId,
657 };
658}
659
660/** Keep restored drafts and every plan control on the selected instance's supported mode. */
661export function resolveComposerInteractionMode(input: {
662 planModeEnabled: boolean;
663 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
664 interactionMode: ProviderInteractionMode;
665}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
666 const enabled =
667 input.planModeEnabled &&
668 input.provider != null &&
669 input.provider.showInteractionModeToggle !== false;
670 return {
671 enabled,
672 interactionMode: enabled ? input.interactionMode : "default",
673 };
674}
675
676export function getAntigravitySendBlockReason(
677 provider:
678 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
679 | null
680 | undefined,
681 model: string,
682): string | null {
683 if (provider?.driver !== "antigravity") return null;
684 if (!provider.installed) {
685 return "Install Antigravity in provider settings before sending.";
686 }
687 if (provider.auth.status === "unauthenticated") {
688 return "Sign in to Antigravity in provider settings before sending.";
689 }
690 const slug = model.trim();
691 if (slug.length === 0) return "Choose an Antigravity model before sending.";
692 // A restart clears the account status and catalog. Session startup checks
693 // saved credentials and validates the model before sending the prompt.
694 if (provider.auth.status === "unknown") return null;
695 if (provider.models.length === 0) {
696 return "Refresh Antigravity models in provider settings before sending.";
697 }
698 // A saved model that left the catalog is kept in the picker as unavailable
699 // so the user sees what the thread used. The server rejects it at turn
700 // start, so block here unless the provider is in an error state, where a
701 // retry with the same model is the right move.
702 if (
703 provider.status === "ready" &&
704 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
705 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
706 ) {
707 return "That Antigravity model is no longer available. Choose another model.";
708 }
709 return null;
710}
711
712export function buildRunningThreadTurnInterruptInput(
713 thread: Pick<Thread, "id" | "session"> | null | undefined,
714 phase: SessionPhase,
715): { threadId: ThreadId; turnId?: TurnId } | null {
716 if (phase !== "running" || thread?.session?.status !== "running") {
717 return null;
718 }
719 return buildThreadTurnInterruptInput(thread);
720}
721
722export function reconcileMountedTerminalThreadIds(input: {
723 currentThreadIds: ReadonlyArray<string>;
724 openThreadIds: ReadonlyArray<string>;
725 activeThreadId: string | null;
726 activeThreadTerminalOpen: boolean;
727 maxHiddenThreadCount?: number;
728}): string[] {
729 return reconcileRetainedMountedThreadIds({
730 currentThreadIds: input.currentThreadIds,
731 openThreadIds: input.openThreadIds,
732 activeThreadId: input.activeThreadId,
733 activeThreadOpen: input.activeThreadTerminalOpen,
734 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
735 });
736}
737
738export function reconcileRetainedMountedThreadIds(input: {
739 currentThreadIds: ReadonlyArray<string>;
740 openThreadIds: ReadonlyArray<string>;
741 activeThreadId: string | null;
742 activeThreadOpen: boolean;
743 maxHiddenThreadCount: number;
744 retainInactiveActiveThread?: boolean;
745}): string[] {
746 const openThreadIdSet = new Set(input.openThreadIds);
747 const hiddenThreadIds = input.currentThreadIds.filter(
748 (threadId) =>
749 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
750 openThreadIdSet.has(threadId),
751 );
752 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
753 const nextThreadIds =
754 hiddenThreadIds.length > maxHiddenThreadCount
755 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
756 : hiddenThreadIds;
757
758 if (
759 input.activeThreadId &&
760 input.activeThreadOpen &&
761 !nextThreadIds.includes(input.activeThreadId)
762 ) {
763 nextThreadIds.push(input.activeThreadId);
764 }
765
766 return nextThreadIds;
767}
768
769export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
770 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
771 return;
772 }
773 URL.revokeObjectURL(previewUrl);
774}
775
776/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
777export async function resolveFileAttachmentUrl(input: {
778 attachment: ChatFileAttachment;
779 environmentId: EnvironmentId;
780 httpBaseUrl: string;
781 createAssetUrl: (input: {
782 environmentId: EnvironmentId;
783 input: AssetCreateUrlInput;
784 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
785}): Promise<string> {
786 const { attachment } = input;
787 const result = await input.createAssetUrl({
788 environmentId: input.environmentId,
789 input: {
790 resource: {
791 _tag: "attachment",
792 attachmentId: attachment.id,
793 fileName: attachment.name,
794 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
795 },
796 },
797 });
798 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
799 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
800 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
801 return url;
802}
803
804export async function prepareRevertedMessageAttachments(input: {
805 message: ChatMessage;
806 environmentId: EnvironmentId;
807 httpBaseUrl: string;
808 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
809}): Promise<File[]> {
810 return Promise.all(
811 (input.message.attachments ?? []).map(async (attachment) => {
812 if (attachment.type !== "image" && attachment.type !== "file") {
813 throw new Error("This message has an attachment that cannot be restored.");
814 }
815 const result = await input.createAssetUrl({
816 environmentId: input.environmentId,
817 input: {
818 resource: {
819 _tag: "attachment",
820 attachmentId: attachment.id,
821 fileName: attachment.name,
822 mimeType: attachment.mimeType,
823 },
824 },
825 });
826 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
827 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
828 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
829 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
830 if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
831 return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
832 }),
833 );
834}
835
836export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
837 if (message.role !== "user" || !message.attachments) {
838 return;
839 }
840 for (const attachment of message.attachments) {
841 if (!isImageAttachment(attachment)) {
842 continue;
843 }
844 revokeBlobPreviewUrl(attachment.previewUrl);
845 }
846}
847
848export function timelineHasEphemeralPreviewUrls(
849 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
850): boolean {
851 return entries.some(
852 (entry) =>
853 entry.kind === "message" &&
854 entry.message !== undefined &&
855 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
856 );
857}
858
859export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
860 if (message.role !== "user" || !message.attachments) {
861 return [];
862 }
863 const previewUrls: string[] = [];
864 for (const attachment of message.attachments) {
865 if (!isImageAttachment(attachment)) continue;
866 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
867 previewUrls.push(attachment.previewUrl);
868 }
869 return previewUrls;
870}
871
872export interface PullRequestDialogState {
873 initialReference: string | null;
874 key: number;
875}
876
877export function readFileAsDataUrl(file: File): Promise<string> {
878 return new Promise((resolve, reject) => {
879 const reader = new FileReader();
880 reader.addEventListener("load", () => {
881 if (typeof reader.result === "string") {
882 resolve(reader.result);
883 return;
884 }
885 reject(new Error("Could not read image data."));
886 });
887 reader.addEventListener("error", () => {
888 reject(reader.error ?? new Error("Failed to read image."));
889 });
890 reader.readAsDataURL(file);
891 });
892}
893
894export function resolveSendEnvMode(input: {
895 requestedEnvMode: DraftThreadEnvMode;
896 isGitRepo: boolean;
897}): DraftThreadEnvMode {
898 return input.isGitRepo ? input.requestedEnvMode : "local";
899}
900
901export function resolveBackgroundDraftWorkspaceOptions(input: {
902 envMode: DraftThreadEnvMode;
903 branch: string | null;
904 startFromOrigin: boolean;
905}): {
906 envMode: DraftThreadEnvMode;
907 branch: string | null;
908 worktreePath: null;
909 startFromOrigin: boolean;
910} {
911 return {
912 envMode: input.envMode,
913 branch: input.branch,
914 worktreePath: null,
915 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
916 };
917}
918
919export function cloneComposerImageForRetry(
920 image: ComposerImageAttachment,
921): ComposerImageAttachment {
922 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
923 return image;
924 }
925 try {
926 return {
927 ...image,
928 previewUrl: URL.createObjectURL(image.file),
929 };
930 } catch {
931 return image;
932 }
933}
934
935export function deriveComposerSendState(options: {
936 prompt: string;
937 imageCount: number;
938 terminalContexts: ReadonlyArray<TerminalContextDraft>;
939 /**
940 * Optional element-pick attachment count. Element contexts contribute to
941 * "sendable content" exactly like images and (text-bearing) terminal
942 * contexts do: a prompt of just element chips is still a valid send.
943 */
944 elementContextCount?: number;
945}): {
946 trimmedPrompt: string;
947 sendableTerminalContexts: TerminalContextDraft[];
948 expiredTerminalContextCount: number;
949 hasSendableContent: boolean;
950} {
951 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
952 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
953 const expiredTerminalContextCount =
954 options.terminalContexts.length - sendableTerminalContexts.length;
955 const elementContextCount = options.elementContextCount ?? 0;
956 return {
957 trimmedPrompt,
958 sendableTerminalContexts,
959 expiredTerminalContextCount,
960 hasSendableContent:
961 trimmedPrompt.length > 0 ||
962 options.imageCount > 0 ||
963 sendableTerminalContexts.length > 0 ||
964 elementContextCount > 0,
965 };
966}
967
968export function buildExpiredTerminalContextToastCopy(
969 expiredTerminalContextCount: number,
970 variant: "omitted" | "empty",
971): { title: string; description: string } {
972 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
973 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
974 if (variant === "empty") {
975 return {
976 title: `${noun} won't be sent`,
977 description: "Remove it or re-add it to include terminal output.",
978 };
979 }
980 return {
981 title: `${noun} omitted from message`,
982 description: "Re-add it if you want that terminal output included.",
983 };
984}
985
986export function branchMismatchKey(
987 threadId: string | null,
988 mismatch: { threadBranch: string; currentBranch: string } | null,
989): string | null {
990 if (!threadId || !mismatch) {
991 return null;
992 }
993 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
994}
995
996// The mismatch banner only matters when the user is about to send: passive
997// reading of an old thread carries no risk (the branch picker tint already
998// covers ambient awareness). Draft content is the intent signal — composer
999// focus is useless here because ChatView autofocuses the composer on every
1000// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
1001// revealed so it doesn't flicker away when the draft is cleared.
1002export function shouldShowBranchMismatchBanner(input: {
1003 hasMismatch: boolean;
1004 isDismissed: boolean;
1005 composerHasContent: boolean;
1006 wasShownForCurrentMismatch: boolean;
1007}): boolean {
1008 if (!input.hasMismatch || input.isDismissed) {
1009 return false;
1010 }
1011 return input.composerHasContent || input.wasShownForCurrentMismatch;
1012}
1013
1014export function shouldShowPlanFollowUpPrompt(input: {
1015 pendingUserInputCount: number;
1016 interactionMode: ProviderInteractionMode;
1017 latestTurnSettled: boolean;
1018 hasActionableProposedPlan: boolean;
1019 hasComposerAttachments: boolean;
1020}): boolean {
1021 return (
1022 input.pendingUserInputCount === 0 &&
1023 input.interactionMode === "plan" &&
1024 input.latestTurnSettled &&
1025 input.hasActionableProposedPlan &&
1026 !input.hasComposerAttachments
1027 );
1028}
1029
1030// Session-scoped (module-level so it survives ChatView remounts, e.g. route
1031// changes). Durable cross-device dismissal is planned as a server-side ack.
1032const sessionDismissedBranchMismatchKeys = new Set<string>();
1033
1034export function dismissBranchMismatchForSession(key: string): void {
1035 sessionDismissedBranchMismatchKeys.add(key);
1036}
1037
1038export function isBranchMismatchDismissedForSession(key: string | null): boolean {
1039 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
1040}
1041
1042// Git status for a checkout arrives after the composer paints, and the branch
1043// strip mounts on the assumption that a project is a Git repo. Without a
1044// memory, a non-Git project would mount the strip and drop it on every visit.
1045// Keyed by environment and checkout for the session; never persisted.
1046const sessionCheckoutIsRepo = new Map<string, boolean>();
1047
1048function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
1049 return JSON.stringify([environmentId, cwd]);
1050}
1051
1052export function rememberCheckoutIsRepo(
1053 environmentId: EnvironmentId,
1054 cwd: string,
1055 isRepo: boolean,
1056): void {
1057 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
1058}
1059
1060export function recallCheckoutIsRepo(
1061 environmentId: EnvironmentId,
1062 cwd: string | null,
1063): boolean | undefined {
1064 return cwd === null
1065 ? undefined
1066 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
1067}
1068
1069export function threadHasStarted(thread: Thread | null | undefined): boolean {
1070 return Boolean(
1071 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
1072 );
1073}
1074
1075/**
1076 * Whether a thread ran at least one turn, judged from its shell alone.
1077 *
1078 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
1079 * still has messages, and the loading shell carries none. The shell records
1080 * when the last user message landed, which every started thread has.
1081 */
1082export function threadShellHasStarted(
1083 shell: Pick<ThreadShell, "latestTurn" | "latestUserMessageAt" | "session"> | null | undefined,
1084): boolean {
1085 return Boolean(
1086 shell &&
1087 (shell.latestTurn !== null || shell.latestUserMessageAt !== null || shell.session !== null),
1088 );
1089}
1090
1091// Imported history has no session until its first prompt. Resolve its instance
1092// through the environment's provider catalog before locking to a driver.
1093export function deriveLockedProvider(input: {
1094 thread: Thread | null | undefined;
1095 selectedProvider: string | null;
1096 threadProvider: string | null;
1097 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
1098}): ProviderDriverKind | null {
1099 if (!threadHasStarted(input.thread)) {
1100 return null;
1101 }
1102 const sessionProvider = input.thread?.session?.providerName ?? null;
1103 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
1104 return sessionProvider;
1105 }
1106 // Preserve the existing lock while an instance is missing from the catalog;
1107 // a started thread must not silently fall back to a different driver.
1108 const threadProvider =
1109 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
1110 input.threadProvider;
1111 const selectedProvider =
1112 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
1113 input.selectedProvider;
1114 const narrowedThreadProvider =
1115 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
1116 const narrowedSelectedProvider =
1117 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
1118 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
1119}
1120
1121export function getStartedThreadModelChangeBlockReason(input: {
1122 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
1123 hasStartedSession: boolean;
1124 currentModelSelection: ModelSelection;
1125 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
1126 nextModelSelection: ModelSelection;
1127}): { title: string; description: string } | null {
1128 if (!input.hasStartedSession) {
1129 return null;
1130 }
1131 const currentModelSelection = {
1132 ...input.currentModelSelection,
1133 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
1134 };
1135 if (
1136 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
1137 currentModelSelection.model === input.nextModelSelection.model
1138 ) {
1139 return null;
1140 }
1141 const currentProvider = input.providers.find(
1142 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1143 );
1144 const nextProvider = input.providers.find(
1145 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1146 );
1147 if (
1148 currentProvider?.requiresNewThreadForModelChange !== true &&
1149 nextProvider?.requiresNewThreadForModelChange !== true
1150 ) {
1151 return null;
1152 }
1153 return {
1154 title: "Start a new chat to change models",
1155 description: "This provider does not allow switching models after a conversation has started.",
1156 };
1157}
1158
1159export async function waitForStartedServerThread(
1160 threadRef: ScopedThreadRef,
1161 timeoutMs = 1_000,
1162): Promise<boolean> {
1163 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1164 const getThread = () => appAtomRegistry.get(threadAtom);
1165 const thread = getThread();
1166
1167 if (threadHasStarted(thread)) {
1168 return true;
1169 }
1170
1171 return await new Promise<boolean>((resolve) => {
1172 let settled = false;
1173 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
1174 const finish = (result: boolean) => {
1175 if (settled) {
1176 return;
1177 }
1178 settled = true;
1179 if (timeoutId !== null) {
1180 globalThis.clearTimeout(timeoutId);
1181 }
1182 unsubscribe();
1183 resolve(result);
1184 };
1185
1186 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
1187 if (!threadHasStarted(thread)) {
1188 return;
1189 }
1190 finish(true);
1191 });
1192
1193 if (threadHasStarted(getThread())) {
1194 finish(true);
1195 return;
1196 }
1197
1198 timeoutId = globalThis.setTimeout(() => {
1199 finish(false);
1200 }, timeoutMs);
1201 });
1202}
1203
1204export async function waitForRevertedMessage(
1205 threadRef: ScopedThreadRef,
1206 messageId: MessageId,
1207 turnCount: number,
1208 revert: () => Promise<void>,
1209 timeoutMs = 120_000,
1210): Promise<void> {
1211 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1212 const initial = appAtomRegistry.get(threadAtom);
1213 if (!initial?.messages.some((message) => message.id === messageId)) {
1214 throw new Error("The message to rewind is no longer available.");
1215 }
1216 const previousFailures = new Set(
1217 initial.activities
1218 .filter((activity) => activity.kind === "checkpoint.revert.failed")
1219 .map((activity) => activity.id),
1220 );
1221 return new Promise<void>((resolve, reject) => {
1222 let settled = false;
1223 let accepted = false;
1224 let unsubscribe = () => {};
1225 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1226 const finish = (error?: unknown) => {
1227 if (settled) return;
1228 settled = true;
1229 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1230 unsubscribe();
1231 if (error !== undefined) reject(error);
1232 else resolve();
1233 };
1234 const inspect = () => {
1235 const thread = appAtomRegistry.get(threadAtom);
1236 if (!thread) return;
1237 const failure = thread.activities.findLast(
1238 (activity) =>
1239 activity.kind === "checkpoint.revert.failed" && !previousFailures.has(activity.id),
1240 );
1241 if (failure) {
1242 const payload = failure.payload;
1243 finish(
1244 new Error(
1245 typeof payload === "object" &&
1246 payload !== null &&
1247 "detail" in payload &&
1248 typeof payload.detail === "string"
1249 ? payload.detail
1250 : failure.summary,
1251 ),
1252 );
1253 } else if (
1254 accepted &&
1255 !thread.messages.some((message) => message.id === messageId) &&
1256 thread.checkpoints.every((checkpoint) => checkpoint.checkpointTurnCount <= turnCount) &&
1257 (turnCount === 0
1258 ? thread.latestTurn === null
1259 : thread.checkpoints.some(
1260 (checkpoint) => checkpoint.turnId === thread.latestTurn?.turnId,
1261 ))
1262 ) {
1263 finish();
1264 }
1265 };
1266 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1267 timeout = globalThis.setTimeout(() => {
1268 finish(new Error("Timed out waiting for the thread to rewind."));
1269 }, timeoutMs);
1270 Promise.resolve()
1271 .then(revert)
1272 .then(() => {
1273 accepted = true;
1274 inspect();
1275 }, finish);
1276 });
1277}
1278
1279export interface LocalDispatchSnapshot {
1280 startedAt: string;
1281 preparingWorktree: boolean;
1282 submissionIntent: ComposerSubmissionIntent;
1283 latestUserMessageId: ChatMessage["id"] | null;
1284 latestTurnTurnId: TurnId | null;
1285 latestTurnRequestedAt: string | null;
1286 latestTurnStartedAt: string | null;
1287 latestTurnCompletedAt: string | null;
1288 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
1289 sessionUpdatedAt: string | null;
1290 latestTurnStartFailureId: string | null;
1291}
1292
1293export function latestTurnStartFailureId(
1294 activeThread: Thread | undefined,
1295 latestUserMessageId: ChatMessage["id"] | null,
1296): string | null {
1297 if (latestUserMessageId === null) return null;
1298 return (
1299 activeThread?.activities.findLast((activity) => {
1300 if (activity.kind !== "provider.turn.start.failed") return false;
1301 const payload =
1302 typeof activity.payload === "object" && activity.payload !== null
1303 ? (activity.payload as { readonly requestId?: unknown })
1304 : null;
1305 return payload?.requestId === latestUserMessageId;
1306 })?.id ?? null
1307 );
1308}
1309
1310export function createLocalDispatchSnapshot(
1311 activeThread: Thread | undefined,
1312 options?: {
1313 preparingWorktree?: boolean;
1314 submissionIntent?: ComposerSubmissionIntent;
1315 },
1316): LocalDispatchSnapshot {
1317 const latestTurn = activeThread?.latestTurn ?? null;
1318 const session = activeThread?.session ?? null;
1319 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
1320 return {
1321 startedAt: new Date().toISOString(),
1322 preparingWorktree: Boolean(options?.preparingWorktree),
1323 submissionIntent: options?.submissionIntent ?? "foreground",
1324 latestUserMessageId: latestUserMessage?.id ?? null,
1325 latestTurnTurnId: latestTurn?.turnId ?? null,
1326 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
1327 latestTurnStartedAt: latestTurn?.startedAt ?? null,
1328 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
1329 sessionStatus: session?.status ?? null,
1330 sessionUpdatedAt: session?.updatedAt ?? null,
1331 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
1332 };
1333}
1334
1335export function hasServerAcknowledgedLocalDispatch(input: {
1336 localDispatch: LocalDispatchSnapshot | null;
1337 phase: SessionPhase;
1338 latestTurn: Thread["latestTurn"] | null;
1339 latestUserMessageId: ChatMessage["id"] | null;
1340 session: Thread["session"] | null;
1341 hasPendingApproval: boolean;
1342 hasPendingUserInput: boolean;
1343 latestTurnStartFailureId?: string | null;
1344 threadError: string | null | undefined;
1345}): boolean {
1346 if (!input.localDispatch) {
1347 return false;
1348 }
1349 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1350 return true;
1351 }
1352 if (
1353 input.latestTurnStartFailureId !== undefined &&
1354 input.latestTurnStartFailureId !== null &&
1355 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
1356 ) {
1357 return true;
1358 }
1359 if (input.phase === "connecting") {
1360 return false;
1361 }
1362
1363 const latestTurn = input.latestTurn ?? null;
1364 const session = input.session ?? null;
1365 const latestUserMessageChanged =
1366 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
1367 const latestTurnChanged =
1368 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
1369 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
1370 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
1371 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
1372
1373 if (input.phase === "running") {
1374 // Steering adds a user message to the current running turn without
1375 // necessarily changing any of the turn timestamps. Treat that projected
1376 // message as the server acknowledgment so the composer does not remain
1377 // stuck in its local "Sending" state until the turn settles.
1378 if (latestUserMessageChanged) {
1379 return true;
1380 }
1381 if (!latestTurnChanged) {
1382 return false;
1383 }
1384 if (latestTurn?.startedAt === null || latestTurn === null) {
1385 return false;
1386 }
1387 if (
1388 session?.activeTurnId !== null &&
1389 session?.activeTurnId !== undefined &&
1390 latestTurn?.turnId !== session.activeTurnId
1391 ) {
1392 return false;
1393 }
1394 return true;
1395 }
1396
1397 return (
1398 latestTurnChanged ||
1399 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1400 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1401 );
1402}
1403
1404// Returning to the window should land the caret in the composer, so the reader can type right
1405// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1406// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1407// not one of them, so it yields to the composer.
1408export function shouldRefocusComposerOnWindowFocus(
1409 activeElement:
1410 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1411 | null,
1412): boolean {
1413 if (activeElement === null || activeElement.tagName === "BODY") return true;
1414 if (
1415 activeElement.tagName === "INPUT" ||
1416 activeElement.tagName === "TEXTAREA" ||
1417 activeElement.tagName === "SELECT" ||
1418 activeElement.tagName === "IFRAME" ||
1419 activeElement.tagName === "WEBVIEW" ||
1420 activeElement.isContentEditable === true ||
1421 activeElement.getAttribute("role") === "textbox"
1422 ) {
1423 return false;
1424 }
1425 return (
1426 activeElement.closest(
1427 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1428 ) === null
1429 );
1430}
1431
1432export interface PlanFollowUpComposerSnapshot {
1433 readonly prompt: string;
1434 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1435 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1436 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1437}
1438
1439/**
1440 * Puts back everything a plan follow-up send cleared when the send fails. The
1441 * caller clears the composer before awaiting the send, so every field it held
1442 * has to be written back here: a dropped field silently discards user context.
1443 */
1444export function restorePlanFollowUpComposer(input: {
1445 readonly snapshot: PlanFollowUpComposerSnapshot;
1446 readonly writePrompt: (prompt: string) => void;
1447 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1448 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1449 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1450 readonly resetCursor: (options: {
1451 cursor: number;
1452 prompt: string;
1453 detectTrigger: boolean;
1454 }) => void;
1455}): void {
1456 input.writePrompt(input.snapshot.prompt);
1457 input.writeTerminalContexts(input.snapshot.terminalContexts);
1458 input.writeReviewComments(input.snapshot.reviewComments);
1459 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1460 input.resetCursor({
1461 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1462 prompt: input.snapshot.prompt,
1463 detectTrigger: true,
1464 });
1465}