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

ChatView.logic.ts

1,386 lines47.9 KB

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