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