Open History to see the last commit
1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 type AssetCreateUrlInput,
4 type AssetCreateUrlResult,
5 type ChatFileAttachment,
6 type EnvironmentId,
7 isProviderDriverKind,
8 ProjectId,
9 type MessageId,
10 type ModelSelection,
11 type ProviderInteractionMode,
12 ProviderDriverKind,
13 type ProviderInstanceId,
14 type ServerProvider,
15 type ScopedProjectRef,
16 type ScopedThreadRef,
17 type ThreadId,
18 type ThreadLinkedPullRequest,
19 type TurnId,
20} from "@t3tools/contracts";
21import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
22import {
23 squashAtomCommandFailure,
24 type AtomCommandResult,
25} from "@t3tools/client-runtime/state/runtime";
26import { videoMimeType } from "@t3tools/shared/video";
27import {
28 appendCodexArtifactTemplateUsePrompt,
29 codexArtifactTemplateUsePrompt,
30 type CodexArtifactTemplate,
31} from "@t3tools/client-runtime/codex-artifact-templates";
32import {
33 type ChatMessage,
34 isImageAttachment,
35 type SessionPhase,
36 type Thread,
37 type ThreadShell,
38 type TurnDiffSummary,
39} from "../types";
40import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
41import * as Schema from "effect/Schema";
42import { appAtomRegistry } from "../rpc/atomRegistry";
43import { environmentThreadDetails } from "../state/threads";
44import {
45 filterTerminalContextsWithText,
46 stripInlineTerminalContextPlaceholders,
47 type TerminalContextDraft,
48} from "../lib/terminalContext";
49import type { DraftThreadEnvMode } from "../composerDraftStore";
50import type { ComposerSubmissionIntent } from "../composer-logic";
51import type { TimelineEntry } from "../session-logic";
52import type { DesktopPreviewOverlay } from "../previewStateStore";
53import type { RightPanelSurface } from "../rightPanelStore";
54import {
55 NO_PROVIDER_MODEL_SELECTION,
56 resolveSelectableProviderInstanceEntry,
57 type ProviderInstanceEntry,
58} from "../providerInstances";
59
60export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
61export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
62export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
63export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
64
65export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
66
67export function agentControlledBrowserCloseConfirmation(
68 surfaces: readonly RightPanelSurface[],
69 desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
70): string | null {
71 const activeBrowserCount = surfaces.filter(
72 (surface) =>
73 surface.kind === "preview" &&
74 surface.resourceId !== null &&
75 desktopByTabId[surface.resourceId]?.controller === "agent",
76 ).length;
77 if (activeBrowserCount === 0) return null;
78 if (activeBrowserCount === 1) {
79 return [
80 "Close browser while the agent is using it?",
81 "The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
82 ].join("\n");
83 }
84 return [
85 `Close ${activeBrowserCount} browsers while the agent is using them?`,
86 "The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
87 ].join("\n");
88}
89
90export function shouldRenderPreviewMiniPlayer(
91 miniPlayerTabId: string | null,
92 renderedRightPanelSurface: RightPanelSurface | null,
93): boolean {
94 return (
95 miniPlayerTabId !== null &&
96 !(
97 renderedRightPanelSurface?.kind === "preview" &&
98 renderedRightPanelSurface.resourceId === miniPlayerTabId
99 )
100 );
101}
102
103export function shouldOpenProactivePullRequest(
104 previousTargetKey: string | null | undefined,
105 targetKey: string | null,
106): boolean {
107 return targetKey !== null && targetKey !== previousTargetKey;
108}
109
110interface ProactivePanelObservation {
111 threadKey: string;
112 runningTurnId: TurnId | null | undefined;
113 targetKey: string | null | undefined;
114 userActionTurnId: TurnId | null;
115 userActionRevision: number;
116}
117
118/** Capture user intent before loading or metadata writes can defer panel activation. */
119export function observeProactivePanelUserChoice(
120 previous: ProactivePanelObservation | null,
121 input: { threadKey: string; runningTurnId: TurnId | null; userActionRevision: number },
122): ProactivePanelObservation {
123 const sameThread = previous?.threadKey === input.threadKey;
124 const newTurn =
125 sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;
126 return {
127 threadKey: input.threadKey,
128 runningTurnId: sameThread ? previous.runningTurnId : undefined,
129 targetKey: sameThread ? previous.targetKey : undefined,
130 userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),
131 userActionRevision:
132 !sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,
133 };
134}
135
136/** Follow a changed server link only when the panel still shows the previous linked PR. */
137export function shouldRetargetThreadPullRequestPanel(
138 previous: ThreadLinkedPullRequest | null,
139 current: ThreadLinkedPullRequest | null,
140 surface: RightPanelSurface | null,
141): boolean {
142 if (previous === null || current === null || surface?.kind !== "pull-request") return false;
143 const previousRepository = previous.repository.toLowerCase();
144 return (
145 (previous.projectId !== current.projectId ||
146 previousRepository !== current.repository.toLowerCase() ||
147 previous.number !== current.number) &&
148 surface.projectId === previous.projectId &&
149 surface.repository.toLowerCase() === previousRepository &&
150 surface.number === previous.number
151 );
152}
153
154export function shouldOpenProactiveTurnDiff(input: {
155 previousRunningTurnId: TurnId | null | undefined;
156 runningTurnId: TurnId | null;
157 settledTurnId: TurnId | null;
158 turnCompleted: boolean;
159}): boolean {
160 return (
161 input.runningTurnId === null &&
162 input.turnCompleted &&
163 input.settledTurnId !== null &&
164 (input.previousRunningTurnId === undefined ||
165 input.settledTurnId === input.previousRunningTurnId)
166 );
167}
168
169export function resolveProactiveTurnDiffAction(input: {
170 checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;
171 isGitRepo: boolean | undefined;
172}): "defer" | "ignore" | "open" {
173 if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
174 if (input.isGitRepo === undefined) return "defer";
175 if (
176 !input.isGitRepo ||
177 input.checkpoint.status !== "ready" ||
178 input.checkpoint.files.length === 0
179 ) {
180 return "ignore";
181 }
182 return "open";
183}
184
185export function codexArtifactTemplatePromptToAppend(
186 currentDraft: string,
187 template: CodexArtifactTemplate,
188): string | null {
189 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
190 ? null
191 : codexArtifactTemplateUsePrompt(template);
192}
193
194export function shouldDockDraftHeroForSubmission(input: {
195 isDraftHeroState: boolean;
196 activeThreadKey: string | null;
197 submissionIntent: ComposerSubmissionIntent;
198}): boolean {
199 return (
200 input.submissionIntent === "foreground" &&
201 input.isDraftHeroState &&
202 input.activeThreadKey !== null
203 );
204}
205
206export function shouldReleaseTimelineAnchorForToolActivity(input: {
207 anchorMessageId: MessageId | null;
208 liveFollowEnabled: boolean;
209 runningTurnId: TurnId | null;
210 timelineEntries: ReadonlyArray<TimelineEntry>;
211}): boolean {
212 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
213 return false;
214 }
215
216 return input.timelineEntries.some((timelineEntry) => {
217 if (timelineEntry.kind !== "work" || timelineEntry.entry.turnId !== input.runningTurnId) {
218 return false;
219 }
220
221 const entry = timelineEntry.entry;
222 return (
223 entry.tone === "tool" ||
224 entry.itemType !== undefined ||
225 entry.requestKind !== undefined ||
226 (entry.command?.trim().length ?? 0) > 0
227 );
228 });
229}
230
231export function toolGroupConsumesUpwardNavigation(target: EventTarget | null): boolean {
232 const elementTarget = target instanceof Element ? target : null;
233 const group = elementTarget?.closest<HTMLElement>("[data-tool-group-scroll]");
234 if (!group) return false;
235
236 // A nested result or the group itself can consume an upward scroll.
237 for (let element = elementTarget; element; element = element.parentElement) {
238 if (element.scrollTop > 0) {
239 const overflowY = getComputedStyle(element).overflowY;
240 if (overflowY === "auto" || overflowY === "scroll") return true;
241 }
242 if (element === group) break;
243 }
244 return false;
245}
246
247export function resolveDraftHeroState(input: {
248 isLocalDraftThread: boolean;
249 hasTimelineEntries: boolean;
250 isWorking: boolean;
251 draftHeroDockRequested: boolean;
252 backgroundSubmissionPending: boolean;
253}): boolean {
254 if (input.backgroundSubmissionPending) {
255 return true;
256 }
257 return (
258 input.isLocalDraftThread &&
259 !input.hasTimelineEntries &&
260 !input.isWorking &&
261 !input.draftHeroDockRequested
262 );
263}
264
265export function resolveDraftPromotionNavigationTarget(input: {
266 serverThreadRef: ScopedThreadRef | null;
267 serverThread: Pick<Thread, "latestTurn" | "session"> | null | undefined;
268 backgroundSubmissionPending: boolean;
269}): ScopedThreadRef | null {
270 if (input.backgroundSubmissionPending) {
271 return null;
272 }
273 const sessionStatus = input.serverThread?.session?.status;
274 const turnStarted = input.serverThread?.latestTurn?.startedAt != null;
275 const startupStopped =
276 sessionStatus === "error" || sessionStatus === "stopped" || sessionStatus === "interrupted";
277 // Keep local preparation feedback mounted until the server can render the
278 // running turn or its startup error on the canonical thread route.
279 return turnStarted || startupStopped ? input.serverThreadRef : null;
280}
281
282export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
283 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
284 return () => globalThis.clearTimeout(timeoutId);
285}
286
287export function hasEnvironmentReconnectWarningGraceElapsed(
288 activeEnvironmentId: EnvironmentId | null,
289 elapsedEnvironmentId: EnvironmentId | null,
290): boolean {
291 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
292}
293
294export function startNewThreadForProject(
295 projectRef: ScopedProjectRef | null,
296 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
297): boolean {
298 if (projectRef === null) return false;
299 void handleNewThread(projectRef);
300
301 return true;
302}
303
304export function resolveThreadMetadataUpdateForNextTurn(input: {
305 currentModelSelection: ModelSelection;
306 nextModelSelection?: ModelSelection;
307 currentBranch: string | null;
308 nextBranch?: string;
309}): {
310 modelSelection?: ModelSelection;
311 branch?: string;
312 worktreePath?: null;
313} | null {
314 const nextModelSelection = input.nextModelSelection;
315 const modelSelectionChanged =
316 nextModelSelection !== undefined &&
317 (nextModelSelection.model !== input.currentModelSelection.model ||
318 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
319 JSON.stringify(nextModelSelection.options ?? null) !==
320 JSON.stringify(input.currentModelSelection.options ?? null));
321 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
322 if (!modelSelectionChanged && !branchChanged) {
323 return null;
324 }
325 return {
326 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
327 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
328 };
329}
330
331export function buildLocalDraftThread(
332 threadId: ThreadId,
333 draftThread: DraftThreadState,
334 fallbackModelSelection: ModelSelection,
335): Thread {
336 return {
337 id: threadId,
338 environmentId: draftThread.environmentId,
339 projectId: draftThread.projectId,
340 title: "New thread",
341 modelSelection: fallbackModelSelection,
342 runtimeMode: draftThread.runtimeMode,
343 interactionMode: draftThread.interactionMode,
344 session: null,
345 messages: [],
346 createdAt: draftThread.createdAt,
347 updatedAt: draftThread.createdAt,
348 archivedAt: null,
349 settledOverride: null,
350 settledAt: null,
351 deletedAt: null,
352 latestTurn: null,
353 branch: draftThread.branch,
354 worktreePath: draftThread.worktreePath,
355 checkpoints: [],
356 pullRequests: [],
357 activities: [],
358 proposedPlans: [],
359 };
360}
361
362export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
363 return {
364 ...shell,
365 messages: [],
366 proposedPlans: [],
367 activities: [],
368 checkpoints: [],
369 deletedAt: null,
370 };
371}
372
373export function shouldWriteThreadErrorToCurrentServerThread(input: {
374 activeServerThread:
375 | {
376 environmentId: EnvironmentId;
377 id: ThreadId;
378 }
379 | null
380 | undefined;
381 routeThreadRef: ScopedThreadRef;
382 targetThreadId: ThreadId;
383}): boolean {
384 return Boolean(
385 input.activeServerThread &&
386 input.targetThreadId === input.routeThreadRef.threadId &&
387 input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
388 input.activeServerThread.id === input.targetThreadId,
389 );
390}
391
392export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
393 threadId: ThreadId;
394 turnId?: TurnId;
395} {
396 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
397 return {
398 threadId: thread.id,
399 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
400 };
401}
402
403/** The pending question seen on the previous render and the draft target of
404 * the thread that showed it, so a disappearance can be attributed. */
405export interface PendingUserInputRequestSnapshot<TDraftTarget> {
406 requestId: string;
407 draftTarget: TDraftTarget;
408}
409
410/** Keeps answers and submission bookkeeping isolated when providers reuse request ids. */
411export function pendingUserInputRequestKey(
412 target: ScopedThreadRef | string,
413 requestId: string | null,
414) {
415 return JSON.stringify(
416 typeof target === "string"
417 ? [target, requestId]
418 : [target.environmentId, target.threadId, requestId],
419 );
420}
421
422/**
423 * While a question is pending, the composer routes typed text into that
424 * question's custom answer instead of the persisted draft. The question can
425 * disappear for reasons other than being answered (Stop, provider abort,
426 * teardown), which would silently discard the text (issue #8963). True when
427 * the request that just disappeared should have its typed answers rescued into
428 * the composer draft: the request changed, it was not submitted, and the same
429 * thread is still on screen (an off-screen cancellation is left alone rather
430 * than risk the wrong draft).
431 */
432export function shouldRescueCancelledPendingUserInput<
433 TDraftTarget extends ScopedThreadRef | string,
434>(input: {
435 previous: PendingUserInputRequestSnapshot<TDraftTarget> | null;
436 nextRequestId: string | null;
437 currentDraftTarget: TDraftTarget;
438 wasSubmitted: boolean;
439}): boolean {
440 const { previous, nextRequestId, currentDraftTarget, wasSubmitted } = input;
441 if (!previous || previous.requestId === nextRequestId) {
442 return false;
443 }
444 return (
445 !wasSubmitted &&
446 pendingUserInputRequestKey(previous.draftTarget, null) ===
447 pendingUserInputRequestKey(currentDraftTarget, null)
448 );
449}
450
451/**
452 * Joins a request's non-blank typed custom answers, one per question, so a
453 * multi-question request keeps every answer the user wrote. Returns null when
454 * nothing non-blank was typed.
455 */
456export function collectPendingUserInputCustomAnswers(
457 answersByQuestion: Record<string, { readonly customAnswer?: string }> | undefined,
458): string | null {
459 const answers = Object.values(answersByQuestion ?? {})
460 .map((draft) => draft.customAnswer ?? "")
461 .filter((answer) => answer.trim().length > 0);
462 return answers.length === 0 ? null : answers.join("\n\n");
463}
464
465/**
466 * Merges a rescued pending-question answer into a thread's composer draft
467 * prompt. The draft store is untouched while a question is pending, so it
468 * can still hold older unsent text — a blank draft is replaced outright,
469 * but non-blank text is preserved and the rescued answer is appended after
470 * a blank line rather than clobbering it. Returns `null` when there is
471 * nothing worth persisting (blank answer).
472 */
473export function mergeComposerDraftPromptWithPendingAnswer(
474 existingDraftPrompt: string,
475 pendingCustomAnswer: string,
476): string | null {
477 if (pendingCustomAnswer.trim().length === 0) {
478 return null;
479 }
480 if (existingDraftPrompt.trim().length === 0) {
481 return pendingCustomAnswer;
482 }
483 if (existingDraftPrompt === pendingCustomAnswer) {
484 return existingDraftPrompt;
485 }
486 return `${existingDraftPrompt}\n\n${pendingCustomAnswer}`;
487}
488
489/**
490 * Resolves the draft update when typed pending-question text leaves its answer
491 * slot. A null result means there is no text to return, so the caller must
492 * preserve both the persisted draft and any carried-draft bookkeeping.
493 */
494export function resolveComposerDraftPromptAfterReturningPendingAnswer(input: {
495 draftPrompt: string;
496 carriedDraftPrompt: string | null;
497 pendingCustomAnswer: string;
498 discardEmptyCarriedDraft?: boolean;
499 unrelatedDraftPrompt?: string;
500}): string | null {
501 if (
502 input.discardEmptyCarriedDraft &&
503 input.pendingCustomAnswer.trim().length === 0 &&
504 input.carriedDraftPrompt !== null &&
505 input.draftPrompt === input.carriedDraftPrompt
506 ) {
507 return input.unrelatedDraftPrompt ?? "";
508 }
509 const existingDraftPrompt =
510 input.carriedDraftPrompt !== null && input.draftPrompt === input.carriedDraftPrompt
511 ? (input.unrelatedDraftPrompt ?? "")
512 : input.draftPrompt;
513 return mergeComposerDraftPromptWithPendingAnswer(existingDraftPrompt, input.pendingCustomAnswer);
514}
515
516/**
517 * A question that has just arrived takes over the composer, which would hide
518 * whatever the user was typing until the question resolves (issue #8963).
519 * Returns the draft text to carry into the request's first question as its
520 * free-form answer, so the composer visibly keeps it and Send offers it as
521 * the reply. Null when there is nothing to carry: the request already has
522 * answer state (it was seen before, e.g. on an earlier visit to the thread),
523 * the question rejects custom answers, or the draft is blank.
524 */
525export function resolveComposerDraftToCarryIntoPendingUserInput(input: {
526 hasAnswerState: boolean;
527 allowCustomAnswer?: boolean;
528 draftPrompt: string;
529}): string | null {
530 if (
531 input.hasAnswerState ||
532 input.allowCustomAnswer === false ||
533 input.draftPrompt.trim().length === 0
534 ) {
535 return null;
536 }
537 return input.draftPrompt;
538}
539
540/** Use the same enabled instance for the composer, provider status, and chat actions. */
541export function resolveComposerProviderSelection(input: {
542 entries: ReadonlyArray<ProviderInstanceEntry>;
543 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
544 lockedProvider: ProviderDriverKind | null;
545 lockedInstanceId: ProviderInstanceId | null | undefined;
546}) {
547 const requestedInstanceId = input.candidateInstanceIds.find(
548 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
549 );
550 const requestedDriverKind =
551 input.lockedProvider ??
552 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
553 input.entries[0]?.driverKind ??
554 ProviderDriverKind.make("unconfigured");
555 const lockedContinuationGroupKey = input.lockedProvider
556 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
557 ?.continuationGroupKey ?? null)
558 : null;
559 // Missing metadata must not move Antigravity history into another Google profile.
560 const requiresExactInstance =
561 input.lockedProvider === "antigravity" &&
562 input.lockedInstanceId != null &&
563 lockedContinuationGroupKey === null;
564 const compatibleEntries = input.entries.filter(
565 (entry) =>
566 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
567 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
568 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
569 );
570 const selectedProviderEntry =
571 input.candidateInstanceIds
572 .map((candidate) =>
573 compatibleEntries.find(
574 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
575 ),
576 )
577 .find((entry) => entry !== undefined) ??
578 resolveSelectableProviderInstanceEntry(
579 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
580 undefined,
581 ) ??
582 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
583 const unavailableProviderInstanceId = selectedProviderEntry
584 ? undefined
585 : input.lockedProvider
586 ? (input.lockedInstanceId ?? requestedInstanceId)
587 : requestedInstanceId;
588 return {
589 selectedProviderEntry,
590 requestedDriverKind,
591 lockedContinuationGroupKey,
592 unavailableProviderInstanceId,
593 };
594}
595
596/** Keep restored drafts and every plan control on the selected instance's supported mode. */
597export function resolveComposerInteractionMode(input: {
598 planModeEnabled: boolean;
599 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
600 interactionMode: ProviderInteractionMode;
601}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
602 const enabled =
603 input.planModeEnabled &&
604 input.provider != null &&
605 input.provider.showInteractionModeToggle !== false;
606 return {
607 enabled,
608 interactionMode: enabled ? input.interactionMode : "default",
609 };
610}
611
612export function getAntigravitySendBlockReason(
613 provider:
614 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
615 | null
616 | undefined,
617 model: string,
618): string | null {
619 if (provider?.driver !== "antigravity") return null;
620 if (!provider.installed) {
621 return "Install Antigravity in provider settings before sending.";
622 }
623 if (provider.auth.status === "unauthenticated") {
624 return "Sign in to Antigravity in provider settings before sending.";
625 }
626 const slug = model.trim();
627 if (slug.length === 0) return "Choose an Antigravity model before sending.";
628 // A restart clears the account status and catalog. Session startup checks
629 // saved credentials and validates the model before sending the prompt.
630 if (provider.auth.status === "unknown") return null;
631 if (provider.models.length === 0) {
632 return "Refresh Antigravity models in provider settings before sending.";
633 }
634 // A saved model that left the catalog is kept in the picker as unavailable
635 // so the user sees what the thread used. The server rejects it at turn
636 // start, so block here unless the provider is in an error state, where a
637 // retry with the same model is the right move.
638 if (
639 provider.status === "ready" &&
640 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
641 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
642 ) {
643 return "That Antigravity model is no longer available. Choose another model.";
644 }
645 return null;
646}
647
648export function buildRunningThreadTurnInterruptInput(
649 thread: Pick<Thread, "id" | "session"> | null | undefined,
650 phase: SessionPhase,
651): { threadId: ThreadId; turnId?: TurnId } | null {
652 if (phase !== "running" || thread?.session?.status !== "running") {
653 return null;
654 }
655 return buildThreadTurnInterruptInput(thread);
656}
657
658export function reconcileMountedTerminalThreadIds(input: {
659 currentThreadIds: ReadonlyArray<string>;
660 openThreadIds: ReadonlyArray<string>;
661 activeThreadId: string | null;
662 activeThreadTerminalOpen: boolean;
663 maxHiddenThreadCount?: number;
664}): string[] {
665 return reconcileRetainedMountedThreadIds({
666 currentThreadIds: input.currentThreadIds,
667 openThreadIds: input.openThreadIds,
668 activeThreadId: input.activeThreadId,
669 activeThreadOpen: input.activeThreadTerminalOpen,
670 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
671 });
672}
673
674export function reconcileRetainedMountedThreadIds(input: {
675 currentThreadIds: ReadonlyArray<string>;
676 openThreadIds: ReadonlyArray<string>;
677 activeThreadId: string | null;
678 activeThreadOpen: boolean;
679 maxHiddenThreadCount: number;
680 retainInactiveActiveThread?: boolean;
681}): string[] {
682 const openThreadIdSet = new Set(input.openThreadIds);
683 const hiddenThreadIds = input.currentThreadIds.filter(
684 (threadId) =>
685 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
686 openThreadIdSet.has(threadId),
687 );
688 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
689 const nextThreadIds =
690 hiddenThreadIds.length > maxHiddenThreadCount
691 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
692 : hiddenThreadIds;
693
694 if (
695 input.activeThreadId &&
696 input.activeThreadOpen &&
697 !nextThreadIds.includes(input.activeThreadId)
698 ) {
699 nextThreadIds.push(input.activeThreadId);
700 }
701
702 return nextThreadIds;
703}
704
705export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
706 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
707 return;
708 }
709 URL.revokeObjectURL(previewUrl);
710}
711
712/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
713export async function resolveFileAttachmentUrl(input: {
714 attachment: ChatFileAttachment;
715 environmentId: EnvironmentId;
716 httpBaseUrl: string;
717 createAssetUrl: (input: {
718 environmentId: EnvironmentId;
719 input: AssetCreateUrlInput;
720 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
721}): Promise<string> {
722 const { attachment } = input;
723 const result = await input.createAssetUrl({
724 environmentId: input.environmentId,
725 input: {
726 resource: {
727 _tag: "attachment",
728 attachmentId: attachment.id,
729 fileName: attachment.name,
730 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
731 },
732 },
733 });
734 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
735 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
736 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
737 return url;
738}
739
740export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
741 if (message.role !== "user" || !message.attachments) {
742 return;
743 }
744 for (const attachment of message.attachments) {
745 if (!isImageAttachment(attachment)) {
746 continue;
747 }
748 revokeBlobPreviewUrl(attachment.previewUrl);
749 }
750}
751
752export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
753 if (message.role !== "user" || !message.attachments) {
754 return [];
755 }
756 const previewUrls: string[] = [];
757 for (const attachment of message.attachments) {
758 if (!isImageAttachment(attachment)) continue;
759 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
760 previewUrls.push(attachment.previewUrl);
761 }
762 return previewUrls;
763}
764
765export interface PullRequestDialogState {
766 initialReference: string | null;
767 key: number;
768}
769
770export function readFileAsDataUrl(file: File): Promise<string> {
771 return new Promise((resolve, reject) => {
772 const reader = new FileReader();
773 reader.addEventListener("load", () => {
774 if (typeof reader.result === "string") {
775 resolve(reader.result);
776 return;
777 }
778 reject(new Error("Could not read image data."));
779 });
780 reader.addEventListener("error", () => {
781 reject(reader.error ?? new Error("Failed to read image."));
782 });
783 reader.readAsDataURL(file);
784 });
785}
786
787export function resolveSendEnvMode(input: {
788 requestedEnvMode: DraftThreadEnvMode;
789 isGitRepo: boolean;
790}): DraftThreadEnvMode {
791 return input.isGitRepo ? input.requestedEnvMode : "local";
792}
793
794export function resolveBackgroundDraftWorkspaceOptions(input: {
795 envMode: DraftThreadEnvMode;
796 branch: string | null;
797 startFromOrigin: boolean;
798}): {
799 envMode: DraftThreadEnvMode;
800 branch: string | null;
801 worktreePath: null;
802 startFromOrigin: boolean;
803} {
804 return {
805 envMode: input.envMode,
806 branch: input.branch,
807 worktreePath: null,
808 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
809 };
810}
811
812export function cloneComposerImageForRetry(
813 image: ComposerImageAttachment,
814): ComposerImageAttachment {
815 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
816 return image;
817 }
818 try {
819 return {
820 ...image,
821 previewUrl: URL.createObjectURL(image.file),
822 };
823 } catch {
824 return image;
825 }
826}
827
828export function deriveComposerSendState(options: {
829 prompt: string;
830 imageCount: number;
831 terminalContexts: ReadonlyArray<TerminalContextDraft>;
832 /**
833 * Optional element-pick attachment count. Element contexts contribute to
834 * "sendable content" exactly like images and (text-bearing) terminal
835 * contexts do: a prompt of just element chips is still a valid send.
836 */
837 elementContextCount?: number;
838}): {
839 trimmedPrompt: string;
840 sendableTerminalContexts: TerminalContextDraft[];
841 expiredTerminalContextCount: number;
842 hasSendableContent: boolean;
843} {
844 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
845 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
846 const expiredTerminalContextCount =
847 options.terminalContexts.length - sendableTerminalContexts.length;
848 const elementContextCount = options.elementContextCount ?? 0;
849 return {
850 trimmedPrompt,
851 sendableTerminalContexts,
852 expiredTerminalContextCount,
853 hasSendableContent:
854 trimmedPrompt.length > 0 ||
855 options.imageCount > 0 ||
856 sendableTerminalContexts.length > 0 ||
857 elementContextCount > 0,
858 };
859}
860
861export function buildExpiredTerminalContextToastCopy(
862 expiredTerminalContextCount: number,
863 variant: "omitted" | "empty",
864): { title: string; description: string } {
865 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
866 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
867 if (variant === "empty") {
868 return {
869 title: `${noun} won't be sent`,
870 description: "Remove it or re-add it to include terminal output.",
871 };
872 }
873 return {
874 title: `${noun} omitted from message`,
875 description: "Re-add it if you want that terminal output included.",
876 };
877}
878
879export function branchMismatchKey(
880 threadId: string | null,
881 mismatch: { threadBranch: string; currentBranch: string } | null,
882): string | null {
883 if (!threadId || !mismatch) {
884 return null;
885 }
886 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
887}
888
889// The mismatch banner only matters when the user is about to send: passive
890// reading of an old thread carries no risk (the branch picker tint already
891// covers ambient awareness). Draft content is the intent signal — composer
892// focus is useless here because ChatView autofocuses the composer on every
893// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
894// revealed so it doesn't flicker away when the draft is cleared.
895export function shouldShowBranchMismatchBanner(input: {
896 hasMismatch: boolean;
897 isDismissed: boolean;
898 composerHasContent: boolean;
899 wasShownForCurrentMismatch: boolean;
900}): boolean {
901 if (!input.hasMismatch || input.isDismissed) {
902 return false;
903 }
904 return input.composerHasContent || input.wasShownForCurrentMismatch;
905}
906
907export function shouldShowPlanFollowUpPrompt(input: {
908 pendingUserInputCount: number;
909 interactionMode: ProviderInteractionMode;
910 latestTurnSettled: boolean;
911 hasActionableProposedPlan: boolean;
912 hasComposerAttachments: boolean;
913}): boolean {
914 return (
915 input.pendingUserInputCount === 0 &&
916 input.interactionMode === "plan" &&
917 input.latestTurnSettled &&
918 input.hasActionableProposedPlan &&
919 !input.hasComposerAttachments
920 );
921}
922
923// Session-scoped (module-level so it survives ChatView remounts, e.g. route
924// changes). Durable cross-device dismissal is planned as a server-side ack.
925const sessionDismissedBranchMismatchKeys = new Set<string>();
926
927export function dismissBranchMismatchForSession(key: string): void {
928 sessionDismissedBranchMismatchKeys.add(key);
929}
930
931export function isBranchMismatchDismissedForSession(key: string | null): boolean {
932 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
933}
934
935// Git status for a checkout arrives after the composer paints, and the branch
936// strip mounts on the assumption that a project is a Git repo. Without a
937// memory, a non-Git project would mount the strip and drop it on every visit.
938// Keyed by environment and checkout for the session; never persisted.
939const sessionCheckoutIsRepo = new Map<string, boolean>();
940
941function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
942 return JSON.stringify([environmentId, cwd]);
943}
944
945export function rememberCheckoutIsRepo(
946 environmentId: EnvironmentId,
947 cwd: string,
948 isRepo: boolean,
949): void {
950 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
951}
952
953export function recallCheckoutIsRepo(
954 environmentId: EnvironmentId,
955 cwd: string | null,
956): boolean | undefined {
957 return cwd === null
958 ? undefined
959 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
960}
961
962export function threadHasStarted(thread: Thread | null | undefined): boolean {
963 return Boolean(
964 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
965 );
966}
967
968/**
969 * Whether a thread ran at least one turn, judged from its shell alone.
970 *
971 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
972 * still has messages, and the loading shell carries none. The shell records
973 * when the last user message landed, which every started thread has.
974 */
975export function threadShellHasStarted(
976 shell: Pick<ThreadShell, "latestTurn" | "latestUserMessageAt" | "session"> | null | undefined,
977): boolean {
978 return Boolean(
979 shell &&
980 (shell.latestTurn !== null || shell.latestUserMessageAt !== null || shell.session !== null),
981 );
982}
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?.session?.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;
1012}
1013
1014export function getStartedThreadModelChangeBlockReason(input: {
1015 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
1016 hasStartedSession: boolean;
1017 currentModelSelection: ModelSelection;
1018 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
1019 nextModelSelection: ModelSelection;
1020}): { title: string; description: string } | null {
1021 if (!input.hasStartedSession) {
1022 return null;
1023 }
1024 const currentModelSelection = {
1025 ...input.currentModelSelection,
1026 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
1027 };
1028 if (
1029 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
1030 currentModelSelection.model === input.nextModelSelection.model
1031 ) {
1032 return null;
1033 }
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;
1045 }
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 };
1050}
1051
1052export async function waitForStartedServerThread(
1053 threadRef: ScopedThreadRef,
1054 timeoutMs = 1_000,
1055): Promise<boolean> {
1056 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
1057 const getThread = () => appAtomRegistry.get(threadAtom);
1058 const thread = getThread();
1059
1060 if (threadHasStarted(thread)) {
1061 return true;
1062 }
1063
1064 return await new Promise<boolean>((resolve) => {
1065 let settled = false;
1066 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
1067 const finish = (result: boolean) => {
1068 if (settled) {
1069 return;
1070 }
1071 settled = true;
1072 if (timeoutId !== null) {
1073 globalThis.clearTimeout(timeoutId);
1074 }
1075 unsubscribe();
1076 resolve(result);
1077 };
1078
1079 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
1080 if (!threadHasStarted(thread)) {
1081 return;
1082 }
1083 finish(true);
1084 });
1085
1086 if (threadHasStarted(getThread())) {
1087 finish(true);
1088 return;
1089 }
1090
1091 timeoutId = globalThis.setTimeout(() => {
1092 finish(false);
1093 }, timeoutMs);
1094 });
1095}
1096
1097export interface LocalDispatchSnapshot {
1098 startedAt: string;
1099 preparingWorktree: boolean;
1100 submissionIntent: ComposerSubmissionIntent;
1101 latestUserMessageId: ChatMessage["id"] | null;
1102 latestTurnTurnId: TurnId | null;
1103 latestTurnRequestedAt: string | null;
1104 latestTurnStartedAt: string | null;
1105 latestTurnCompletedAt: string | null;
1106 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
1107 sessionUpdatedAt: string | null;
1108 latestTurnStartFailureId: string | null;
1109}
1110
1111export function latestTurnStartFailureId(
1112 activeThread: Thread | undefined,
1113 latestUserMessageId: ChatMessage["id"] | null,
1114): string | null {
1115 if (latestUserMessageId === null) return null;
1116 return (
1117 activeThread?.activities.findLast((activity) => {
1118 if (activity.kind !== "provider.turn.start.failed") return false;
1119 const payload =
1120 typeof activity.payload === "object" && activity.payload !== null
1121 ? (activity.payload as { readonly requestId?: unknown })
1122 : null;
1123 return payload?.requestId === latestUserMessageId;
1124 })?.id ?? null
1125 );
1126}
1127
1128export function createLocalDispatchSnapshot(
1129 activeThread: Thread | undefined,
1130 options?: {
1131 preparingWorktree?: boolean;
1132 submissionIntent?: ComposerSubmissionIntent;
1133 },
1134): LocalDispatchSnapshot {
1135 const latestTurn = activeThread?.latestTurn ?? null;
1136 const session = activeThread?.session ?? null;
1137 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
1138 return {
1139 startedAt: new Date().toISOString(),
1140 preparingWorktree: Boolean(options?.preparingWorktree),
1141 submissionIntent: options?.submissionIntent ?? "foreground",
1142 latestUserMessageId: latestUserMessage?.id ?? null,
1143 latestTurnTurnId: latestTurn?.turnId ?? null,
1144 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
1145 latestTurnStartedAt: latestTurn?.startedAt ?? null,
1146 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
1147 sessionStatus: session?.status ?? null,
1148 sessionUpdatedAt: session?.updatedAt ?? null,
1149 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
1150 };
1151}
1152
1153export function hasServerAcknowledgedLocalDispatch(input: {
1154 localDispatch: LocalDispatchSnapshot | null;
1155 phase: SessionPhase;
1156 latestTurn: Thread["latestTurn"] | null;
1157 latestUserMessageId: ChatMessage["id"] | null;
1158 session: Thread["session"] | null;
1159 hasPendingApproval: boolean;
1160 hasPendingUserInput: boolean;
1161 latestTurnStartFailureId?: string | null;
1162 threadError: string | null | undefined;
1163}): boolean {
1164 if (!input.localDispatch) {
1165 return false;
1166 }
1167 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1168 return true;
1169 }
1170 if (
1171 input.latestTurnStartFailureId !== undefined &&
1172 input.latestTurnStartFailureId !== null &&
1173 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
1174 ) {
1175 return true;
1176 }
1177 if (input.phase === "connecting") {
1178 return false;
1179 }
1180
1181 const latestTurn = input.latestTurn ?? null;
1182 const session = input.session ?? null;
1183 const latestUserMessageChanged =
1184 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
1185 const latestTurnChanged =
1186 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
1187 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
1188 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
1189 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
1190
1191 if (input.phase === "running") {
1192 // Steering adds a user message to the current running turn without
1193 // necessarily changing any of the turn timestamps. Treat that projected
1194 // message as the server acknowledgment so the composer does not remain
1195 // stuck in its local "Sending" state until the turn settles.
1196 if (latestUserMessageChanged) {
1197 return true;
1198 }
1199 if (!latestTurnChanged) {
1200 return false;
1201 }
1202 if (latestTurn?.startedAt === null || latestTurn === null) {
1203 return false;
1204 }
1205 if (
1206 session?.activeTurnId !== null &&
1207 session?.activeTurnId !== undefined &&
1208 latestTurn?.turnId !== session.activeTurnId
1209 ) {
1210 return false;
1211 }
1212 return true;
1213 }
1214
1215 return (
1216 latestTurnChanged ||
1217 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1218 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1219 );
1220}
1221
1222// Returning to the window should land the caret in the composer, so the reader can type right
1223// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1224// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1225// not one of them, so it yields to the composer.
1226export function shouldRefocusComposerOnWindowFocus(
1227 activeElement:
1228 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1229 | null,
1230): boolean {
1231 if (activeElement === null || activeElement.tagName === "BODY") return true;
1232 if (
1233 activeElement.tagName === "INPUT" ||
1234 activeElement.tagName === "TEXTAREA" ||
1235 activeElement.tagName === "SELECT" ||
1236 activeElement.isContentEditable === true ||
1237 activeElement.getAttribute("role") === "textbox"
1238 ) {
1239 return false;
1240 }
1241 return (
1242 activeElement.closest(
1243 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1244 ) === null
1245 );
1246}