Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatView.logic.ts

1,405 lines48.2 KB

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