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

ChatView.logic.ts

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