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

ChatView.logic.ts

1,376 lines48.3 KB

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