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 function readFileAsDataUrl(file: File): Promise<string> {
814 return new Promise((resolve, reject) => {
815 const reader = new FileReader();
816 reader.addEventListener("load", () => {
817 if (typeof reader.result === "string") {
818 resolve(reader.result);
819 return;
820 }
821 reject(new Error("Could not read image data."));
822 });
823 reader.addEventListener("error", () => {
824 reject(reader.error ?? new Error("Failed to read image."));
825 });
826 reader.readAsDataURL(file);
827 });
828}
829
830export function resolveSendEnvMode(input: {
831 requestedEnvMode: DraftThreadEnvMode;
832 isGitRepo: boolean;
833}): DraftThreadEnvMode {
834 return input.isGitRepo ? input.requestedEnvMode : "local";
835}
836
837export function resolveBackgroundDraftWorkspaceOptions(input: {
838 envMode: DraftThreadEnvMode;
839 branch: string | null;
840 startFromOrigin: boolean;
841}): {
842 envMode: DraftThreadEnvMode;
843 branch: string | null;
844 worktreePath: null;
845 startFromOrigin: boolean;
846} {
847 return {
848 envMode: input.envMode,
849 branch: input.branch,
850 worktreePath: null,
851 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
852 };
853}
854
855export function cloneComposerImageForRetry(
856 image: ComposerImageAttachment,
857): ComposerImageAttachment {
858 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
859 return image;
860 }
861 try {
862 return {
863 ...image,
864 previewUrl: URL.createObjectURL(image.file),
865 };
866 } catch {
867 return image;
868 }
869}
870
871export function deriveComposerSendState(options: {
872 prompt: string;
873 imageCount: number;
874 terminalContexts: ReadonlyArray<TerminalContextDraft>;
875 /**
876 * Optional element-pick attachment count. Element contexts contribute to
877 * "sendable content" exactly like images and (text-bearing) terminal
878 * contexts do: a prompt of just element chips is still a valid send.
879 */
880 elementContextCount?: number;
881}): {
882 trimmedPrompt: string;
883 sendableTerminalContexts: TerminalContextDraft[];
884 expiredTerminalContextCount: number;
885 hasSendableContent: boolean;
886} {
887 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
888 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
889 const expiredTerminalContextCount =
890 options.terminalContexts.length - sendableTerminalContexts.length;
891 const elementContextCount = options.elementContextCount ?? 0;
892 return {
893 trimmedPrompt,
894 sendableTerminalContexts,
895 expiredTerminalContextCount,
896 hasSendableContent:
897 trimmedPrompt.length > 0 ||
898 options.imageCount > 0 ||
899 sendableTerminalContexts.length > 0 ||
900 elementContextCount > 0,
901 };
902}
903
904export function buildExpiredTerminalContextToastCopy(
905 expiredTerminalContextCount: number,
906 variant: "omitted" | "empty",
907): { title: string; description: string } {
908 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
909 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
910 if (variant === "empty") {
911 return {
912 title: `${noun} won't be sent`,
913 description: "Remove it or re-add it to include terminal output.",
914 };
915 }
916 return {
917 title: `${noun} omitted from message`,
918 description: "Re-add it if you want that terminal output included.",
919 };
920}
921
922export function branchMismatchKey(
923 threadId: string | null,
924 mismatch: { threadBranch: string; currentBranch: string } | null,
925): string | null {
926 if (!threadId || !mismatch) {
927 return null;
928 }
929 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
930}
931
932// The mismatch banner only matters when the user is about to send: passive
933// reading of an old thread carries no risk (the branch picker tint already
934// covers ambient awareness). Draft content is the intent signal — composer
935// focus is useless here because ChatView autofocuses the composer on every
936// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
937// revealed so it doesn't flicker away when the draft is cleared.
938export function shouldShowBranchMismatchBanner(input: {
939 hasMismatch: boolean;
940 isDismissed: boolean;
941 composerHasContent: boolean;
942 wasShownForCurrentMismatch: boolean;
943}): boolean {
944 if (!input.hasMismatch || input.isDismissed) {
945 return false;
946 }
947 return input.composerHasContent || input.wasShownForCurrentMismatch;
948}
949
950export function shouldShowPlanFollowUpPrompt(input: {
951 pendingUserInputCount: number;
952 interactionMode: ProviderInteractionMode;
953 latestTurnSettled: boolean;
954 hasActionableProposedPlan: boolean;
955 hasComposerAttachments: boolean;
956}): boolean {
957 return (
958 input.pendingUserInputCount === 0 &&
959 input.interactionMode === "plan" &&
960 input.latestTurnSettled &&
961 input.hasActionableProposedPlan &&
962 !input.hasComposerAttachments
963 );
964}
965
966// Session-scoped (module-level so it survives ChatView remounts, e.g. route
967// changes). Durable cross-device dismissal is planned as a server-side ack.
968const sessionDismissedBranchMismatchKeys = new Set<string>();
969
970export function dismissBranchMismatchForSession(key: string): void {
971 sessionDismissedBranchMismatchKeys.add(key);
972}
973
974export function isBranchMismatchDismissedForSession(key: string | null): boolean {
975 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
976}
977
978// Git status for a checkout arrives after the composer paints, and the branch
979// strip mounts on the assumption that a project is a Git repo. Without a
980// memory, a non-Git project would mount the strip and drop it on every visit.
981// Keyed by environment and checkout for the session; never persisted.
982const sessionCheckoutIsRepo = new Map<string, boolean>();
983
984function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
985 return JSON.stringify([environmentId, cwd]);
986}
987
988export function rememberCheckoutIsRepo(
989 environmentId: EnvironmentId,
990 cwd: string,
991 isRepo: boolean,
992): void {
993 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
994}
995
996export function recallCheckoutIsRepo(
997 environmentId: EnvironmentId,
998 cwd: string | null,
999): boolean | undefined {
1000 return cwd === null
1001 ? undefined
1002 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
1003}
1004
1005export function threadHasStarted(thread: Thread | null | undefined): boolean {
1006 return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
1007}
1008
1009/**
1010 * Whether a thread ran at least one turn, judged from its shell alone.
1011 *
1012 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
1013 * still has messages, and the loading shell carries none. The shell records
1014 * when the last user message landed, which every started thread has.
1015 */
1016export function threadShellHasStarted(
1017 shell:
1018 | Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt" | "runtime">
1019 | null
1020 | undefined,
1021): boolean {
1022 return Boolean(
1023 shell &&
1024 (shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null),
1025 );
1026}
1027
1028// Imported history has no session until its first prompt. Resolve its instance
1029// through the environment's provider catalog before locking to a driver.
1030export function deriveLockedProvider(input: {
1031 thread: Thread | null | undefined;
1032 selectedProvider: string | null;
1033 threadProvider: string | null;
1034 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
1035}): ProviderDriverKind | null {
1036 if (!threadHasStarted(input.thread)) {
1037 return null;
1038 }
1039 const sessionProvider = input.thread?.runtime?.providerName ?? null;
1040 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
1041 return sessionProvider;
1042 }
1043 // Preserve the existing lock while an instance is missing from the catalog;
1044 // a started thread must not silently fall back to a different driver.
1045 const threadProvider =
1046 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
1047 input.threadProvider;
1048 const selectedProvider =
1049 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
1050 input.selectedProvider;
1051 const narrowedThreadProvider =
1052 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
1053 const narrowedSelectedProvider =
1054 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
1055 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
1056}
1057
1058export function getStartedThreadModelChangeBlockReason(input: {
1059 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
1060 hasStartedSession: boolean;
1061 supportsProviderSwitchingViaHandoff?: 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 if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
1080 if (input.supportsProviderSwitchingViaHandoff === true) {
1081 return null;
1082 }
1083 return {
1084 title: "Start a new chat to switch providers",
1085 description: "This thread does not support switching providers after it has started.",
1086 };
1087 }
1088 const currentProvider = input.providers.find(
1089 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1090 );
1091 const nextProvider = input.providers.find(
1092 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1093 );
1094 if (
1095 currentProvider?.requiresNewThreadForModelChange !== true &&
1096 nextProvider?.requiresNewThreadForModelChange !== true
1097 ) {
1098 return null;
1099 }
1100 return {
1101 title: "Start a new chat to change models",
1102 description: "This provider does not allow switching models after a conversation has started.",
1103 };
1104}
1105
1106export async function waitForStartedServerThread(
1107 threadRef: ScopedThreadRef,
1108 timeoutMs = 1_000,
1109): Promise<boolean> {
1110 const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
1111 return waitForAtomValue({
1112 registry: appAtomRegistry,
1113 atom: threadAtom,
1114 predicate: threadHasStarted,
1115 timeoutMs,
1116 });
1117}
1118
1119/**
1120 * Runs `revert` (the rollback command `requestId`) and resolves once the
1121 * message's run is rolled back. Rejects with the server's reason as soon as
1122 * the thread records that this rollback failed.
1123 */
1124export async function waitForRevertedMessage(
1125 threadRef: ScopedThreadRef,
1126 messageId: MessageId,
1127 turnCount: number,
1128 requestId: CommandId,
1129 revert: () => Promise<void>,
1130 timeoutMs = 120_000,
1131): Promise<void> {
1132 const threadAtom = environmentThreadDetails.stateAtom(threadRef);
1133 const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);
1134 const initial = readProjection();
1135 if (!initial?.messages.some((message) => message.id === messageId)) {
1136 throw new Error("The message to rewind is no longer available.");
1137 }
1138 const messageRunId = initial.messages.find((message) => message.id === messageId)?.runId;
1139 return new Promise<void>((resolve, reject) => {
1140 let settled = false;
1141 let accepted = false;
1142 let unsubscribe = () => {};
1143 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1144 const finish = (error?: unknown) => {
1145 if (settled) return;
1146 settled = true;
1147 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1148 unsubscribe();
1149 if (error !== undefined) reject(error);
1150 else resolve();
1151 };
1152 const inspect = () => {
1153 const thread = readProjection();
1154 if (!thread) return;
1155 const failure = thread.thread.rollbackFailure;
1156 if (failure?.requestId === requestId) {
1157 finish(new Error(failure.message));
1158 return;
1159 }
1160 if (
1161 accepted &&
1162 thread.runs.some(
1163 (run) =>
1164 run.id === messageRunId && run.ordinal > turnCount && run.status === "rolled_back",
1165 )
1166 )
1167 finish();
1168 };
1169 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1170 timeout = globalThis.setTimeout(() => {
1171 finish(new Error("Timed out waiting for the thread to rewind."));
1172 }, timeoutMs);
1173 Promise.resolve()
1174 .then(revert)
1175 .then(() => {
1176 accepted = true;
1177 inspect();
1178 }, finish);
1179 });
1180}
1181
1182export interface LocalDispatchSnapshot {
1183 startedAt: string;
1184 preparingWorktree: boolean;
1185 submissionIntent: ComposerSubmissionIntent;
1186 latestUserMessageId: ChatMessage["id"] | null;
1187 latestRunId: RunId | null;
1188 latestRunRequestedAt: string | null;
1189 latestRunStartedAt: string | null;
1190 latestRunCompletedAt: string | null;
1191 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
1192 runtimeUpdatedAt: string | null;
1193}
1194
1195export function createLocalDispatchSnapshot(
1196 activeThread: Thread | undefined,
1197 options?: {
1198 preparingWorktree?: boolean;
1199 latestUserMessageId?: ChatMessage["id"] | null;
1200 submissionIntent?: ComposerSubmissionIntent;
1201 },
1202): LocalDispatchSnapshot {
1203 const latestRun = activeThread?.latestRun ?? null;
1204 const runtime = activeThread?.runtime ?? null;
1205 return {
1206 startedAt: new Date().toISOString(),
1207 preparingWorktree: Boolean(options?.preparingWorktree),
1208 submissionIntent: options?.submissionIntent ?? "foreground",
1209 latestUserMessageId: options?.latestUserMessageId ?? null,
1210 latestRunId: latestRun?.runId ?? null,
1211 latestRunRequestedAt: latestRun?.requestedAt ?? null,
1212 latestRunStartedAt: latestRun?.startedAt ?? null,
1213 latestRunCompletedAt: latestRun?.completedAt ?? null,
1214 runtimeStatus: runtime?.status ?? null,
1215 runtimeUpdatedAt: runtime?.updatedAt ?? null,
1216 };
1217}
1218
1219/**
1220 * The timeline renders committed user rows from `visibleTurnItems`, but
1221 * `message.updated` can land in `projection.messages` one event earlier than
1222 * the matching `turn-item.updated`. Basing optimistic eviction on visible user
1223 * turn items avoids dropping steer rows in that gap.
1224 */
1225export function deriveCommittedServerUserMessageIds(
1226 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1227): ReadonlySet<ChatMessage["id"]> {
1228 return new Set(
1229 visibleTurnItems.flatMap((row) =>
1230 row.item.type === "user_message" ? [row.item.messageId] : [],
1231 ),
1232 );
1233}
1234
1235export function hasServerAcknowledgedLocalDispatch(input: {
1236 localDispatch: LocalDispatchSnapshot | null;
1237 phase: SessionPhase;
1238 latestRun: Thread["latestRun"] | null;
1239 latestUserMessageId?: ChatMessage["id"] | null;
1240 runtime: Thread["runtime"] | null;
1241 hasPendingApproval: boolean;
1242 hasPendingUserInput: boolean;
1243 threadError: string | null | undefined;
1244}): boolean {
1245 if (!input.localDispatch) {
1246 return false;
1247 }
1248 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1249 return true;
1250 }
1251 // The thread shell can report a preparing or starting run before the detail
1252 // projection behind `phase` loads, so either source still connecting holds
1253 // the send.
1254 if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") {
1255 return false;
1256 }
1257
1258 const latestRun = input.latestRun ?? null;
1259 const runtime = input.runtime ?? null;
1260 const latestUserMessageChanged =
1261 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
1262 const latestRunChanged =
1263 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
1264 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
1265 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
1266 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
1267
1268 if (input.phase === "running") {
1269 if (latestUserMessageChanged) {
1270 return true;
1271 }
1272 if (!latestRunChanged) {
1273 return false;
1274 }
1275 if (latestRun?.startedAt === null || latestRun === null) {
1276 return false;
1277 }
1278 if (
1279 runtime?.activeRunId !== null &&
1280 runtime?.activeRunId !== undefined &&
1281 latestRun?.runId !== runtime.activeRunId
1282 ) {
1283 return false;
1284 }
1285 return true;
1286 }
1287
1288 return (
1289 latestRunChanged ||
1290 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
1291 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
1292 );
1293}
1294
1295// Returning to the window should land the caret in the composer, so the reader can type right
1296// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1297// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1298// not one of them, so it yields to the composer.
1299export function shouldRefocusComposerOnWindowFocus(
1300 activeElement:
1301 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1302 | null,
1303): boolean {
1304 if (activeElement === null || activeElement.tagName === "BODY") return true;
1305 if (
1306 activeElement.tagName === "INPUT" ||
1307 activeElement.tagName === "TEXTAREA" ||
1308 activeElement.tagName === "SELECT" ||
1309 activeElement.tagName === "IFRAME" ||
1310 activeElement.tagName === "WEBVIEW" ||
1311 activeElement.isContentEditable === true ||
1312 activeElement.getAttribute("role") === "textbox"
1313 ) {
1314 return false;
1315 }
1316 return (
1317 activeElement.closest(
1318 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1319 ) === null
1320 );
1321}
1322
1323export interface PlanFollowUpComposerSnapshot {
1324 readonly prompt: string;
1325 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1326 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1327 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1328 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
1329}
1330
1331/**
1332 * Puts back everything a plan follow-up send cleared when the send fails. The
1333 * caller clears the composer before awaiting the send, so every field it held
1334 * has to be written back here: a dropped field silently discards user context.
1335 */
1336export function restorePlanFollowUpComposer(input: {
1337 readonly snapshot: PlanFollowUpComposerSnapshot;
1338 readonly writePrompt: (prompt: string) => void;
1339 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1340 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1341 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1342 readonly writeThreadContexts: (records: ReadonlyArray<ThreadContextRecord>) => void;
1343 readonly resetCursor: (options: {
1344 cursor: number;
1345 prompt: string;
1346 detectTrigger: boolean;
1347 }) => void;
1348}): void {
1349 input.writePrompt(input.snapshot.prompt);
1350 input.writeTerminalContexts(input.snapshot.terminalContexts);
1351 input.writeReviewComments(input.snapshot.reviewComments);
1352 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1353 input.writeThreadContexts(input.snapshot.threadContexts);
1354 input.resetCursor({
1355 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1356 prompt: input.snapshot.prompt,
1357 detectTrigger: true,
1358 });
1359}