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