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