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

ChatView.logic.ts

1,469 lines51.2 KB

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