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

ChatView.logic.ts

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