Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatView.logic.ts

1,388 lines47.5 KB

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