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