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

ChatView.logic.ts

1,458 lines50.5 KB

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