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

ChatView.logic.ts

1,387 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 worktreePath?: null;
478} | null {
479 const nextModelSelection = input.nextModelSelection;
480 const modelSelectionChanged =
481 nextModelSelection !== undefined &&
482 (nextModelSelection.model !== input.currentModelSelection.model ||
483 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
484 JSON.stringify(nextModelSelection.options ?? null) !==
485 JSON.stringify(input.currentModelSelection.options ?? null));
486 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
487 if (!modelSelectionChanged && !branchChanged) {
488 return null;
489 }
490 return {
491 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
492 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
493 };
495​
496export function buildLocalDraftThread(
497 threadId: ThreadId,
498 draftThread: DraftThreadState,
499 fallbackModelSelection: ModelSelection,
500): Thread {
501 const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
502 return presentThreadShell(draftThread.environmentId, {
503 id: threadId,
504 projectId: draftThread.projectId,
505 title: "New thread",
506 providerInstanceId: fallbackModelSelection.instanceId,
507 modelSelection: fallbackModelSelection,
508 runtimeMode: draftThread.runtimeMode,
509 interactionMode: draftThread.interactionMode,
510 branch: draftThread.branch,
511 worktreePath: draftThread.worktreePath,
512 activeProviderThreadId: null,
513 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
514 forkedFrom: null,
515 createdBy: "user",
516 creationSource: "web",
517 latestRunId: null,
518 activeRunId: null,
519 status: "idle",
520 pendingRuntimeRequest: null,
521 latestVisibleMessage: null,
522 latestUserMessageAt: null,
523 hasActionableProposedPlan: false,
524 itemCount: 0,
525 visibleItemCount: 0,
526 createdAt: timestamp,
527 updatedAt: timestamp,
528 archivedAt: null,
529 settledOverride: null,
530 settledAt: null,
531 deletedAt: null,
532 });
534​
535export function shouldWriteThreadErrorToCurrentServerThread(input: {
536 serverThread:
537 | {
538 environmentId: EnvironmentId;
539 id: ThreadId;
540 }
541 | null
542 | undefined;
543 routeThreadRef: ScopedThreadRef;
544 targetThreadId: ThreadId;
545}): boolean {
546 return Boolean(
547 input.serverThread &&
548 input.targetThreadId === input.routeThreadRef.threadId &&
549 input.serverThread.environmentId === input.routeThreadRef.environmentId &&
550 input.serverThread.id === input.targetThreadId,
551 );
553​
554export function resolveComposerProviderSelection(input: {
555 entries: ReadonlyArray<ProviderInstanceEntry>;
556 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
557 lockedProvider: ProviderDriverKind | null;
558 lockedInstanceId: ProviderInstanceId | null | undefined;
559}) {
560 const requestedInstanceId = input.candidateInstanceIds.find(
561 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
562 );
563 const requestedDriverKind =
564 input.lockedProvider ??
565 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
566 input.entries[0]?.driverKind ??
567 ProviderDriverKind.make("unconfigured");
568 const lockedContinuationGroupKey = input.lockedProvider
569 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
570 ?.continuationGroupKey ?? null)
571 : null;
572 // Missing metadata must not move Antigravity history into another Google profile.
573 const requiresExactInstance =
574 input.lockedProvider === "antigravity" &&
575 input.lockedInstanceId != null &&
576 lockedContinuationGroupKey === null;
577 const compatibleEntries = input.entries.filter(
578 (entry) =>
579 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
580 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
581 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
582 );
583 const selectedProviderEntry =
584 input.candidateInstanceIds
585 .map((candidate) =>
586 compatibleEntries.find(
587 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
588 ),
589 )
590 .find((entry) => entry !== undefined) ??
591 resolveSelectableProviderInstanceEntry(
592 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
593 undefined,
594 ) ??
595 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
596 const unavailableProviderInstanceId = selectedProviderEntry
597 ? undefined
598 : input.lockedProvider
599 ? (input.lockedInstanceId ?? requestedInstanceId)
600 : requestedInstanceId;
601 return {
602 selectedProviderEntry,
603 requestedDriverKind,
604 lockedContinuationGroupKey,
605 unavailableProviderInstanceId,
606 };
608​
609export function resolveComposerInteractionMode(input: {
610 planModeEnabled: boolean;
611 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
612 interactionMode: ProviderInteractionMode;
613}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
614 const enabled =
615 input.planModeEnabled &&
616 input.provider != null &&
617 input.provider.showInteractionModeToggle !== false;
618 return {
619 enabled,
620 interactionMode: enabled ? input.interactionMode : "default",
621 };
623​
624export function getAntigravitySendBlockReason(
625 provider:
626 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
627 | null
628 | undefined,
629 model: string,
630): string | null {
631 if (provider?.driver !== "antigravity") return null;
632 if (!provider.installed) {
633 return "Install Antigravity in provider settings before sending.";
634 }
635 if (provider.auth.status === "unauthenticated") {
636 return "Sign in to Antigravity in provider settings before sending.";
637 }
638 const slug = model.trim();
639 if (slug.length === 0) return "Choose an Antigravity model before sending.";
640 if (provider.auth.status === "unknown") return null;
641 if (provider.models.length === 0) {
642 return "Refresh Antigravity models in provider settings before sending.";
643 }
644 if (
645 provider.status === "ready" &&
646 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
647 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
648 ) {
649 return "That Antigravity model is no longer available. Choose another model.";
650 }
651 return null;
653​
654export function reconcileMountedTerminalThreadIds(input: {
655 currentThreadIds: ReadonlyArray<string>;
656 openThreadIds: ReadonlyArray<string>;
657 activeThreadId: string | null;
658 activeThreadTerminalOpen: boolean;
659 maxHiddenThreadCount?: number;
660}): string[] {
661 const openThreadIdSet = new Set(input.openThreadIds);
662 const hiddenThreadIds = input.currentThreadIds.filter(
663 (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
664 );
665 const maxHiddenThreadCount = Math.max(
666 0,
667 input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
668 );
669 const nextThreadIds =
670 hiddenThreadIds.length > maxHiddenThreadCount
671 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
672 : hiddenThreadIds;
673​
674 if (
675 input.activeThreadId &&
676 input.activeThreadTerminalOpen &&
677 !nextThreadIds.includes(input.activeThreadId)
678 ) {
679 nextThreadIds.push(input.activeThreadId);
680 }
681​
682 return nextThreadIds;
684​
685// Null identifies the project checkout when a launch or session is known.
686export function resolveTerminalWorktreePath(input: {
687 launchContext: { readonly worktreePath: string | null } | null;
688 summary: { readonly worktreePath: string | null } | null;
689 threadWorktreePath: string | null;
690}): string | null {
691 if (input.launchContext !== null) return input.launchContext.worktreePath;
692 if (input.summary !== null) return input.summary.worktreePath;
693 return input.threadWorktreePath;
695​
696export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
697 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
698 return;
699 }
700 URL.revokeObjectURL(previewUrl);
702​
703export async function resolveFileAttachmentUrl(input: {
704 attachment: ChatFileAttachment;
705 environmentId: EnvironmentId;
706 httpBaseUrl: string;
707 createAssetUrl: (input: {
708 environmentId: EnvironmentId;
709 input: AssetCreateUrlInput;
710 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
711}): Promise<string> {
712 const { attachment } = input;
713 const result = await input.createAssetUrl({
714 environmentId: input.environmentId,
715 input: {
716 resource: {
717 _tag: "attachment",
718 attachmentId: attachment.id,
719 fileName: attachment.name,
720 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
721 },
722 },
723 });
724 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
725 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
726 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
727 return url;
729​
730export async function prepareRevertedMessageAttachments(input: {
731 message: ChatMessage;
732 environmentId: EnvironmentId;
733 httpBaseUrl: string;
734 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
735}): Promise<File[]> {
736 return Promise.all(
737 (input.message.attachments ?? []).map(async (attachment) => {
738 if (attachment.type !== "image" && attachment.type !== "file") {
739 throw new Error("This message has an attachment that cannot be restored.");
740 }
741 const result = await input.createAssetUrl({
742 environmentId: input.environmentId,
743 input: {
744 resource: {
745 _tag: "attachment",
746 attachmentId: attachment.id,
747 fileName: attachment.name,
748 mimeType: attachment.mimeType,
749 },
750 },
751 });
752 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
753 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
754 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
755 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
756 if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
757 return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
758 }),
759 );
761​
762export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
763 if (message.role !== "user" || !message.attachments) {
764 return;
765 }
766 for (const attachment of message.attachments) {
767 if (!isImageAttachment(attachment)) {
768 continue;
769 }
770 revokeBlobPreviewUrl(attachment.previewUrl);
771 }
773​
774export function timelineHasEphemeralPreviewUrls(
775 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
776): boolean {
777 return entries.some(
778 (entry) =>
779 entry.kind === "message" &&
780 entry.message !== undefined &&
781 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
782 );
784​
785export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
786 if (message.role !== "user" || !message.attachments) {
787 return [];
788 }
789 const previewUrls: string[] = [];
790 for (const attachment of message.attachments) {
791 if (!isImageAttachment(attachment)) continue;
792 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
793 previewUrls.push(attachment.previewUrl);
794 }
795 return previewUrls;
797​
798export { readFileAsDataUrl } from "../lib/imageCompression";
799​
800export function resolveSendEnvMode(input: {
801 requestedEnvMode: DraftThreadEnvMode;
802 isGitRepo: boolean;
803}): DraftThreadEnvMode {
804 return input.isGitRepo ? input.requestedEnvMode : "local";
806​
807export function resolveBackgroundDraftWorkspaceOptions(input: {
808 envMode: DraftThreadEnvMode;
809 branch: string | null;
810 startFromOrigin: boolean;
811}): {
812 envMode: DraftThreadEnvMode;
813 branch: string | null;
814 worktreePath: null;
815 startFromOrigin: boolean;
816} {
817 return {
818 envMode: input.envMode,
819 branch: input.branch,
820 worktreePath: null,
821 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
822 };
824​
825export function cloneComposerImageForRetry(
826 image: ComposerImageAttachment,
827): ComposerImageAttachment {
828 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
829 return image;
830 }
831 try {
832 return {
833 ...image,
834 previewUrl: URL.createObjectURL(image.file),
835 };
836 } catch {
837 return image;
838 }
840​
841export function deriveComposerSendState(options: {
842 prompt: string;
843 imageCount: number;
844 terminalContexts: ReadonlyArray<TerminalContextDraft>;
845 elementContextCount?: number;
846}): {
847 trimmedPrompt: string;
848 sendableTerminalContexts: TerminalContextDraft[];
849 expiredTerminalContextCount: number;
850 hasSendableContent: boolean;
851} {
852 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
853 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
854 const expiredTerminalContextCount =
855 options.terminalContexts.length - sendableTerminalContexts.length;
856 const elementContextCount = options.elementContextCount ?? 0;
857 return {
858 trimmedPrompt,
859 sendableTerminalContexts,
860 expiredTerminalContextCount,
861 hasSendableContent:
862 trimmedPrompt.length > 0 ||
863 options.imageCount > 0 ||
864 sendableTerminalContexts.length > 0 ||
865 elementContextCount > 0,
866 };
868​
869export function buildExpiredTerminalContextToastCopy(
870 expiredTerminalContextCount: number,
871 variant: "omitted" | "empty",
872): { title: string; description: string } {
873 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
874 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
875 if (variant === "empty") {
876 return {
877 title: `${noun} won't be sent`,
878 description: "Remove it or re-add it to include terminal output.",
879 };
880 }
881 return {
882 title: `${noun} omitted from message`,
883 description: "Re-add it if you want that terminal output included.",
884 };
886​
887export function branchMismatchKey(
888 threadId: string | null,
889 mismatch: { threadBranch: string; currentBranch: string } | null,
890): string | null {
891 if (!threadId || !mismatch) {
892 return null;
893 }
894 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
896​
897// Draft content is the intent signal — composer focus is useless here because
898// ChatView autofocuses the composer on every thread open.
899export function shouldShowBranchMismatchBanner(input: {
900 hasMismatch: boolean;
901 isDismissed: boolean;
902 composerHasContent: boolean;
903 wasShownForCurrentMismatch: boolean;
904}): boolean {
905 if (!input.hasMismatch || input.isDismissed) {
906 return false;
907 }
908 return input.composerHasContent || input.wasShownForCurrentMismatch;
910​
911export function shouldShowPlanFollowUpPrompt(input: {
912 pendingUserInputCount: number;
913 interactionMode: ProviderInteractionMode;
914 latestTurnSettled: boolean;
915 hasActionableProposedPlan: boolean;
916 hasComposerAttachments: boolean;
917}): boolean {
918 return (
919 input.pendingUserInputCount === 0 &&
920 input.interactionMode === "plan" &&
921 input.latestTurnSettled &&
922 input.hasActionableProposedPlan &&
923 !input.hasComposerAttachments
924 );
926​
927const sessionDismissedBranchMismatchKeys = new Set<string>();
928​
929export function dismissBranchMismatchForSession(key: string): void {
930 sessionDismissedBranchMismatchKeys.add(key);
932​
933export function isBranchMismatchDismissedForSession(key: string | null): boolean {
934 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
936​
937// Git status for a checkout arrives after the composer paints, and the branch
938// strip mounts on the assumption that a project is a Git repo. Without a
939// memory, a non-Git project would mount the strip and drop it on every visit.
940const sessionCheckoutIsRepo = new Map<string, boolean>();
941​
942function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
943 return JSON.stringify([environmentId, cwd]);
945​
946export function rememberCheckoutIsRepo(
947 environmentId: EnvironmentId,
948 cwd: string,
949 isRepo: boolean,
950): void {
951 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
953​
954export function recallCheckoutIsRepo(
955 environmentId: EnvironmentId,
956 cwd: string | null,
957): boolean | undefined {
958 return cwd === null
959 ? undefined
960 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
962​
963export function threadHasStarted(thread: Thread | null | undefined): boolean {
964 return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
966​
967export function threadShellHasStarted(
968 shell:
969 | Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt" | "runtime">
970 | null
971 | undefined,
972): boolean {
973 return Boolean(
974 shell &&
975 (shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null),
976 );
978​
979// Imported history has no session until its first prompt. Resolve its instance
980// through the environment's provider catalog before locking to a driver.
981export function deriveLockedProvider(input: {
982 thread: Thread | null | undefined;
983 selectedProvider: string | null;
984 threadProvider: string | null;
985 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
986}): ProviderDriverKind | null {
987 if (!threadHasStarted(input.thread)) {
988 return null;
989 }
990 const sessionProvider = input.thread?.runtime?.providerName ?? null;
991 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
992 return sessionProvider;
993 }
994 // Preserve the existing lock while an instance is missing from the catalog;
995 // a started thread must not silently fall back to a different driver.
996 const threadProvider =
997 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
998 input.threadProvider;
999 const selectedProvider =
1000 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
1001 input.selectedProvider;
1002 const narrowedThreadProvider =
1003 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
1004 const narrowedSelectedProvider =
1005 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
1006 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
1008​
1009export function getStartedThreadModelChangeBlockReason(input: {
1010 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
1011 hasStartedSession: boolean;
1012 supportsProviderSwitchingViaHandoff?: boolean;
1013 currentModelSelection: ModelSelection;
1014 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
1015 nextModelSelection: ModelSelection;
1016}): { title: string; description: string } | null {
1017 if (!input.hasStartedSession) {
1018 return null;
1020 const currentModelSelection = {
1021 ...input.currentModelSelection,
1022 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
1023 };
1024 if (
1025 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
1026 currentModelSelection.model === input.nextModelSelection.model
1027 ) {
1028 return null;
1030 if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
1031 if (input.supportsProviderSwitchingViaHandoff === true) {
1032 return null;
1034 return {
1035 title: "Start a new chat to switch providers",
1036 description: "This thread does not support switching providers after it has started.",
1037 };
1039 const currentProvider = input.providers.find(
1040 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1041 );
1042 const nextProvider = input.providers.find(
1043 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1044 );
1045 if (
1046 currentProvider?.requiresNewThreadForModelChange !== true &&
1047 nextProvider?.requiresNewThreadForModelChange !== true
1048 ) {
1049 return null;
1051 return {
1052 title: "Start a new chat to change models",
1053 description: "This provider does not allow switching models after a conversation has started.",
1054 };
1056​
1057export async function waitForStartedServerThread(
1058 threadRef: ScopedThreadRef,
1059 timeoutMs = 1_000,
1060): Promise<boolean> {
1061 const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
1062 return waitForAtomValue({
1063 registry: appAtomRegistry,
1064 atom: threadAtom,
1065 predicate: threadHasStarted,
1066 timeoutMs,
1067 });
1069​
1070export async function waitForRevertedMessage(
1071 threadRef: ScopedThreadRef,
1072 turnCount: number,
1073 requestId: CommandId,
1074 revert: () => Promise<void>,
1075 timeoutMs = 120_000,
1076): Promise<void> {
1077 const threadAtom = environmentThreadDetails.stateAtom(threadRef);
1078 const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);
1079 const initial = readProjection();
1080 const providerThreadId = initial?.thread.activeProviderThreadId;
1081 const initialProviderThread = initial?.providerThreads.find(
1082 (providerThread) => providerThread.id === providerThreadId,
1083 );
1084 const initialProviderThreadIds = new Set(initial?.providerThreads.map((thread) => thread.id));
1085 // Paging can omit the source run. Rollback commits the entire settled suffix atomically.
1086 const witness = initial?.runs.reduce<(typeof initial.runs)[number] | undefined>((latest, run) => {
1087 if (
1088 run.ordinal <= turnCount ||
1089 (run.status !== "completed" &&
1090 run.status !== "interrupted" &&
1091 run.status !== "failed" &&
1092 run.status !== "cancelled")
1094 return latest;
1095 return latest === undefined || run.ordinal > latest.ordinal ? run : latest;
1096 }, undefined);
1097 if (witness === undefined) {
1098 throw new Error("The thread has changed. Select a message to rewind again.");
1100 return new Promise<void>((resolve, reject) => {
1101 let settled = false;
1102 let accepted = false;
1103 let unsubscribe = () => {};
1104 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1105 const finish = (error?: unknown) => {
1106 if (settled) return;
1107 settled = true;
1108 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1109 unsubscribe();
1110 if (error !== undefined) reject(error);
1111 else resolve();
1112 };
1113 const inspect = () => {
1114 const thread = readProjection();
1115 if (!thread) return;
1116 const failure = thread.thread.rollbackFailure;
1117 if (failure?.requestId === requestId) {
1118 finish(new Error(failure.message));
1119 return;
1121 if (
1122 accepted &&
1123 thread.providerThreads.some(
1124 (providerThread) =>
1125 (providerThread.id === providerThreadId ||
1126 // Claude resets to a fresh root session when rewinding to thread start.
1127 (turnCount === 0 &&
1128 providerThread.ownerNodeId === null &&
1129 providerThread.appThreadId === initial?.thread.id &&
1130 providerThread.providerInstanceId === initialProviderThread?.providerInstanceId &&
1131 !initialProviderThreadIds.has(providerThread.id))) &&
1132 providerThread.lastRunOrdinal === (turnCount === 0 ? null : turnCount),
1133 ) &&
1134 thread.runs.some((run) => run.id === witness.id && run.status === "rolled_back")
1136 finish();
1137 };
1138 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1139 timeout = globalThis.setTimeout(() => {
1140 finish(new Error("Timed out waiting for the thread to rewind."));
1141 }, timeoutMs);
1142 Promise.resolve()
1143 .then(revert)
1144 .then(() => {
1145 accepted = true;
1146 inspect();
1147 }, finish);
1148 });
1150​
1151export interface LocalDispatchSnapshot {
1152 startedAt: string;
1153 preparingWorktree: boolean;
1154 submissionIntent: ComposerSubmissionIntent;
1155 latestUserMessageId: ChatMessage["id"] | null;
1156 latestRunId: RunId | null;
1157 latestRunRequestedAt: string | null;
1158 latestRunStartedAt: string | null;
1159 latestRunCompletedAt: string | null;
1160 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
1161 runtimeUpdatedAt: string | null;
1163​
1164export function createLocalDispatchSnapshot(
1165 activeThread: Thread | undefined,
1166 options?: {
1167 preparingWorktree?: boolean;
1168 latestUserMessageId?: ChatMessage["id"] | null;
1169 submissionIntent?: ComposerSubmissionIntent;
1170 },
1171): LocalDispatchSnapshot {
1172 const latestRun = activeThread?.latestRun ?? null;
1173 const runtime = activeThread?.runtime ?? null;
1174 return {
1175 startedAt: new Date().toISOString(),
1176 preparingWorktree: Boolean(options?.preparingWorktree),
1177 submissionIntent: options?.submissionIntent ?? "foreground",
1178 latestUserMessageId: options?.latestUserMessageId ?? null,
1179 latestRunId: latestRun?.runId ?? null,
1180 latestRunRequestedAt: latestRun?.requestedAt ?? null,
1181 latestRunStartedAt: latestRun?.startedAt ?? null,
1182 latestRunCompletedAt: latestRun?.completedAt ?? null,
1183 runtimeStatus: runtime?.status ?? null,
1184 runtimeUpdatedAt: runtime?.updatedAt ?? null,
1185 };
1187​
1188/**
1189 * The timeline renders committed user rows from `visibleTurnItems`, but
1190 * `message.updated` can land in `projection.messages` one event earlier than
1191 * the matching `turn-item.updated`. Basing optimistic eviction on visible user
1192 * turn items avoids dropping steer rows in that gap.
1193 */
1194export function deriveCommittedServerUserMessageIds(
1195 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1196): ReadonlySet<ChatMessage["id"]> {
1197 return new Set(
1198 visibleTurnItems.flatMap((row) =>
1199 row.item.type === "user_message" ? [row.item.messageId] : [],
1200 ),
1201 );
1203​
1204export function hasServerAcknowledgedLocalDispatch(input: {
1205 localDispatch: LocalDispatchSnapshot | null;
1206 phase: SessionPhase;
1207 latestRun: Thread["latestRun"] | null;
1208 latestUserMessageId?: ChatMessage["id"] | null;
1209 runtime: Thread["runtime"] | null;
1210 hasPendingApproval: boolean;
1211 hasPendingUserInput: boolean;
1212 threadError: string | null | undefined;
1213}): boolean {
1214 if (!input.localDispatch) {
1215 return false;
1217 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1218 return true;
1220 if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") {
1221 return false;
1223​
1224 const latestRun = input.latestRun ?? null;
1225 const runtime = input.runtime ?? null;
1226 const latestUserMessageChanged =
1227 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
1228 const latestRunChanged =
1229 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
1230 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
1231 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
1232 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
1233​
1234 if (input.phase === "running") {
1235 if (latestUserMessageChanged) {
1236 return true;
1238 if (!latestRunChanged) {
1239 return false;
1241 if (latestRun?.startedAt === null || latestRun === null) {
1242 return false;
1244 if (
1245 runtime?.activeRunId !== null &&
1246 runtime?.activeRunId !== undefined &&
1247 latestRun?.runId !== runtime.activeRunId
1248 ) {
1249 return false;
1251 return true;
1253​
1254 return (
1255 latestRunChanged ||
1256 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
1257 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
1258 );
1260​
1261export function shouldRefocusComposerOnWindowFocus(
1262 activeElement:
1263 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1264 | null,
1265): boolean {
1266 if (activeElement === null || activeElement.tagName === "BODY") return true;
1267 if (
1268 activeElement.tagName === "INPUT" ||
1269 activeElement.tagName === "TEXTAREA" ||
1270 activeElement.tagName === "SELECT" ||
1271 activeElement.tagName === "IFRAME" ||
1272 activeElement.tagName === "WEBVIEW" ||
1273 activeElement.isContentEditable === true ||
1274 activeElement.getAttribute("role") === "textbox"
1275 ) {
1276 return false;
1278 return (
1279 activeElement.closest(
1280 '[role="dialog"], [role="alertdialog"], [role="application"], [data-slot$="-popup"], [data-terminal-owner]',
1281 ) === null
1282 );
1284​
1285export interface PlanFollowUpComposerSnapshot {
1286 readonly prompt: string;
1287 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1288 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1289 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1290 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
1292​
1293/**
1294 * The caller clears the composer before awaiting the send, so every field it
1295 * held has to be written back here: a dropped field silently discards user
1296 * context.
1297 */
1298export function restorePlanFollowUpComposer(input: {
1299 readonly snapshot: PlanFollowUpComposerSnapshot;
1300 readonly writePrompt: (prompt: string) => void;
1301 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1302 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1303 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1304 readonly writeThreadContexts: (records: ReadonlyArray<ThreadContextRecord>) => void;
1305 readonly resetCursor: (options: {
1306 cursor: number;
1307 prompt: string;
1308 detectTrigger: boolean;
1309 }) => void;
1310}): void {
1311 input.writePrompt(input.snapshot.prompt);
1312 input.writeTerminalContexts(input.snapshot.terminalContexts);
1313 input.writeReviewComments(input.snapshot.reviewComments);
1314 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1315 input.writeThreadContexts(input.snapshot.threadContexts);
1316 input.resetCursor({
1317 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1318 prompt: input.snapshot.prompt,
1319 detectTrigger: true,
1320 });
1322​
1323/**
1324 * Adds a directly sent preview annotation to the composer's images and
1325 * annotations. Its screenshot rides along only while the turn has room for
1326 * another attachment; over the cap the server rejects the whole turn.
1327 */
1328export function mergeDirectPreviewAnnotation(input: {
1329 readonly images: ReadonlyArray<ComposerImageAttachment>;
1330 readonly fileCount: number;
1331 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1332 readonly direct:
1333 | {
1334 readonly annotation: PreviewAnnotationPayload;
1335 readonly image: ComposerImageAttachment | null;
1337 | undefined;
1338}): {
1339 readonly images: ReadonlyArray<ComposerImageAttachment>;
1340 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1341} {
1342 const { direct } = input;
1343 if (!direct) return { images: input.images, previewAnnotations: input.previewAnnotations };
1344 const imageAlreadyAttached =
1345 direct.image !== null && input.images.some((image) => image.id === direct.image?.id);
1346 const imageAppended =
1347 direct.image !== null &&
1348 !imageAlreadyAttached &&
1349 input.images.length + input.fileCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
1350 const images = direct.image && imageAppended ? [...input.images, direct.image] : input.images;
1351 const previewAnnotations = input.previewAnnotations.some(
1352 (annotation) => annotation.id === direct.annotation.id,
1354 ? input.previewAnnotations
1355 : [
1356 ...input.previewAnnotations,
1358 ...direct.annotation,
1359 // Claim an attached crop only when the screenshot really rides
1360 // along; a cap-dropped image must not produce a lying prompt.
1361 screenshot:
1362 direct.annotation.screenshot && (imageAppended || imageAlreadyAttached)
1363 ? { ...direct.annotation.screenshot, dataUrl: "" }
1364 : null,
1365 },
1366 ];
1367 return { images, previewAnnotations };
1369​
1370/**
1371 * Whether a woken thread woke after the user last saw it. A run that completed
1372 * after the last visit counts as seeing it, since the user watched it finish.
1373 */
1374export function isThreadWokeUnseen(input: {
1375 readonly wokeAt: string | null;
1376 readonly settled: boolean;
1377 readonly lastVisitedAt: string | null | undefined;
1378 readonly latestRunCompletedAt: string | null;
1379}): boolean {
1380 if (input.wokeAt === null || input.settled) return false;
1381 const wokeAtMs = Date.parse(input.wokeAt);
1382 if (Number.isNaN(wokeAtMs)) return false;
1383 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
1384 .map((value) => (value ? Date.parse(value) : NaN))
1385 .filter((ms) => !Number.isNaN(ms));
1386 return seenAt.every((ms) => ms < wokeAtMs);