Open History to see the last commit
1import * as Option from "effect/Option";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import {
4 ANTIGRAVITY_DEFAULT_MODEL,
5 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");
97}
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 );
115}
116
117export function shouldOpenProactivePullRequest(
118 previousTargetKey: string | null | undefined,
119 targetKey: string | null,
120): boolean {
121 return targetKey !== null && targetKey !== previousTargetKey;
122}
123
124interface ProactivePanelObservation {
125 threadKey: string;
126 runningTurnId: RunId | null | undefined;
127 targetKey: string | null | undefined;
128 userActionTurnId: RunId | null;
129 userActionRevision: number;
130}
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 };
147}
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 );
164}
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 );
179}
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";
199}
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;
213}
214
215export function codexArtifactTemplatePromptToAppend(
216 currentDraft: string,
217 template: CodexArtifactTemplate,
218): string | null {
219 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
220 ? null
221 : codexArtifactTemplateUsePrompt(template);
222}
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";
233}
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 );
245}
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 });
270}
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 };
294}
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 );
316}
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;
352}
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);
361}
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;
370}
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>;
383}
384
385export function resetHeldThreadTimeline(): void {
386 rememberedThreadTimelines = new Map();
387 rememberedThreadTimelineOrder = [];
388 lastReadyThreadKey = null;
389}
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;
398}
399
400export function isPaintOnlyThreadTimeline(
401 displayThreadKey: string | null,
402 activeThreadKey: string | null,
403): boolean {
404 return (
405 displayThreadKey !== null && activeThreadKey !== null && displayThreadKey !== activeThreadKey
406 );
407}
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 };
427}
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;
445}
446
447export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
448 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
449 return () => globalThis.clearTimeout(timeoutId);
450}
451
452export function hasEnvironmentReconnectWarningGraceElapsed(
453 activeEnvironmentId: EnvironmentId | null,
454 elapsedEnvironmentId: EnvironmentId | null,
455): boolean {
456 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
457}
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;
467}
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 };
493}
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 });
532}
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 );
551}
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 };
606}
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 };
621}
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;
651}
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;
682}
683
684export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
685 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
686 return;
687 }
688 URL.revokeObjectURL(previewUrl);
689}
690
691export async function resolveFileAttachmentUrl(input: {
692 attachment: ChatFileAttachment;
693 environmentId: EnvironmentId;
694 httpBaseUrl: string;
695 createAssetUrl: (input: {
696 environmentId: EnvironmentId;
697 input: AssetCreateUrlInput;
698 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
699}): Promise<string> {
700 const { attachment } = input;
701 const result = await input.createAssetUrl({
702 environmentId: input.environmentId,
703 input: {
704 resource: {
705 _tag: "attachment",
706 attachmentId: attachment.id,
707 fileName: attachment.name,
708 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
709 },
710 },
711 });
712 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
713 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
714 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
715 return url;
716}
717
718export async function prepareRevertedMessageAttachments(input: {
719 message: ChatMessage;
720 environmentId: EnvironmentId;
721 httpBaseUrl: string;
722 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
723}): Promise<File[]> {
724 return Promise.all(
725 (input.message.attachments ?? []).map(async (attachment) => {
726 if (attachment.type !== "image" && attachment.type !== "file") {
727 throw new Error("This message has an attachment that cannot be restored.");
728 }
729 const result = await input.createAssetUrl({
730 environmentId: input.environmentId,
731 input: {
732 resource: {
733 _tag: "attachment",
734 attachmentId: attachment.id,
735 fileName: attachment.name,
736 mimeType: attachment.mimeType,
737 },
738 },
739 });
740 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
741 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
742 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
743 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
744 if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
745 return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
746 }),
747 );
748}
749
750export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
751 if (message.role !== "user" || !message.attachments) {
752 return;
753 }
754 for (const attachment of message.attachments) {
755 if (!isImageAttachment(attachment)) {
756 continue;
757 }
758 revokeBlobPreviewUrl(attachment.previewUrl);
759 }
760}
761
762export function timelineHasEphemeralPreviewUrls(
763 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
764): boolean {
765 return entries.some(
766 (entry) =>
767 entry.kind === "message" &&
768 entry.message !== undefined &&
769 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
770 );
771}
772
773export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
774 if (message.role !== "user" || !message.attachments) {
775 return [];
776 }
777 const previewUrls: string[] = [];
778 for (const attachment of message.attachments) {
779 if (!isImageAttachment(attachment)) continue;
780 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
781 previewUrls.push(attachment.previewUrl);
782 }
783 return previewUrls;
784}
785
786export { readFileAsDataUrl } from "../lib/imageCompression";
787
788export function resolveSendEnvMode(input: {
789 requestedEnvMode: DraftThreadEnvMode;
790 isGitRepo: boolean;
791}): DraftThreadEnvMode {
792 return input.isGitRepo ? input.requestedEnvMode : "local";
793}
794
795export function resolveBackgroundDraftWorkspaceOptions(input: {
796 envMode: DraftThreadEnvMode;
797 branch: string | null;
798 startFromOrigin: boolean;
799}): {
800 envMode: DraftThreadEnvMode;
801 branch: string | null;
802 worktreePath: null;
803 startFromOrigin: boolean;
804} {
805 return {
806 envMode: input.envMode,
807 branch: input.branch,
808 worktreePath: null,
809 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
810 };
811}
812
813export function cloneComposerImageForRetry(
814 image: ComposerImageAttachment,
815): ComposerImageAttachment {
816 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
817 return image;
818 }
819 try {
820 return {
821 ...image,
822 previewUrl: URL.createObjectURL(image.file),
823 };
824 } catch {
825 return image;
826 }
827}
828
829export function deriveComposerSendState(options: {
830 prompt: string;
831 imageCount: number;
832 terminalContexts: ReadonlyArray<TerminalContextDraft>;
833 elementContextCount?: number;
834}): {
835 trimmedPrompt: string;
836 sendableTerminalContexts: TerminalContextDraft[];
837 expiredTerminalContextCount: number;
838 hasSendableContent: boolean;
839} {
840 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
841 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
842 const expiredTerminalContextCount =
843 options.terminalContexts.length - sendableTerminalContexts.length;
844 const elementContextCount = options.elementContextCount ?? 0;
845 return {
846 trimmedPrompt,
847 sendableTerminalContexts,
848 expiredTerminalContextCount,
849 hasSendableContent:
850 trimmedPrompt.length > 0 ||
851 options.imageCount > 0 ||
852 sendableTerminalContexts.length > 0 ||
853 elementContextCount > 0,
854 };
855}
856
857export function buildExpiredTerminalContextToastCopy(
858 expiredTerminalContextCount: number,
859 variant: "omitted" | "empty",
860): { title: string; description: string } {
861 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
862 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
863 if (variant === "empty") {
864 return {
865 title: `${noun} won't be sent`,
866 description: "Remove it or re-add it to include terminal output.",
867 };
868 }
869 return {
870 title: `${noun} omitted from message`,
871 description: "Re-add it if you want that terminal output included.",
872 };
873}
874
875export function branchMismatchKey(
876 threadId: string | null,
877 mismatch: { threadBranch: string; currentBranch: string } | null,
878): string | null {
879 if (!threadId || !mismatch) {
880 return null;
881 }
882 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
883}
884
885// Draft content is the intent signal — composer focus is useless here because
886// ChatView autofocuses the composer on every thread open.
887export function shouldShowBranchMismatchBanner(input: {
888 hasMismatch: boolean;
889 isDismissed: boolean;
890 composerHasContent: boolean;
891 wasShownForCurrentMismatch: boolean;
892}): boolean {
893 if (!input.hasMismatch || input.isDismissed) {
894 return false;
895 }
896 return input.composerHasContent || input.wasShownForCurrentMismatch;
897}
898
899export function shouldShowPlanFollowUpPrompt(input: {
900 pendingUserInputCount: number;
901 interactionMode: ProviderInteractionMode;
902 latestTurnSettled: boolean;
903 hasActionableProposedPlan: boolean;
904 hasComposerAttachments: boolean;
905}): boolean {
906 return (
907 input.pendingUserInputCount === 0 &&
908 input.interactionMode === "plan" &&
909 input.latestTurnSettled &&
910 input.hasActionableProposedPlan &&
911 !input.hasComposerAttachments
912 );
913}
914
915const sessionDismissedBranchMismatchKeys = new Set<string>();
916
917export function dismissBranchMismatchForSession(key: string): void {
918 sessionDismissedBranchMismatchKeys.add(key);
919}
920
921export function isBranchMismatchDismissedForSession(key: string | null): boolean {
922 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
923}
924
925// Git status for a checkout arrives after the composer paints, and the branch
926// strip mounts on the assumption that a project is a Git repo. Without a
927// memory, a non-Git project would mount the strip and drop it on every visit.
928const sessionCheckoutIsRepo = new Map<string, boolean>();
929
930function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
931 return JSON.stringify([environmentId, cwd]);
932}
933
934export function rememberCheckoutIsRepo(
935 environmentId: EnvironmentId,
936 cwd: string,
937 isRepo: boolean,
938): void {
939 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
940}
941
942export function recallCheckoutIsRepo(
943 environmentId: EnvironmentId,
944 cwd: string | null,
945): boolean | undefined {
946 return cwd === null
947 ? undefined
948 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
949}
950
951export function threadHasStarted(thread: Thread | null | undefined): boolean {
952 return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
953}
954
955export function threadShellHasStarted(
956 shell:
957 | Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt" | "runtime">
958 | null
959 | undefined,
960): boolean {
961 return Boolean(
962 shell &&
963 (shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null),
964 );
965}
966
967// Imported history has no session until its first prompt. Resolve its instance
968// through the environment's provider catalog before locking to a driver.
969export function deriveLockedProvider(input: {
970 thread: Thread | null | undefined;
971 selectedProvider: string | null;
972 threadProvider: string | null;
973 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
974}): ProviderDriverKind | null {
975 if (!threadHasStarted(input.thread)) {
976 return null;
977 }
978 const sessionProvider = input.thread?.runtime?.providerName ?? null;
979 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
980 return sessionProvider;
981 }
982 // Preserve the existing lock while an instance is missing from the catalog;
983 // a started thread must not silently fall back to a different driver.
984 const threadProvider =
985 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
986 input.threadProvider;
987 const selectedProvider =
988 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
989 input.selectedProvider;
990 const narrowedThreadProvider =
991 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
992 const narrowedSelectedProvider =
993 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
994 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
995}
996
997export function getStartedThreadModelChangeBlockReason(input: {
998 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
999 hasStartedSession: boolean;
1000 supportsProviderSwitchingViaHandoff?: boolean;
1001 currentModelSelection: ModelSelection;
1002 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
1003 nextModelSelection: ModelSelection;
1004}): { title: string; description: string } | null {
1005 if (!input.hasStartedSession) {
1006 return null;
1007 }
1008 const currentModelSelection = {
1009 ...input.currentModelSelection,
1010 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
1011 };
1012 if (
1013 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
1014 currentModelSelection.model === input.nextModelSelection.model
1015 ) {
1016 return null;
1017 }
1018 if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
1019 if (input.supportsProviderSwitchingViaHandoff === true) {
1020 return null;
1021 }
1022 return {
1023 title: "Start a new chat to switch providers",
1024 description: "This thread does not support switching providers after it has started.",
1025 };
1026 }
1027 const currentProvider = input.providers.find(
1028 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1029 );
1030 const nextProvider = input.providers.find(
1031 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1032 );
1033 if (
1034 currentProvider?.requiresNewThreadForModelChange !== true &&
1035 nextProvider?.requiresNewThreadForModelChange !== true
1036 ) {
1037 return null;
1038 }
1039 return {
1040 title: "Start a new chat to change models",
1041 description: "This provider does not allow switching models after a conversation has started.",
1042 };
1043}
1044
1045export async function waitForStartedServerThread(
1046 threadRef: ScopedThreadRef,
1047 timeoutMs = 1_000,
1048): Promise<boolean> {
1049 const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
1050 return waitForAtomValue({
1051 registry: appAtomRegistry,
1052 atom: threadAtom,
1053 predicate: threadHasStarted,
1054 timeoutMs,
1055 });
1056}
1057
1058export async function waitForRevertedMessage(
1059 threadRef: ScopedThreadRef,
1060 messageId: MessageId,
1061 turnCount: number,
1062 requestId: CommandId,
1063 revert: () => Promise<void>,
1064 timeoutMs = 120_000,
1065): Promise<void> {
1066 const threadAtom = environmentThreadDetails.stateAtom(threadRef);
1067 const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);
1068 const initial = readProjection();
1069 if (!initial?.messages.some((message) => message.id === messageId)) {
1070 throw new Error("The message to rewind is no longer available.");
1071 }
1072 const messageRunId = initial.messages.find((message) => message.id === messageId)?.runId;
1073 return new Promise<void>((resolve, reject) => {
1074 let settled = false;
1075 let accepted = false;
1076 let unsubscribe = () => {};
1077 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1078 const finish = (error?: unknown) => {
1079 if (settled) return;
1080 settled = true;
1081 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1082 unsubscribe();
1083 if (error !== undefined) reject(error);
1084 else resolve();
1085 };
1086 const inspect = () => {
1087 const thread = readProjection();
1088 if (!thread) return;
1089 const failure = thread.thread.rollbackFailure;
1090 if (failure?.requestId === requestId) {
1091 finish(new Error(failure.message));
1092 return;
1093 }
1094 if (
1095 accepted &&
1096 thread.runs.some(
1097 (run) =>
1098 run.id === messageRunId && run.ordinal > turnCount && run.status === "rolled_back",
1099 )
1100 )
1101 finish();
1102 };
1103 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1104 timeout = globalThis.setTimeout(() => {
1105 finish(new Error("Timed out waiting for the thread to rewind."));
1106 }, timeoutMs);
1107 Promise.resolve()
1108 .then(revert)
1109 .then(() => {
1110 accepted = true;
1111 inspect();
1112 }, finish);
1113 });
1114}
1115
1116export interface LocalDispatchSnapshot {
1117 startedAt: string;
1118 preparingWorktree: boolean;
1119 submissionIntent: ComposerSubmissionIntent;
1120 latestUserMessageId: ChatMessage["id"] | null;
1121 latestRunId: RunId | null;
1122 latestRunRequestedAt: string | null;
1123 latestRunStartedAt: string | null;
1124 latestRunCompletedAt: string | null;
1125 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
1126 runtimeUpdatedAt: string | null;
1127}
1128
1129export function createLocalDispatchSnapshot(
1130 activeThread: Thread | undefined,
1131 options?: {
1132 preparingWorktree?: boolean;
1133 latestUserMessageId?: ChatMessage["id"] | null;
1134 submissionIntent?: ComposerSubmissionIntent;
1135 },
1136): LocalDispatchSnapshot {
1137 const latestRun = activeThread?.latestRun ?? null;
1138 const runtime = activeThread?.runtime ?? null;
1139 return {
1140 startedAt: new Date().toISOString(),
1141 preparingWorktree: Boolean(options?.preparingWorktree),
1142 submissionIntent: options?.submissionIntent ?? "foreground",
1143 latestUserMessageId: options?.latestUserMessageId ?? null,
1144 latestRunId: latestRun?.runId ?? null,
1145 latestRunRequestedAt: latestRun?.requestedAt ?? null,
1146 latestRunStartedAt: latestRun?.startedAt ?? null,
1147 latestRunCompletedAt: latestRun?.completedAt ?? null,
1148 runtimeStatus: runtime?.status ?? null,
1149 runtimeUpdatedAt: runtime?.updatedAt ?? null,
1150 };
1151}
1152
1153/**
1154 * The timeline renders committed user rows from `visibleTurnItems`, but
1155 * `message.updated` can land in `projection.messages` one event earlier than
1156 * the matching `turn-item.updated`. Basing optimistic eviction on visible user
1157 * turn items avoids dropping steer rows in that gap.
1158 */
1159export function deriveCommittedServerUserMessageIds(
1160 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1161): ReadonlySet<ChatMessage["id"]> {
1162 return new Set(
1163 visibleTurnItems.flatMap((row) =>
1164 row.item.type === "user_message" ? [row.item.messageId] : [],
1165 ),
1166 );
1167}
1168
1169export function hasServerAcknowledgedLocalDispatch(input: {
1170 localDispatch: LocalDispatchSnapshot | null;
1171 phase: SessionPhase;
1172 latestRun: Thread["latestRun"] | null;
1173 latestUserMessageId?: ChatMessage["id"] | null;
1174 runtime: Thread["runtime"] | null;
1175 hasPendingApproval: boolean;
1176 hasPendingUserInput: boolean;
1177 threadError: string | null | undefined;
1178}): boolean {
1179 if (!input.localDispatch) {
1180 return false;
1181 }
1182 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1183 return true;
1184 }
1185 if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") {
1186 return false;
1187 }
1188
1189 const latestRun = input.latestRun ?? null;
1190 const runtime = input.runtime ?? null;
1191 const latestUserMessageChanged =
1192 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
1193 const latestRunChanged =
1194 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
1195 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
1196 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
1197 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
1198
1199 if (input.phase === "running") {
1200 if (latestUserMessageChanged) {
1201 return true;
1202 }
1203 if (!latestRunChanged) {
1204 return false;
1205 }
1206 if (latestRun?.startedAt === null || latestRun === null) {
1207 return false;
1208 }
1209 if (
1210 runtime?.activeRunId !== null &&
1211 runtime?.activeRunId !== undefined &&
1212 latestRun?.runId !== runtime.activeRunId
1213 ) {
1214 return false;
1215 }
1216 return true;
1217 }
1218
1219 return (
1220 latestRunChanged ||
1221 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
1222 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
1223 );
1224}
1225
1226export function shouldRefocusComposerOnWindowFocus(
1227 activeElement:
1228 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1229 | null,
1230): boolean {
1231 if (activeElement === null || activeElement.tagName === "BODY") return true;
1232 if (
1233 activeElement.tagName === "INPUT" ||
1234 activeElement.tagName === "TEXTAREA" ||
1235 activeElement.tagName === "SELECT" ||
1236 activeElement.tagName === "IFRAME" ||
1237 activeElement.tagName === "WEBVIEW" ||
1238 activeElement.isContentEditable === true ||
1239 activeElement.getAttribute("role") === "textbox"
1240 ) {
1241 return false;
1242 }
1243 return (
1244 activeElement.closest(
1245 '[role="dialog"], [role="alertdialog"], [role="application"], [data-slot$="-popup"], [data-terminal-owner]',
1246 ) === null
1247 );
1248}
1249
1250export interface PlanFollowUpComposerSnapshot {
1251 readonly prompt: string;
1252 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1253 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1254 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1255 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
1256}
1257
1258/**
1259 * The caller clears the composer before awaiting the send, so every field it
1260 * held has to be written back here: a dropped field silently discards user
1261 * context.
1262 */
1263export function restorePlanFollowUpComposer(input: {
1264 readonly snapshot: PlanFollowUpComposerSnapshot;
1265 readonly writePrompt: (prompt: string) => void;
1266 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1267 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1268 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1269 readonly writeThreadContexts: (records: ReadonlyArray<ThreadContextRecord>) => void;
1270 readonly resetCursor: (options: {
1271 cursor: number;
1272 prompt: string;
1273 detectTrigger: boolean;
1274 }) => void;
1275}): void {
1276 input.writePrompt(input.snapshot.prompt);
1277 input.writeTerminalContexts(input.snapshot.terminalContexts);
1278 input.writeReviewComments(input.snapshot.reviewComments);
1279 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1280 input.writeThreadContexts(input.snapshot.threadContexts);
1281 input.resetCursor({
1282 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1283 prompt: input.snapshot.prompt,
1284 detectTrigger: true,
1285 });
1286}
1287
1288/**
1289 * Adds a directly sent preview annotation to the composer's images and
1290 * annotations. Its screenshot rides along only while the turn has room for
1291 * another attachment; over the cap the server rejects the whole turn.
1292 */
1293export function mergeDirectPreviewAnnotation(input: {
1294 readonly images: ReadonlyArray<ComposerImageAttachment>;
1295 readonly fileCount: number;
1296 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1297 readonly direct:
1298 | {
1299 readonly annotation: PreviewAnnotationPayload;
1300 readonly image: ComposerImageAttachment | null;
1301 }
1302 | undefined;
1303}): {
1304 readonly images: ReadonlyArray<ComposerImageAttachment>;
1305 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1306} {
1307 const { direct } = input;
1308 if (!direct) return { images: input.images, previewAnnotations: input.previewAnnotations };
1309 const imageAlreadyAttached =
1310 direct.image !== null && input.images.some((image) => image.id === direct.image?.id);
1311 const imageAppended =
1312 direct.image !== null &&
1313 !imageAlreadyAttached &&
1314 input.images.length + input.fileCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
1315 const images = direct.image && imageAppended ? [...input.images, direct.image] : input.images;
1316 const previewAnnotations = input.previewAnnotations.some(
1317 (annotation) => annotation.id === direct.annotation.id,
1318 )
1319 ? input.previewAnnotations
1320 : [
1321 ...input.previewAnnotations,
1322 {
1323 ...direct.annotation,
1324 // Claim an attached crop only when the screenshot really rides
1325 // along; a cap-dropped image must not produce a lying prompt.
1326 screenshot:
1327 direct.annotation.screenshot && (imageAppended || imageAlreadyAttached)
1328 ? { ...direct.annotation.screenshot, dataUrl: "" }
1329 : null,
1330 },
1331 ];
1332 return { images, previewAnnotations };
1333}
1334
1335/**
1336 * Whether a woken thread woke after the user last saw it. A run that completed
1337 * after the last visit counts as seeing it, since the user watched it finish.
1338 */
1339export function isThreadWokeUnseen(input: {
1340 readonly wokeAt: string | null;
1341 readonly settled: boolean;
1342 readonly lastVisitedAt: string | null | undefined;
1343 readonly latestRunCompletedAt: string | null;
1344}): boolean {
1345 if (input.wokeAt === null || input.settled) return false;
1346 const wokeAtMs = Date.parse(input.wokeAt);
1347 if (Number.isNaN(wokeAtMs)) return false;
1348 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
1349 .map((value) => (value ? Date.parse(value) : NaN))
1350 .filter((ms) => !Number.isNaN(ms));
1351 return seenAt.every((ms) => ms < wokeAtMs);
1352}