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