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

ChatView.logic.ts

1,293 lines43.8 KB

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