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