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

ChatView.logic.ts

1,388 lines48.7 KB

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