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

ChatView.logic.ts

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