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

ChatView.logic.ts

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