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