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 activities: [],
357 proposedPlans: [],
358 };
359}
360
361export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
362 return {
363 ...shell,
364 messages: [],
365 proposedPlans: [],
366 activities: [],
367 checkpoints: [],
368 deletedAt: null,
369 };
370}
371
372export function shouldWriteThreadErrorToCurrentServerThread(input: {
373 activeServerThread:
374 | {
375 environmentId: EnvironmentId;
376 id: ThreadId;
377 }
378 | null
379 | undefined;
380 routeThreadRef: ScopedThreadRef;
381 targetThreadId: ThreadId;
382}): boolean {
383 return Boolean(
384 input.activeServerThread &&
385 input.targetThreadId === input.routeThreadRef.threadId &&
386 input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
387 input.activeServerThread.id === input.targetThreadId,
388 );
389}
390
391export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
392 threadId: ThreadId;
393 turnId?: TurnId;
394} {
395 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
396 return {
397 threadId: thread.id,
398 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
399 };
400}
401
402/** Use the same enabled instance for the composer, provider status, and chat actions. */
403export function resolveComposerProviderSelection(input: {
404 entries: ReadonlyArray<ProviderInstanceEntry>;
405 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
406 lockedProvider: ProviderDriverKind | null;
407 lockedInstanceId: ProviderInstanceId | null | undefined;
408}) {
409 const requestedInstanceId = input.candidateInstanceIds.find(
410 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
411 );
412 const requestedDriverKind =
413 input.lockedProvider ??
414 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
415 input.entries[0]?.driverKind ??
416 ProviderDriverKind.make("unconfigured");
417 const lockedContinuationGroupKey = input.lockedProvider
418 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
419 ?.continuationGroupKey ?? null)
420 : null;
421 // Missing metadata must not move Antigravity history into another Google profile.
422 const requiresExactInstance =
423 input.lockedProvider === "antigravity" &&
424 input.lockedInstanceId != null &&
425 lockedContinuationGroupKey === null;
426 const compatibleEntries = input.entries.filter(
427 (entry) =>
428 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
429 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
430 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
431 );
432 const selectedProviderEntry =
433 input.candidateInstanceIds
434 .map((candidate) =>
435 compatibleEntries.find(
436 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
437 ),
438 )
439 .find((entry) => entry !== undefined) ??
440 resolveSelectableProviderInstanceEntry(
441 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
442 undefined,
443 ) ??
444 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
445 const unavailableProviderInstanceId = selectedProviderEntry
446 ? undefined
447 : input.lockedProvider
448 ? (input.lockedInstanceId ?? requestedInstanceId)
449 : requestedInstanceId;
450 return {
451 selectedProviderEntry,
452 requestedDriverKind,
453 lockedContinuationGroupKey,
454 unavailableProviderInstanceId,
455 };
456}
457
458/** Keep restored drafts and every plan control on the selected instance's supported mode. */
459export function resolveComposerInteractionMode(input: {
460 planModeEnabled: boolean;
461 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
462 interactionMode: ProviderInteractionMode;
463}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
464 const enabled =
465 input.planModeEnabled &&
466 input.provider != null &&
467 input.provider.showInteractionModeToggle !== false;
468 return {
469 enabled,
470 interactionMode: enabled ? input.interactionMode : "default",
471 };
472}
473
474export function getAntigravitySendBlockReason(
475 provider:
476 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
477 | null
478 | undefined,
479 model: string,
480): string | null {
481 if (provider?.driver !== "antigravity") return null;
482 if (!provider.installed) {
483 return "Install Antigravity in provider settings before sending.";
484 }
485 if (provider.auth.status === "unauthenticated") {
486 return "Sign in to Antigravity in provider settings before sending.";
487 }
488 const slug = model.trim();
489 if (slug.length === 0) return "Choose an Antigravity model before sending.";
490 // A restart clears the account status and catalog. Session startup checks
491 // saved credentials and validates the model before sending the prompt.
492 if (provider.auth.status === "unknown") return null;
493 if (provider.models.length === 0) {
494 return "Refresh Antigravity models in provider settings before sending.";
495 }
496 // A saved model that left the catalog is kept in the picker as unavailable
497 // so the user sees what the thread used. The server rejects it at turn
498 // start, so block here unless the provider is in an error state, where a
499 // retry with the same model is the right move.
500 if (
501 provider.status === "ready" &&
502 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
503 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
504 ) {
505 return "That Antigravity model is no longer available. Choose another model.";
506 }
507 return null;
508}
509
510export function buildRunningThreadTurnInterruptInput(
511 thread: Pick<Thread, "id" | "session"> | null | undefined,
512 phase: SessionPhase,
513): { threadId: ThreadId; turnId?: TurnId } | null {
514 if (phase !== "running" || thread?.session?.status !== "running") {
515 return null;
516 }
517 return buildThreadTurnInterruptInput(thread);
518}
519
520export function reconcileMountedTerminalThreadIds(input: {
521 currentThreadIds: ReadonlyArray<string>;
522 openThreadIds: ReadonlyArray<string>;
523 activeThreadId: string | null;
524 activeThreadTerminalOpen: boolean;
525 maxHiddenThreadCount?: number;
526}): string[] {
527 return reconcileRetainedMountedThreadIds({
528 currentThreadIds: input.currentThreadIds,
529 openThreadIds: input.openThreadIds,
530 activeThreadId: input.activeThreadId,
531 activeThreadOpen: input.activeThreadTerminalOpen,
532 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
533 });
534}
535
536export function reconcileRetainedMountedThreadIds(input: {
537 currentThreadIds: ReadonlyArray<string>;
538 openThreadIds: ReadonlyArray<string>;
539 activeThreadId: string | null;
540 activeThreadOpen: boolean;
541 maxHiddenThreadCount: number;
542 retainInactiveActiveThread?: boolean;
543}): string[] {
544 const openThreadIdSet = new Set(input.openThreadIds);
545 const hiddenThreadIds = input.currentThreadIds.filter(
546 (threadId) =>
547 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
548 openThreadIdSet.has(threadId),
549 );
550 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
551 const nextThreadIds =
552 hiddenThreadIds.length > maxHiddenThreadCount
553 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
554 : hiddenThreadIds;
555
556 if (
557 input.activeThreadId &&
558 input.activeThreadOpen &&
559 !nextThreadIds.includes(input.activeThreadId)
560 ) {
561 nextThreadIds.push(input.activeThreadId);
562 }
563
564 return nextThreadIds;
565}
566
567export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
568 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
569 return;
570 }
571 URL.revokeObjectURL(previewUrl);
572}
573
574/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
575export async function resolveFileAttachmentUrl(input: {
576 attachment: ChatFileAttachment;
577 environmentId: EnvironmentId;
578 httpBaseUrl: string;
579 createAssetUrl: (input: {
580 environmentId: EnvironmentId;
581 input: AssetCreateUrlInput;
582 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
583}): Promise<string> {
584 const { attachment } = input;
585 const result = await input.createAssetUrl({
586 environmentId: input.environmentId,
587 input: {
588 resource: {
589 _tag: "attachment",
590 attachmentId: attachment.id,
591 fileName: attachment.name,
592 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
593 },
594 },
595 });
596 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
597 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
598 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
599 return url;
600}
601
602export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
603 if (message.role !== "user" || !message.attachments) {
604 return;
605 }
606 for (const attachment of message.attachments) {
607 if (!isImageAttachment(attachment)) {
608 continue;
609 }
610 revokeBlobPreviewUrl(attachment.previewUrl);
611 }
612}
613
614export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
615 if (message.role !== "user" || !message.attachments) {
616 return [];
617 }
618 const previewUrls: string[] = [];
619 for (const attachment of message.attachments) {
620 if (!isImageAttachment(attachment)) continue;
621 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
622 previewUrls.push(attachment.previewUrl);
623 }
624 return previewUrls;
625}
626
627export interface PullRequestDialogState {
628 initialReference: string | null;
629 key: number;
630}
631
632export function readFileAsDataUrl(file: File): Promise<string> {
633 return new Promise((resolve, reject) => {
634 const reader = new FileReader();
635 reader.addEventListener("load", () => {
636 if (typeof reader.result === "string") {
637 resolve(reader.result);
638 return;
639 }
640 reject(new Error("Could not read image data."));
641 });
642 reader.addEventListener("error", () => {
643 reject(reader.error ?? new Error("Failed to read image."));
644 });
645 reader.readAsDataURL(file);
646 });
647}
648
649export function resolveSendEnvMode(input: {
650 requestedEnvMode: DraftThreadEnvMode;
651 isGitRepo: boolean;
652}): DraftThreadEnvMode {
653 return input.isGitRepo ? input.requestedEnvMode : "local";
654}
655
656export function resolveBackgroundDraftWorkspaceOptions(input: {
657 envMode: DraftThreadEnvMode;
658 branch: string | null;
659 startFromOrigin: boolean;
660}): {
661 envMode: DraftThreadEnvMode;
662 branch: string | null;
663 worktreePath: null;
664 startFromOrigin: boolean;
665} {
666 return {
667 envMode: input.envMode,
668 branch: input.branch,
669 worktreePath: null,
670 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
671 };
672}
673
674export function cloneComposerImageForRetry(
675 image: ComposerImageAttachment,
676): ComposerImageAttachment {
677 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
678 return image;
679 }
680 try {
681 return {
682 ...image,
683 previewUrl: URL.createObjectURL(image.file),
684 };
685 } catch {
686 return image;
687 }
688}
689
690export function deriveComposerSendState(options: {
691 prompt: string;
692 imageCount: number;
693 terminalContexts: ReadonlyArray<TerminalContextDraft>;
694 /**
695 * Optional element-pick attachment count. Element contexts contribute to
696 * "sendable content" exactly like images and (text-bearing) terminal
697 * contexts do: a prompt of just element chips is still a valid send.
698 */
699 elementContextCount?: number;
700}): {
701 trimmedPrompt: string;
702 sendableTerminalContexts: TerminalContextDraft[];
703 expiredTerminalContextCount: number;
704 hasSendableContent: boolean;
705} {
706 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
707 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
708 const expiredTerminalContextCount =
709 options.terminalContexts.length - sendableTerminalContexts.length;
710 const elementContextCount = options.elementContextCount ?? 0;
711 return {
712 trimmedPrompt,
713 sendableTerminalContexts,
714 expiredTerminalContextCount,
715 hasSendableContent:
716 trimmedPrompt.length > 0 ||
717 options.imageCount > 0 ||
718 sendableTerminalContexts.length > 0 ||
719 elementContextCount > 0,
720 };
721}
722
723export function buildExpiredTerminalContextToastCopy(
724 expiredTerminalContextCount: number,
725 variant: "omitted" | "empty",
726): { title: string; description: string } {
727 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
728 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
729 if (variant === "empty") {
730 return {
731 title: `${noun} won't be sent`,
732 description: "Remove it or re-add it to include terminal output.",
733 };
734 }
735 return {
736 title: `${noun} omitted from message`,
737 description: "Re-add it if you want that terminal output included.",
738 };
739}
740
741export function branchMismatchKey(
742 threadId: string | null,
743 mismatch: { threadBranch: string; currentBranch: string } | null,
744): string | null {
745 if (!threadId || !mismatch) {
746 return null;
747 }
748 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
749}
750
751// The mismatch banner only matters when the user is about to send: passive
752// reading of an old thread carries no risk (the branch picker tint already
753// covers ambient awareness). Draft content is the intent signal — composer
754// focus is useless here because ChatView autofocuses the composer on every
755// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
756// revealed so it doesn't flicker away when the draft is cleared.
757export function shouldShowBranchMismatchBanner(input: {
758 hasMismatch: boolean;
759 isDismissed: boolean;
760 composerHasContent: boolean;
761 wasShownForCurrentMismatch: boolean;
762}): boolean {
763 if (!input.hasMismatch || input.isDismissed) {
764 return false;
765 }
766 return input.composerHasContent || input.wasShownForCurrentMismatch;
767}
768
769export function shouldShowPlanFollowUpPrompt(input: {
770 pendingUserInputCount: number;
771 interactionMode: ProviderInteractionMode;
772 latestTurnSettled: boolean;
773 hasActionableProposedPlan: boolean;
774 hasComposerAttachments: boolean;
775}): boolean {
776 return (
777 input.pendingUserInputCount === 0 &&
778 input.interactionMode === "plan" &&
779 input.latestTurnSettled &&
780 input.hasActionableProposedPlan &&
781 !input.hasComposerAttachments
782 );
783}
784
785// Session-scoped (module-level so it survives ChatView remounts, e.g. route
786// changes). Durable cross-device dismissal is planned as a server-side ack.
787const sessionDismissedBranchMismatchKeys = new Set<string>();
788
789export function dismissBranchMismatchForSession(key: string): void {
790 sessionDismissedBranchMismatchKeys.add(key);
791}
792
793export function isBranchMismatchDismissedForSession(key: string | null): boolean {
794 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
795}
796
797// Git status for a checkout arrives after the composer paints, and the branch
798// strip mounts on the assumption that a project is a Git repo. Without a
799// memory, a non-Git project would mount the strip and drop it on every visit.
800// Keyed by environment and checkout for the session; never persisted.
801const sessionCheckoutIsRepo = new Map<string, boolean>();
802
803function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
804 return JSON.stringify([environmentId, cwd]);
805}
806
807export function rememberCheckoutIsRepo(
808 environmentId: EnvironmentId,
809 cwd: string,
810 isRepo: boolean,
811): void {
812 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
813}
814
815export function recallCheckoutIsRepo(
816 environmentId: EnvironmentId,
817 cwd: string | null,
818): boolean | undefined {
819 return cwd === null
820 ? undefined
821 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
822}
823
824export function threadHasStarted(thread: Thread | null | undefined): boolean {
825 return Boolean(
826 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
827 );
828}
829
830/**
831 * Whether a thread ran at least one turn, judged from its shell alone.
832 *
833 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
834 * still has messages, and the loading shell carries none. The shell records
835 * when the last user message landed, which every started thread has.
836 */
837export function threadShellHasStarted(
838 shell: Pick<ThreadShell, "latestTurn" | "latestUserMessageAt" | "session"> | null | undefined,
839): boolean {
840 return Boolean(
841 shell &&
842 (shell.latestTurn !== null || shell.latestUserMessageAt !== null || shell.session !== null),
843 );
844}
845
846// Imported history has no session until its first prompt. Resolve its instance
847// through the environment's provider catalog before locking to a driver.
848export function deriveLockedProvider(input: {
849 thread: Thread | null | undefined;
850 selectedProvider: string | null;
851 threadProvider: string | null;
852 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
853}): ProviderDriverKind | null {
854 if (!threadHasStarted(input.thread)) {
855 return null;
856 }
857 const sessionProvider = input.thread?.session?.providerName ?? null;
858 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
859 return sessionProvider;
860 }
861 // Preserve the existing lock while an instance is missing from the catalog;
862 // a started thread must not silently fall back to a different driver.
863 const threadProvider =
864 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
865 input.threadProvider;
866 const selectedProvider =
867 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
868 input.selectedProvider;
869 const narrowedThreadProvider =
870 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
871 const narrowedSelectedProvider =
872 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
873 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
874}
875
876export function getStartedThreadModelChangeBlockReason(input: {
877 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
878 hasStartedSession: boolean;
879 currentModelSelection: ModelSelection;
880 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
881 nextModelSelection: ModelSelection;
882}): { title: string; description: string } | null {
883 if (!input.hasStartedSession) {
884 return null;
885 }
886 const currentModelSelection = {
887 ...input.currentModelSelection,
888 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
889 };
890 if (
891 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
892 currentModelSelection.model === input.nextModelSelection.model
893 ) {
894 return null;
895 }
896 const currentProvider = input.providers.find(
897 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
898 );
899 const nextProvider = input.providers.find(
900 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
901 );
902 if (
903 currentProvider?.requiresNewThreadForModelChange !== true &&
904 nextProvider?.requiresNewThreadForModelChange !== true
905 ) {
906 return null;
907 }
908 return {
909 title: "Start a new chat to change models",
910 description: "This provider does not allow switching models after a conversation has started.",
911 };
912}
913
914export async function waitForStartedServerThread(
915 threadRef: ScopedThreadRef,
916 timeoutMs = 1_000,
917): Promise<boolean> {
918 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
919 const getThread = () => appAtomRegistry.get(threadAtom);
920 const thread = getThread();
921
922 if (threadHasStarted(thread)) {
923 return true;
924 }
925
926 return await new Promise<boolean>((resolve) => {
927 let settled = false;
928 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
929 const finish = (result: boolean) => {
930 if (settled) {
931 return;
932 }
933 settled = true;
934 if (timeoutId !== null) {
935 globalThis.clearTimeout(timeoutId);
936 }
937 unsubscribe();
938 resolve(result);
939 };
940
941 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
942 if (!threadHasStarted(thread)) {
943 return;
944 }
945 finish(true);
946 });
947
948 if (threadHasStarted(getThread())) {
949 finish(true);
950 return;
951 }
952
953 timeoutId = globalThis.setTimeout(() => {
954 finish(false);
955 }, timeoutMs);
956 });
957}
958
959export interface LocalDispatchSnapshot {
960 startedAt: string;
961 preparingWorktree: boolean;
962 submissionIntent: ComposerSubmissionIntent;
963 latestUserMessageId: ChatMessage["id"] | null;
964 latestTurnTurnId: TurnId | null;
965 latestTurnRequestedAt: string | null;
966 latestTurnStartedAt: string | null;
967 latestTurnCompletedAt: string | null;
968 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
969 sessionUpdatedAt: string | null;
970 latestTurnStartFailureId: string | null;
971}
972
973export function latestTurnStartFailureId(
974 activeThread: Thread | undefined,
975 latestUserMessageId: ChatMessage["id"] | null,
976): string | null {
977 if (latestUserMessageId === null) return null;
978 return (
979 activeThread?.activities.findLast((activity) => {
980 if (activity.kind !== "provider.turn.start.failed") return false;
981 const payload =
982 typeof activity.payload === "object" && activity.payload !== null
983 ? (activity.payload as { readonly requestId?: unknown })
984 : null;
985 return payload?.requestId === latestUserMessageId;
986 })?.id ?? null
987 );
988}
989
990export function createLocalDispatchSnapshot(
991 activeThread: Thread | undefined,
992 options?: {
993 preparingWorktree?: boolean;
994 submissionIntent?: ComposerSubmissionIntent;
995 },
996): LocalDispatchSnapshot {
997 const latestTurn = activeThread?.latestTurn ?? null;
998 const session = activeThread?.session ?? null;
999 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
1000 return {
1001 startedAt: new Date().toISOString(),
1002 preparingWorktree: Boolean(options?.preparingWorktree),
1003 submissionIntent: options?.submissionIntent ?? "foreground",
1004 latestUserMessageId: latestUserMessage?.id ?? null,
1005 latestTurnTurnId: latestTurn?.turnId ?? null,
1006 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
1007 latestTurnStartedAt: latestTurn?.startedAt ?? null,
1008 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
1009 sessionStatus: session?.status ?? null,
1010 sessionUpdatedAt: session?.updatedAt ?? null,
1011 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
1012 };
1013}
1014
1015export function hasServerAcknowledgedLocalDispatch(input: {
1016 localDispatch: LocalDispatchSnapshot | null;
1017 phase: SessionPhase;
1018 latestTurn: Thread["latestTurn"] | null;
1019 latestUserMessageId: ChatMessage["id"] | null;
1020 session: Thread["session"] | null;
1021 hasPendingApproval: boolean;
1022 hasPendingUserInput: boolean;
1023 latestTurnStartFailureId?: string | null;
1024 threadError: string | null | undefined;
1025}): boolean {
1026 if (!input.localDispatch) {
1027 return false;
1028 }
1029 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1030 return true;
1031 }
1032 if (
1033 input.latestTurnStartFailureId !== undefined &&
1034 input.latestTurnStartFailureId !== null &&
1035 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
1036 ) {
1037 return true;
1038 }
1039 if (input.phase === "connecting") {
1040 return false;
1041 }
1042
1043 const latestTurn = input.latestTurn ?? null;
1044 const session = input.session ?? null;
1045 const latestUserMessageChanged =
1046 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
1047 const latestTurnChanged =
1048 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
1049 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
1050 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
1051 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
1052
1053 if (input.phase === "running") {
1054 // Steering adds a user message to the current running turn without
1055 // necessarily changing any of the turn timestamps. Treat that projected
1056 // message as the server acknowledgment so the composer does not remain
1057 // stuck in its local "Sending" state until the turn settles.
1058 if (latestUserMessageChanged) {
1059 return true;
1060 }
1061 if (!latestTurnChanged) {
1062 return false;
1063 }
1064 if (latestTurn?.startedAt === null || latestTurn === null) {
1065 return false;
1066 }
1067 if (
1068 session?.activeTurnId !== null &&
1069 session?.activeTurnId !== undefined &&
1070 latestTurn?.turnId !== session.activeTurnId
1071 ) {
1072 return false;
1073 }
1074 return true;
1075 }
1076
1077 return (
1078 latestTurnChanged ||
1079 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1080 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1081 );
1082}
1083
1084// Returning to the window should land the caret in the composer, so the reader can type right
1085// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1086// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1087// not one of them, so it yields to the composer.
1088export function shouldRefocusComposerOnWindowFocus(
1089 activeElement:
1090 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1091 | null,
1092): boolean {
1093 if (activeElement === null || activeElement.tagName === "BODY") return true;
1094 if (
1095 activeElement.tagName === "INPUT" ||
1096 activeElement.tagName === "TEXTAREA" ||
1097 activeElement.tagName === "SELECT" ||
1098 activeElement.isContentEditable === true ||
1099 activeElement.getAttribute("role") === "textbox"
1100 ) {
1101 return false;
1102 }
1103 return (
1104 activeElement.closest(
1105 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1106 ) === null
1107 );
1108}