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