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 // Shells carry only a wait summary; the detail subscription supplies the
502 // full queued prompt once it loads.
503 pendingProviderTurn: null,
504 messages: [],
505 proposedPlans: [],
506 activities: [],
507 checkpoints: [],
508 deletedAt: null,
509 };
510}
511
512export function shouldWriteThreadErrorToCurrentServerThread(input: {
513 activeServerThread:
514 | {
515 environmentId: EnvironmentId;
516 id: ThreadId;
517 }
518 | null
519 | undefined;
520 routeThreadRef: ScopedThreadRef;
521 targetThreadId: ThreadId;
522}): boolean {
523 return Boolean(
524 input.activeServerThread &&
525 input.targetThreadId === input.routeThreadRef.threadId &&
526 input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
527 input.activeServerThread.id === input.targetThreadId,
528 );
529}
530
531export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
532 threadId: ThreadId;
533 turnId?: TurnId;
534} {
535 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
536 return {
537 threadId: thread.id,
538 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
539 };
540}
541
542/** Use the same enabled instance for the composer, provider status, and chat actions. */
543export function resolveComposerProviderSelection(input: {
544 entries: ReadonlyArray<ProviderInstanceEntry>;
545 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
546 lockedProvider: ProviderDriverKind | null;
547 lockedInstanceId: ProviderInstanceId | null | undefined;
548}) {
549 const requestedInstanceId = input.candidateInstanceIds.find(
550 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
551 );
552 const requestedDriverKind =
553 input.lockedProvider ??
554 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
555 input.entries[0]?.driverKind ??
556 ProviderDriverKind.make("unconfigured");
557 const lockedContinuationGroupKey = input.lockedProvider
558 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
559 ?.continuationGroupKey ?? null)
560 : null;
561 // Missing metadata must not move Antigravity history into another Google profile.
562 const requiresExactInstance =
563 input.lockedProvider === "antigravity" &&
564 input.lockedInstanceId != null &&
565 lockedContinuationGroupKey === null;
566 const compatibleEntries = input.entries.filter(
567 (entry) =>
568 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
569 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
570 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
571 );
572 const selectedProviderEntry =
573 input.candidateInstanceIds
574 .map((candidate) =>
575 compatibleEntries.find(
576 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
577 ),
578 )
579 .find((entry) => entry !== undefined) ??
580 resolveSelectableProviderInstanceEntry(
581 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
582 undefined,
583 ) ??
584 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
585 const unavailableProviderInstanceId = selectedProviderEntry
586 ? undefined
587 : input.lockedProvider
588 ? (input.lockedInstanceId ?? requestedInstanceId)
589 : requestedInstanceId;
590 return {
591 selectedProviderEntry,
592 requestedDriverKind,
593 lockedContinuationGroupKey,
594 unavailableProviderInstanceId,
595 };
596}
597
598/** Keep restored drafts and every plan control on the selected instance's supported mode. */
599export function resolveComposerInteractionMode(input: {
600 planModeEnabled: boolean;
601 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
602 interactionMode: ProviderInteractionMode;
603}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
604 const enabled =
605 input.planModeEnabled &&
606 input.provider != null &&
607 input.provider.showInteractionModeToggle !== false;
608 return {
609 enabled,
610 interactionMode: enabled ? input.interactionMode : "default",
611 };
612}
613
614export function getAntigravitySendBlockReason(
615 provider:
616 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
617 | null
618 | undefined,
619 model: string,
620): string | null {
621 if (provider?.driver !== "antigravity") return null;
622 if (!provider.installed) {
623 return "Install Antigravity in provider settings before sending.";
624 }
625 if (provider.auth.status === "unauthenticated") {
626 return "Sign in to Antigravity in provider settings before sending.";
627 }
628 const slug = model.trim();
629 if (slug.length === 0) return "Choose an Antigravity model before sending.";
630 // A restart clears the account status and catalog. Session startup checks
631 // saved credentials and validates the model before sending the prompt.
632 if (provider.auth.status === "unknown") return null;
633 if (provider.models.length === 0) {
634 return "Refresh Antigravity models in provider settings before sending.";
635 }
636 // A saved model that left the catalog is kept in the picker as unavailable
637 // so the user sees what the thread used. The server rejects it at turn
638 // start, so block here unless the provider is in an error state, where a
639 // retry with the same model is the right move.
640 if (
641 provider.status === "ready" &&
642 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
643 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
644 ) {
645 return "That Antigravity model is no longer available. Choose another model.";
646 }
647 return null;
648}
649
650export function buildRunningThreadTurnInterruptInput(
651 thread: Pick<Thread, "id" | "session"> | null | undefined,
652 phase: SessionPhase,
653): { threadId: ThreadId; turnId?: TurnId } | null {
654 if (phase !== "running" || thread?.session?.status !== "running") {
655 return null;
656 }
657 return buildThreadTurnInterruptInput(thread);
658}
659
660export function reconcileMountedTerminalThreadIds(input: {
661 currentThreadIds: ReadonlyArray<string>;
662 openThreadIds: ReadonlyArray<string>;
663 activeThreadId: string | null;
664 activeThreadTerminalOpen: boolean;
665 maxHiddenThreadCount?: number;
666}): string[] {
667 return reconcileRetainedMountedThreadIds({
668 currentThreadIds: input.currentThreadIds,
669 openThreadIds: input.openThreadIds,
670 activeThreadId: input.activeThreadId,
671 activeThreadOpen: input.activeThreadTerminalOpen,
672 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
673 });
674}
675
676export function reconcileRetainedMountedThreadIds(input: {
677 currentThreadIds: ReadonlyArray<string>;
678 openThreadIds: ReadonlyArray<string>;
679 activeThreadId: string | null;
680 activeThreadOpen: boolean;
681 maxHiddenThreadCount: number;
682 retainInactiveActiveThread?: boolean;
683}): string[] {
684 const openThreadIdSet = new Set(input.openThreadIds);
685 const hiddenThreadIds = input.currentThreadIds.filter(
686 (threadId) =>
687 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
688 openThreadIdSet.has(threadId),
689 );
690 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
691 const nextThreadIds =
692 hiddenThreadIds.length > maxHiddenThreadCount
693 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
694 : hiddenThreadIds;
695
696 if (
697 input.activeThreadId &&
698 input.activeThreadOpen &&
699 !nextThreadIds.includes(input.activeThreadId)
700 ) {
701 nextThreadIds.push(input.activeThreadId);
702 }
703
704 return nextThreadIds;
705}
706
707export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
708 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
709 return;
710 }
711 URL.revokeObjectURL(previewUrl);
712}
713
714/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
715export async function resolveFileAttachmentUrl(input: {
716 attachment: ChatFileAttachment;
717 environmentId: EnvironmentId;
718 httpBaseUrl: string;
719 createAssetUrl: (input: {
720 environmentId: EnvironmentId;
721 input: AssetCreateUrlInput;
722 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
723}): Promise<string> {
724 const { attachment } = input;
725 const result = await input.createAssetUrl({
726 environmentId: input.environmentId,
727 input: {
728 resource: {
729 _tag: "attachment",
730 attachmentId: attachment.id,
731 fileName: attachment.name,
732 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
733 },
734 },
735 });
736 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
737 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
738 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
739 return url;
740}
741
742export async function prepareRevertedMessageAttachments(input: {
743 message: ChatMessage;
744 environmentId: EnvironmentId;
745 httpBaseUrl: string;
746 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
747}): Promise<File[]> {
748 return Promise.all(
749 (input.message.attachments ?? []).map(async (attachment) => {
750 if (attachment.type !== "image" && attachment.type !== "file") {
751 throw new Error("This message has an attachment that cannot be restored.");
752 }
753 const result = await input.createAssetUrl({
754 environmentId: input.environmentId,
755 input: {
756 resource: {
757 _tag: "attachment",
758 attachmentId: attachment.id,
759 fileName: attachment.name,
760 mimeType: attachment.mimeType,
761 },
762 },
763 });
764 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
765 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
766 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
767 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
768 if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
769 return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
770 }),
771 );
772}
773
774export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
775 if (message.role !== "user" || !message.attachments) {
776 return;
777 }
778 for (const attachment of message.attachments) {
779 if (!isImageAttachment(attachment)) {
780 continue;
781 }
782 revokeBlobPreviewUrl(attachment.previewUrl);
783 }
784}
785
786export function timelineHasEphemeralPreviewUrls(
787 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
788): boolean {
789 return entries.some(
790 (entry) =>
791 entry.kind === "message" &&
792 entry.message !== undefined &&
793 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
794 );
795}
796
797export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
798 if (message.role !== "user" || !message.attachments) {
799 return [];
800 }
801 const previewUrls: string[] = [];
802 for (const attachment of message.attachments) {
803 if (!isImageAttachment(attachment)) continue;
804 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
805 previewUrls.push(attachment.previewUrl);
806 }
807 return previewUrls;
808}
809
810export interface PullRequestDialogState {
811 initialReference: string | null;
812 key: number;
813}
814
815export function readFileAsDataUrl(file: File): Promise<string> {
816 return new Promise((resolve, reject) => {
817 const reader = new FileReader();
818 reader.addEventListener("load", () => {
819 if (typeof reader.result === "string") {
820 resolve(reader.result);
821 return;
822 }
823 reject(new Error("Could not read image data."));
824 });
825 reader.addEventListener("error", () => {
826 reject(reader.error ?? new Error("Failed to read image."));
827 });
828 reader.readAsDataURL(file);
829 });
830}
831
832export function resolveSendEnvMode(input: {
833 requestedEnvMode: DraftThreadEnvMode;
834 isGitRepo: boolean;
835}): DraftThreadEnvMode {
836 return input.isGitRepo ? input.requestedEnvMode : "local";
837}
838
839export function resolveBackgroundDraftWorkspaceOptions(input: {
840 envMode: DraftThreadEnvMode;
841 branch: string | null;
842 startFromOrigin: boolean;
843}): {
844 envMode: DraftThreadEnvMode;
845 branch: string | null;
846 worktreePath: null;
847 startFromOrigin: boolean;
848} {
849 return {
850 envMode: input.envMode,
851 branch: input.branch,
852 worktreePath: null,
853 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
854 };
855}
856
857export function cloneComposerImageForRetry(
858 image: ComposerImageAttachment,
859): ComposerImageAttachment {
860 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
861 return image;
862 }
863 try {
864 return {
865 ...image,
866 previewUrl: URL.createObjectURL(image.file),
867 };
868 } catch {
869 return image;
870 }
871}
872
873export function deriveComposerSendState(options: {
874 prompt: string;
875 imageCount: number;
876 terminalContexts: ReadonlyArray<TerminalContextDraft>;
877 /**
878 * Optional element-pick attachment count. Element contexts contribute to
879 * "sendable content" exactly like images and (text-bearing) terminal
880 * contexts do: a prompt of just element chips is still a valid send.
881 */
882 elementContextCount?: number;
883}): {
884 trimmedPrompt: string;
885 sendableTerminalContexts: TerminalContextDraft[];
886 expiredTerminalContextCount: number;
887 hasSendableContent: boolean;
888} {
889 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
890 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
891 const expiredTerminalContextCount =
892 options.terminalContexts.length - sendableTerminalContexts.length;
893 const elementContextCount = options.elementContextCount ?? 0;
894 return {
895 trimmedPrompt,
896 sendableTerminalContexts,
897 expiredTerminalContextCount,
898 hasSendableContent:
899 trimmedPrompt.length > 0 ||
900 options.imageCount > 0 ||
901 sendableTerminalContexts.length > 0 ||
902 elementContextCount > 0,
903 };
904}
905
906export function buildExpiredTerminalContextToastCopy(
907 expiredTerminalContextCount: number,
908 variant: "omitted" | "empty",
909): { title: string; description: string } {
910 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
911 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
912 if (variant === "empty") {
913 return {
914 title: `${noun} won't be sent`,
915 description: "Remove it or re-add it to include terminal output.",
916 };
917 }
918 return {
919 title: `${noun} omitted from message`,
920 description: "Re-add it if you want that terminal output included.",
921 };
922}
923
924export function branchMismatchKey(
925 threadId: string | null,
926 mismatch: { threadBranch: string; currentBranch: string } | null,
927): string | null {
928 if (!threadId || !mismatch) {
929 return null;
930 }
931 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
932}
933
934// The mismatch banner only matters when the user is about to send: passive
935// reading of an old thread carries no risk (the branch picker tint already
936// covers ambient awareness). Draft content is the intent signal — composer
937// focus is useless here because ChatView autofocuses the composer on every
938// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
939// revealed so it doesn't flicker away when the draft is cleared.
940export function shouldShowBranchMismatchBanner(input: {
941 hasMismatch: boolean;
942 isDismissed: boolean;
943 composerHasContent: boolean;
944 wasShownForCurrentMismatch: boolean;
945}): boolean {
946 if (!input.hasMismatch || input.isDismissed) {
947 return false;
948 }
949 return input.composerHasContent || input.wasShownForCurrentMismatch;
950}
951
952export function shouldShowPlanFollowUpPrompt(input: {
953 pendingUserInputCount: number;
954 interactionMode: ProviderInteractionMode;
955 latestTurnSettled: boolean;
956 hasActionableProposedPlan: boolean;
957 hasComposerAttachments: boolean;
958}): boolean {
959 return (
960 input.pendingUserInputCount === 0 &&
961 input.interactionMode === "plan" &&
962 input.latestTurnSettled &&
963 input.hasActionableProposedPlan &&
964 !input.hasComposerAttachments
965 );
966}
967
968// Session-scoped (module-level so it survives ChatView remounts, e.g. route
969// changes). Durable cross-device dismissal is planned as a server-side ack.
970const sessionDismissedBranchMismatchKeys = new Set<string>();
971
972export function dismissBranchMismatchForSession(key: string): void {
973 sessionDismissedBranchMismatchKeys.add(key);
974}
975
976export function isBranchMismatchDismissedForSession(key: string | null): boolean {
977 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
978}
979
980// Git status for a checkout arrives after the composer paints, and the branch
981// strip mounts on the assumption that a project is a Git repo. Without a
982// memory, a non-Git project would mount the strip and drop it on every visit.
983// Keyed by environment and checkout for the session; never persisted.
984const sessionCheckoutIsRepo = new Map<string, boolean>();
985
986function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
987 return JSON.stringify([environmentId, cwd]);
988}
989
990export function rememberCheckoutIsRepo(
991 environmentId: EnvironmentId,
992 cwd: string,
993 isRepo: boolean,
994): void {
995 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
996}
997
998export function recallCheckoutIsRepo(
999 environmentId: EnvironmentId,
1000 cwd: string | null,
1001): boolean | undefined {
1002 return cwd === null
1003 ? undefined
1004 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
1005}
1006
1007export function threadHasStarted(thread: Thread | null | undefined): boolean {
1008 return Boolean(
1009 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
1010 );
1011}
1012
1013/**
1014 * Whether a thread ran at least one turn, judged from its shell alone.
1015 *
1016 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
1017 * still has messages, and the loading shell carries none. The shell records
1018 * when the last user message landed, which every started thread has.
1019 */
1020export function threadShellHasStarted(
1021 shell: Pick<ThreadShell, "latestTurn" | "latestUserMessageAt" | "session"> | null | undefined,
1022): boolean {
1023 return Boolean(
1024 shell &&
1025 (shell.latestTurn !== null || shell.latestUserMessageAt !== null || shell.session !== null),
1026 );
1027}
1028
1029// Imported history has no session until its first prompt. Resolve its instance
1030// through the environment's provider catalog before locking to a driver.
1031export function deriveLockedProvider(input: {
1032 thread: Thread | null | undefined;
1033 selectedProvider: string | null;
1034 threadProvider: string | null;
1035 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
1036}): ProviderDriverKind | null {
1037 if (!threadHasStarted(input.thread)) {
1038 return null;
1039 }
1040 const sessionProvider = input.thread?.session?.providerName ?? null;
1041 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
1042 return sessionProvider;
1043 }
1044 // Preserve the existing lock while an instance is missing from the catalog;
1045 // a started thread must not silently fall back to a different driver.
1046 const threadProvider =
1047 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
1048 input.threadProvider;
1049 const selectedProvider =
1050 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
1051 input.selectedProvider;
1052 const narrowedThreadProvider =
1053 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
1054 const narrowedSelectedProvider =
1055 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
1056 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
1057}
1058
1059export function getStartedThreadModelChangeBlockReason(input: {
1060 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
1061 hasStartedSession: boolean;
1062 currentModelSelection: ModelSelection;
1063 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
1064 nextModelSelection: ModelSelection;
1065}): { title: string; description: string } | null {
1066 if (!input.hasStartedSession) {
1067 return null;
1068 }
1069 const currentModelSelection = {
1070 ...input.currentModelSelection,
1071 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
1072 };
1073 if (
1074 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
1075 currentModelSelection.model === input.nextModelSelection.model
1076 ) {
1077 return null;
1078 }
1079 const currentProvider = input.providers.find(
1080 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1081 );
1082 const nextProvider = input.providers.find(
1083 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1084 );
1085 if (
1086 currentProvider?.requiresNewThreadForModelChange !== true &&
1087 nextProvider?.requiresNewThreadForModelChange !== true
1088 ) {
1089 return null;
1090 }
1091 return {
1092 title: "Start a new chat to change models",
1093 description: "This provider does not allow switching models after a conversation has started.",
1094 };
1095}
1096
1097export async function waitForStartedServerThread(
1098 threadRef: ScopedThreadRef,
1099 timeoutMs = 1_000,
1100): Promise<boolean> {
1101 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1102 const getThread = () => appAtomRegistry.get(threadAtom);
1103 const thread = getThread();
1104
1105 if (threadHasStarted(thread)) {
1106 return true;
1107 }
1108
1109 return await new Promise<boolean>((resolve) => {
1110 let settled = false;
1111 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
1112 const finish = (result: boolean) => {
1113 if (settled) {
1114 return;
1115 }
1116 settled = true;
1117 if (timeoutId !== null) {
1118 globalThis.clearTimeout(timeoutId);
1119 }
1120 unsubscribe();
1121 resolve(result);
1122 };
1123
1124 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
1125 if (!threadHasStarted(thread)) {
1126 return;
1127 }
1128 finish(true);
1129 });
1130
1131 if (threadHasStarted(getThread())) {
1132 finish(true);
1133 return;
1134 }
1135
1136 timeoutId = globalThis.setTimeout(() => {
1137 finish(false);
1138 }, timeoutMs);
1139 });
1140}
1141
1142export async function waitForRevertedMessage(
1143 threadRef: ScopedThreadRef,
1144 messageId: MessageId,
1145 turnCount: number,
1146 revert: () => Promise<void>,
1147 timeoutMs = 120_000,
1148): Promise<void> {
1149 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1150 const initial = appAtomRegistry.get(threadAtom);
1151 if (!initial?.messages.some((message) => message.id === messageId)) {
1152 throw new Error("The message to rewind is no longer available.");
1153 }
1154 const previousFailures = new Set(
1155 initial.activities
1156 .filter((activity) => activity.kind === "checkpoint.revert.failed")
1157 .map((activity) => activity.id),
1158 );
1159 return new Promise<void>((resolve, reject) => {
1160 let settled = false;
1161 let accepted = false;
1162 let unsubscribe = () => {};
1163 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1164 const finish = (error?: unknown) => {
1165 if (settled) return;
1166 settled = true;
1167 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1168 unsubscribe();
1169 if (error !== undefined) reject(error);
1170 else resolve();
1171 };
1172 const inspect = () => {
1173 const thread = appAtomRegistry.get(threadAtom);
1174 if (!thread) return;
1175 const failure = thread.activities.findLast(
1176 (activity) =>
1177 activity.kind === "checkpoint.revert.failed" && !previousFailures.has(activity.id),
1178 );
1179 if (failure) {
1180 const payload = failure.payload;
1181 finish(
1182 new Error(
1183 typeof payload === "object" &&
1184 payload !== null &&
1185 "detail" in payload &&
1186 typeof payload.detail === "string"
1187 ? payload.detail
1188 : failure.summary,
1189 ),
1190 );
1191 } else if (
1192 accepted &&
1193 !thread.messages.some((message) => message.id === messageId) &&
1194 thread.checkpoints.every((checkpoint) => checkpoint.checkpointTurnCount <= turnCount) &&
1195 (turnCount === 0
1196 ? thread.latestTurn === null
1197 : thread.checkpoints.some(
1198 (checkpoint) => checkpoint.turnId === thread.latestTurn?.turnId,
1199 ))
1200 ) {
1201 finish();
1202 }
1203 };
1204 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1205 timeout = globalThis.setTimeout(() => {
1206 finish(new Error("Timed out waiting for the thread to rewind."));
1207 }, timeoutMs);
1208 Promise.resolve()
1209 .then(revert)
1210 .then(() => {
1211 accepted = true;
1212 inspect();
1213 }, finish);
1214 });
1215}
1216
1217export interface LocalDispatchSnapshot {
1218 startedAt: string;
1219 preparingWorktree: boolean;
1220 submissionIntent: ComposerSubmissionIntent;
1221 latestUserMessageId: ChatMessage["id"] | null;
1222 latestTurnTurnId: TurnId | null;
1223 latestTurnRequestedAt: string | null;
1224 latestTurnStartedAt: string | null;
1225 latestTurnCompletedAt: string | null;
1226 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
1227 sessionUpdatedAt: string | null;
1228 latestTurnStartFailureId: string | null;
1229}
1230
1231export function latestTurnStartFailureId(
1232 activeThread: Thread | undefined,
1233 latestUserMessageId: ChatMessage["id"] | null,
1234): string | null {
1235 if (latestUserMessageId === null) return null;
1236 return (
1237 activeThread?.activities.findLast((activity) => {
1238 if (activity.kind !== "provider.turn.start.failed") return false;
1239 const payload =
1240 typeof activity.payload === "object" && activity.payload !== null
1241 ? (activity.payload as { readonly requestId?: unknown })
1242 : null;
1243 return payload?.requestId === latestUserMessageId;
1244 })?.id ?? null
1245 );
1246}
1247
1248export function createLocalDispatchSnapshot(
1249 activeThread: Thread | undefined,
1250 options?: {
1251 preparingWorktree?: boolean;
1252 submissionIntent?: ComposerSubmissionIntent;
1253 },
1254): LocalDispatchSnapshot {
1255 const latestTurn = activeThread?.latestTurn ?? null;
1256 const session = activeThread?.session ?? null;
1257 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
1258 return {
1259 startedAt: new Date().toISOString(),
1260 preparingWorktree: Boolean(options?.preparingWorktree),
1261 submissionIntent: options?.submissionIntent ?? "foreground",
1262 latestUserMessageId: latestUserMessage?.id ?? null,
1263 latestTurnTurnId: latestTurn?.turnId ?? null,
1264 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
1265 latestTurnStartedAt: latestTurn?.startedAt ?? null,
1266 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
1267 sessionStatus: session?.status ?? null,
1268 sessionUpdatedAt: session?.updatedAt ?? null,
1269 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
1270 };
1271}
1272
1273export function hasServerAcknowledgedLocalDispatch(input: {
1274 localDispatch: LocalDispatchSnapshot | null;
1275 phase: SessionPhase;
1276 latestTurn: Thread["latestTurn"] | null;
1277 latestUserMessageId: ChatMessage["id"] | null;
1278 session: Thread["session"] | null;
1279 hasPendingApproval: boolean;
1280 hasPendingUserInput: boolean;
1281 latestTurnStartFailureId?: string | null;
1282 threadError: string | null | undefined;
1283}): boolean {
1284 if (!input.localDispatch) {
1285 return false;
1286 }
1287 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1288 return true;
1289 }
1290 if (
1291 input.latestTurnStartFailureId !== undefined &&
1292 input.latestTurnStartFailureId !== null &&
1293 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
1294 ) {
1295 return true;
1296 }
1297 if (input.phase === "connecting") {
1298 return false;
1299 }
1300
1301 const latestTurn = input.latestTurn ?? null;
1302 const session = input.session ?? null;
1303 const latestUserMessageChanged =
1304 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
1305 const latestTurnChanged =
1306 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
1307 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
1308 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
1309 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
1310
1311 if (input.phase === "running") {
1312 // Steering adds a user message to the current running turn without
1313 // necessarily changing any of the turn timestamps. Treat that projected
1314 // message as the server acknowledgment so the composer does not remain
1315 // stuck in its local "Sending" state until the turn settles.
1316 if (latestUserMessageChanged) {
1317 return true;
1318 }
1319 if (!latestTurnChanged) {
1320 return false;
1321 }
1322 if (latestTurn?.startedAt === null || latestTurn === null) {
1323 return false;
1324 }
1325 if (
1326 session?.activeTurnId !== null &&
1327 session?.activeTurnId !== undefined &&
1328 latestTurn?.turnId !== session.activeTurnId
1329 ) {
1330 return false;
1331 }
1332 return true;
1333 }
1334
1335 return (
1336 latestTurnChanged ||
1337 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1338 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1339 );
1340}
1341
1342// Returning to the window should land the caret in the composer, so the reader can type right
1343// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1344// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1345// not one of them, so it yields to the composer.
1346export function shouldRefocusComposerOnWindowFocus(
1347 activeElement:
1348 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1349 | null,
1350): boolean {
1351 if (activeElement === null || activeElement.tagName === "BODY") return true;
1352 if (
1353 activeElement.tagName === "INPUT" ||
1354 activeElement.tagName === "TEXTAREA" ||
1355 activeElement.tagName === "SELECT" ||
1356 activeElement.isContentEditable === true ||
1357 activeElement.getAttribute("role") === "textbox"
1358 ) {
1359 return false;
1360 }
1361 return (
1362 activeElement.closest(
1363 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1364 ) === null
1365 );
1366}
1367
1368export interface PlanFollowUpComposerSnapshot {
1369 readonly prompt: string;
1370 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1371 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1372 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1373}
1374
1375/**
1376 * Puts back everything a plan follow-up send cleared when the send fails. The
1377 * caller clears the composer before awaiting the send, so every field it held
1378 * has to be written back here: a dropped field silently discards user context.
1379 */
1380export function restorePlanFollowUpComposer(input: {
1381 readonly snapshot: PlanFollowUpComposerSnapshot;
1382 readonly writePrompt: (prompt: string) => void;
1383 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1384 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1385 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1386 readonly resetCursor: (options: {
1387 cursor: number;
1388 prompt: string;
1389 detectTrigger: boolean;
1390 }) => void;
1391}): void {
1392 input.writePrompt(input.snapshot.prompt);
1393 input.writeTerminalContexts(input.snapshot.terminalContexts);
1394 input.writeReviewComments(input.snapshot.reviewComments);
1395 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1396 input.resetCursor({
1397 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1398 prompt: input.snapshot.prompt,
1399 detectTrigger: true,
1400 });
1401}