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

ChatView.logic.ts

1,402 lines48.2 KB

1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 type AssetCreateUrlInput,
4 type AssetCreateUrlResult,
5 type ChatFileAttachment,
6 type EnvironmentId,
7 isProviderDriverKind,
8 ProjectId,
9 type MessageId,
10 type ModelSelection,
11 type PreviewAnnotationPayload,
12 type ProviderInteractionMode,
13 ProviderDriverKind,
14 type ProviderInstanceId,
15 type ServerProvider,
16 type ScopedProjectRef,
17 type ScopedThreadRef,
18 type ThreadId,
19 type ThreadLinkedPullRequest,
20 type TurnId,
21} from "@t3tools/contracts";
22import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
23import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
24import {
25 squashAtomCommandFailure,
26 type AtomCommandResult,
27} from "@t3tools/client-runtime/state/runtime";
28import { videoMimeType } from "@t3tools/shared/video";
29import {
30 appendCodexArtifactTemplateUsePrompt,
31 codexArtifactTemplateUsePrompt,
32 type CodexArtifactTemplate,
33} from "@t3tools/client-runtime/codex-artifact-templates";
34import {
35 type ChatMessage,
36 isImageAttachment,
37 type SessionPhase,
38 type Thread,
39 type ThreadShell,
40 type TurnDiffSummary,
41} from "../types";
42import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
43import * as Schema from "effect/Schema";
44import { appAtomRegistry } from "../rpc/atomRegistry";
45import { environmentThreadDetails } from "../state/threads";
46import { stripInlineContextReferences } from "~/lib/composerContextReferences";
47import { filterTerminalContextsWithText, type TerminalContextDraft } from "../lib/terminalContext";
48import type { DraftThreadEnvMode } from "../composerDraftStore";
49import { collapseExpandedComposerCursor, type ComposerSubmissionIntent } from "../composer-logic";
50import type { ReviewCommentContext } from "../reviewCommentContext";
51import type { TimelineEntry } from "../session-logic";
52import type { PreviewMiniPlayerSource } from "../previewMiniPlayerStore";
53import type { DesktopPreviewOverlay } from "../previewStateStore";
54import type { RightPanelSurface } from "../rightPanelStore";
55import {
56 NO_PROVIDER_MODEL_SELECTION,
57 resolveSelectableProviderInstanceEntry,
58 type ProviderInstanceEntry,
59} from "../providerInstances";
60​
61export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
62export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
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 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 const openThreadIdSet = new Set(input.openThreadIds);
683 const hiddenThreadIds = input.currentThreadIds.filter(
684 (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
685 );
686 const maxHiddenThreadCount = Math.max(
687 0,
688 input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
689 );
690 const nextThreadIds =
691 hiddenThreadIds.length > maxHiddenThreadCount
692 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
693 : hiddenThreadIds;
694​
695 if (
696 input.activeThreadId &&
697 input.activeThreadTerminalOpen &&
698 !nextThreadIds.includes(input.activeThreadId)
699 ) {
700 nextThreadIds.push(input.activeThreadId);
701 }
702​
703 return nextThreadIds;
705​
706export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
707 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
708 return;
709 }
710 URL.revokeObjectURL(previewUrl);
712​
713/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
714export async function resolveFileAttachmentUrl(input: {
715 attachment: ChatFileAttachment;
716 environmentId: EnvironmentId;
717 httpBaseUrl: string;
718 createAssetUrl: (input: {
719 environmentId: EnvironmentId;
720 input: AssetCreateUrlInput;
721 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
722}): Promise<string> {
723 const { attachment } = input;
724 const result = await input.createAssetUrl({
725 environmentId: input.environmentId,
726 input: {
727 resource: {
728 _tag: "attachment",
729 attachmentId: attachment.id,
730 fileName: attachment.name,
731 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
732 },
733 },
734 });
735 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
736 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
737 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
738 return url;
740​
741export async function prepareRevertedMessageAttachments(input: {
742 message: ChatMessage;
743 environmentId: EnvironmentId;
744 httpBaseUrl: string;
745 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
746}): Promise<File[]> {
747 return Promise.all(
748 (input.message.attachments ?? []).map(async (attachment) => {
749 if (attachment.type !== "image" && attachment.type !== "file") {
750 throw new Error("This message has an attachment that cannot be restored.");
751 }
752 const result = await input.createAssetUrl({
753 environmentId: input.environmentId,
754 input: {
755 resource: {
756 _tag: "attachment",
757 attachmentId: attachment.id,
758 fileName: attachment.name,
759 mimeType: attachment.mimeType,
760 },
761 },
762 });
763 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
764 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
765 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
766 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
767 if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
768 return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
769 }),
770 );
772​
773export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
774 if (message.role !== "user" || !message.attachments) {
775 return;
776 }
777 for (const attachment of message.attachments) {
778 if (!isImageAttachment(attachment)) {
779 continue;
780 }
781 revokeBlobPreviewUrl(attachment.previewUrl);
782 }
784​
785export function timelineHasEphemeralPreviewUrls(
786 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
787): boolean {
788 return entries.some(
789 (entry) =>
790 entry.kind === "message" &&
791 entry.message !== undefined &&
792 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
793 );
795​
796export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
797 if (message.role !== "user" || !message.attachments) {
798 return [];
799 }
800 const previewUrls: string[] = [];
801 for (const attachment of message.attachments) {
802 if (!isImageAttachment(attachment)) continue;
803 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
804 previewUrls.push(attachment.previewUrl);
805 }
806 return previewUrls;
808​
809export interface PullRequestDialogState {
810 initialReference: string | null;
811 key: number;
813​
814export function readFileAsDataUrl(file: File): Promise<string> {
815 return new Promise((resolve, reject) => {
816 const reader = new FileReader();
817 reader.addEventListener("load", () => {
818 if (typeof reader.result === "string") {
819 resolve(reader.result);
820 return;
821 }
822 reject(new Error("Could not read image data."));
823 });
824 reader.addEventListener("error", () => {
825 reject(reader.error ?? new Error("Failed to read image."));
826 });
827 reader.readAsDataURL(file);
828 });
830​
831export function resolveSendEnvMode(input: {
832 requestedEnvMode: DraftThreadEnvMode;
833 isGitRepo: boolean;
834}): DraftThreadEnvMode {
835 return input.isGitRepo ? input.requestedEnvMode : "local";
837​
838export function resolveBackgroundDraftWorkspaceOptions(input: {
839 envMode: DraftThreadEnvMode;
840 branch: string | null;
841 startFromOrigin: boolean;
842}): {
843 envMode: DraftThreadEnvMode;
844 branch: string | null;
845 worktreePath: null;
846 startFromOrigin: boolean;
847} {
848 return {
849 envMode: input.envMode,
850 branch: input.branch,
851 worktreePath: null,
852 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
853 };
855​
856export function cloneComposerImageForRetry(
857 image: ComposerImageAttachment,
858): ComposerImageAttachment {
859 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
860 return image;
861 }
862 try {
863 return {
864 ...image,
865 previewUrl: URL.createObjectURL(image.file),
866 };
867 } catch {
868 return image;
869 }
871​
872export function deriveComposerSendState(options: {
873 prompt: string;
874 imageCount: number;
875 terminalContexts: ReadonlyArray<TerminalContextDraft>;
876 /**
877 * Optional element-pick attachment count. Element contexts contribute to
878 * "sendable content" exactly like images and (text-bearing) terminal
879 * contexts do: a prompt of just element chips is still a valid send.
880 */
881 elementContextCount?: number;
882}): {
883 trimmedPrompt: string;
884 sendableTerminalContexts: TerminalContextDraft[];
885 expiredTerminalContextCount: number;
886 hasSendableContent: boolean;
887} {
888 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
889 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
890 const expiredTerminalContextCount =
891 options.terminalContexts.length - sendableTerminalContexts.length;
892 const elementContextCount = options.elementContextCount ?? 0;
893 return {
894 trimmedPrompt,
895 sendableTerminalContexts,
896 expiredTerminalContextCount,
897 hasSendableContent:
898 trimmedPrompt.length > 0 ||
899 options.imageCount > 0 ||
900 sendableTerminalContexts.length > 0 ||
901 elementContextCount > 0,
902 };
904​
905export function buildExpiredTerminalContextToastCopy(
906 expiredTerminalContextCount: number,
907 variant: "omitted" | "empty",
908): { title: string; description: string } {
909 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
910 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
911 if (variant === "empty") {
912 return {
913 title: `${noun} won't be sent`,
914 description: "Remove it or re-add it to include terminal output.",
915 };
916 }
917 return {
918 title: `${noun} omitted from message`,
919 description: "Re-add it if you want that terminal output included.",
920 };
922​
923export function branchMismatchKey(
924 threadId: string | null,
925 mismatch: { threadBranch: string; currentBranch: string } | null,
926): string | null {
927 if (!threadId || !mismatch) {
928 return null;
929 }
930 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
932​
933// The mismatch banner only matters when the user is about to send: passive
934// reading of an old thread carries no risk (the branch picker tint already
935// covers ambient awareness). Draft content is the intent signal — composer
936// focus is useless here because ChatView autofocuses the composer on every
937// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
938// revealed so it doesn't flicker away when the draft is cleared.
939export function shouldShowBranchMismatchBanner(input: {
940 hasMismatch: boolean;
941 isDismissed: boolean;
942 composerHasContent: boolean;
943 wasShownForCurrentMismatch: boolean;
944}): boolean {
945 if (!input.hasMismatch || input.isDismissed) {
946 return false;
947 }
948 return input.composerHasContent || input.wasShownForCurrentMismatch;
950​
951export function shouldShowPlanFollowUpPrompt(input: {
952 pendingUserInputCount: number;
953 interactionMode: ProviderInteractionMode;
954 latestTurnSettled: boolean;
955 hasActionableProposedPlan: boolean;
956 hasComposerAttachments: boolean;
957}): boolean {
958 return (
959 input.pendingUserInputCount === 0 &&
960 input.interactionMode === "plan" &&
961 input.latestTurnSettled &&
962 input.hasActionableProposedPlan &&
963 !input.hasComposerAttachments
964 );
966​
967// Session-scoped (module-level so it survives ChatView remounts, e.g. route
968// changes). Durable cross-device dismissal is planned as a server-side ack.
969const sessionDismissedBranchMismatchKeys = new Set<string>();
970​
971export function dismissBranchMismatchForSession(key: string): void {
972 sessionDismissedBranchMismatchKeys.add(key);
974​
975export function isBranchMismatchDismissedForSession(key: string | null): boolean {
976 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
978​
979// Git status for a checkout arrives after the composer paints, and the branch
980// strip mounts on the assumption that a project is a Git repo. Without a
981// memory, a non-Git project would mount the strip and drop it on every visit.
982// Keyed by environment and checkout for the session; never persisted.
983const sessionCheckoutIsRepo = new Map<string, boolean>();
984​
985function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
986 return JSON.stringify([environmentId, cwd]);
988​
989export function rememberCheckoutIsRepo(
990 environmentId: EnvironmentId,
991 cwd: string,
992 isRepo: boolean,
993): void {
994 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
996​
997export function recallCheckoutIsRepo(
998 environmentId: EnvironmentId,
999 cwd: string | null,
1000): boolean | undefined {
1001 return cwd === null
1002 ? undefined
1003 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
1005​
1006export function threadHasStarted(thread: Thread | null | undefined): boolean {
1007 return Boolean(
1008 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
1009 );
1011​
1012/**
1013 * Whether a thread ran at least one turn, judged from its shell alone.
1015 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
1016 * still has messages, and the loading shell carries none. The shell records
1017 * when the last user message landed, which every started thread has.
1018 */
1019export function threadShellHasStarted(
1020 shell: Pick<ThreadShell, "latestTurn" | "latestUserMessageAt" | "session"> | null | undefined,
1021): boolean {
1022 return Boolean(
1023 shell &&
1024 (shell.latestTurn !== null || shell.latestUserMessageAt !== null || shell.session !== null),
1025 );
1027​
1028// Imported history has no session until its first prompt. Resolve its instance
1029// through the environment's provider catalog before locking to a driver.
1030export function deriveLockedProvider(input: {
1031 thread: Thread | null | undefined;
1032 selectedProvider: string | null;
1033 threadProvider: string | null;
1034 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
1035}): ProviderDriverKind | null {
1036 if (!threadHasStarted(input.thread)) {
1037 return null;
1039 const sessionProvider = input.thread?.session?.providerName ?? null;
1040 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
1041 return sessionProvider;
1043 // Preserve the existing lock while an instance is missing from the catalog;
1044 // a started thread must not silently fall back to a different driver.
1045 const threadProvider =
1046 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
1047 input.threadProvider;
1048 const selectedProvider =
1049 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
1050 input.selectedProvider;
1051 const narrowedThreadProvider =
1052 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
1053 const narrowedSelectedProvider =
1054 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
1055 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
1057​
1058export function getStartedThreadModelChangeBlockReason(input: {
1059 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
1060 hasStartedSession: boolean;
1061 currentModelSelection: ModelSelection;
1062 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
1063 nextModelSelection: ModelSelection;
1064}): { title: string; description: string } | null {
1065 if (!input.hasStartedSession) {
1066 return null;
1068 const currentModelSelection = {
1069 ...input.currentModelSelection,
1070 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
1071 };
1072 if (
1073 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
1074 currentModelSelection.model === input.nextModelSelection.model
1075 ) {
1076 return null;
1078 const currentProvider = input.providers.find(
1079 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1080 );
1081 const nextProvider = input.providers.find(
1082 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1083 );
1084 if (
1085 currentProvider?.requiresNewThreadForModelChange !== true &&
1086 nextProvider?.requiresNewThreadForModelChange !== true
1087 ) {
1088 return null;
1090 return {
1091 title: "Start a new chat to change models",
1092 description: "This provider does not allow switching models after a conversation has started.",
1093 };
1095​
1096export async function waitForStartedServerThread(
1097 threadRef: ScopedThreadRef,
1098 timeoutMs = 1_000,
1099): Promise<boolean> {
1100 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1101 const getThread = () => appAtomRegistry.get(threadAtom);
1102 const thread = getThread();
1103​
1104 if (threadHasStarted(thread)) {
1105 return true;
1107​
1108 return await new Promise<boolean>((resolve) => {
1109 let settled = false;
1110 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
1111 const finish = (result: boolean) => {
1112 if (settled) {
1113 return;
1115 settled = true;
1116 if (timeoutId !== null) {
1117 globalThis.clearTimeout(timeoutId);
1119 unsubscribe();
1120 resolve(result);
1121 };
1122​
1123 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
1124 if (!threadHasStarted(thread)) {
1125 return;
1127 finish(true);
1128 });
1129​
1130 if (threadHasStarted(getThread())) {
1131 finish(true);
1132 return;
1134​
1135 timeoutId = globalThis.setTimeout(() => {
1136 finish(false);
1137 }, timeoutMs);
1138 });
1140​
1141export async function waitForRevertedMessage(
1142 threadRef: ScopedThreadRef,
1143 messageId: MessageId,
1144 turnCount: number,
1145 revert: () => Promise<void>,
1146 timeoutMs = 120_000,
1147): Promise<void> {
1148 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1149 const initial = appAtomRegistry.get(threadAtom);
1150 if (!initial?.messages.some((message) => message.id === messageId)) {
1151 throw new Error("The message to rewind is no longer available.");
1153 const previousFailures = new Set(
1154 initial.activities
1155 .filter((activity) => activity.kind === "checkpoint.revert.failed")
1156 .map((activity) => activity.id),
1157 );
1158 return new Promise<void>((resolve, reject) => {
1159 let settled = false;
1160 let accepted = false;
1161 let unsubscribe = () => {};
1162 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1163 const finish = (error?: unknown) => {
1164 if (settled) return;
1165 settled = true;
1166 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1167 unsubscribe();
1168 if (error !== undefined) reject(error);
1169 else resolve();
1170 };
1171 const inspect = () => {
1172 const thread = appAtomRegistry.get(threadAtom);
1173 if (!thread) return;
1174 const failure = thread.activities.findLast(
1175 (activity) =>
1176 activity.kind === "checkpoint.revert.failed" && !previousFailures.has(activity.id),
1177 );
1178 if (failure) {
1179 const payload = failure.payload;
1180 finish(
1181 new Error(
1182 typeof payload === "object" &&
1183 payload !== null &&
1184 "detail" in payload &&
1185 typeof payload.detail === "string"
1186 ? payload.detail
1187 : failure.summary,
1188 ),
1189 );
1190 } else if (
1191 accepted &&
1192 !thread.messages.some((message) => message.id === messageId) &&
1193 thread.checkpoints.every((checkpoint) => checkpoint.checkpointTurnCount <= turnCount) &&
1194 (turnCount === 0
1195 ? thread.latestTurn === null
1196 : thread.checkpoints.some(
1197 (checkpoint) => checkpoint.turnId === thread.latestTurn?.turnId,
1198 ))
1199 ) {
1200 finish();
1202 };
1203 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1204 timeout = globalThis.setTimeout(() => {
1205 finish(new Error("Timed out waiting for the thread to rewind."));
1206 }, timeoutMs);
1207 Promise.resolve()
1208 .then(revert)
1209 .then(() => {
1210 accepted = true;
1211 inspect();
1212 }, finish);
1213 });
1215​
1216export interface LocalDispatchSnapshot {
1217 startedAt: string;
1218 preparingWorktree: boolean;
1219 submissionIntent: ComposerSubmissionIntent;
1220 latestUserMessageId: ChatMessage["id"] | null;
1221 latestTurnTurnId: TurnId | null;
1222 latestTurnRequestedAt: string | null;
1223 latestTurnStartedAt: string | null;
1224 latestTurnCompletedAt: string | null;
1225 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
1226 sessionUpdatedAt: string | null;
1227 latestTurnStartFailureId: string | null;
1229​
1230export function latestTurnStartFailureId(
1231 activeThread: Thread | undefined,
1232 latestUserMessageId: ChatMessage["id"] | null,
1233): string | null {
1234 if (latestUserMessageId === null) return null;
1235 return (
1236 activeThread?.activities.findLast((activity) => {
1237 if (activity.kind !== "provider.turn.start.failed") return false;
1238 const payload =
1239 typeof activity.payload === "object" && activity.payload !== null
1240 ? (activity.payload as { readonly requestId?: unknown })
1241 : null;
1242 return payload?.requestId === latestUserMessageId;
1243 })?.id ?? null
1244 );
1246​
1247export function createLocalDispatchSnapshot(
1248 activeThread: Thread | undefined,
1249 options?: {
1250 preparingWorktree?: boolean;
1251 submissionIntent?: ComposerSubmissionIntent;
1252 },
1253): LocalDispatchSnapshot {
1254 const latestTurn = activeThread?.latestTurn ?? null;
1255 const session = activeThread?.session ?? null;
1256 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
1257 return {
1258 startedAt: new Date().toISOString(),
1259 preparingWorktree: Boolean(options?.preparingWorktree),
1260 submissionIntent: options?.submissionIntent ?? "foreground",
1261 latestUserMessageId: latestUserMessage?.id ?? null,
1262 latestTurnTurnId: latestTurn?.turnId ?? null,
1263 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
1264 latestTurnStartedAt: latestTurn?.startedAt ?? null,
1265 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
1266 sessionStatus: session?.status ?? null,
1267 sessionUpdatedAt: session?.updatedAt ?? null,
1268 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
1269 };
1271​
1272export function hasServerAcknowledgedLocalDispatch(input: {
1273 localDispatch: LocalDispatchSnapshot | null;
1274 phase: SessionPhase;
1275 latestTurn: Thread["latestTurn"] | null;
1276 latestUserMessageId: ChatMessage["id"] | null;
1277 session: Thread["session"] | null;
1278 hasPendingApproval: boolean;
1279 hasPendingUserInput: boolean;
1280 latestTurnStartFailureId?: string | null;
1281 threadError: string | null | undefined;
1282}): boolean {
1283 if (!input.localDispatch) {
1284 return false;
1286 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1287 return true;
1289 if (
1290 input.latestTurnStartFailureId !== undefined &&
1291 input.latestTurnStartFailureId !== null &&
1292 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
1293 ) {
1294 return true;
1296 if (input.phase === "connecting") {
1297 return false;
1299​
1300 const latestTurn = input.latestTurn ?? null;
1301 const session = input.session ?? null;
1302 const latestUserMessageChanged =
1303 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
1304 const latestTurnChanged =
1305 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
1306 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
1307 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
1308 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
1309​
1310 if (input.phase === "running") {
1311 // Steering adds a user message to the current running turn without
1312 // necessarily changing any of the turn timestamps. Treat that projected
1313 // message as the server acknowledgment so the composer does not remain
1314 // stuck in its local "Sending" state until the turn settles.
1315 if (latestUserMessageChanged) {
1316 return true;
1318 if (!latestTurnChanged) {
1319 return false;
1321 if (latestTurn?.startedAt === null || latestTurn === null) {
1322 return false;
1324 if (
1325 session?.activeTurnId !== null &&
1326 session?.activeTurnId !== undefined &&
1327 latestTurn?.turnId !== session.activeTurnId
1328 ) {
1329 return false;
1331 return true;
1333​
1334 return (
1335 latestTurnChanged ||
1336 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1337 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1338 );
1340​
1341// Returning to the window should land the caret in the composer, so the reader can type right
1342// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1343// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1344// not one of them, so it yields to the composer.
1345export function shouldRefocusComposerOnWindowFocus(
1346 activeElement:
1347 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1348 | null,
1349): boolean {
1350 if (activeElement === null || activeElement.tagName === "BODY") return true;
1351 if (
1352 activeElement.tagName === "INPUT" ||
1353 activeElement.tagName === "TEXTAREA" ||
1354 activeElement.tagName === "SELECT" ||
1355 activeElement.tagName === "IFRAME" ||
1356 activeElement.tagName === "WEBVIEW" ||
1357 activeElement.isContentEditable === true ||
1358 activeElement.getAttribute("role") === "textbox"
1359 ) {
1360 return false;
1362 return (
1363 activeElement.closest(
1364 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1365 ) === null
1366 );
1368​
1369export interface PlanFollowUpComposerSnapshot {
1370 readonly prompt: string;
1371 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1372 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1373 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1375​
1376/**
1377 * Puts back everything a plan follow-up send cleared when the send fails. The
1378 * caller clears the composer before awaiting the send, so every field it held
1379 * has to be written back here: a dropped field silently discards user context.
1380 */
1381export function restorePlanFollowUpComposer(input: {
1382 readonly snapshot: PlanFollowUpComposerSnapshot;
1383 readonly writePrompt: (prompt: string) => void;
1384 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1385 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1386 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1387 readonly resetCursor: (options: {
1388 cursor: number;
1389 prompt: string;
1390 detectTrigger: boolean;
1391 }) => void;
1392}): void {
1393 input.writePrompt(input.snapshot.prompt);
1394 input.writeTerminalContexts(input.snapshot.terminalContexts);
1395 input.writeReviewComments(input.snapshot.reviewComments);
1396 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1397 input.resetCursor({
1398 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1399 prompt: input.snapshot.prompt,
1400 detectTrigger: true,
1401 });