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