Open History to see the last commit
1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import {
3 ANTIGRAVITY_DEFAULT_MODEL,
4 type AssetCreateUrlInput,
5 type AssetCreateUrlResult,
6 type ChatFileAttachment,
7 type EnvironmentId,
8 isProviderDriverKind,
9 ProjectId,
10 type MessageId,
11 type ModelSelection,
12 type OrchestrationV2ProjectedTurnItem,
13 type ProviderInteractionMode,
14 ProviderDriverKind,
15 type ProviderInstanceId,
16 type ServerProvider,
17 type ScopedProjectRef,
18 type ScopedThreadRef,
19 type ThreadId,
20 type ThreadLinkedPullRequest,
21 type RunId,
22} from "@t3tools/contracts";
23import * as DateTime from "effect/DateTime";
24import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
25import {
26 squashAtomCommandFailure,
27 type AtomCommandResult,
28} from "@t3tools/client-runtime/state/runtime";
29import { videoMimeType } from "@t3tools/shared/video";
30import {
31 appendCodexArtifactTemplateUsePrompt,
32 codexArtifactTemplateUsePrompt,
33 type CodexArtifactTemplate,
34} from "@t3tools/client-runtime/codex-artifact-templates";
35import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
36import {
37 type ChatMessage,
38 isImageAttachment,
39 type SessionPhase,
40 type Thread,
41 type TurnDiffSummary,
42} from "../types";
43import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
44import * as Schema from "effect/Schema";
45import { appAtomRegistry } from "../rpc/atomRegistry";
46import { environmentThreadShells } from "../state/threads";
47import { waitForAtomValue } from "../state/waitForAtomValue";
48import {
49 filterTerminalContextsWithText,
50 stripInlineTerminalContextPlaceholders,
51 type TerminalContextDraft,
52} from "../lib/terminalContext";
53import type { DraftThreadEnvMode } from "../composerDraftStore";
54import type { ComposerSubmissionIntent } from "../composer-logic";
55import type { TimelineEntry } from "../session-logic";
56import type { DesktopPreviewOverlay } from "../previewStateStore";
57import type { RightPanelSurface } from "../rightPanelStore";
58import {
59 NO_PROVIDER_MODEL_SELECTION,
60 resolveSelectableProviderInstanceEntry,
61 type ProviderInstanceEntry,
62} from "../providerInstances";
63
64export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
65export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
66export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
67export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
68
69export function agentControlledBrowserCloseConfirmation(
70 surfaces: readonly RightPanelSurface[],
71 desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
72): string | null {
73 const activeBrowserCount = surfaces.filter(
74 (surface) =>
75 surface.kind === "preview" &&
76 surface.resourceId !== null &&
77 desktopByTabId[surface.resourceId]?.controller === "agent",
78 ).length;
79 if (activeBrowserCount === 0) return null;
80 if (activeBrowserCount === 1) {
81 return [
82 "Close browser while the agent is using it?",
83 "The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
84 ].join("\n");
85 }
86 return [
87 `Close ${activeBrowserCount} browsers while the agent is using them?`,
88 "The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
89 ].join("\n");
90}
91
92export function shouldRenderPreviewMiniPlayer(
93 miniPlayerTabId: string | null,
94 renderedRightPanelSurface: RightPanelSurface | null,
95): boolean {
96 return (
97 miniPlayerTabId !== null &&
98 !(
99 renderedRightPanelSurface?.kind === "preview" &&
100 renderedRightPanelSurface.resourceId === miniPlayerTabId
101 )
102 );
103}
104
105export function shouldOpenProactivePullRequest(
106 previousTargetKey: string | null | undefined,
107 targetKey: string | null,
108): boolean {
109 return targetKey !== null && targetKey !== previousTargetKey;
110}
111
112interface ProactivePanelObservation {
113 threadKey: string;
114 runningTurnId: RunId | null | undefined;
115 targetKey: string | null | undefined;
116 userActionTurnId: RunId | null;
117 userActionRevision: number;
118}
119
120/** Capture user intent before loading or metadata writes can defer panel activation. */
121export function observeProactivePanelUserChoice(
122 previous: ProactivePanelObservation | null,
123 input: { threadKey: string; runningTurnId: RunId | null; userActionRevision: number },
124): ProactivePanelObservation {
125 const sameThread = previous?.threadKey === input.threadKey;
126 const newTurn =
127 sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;
128 return {
129 threadKey: input.threadKey,
130 runningTurnId: sameThread ? previous.runningTurnId : undefined,
131 targetKey: sameThread ? previous.targetKey : undefined,
132 userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),
133 userActionRevision:
134 !sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,
135 };
136}
137
138/** Follow a changed server link only when the panel still shows the previous linked PR. */
139export function shouldRetargetThreadPullRequestPanel(
140 previous: ThreadLinkedPullRequest | null,
141 current: ThreadLinkedPullRequest | null,
142 surface: RightPanelSurface | null,
143): boolean {
144 if (previous === null || current === null || surface?.kind !== "pull-request") return false;
145 const previousRepository = previous.repository.toLowerCase();
146 return (
147 (previous.projectId !== current.projectId ||
148 previousRepository !== current.repository.toLowerCase() ||
149 previous.number !== current.number) &&
150 surface.projectId === previous.projectId &&
151 surface.repository.toLowerCase() === previousRepository &&
152 surface.number === previous.number
153 );
154}
155
156export function shouldOpenProactiveTurnDiff(input: {
157 previousRunningTurnId: RunId | null | undefined;
158 runningTurnId: RunId | null;
159 settledTurnId: RunId | null;
160 turnCompleted: boolean;
161}): boolean {
162 return (
163 input.runningTurnId === null &&
164 input.turnCompleted &&
165 input.settledTurnId !== null &&
166 (input.previousRunningTurnId === undefined ||
167 input.settledTurnId === input.previousRunningTurnId)
168 );
169}
170
171export function resolveProactiveTurnDiffAction(input: {
172 checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;
173 isGitRepo: boolean | undefined;
174 activeSurfaceKind: RightPanelSurface["kind"] | null;
175}): "defer" | "ignore" | "open" {
176 if (input.activeSurfaceKind === "pull-request") return "ignore";
177 if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
178 if (input.isGitRepo === undefined) return "defer";
179 if (
180 !input.isGitRepo ||
181 input.checkpoint.status !== "ready" ||
182 input.checkpoint.files.length === 0
183 ) {
184 return "ignore";
185 }
186 return "open";
187}
188
189export function codexArtifactTemplatePromptToAppend(
190 currentDraft: string,
191 template: CodexArtifactTemplate,
192): string | null {
193 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
194 ? null
195 : codexArtifactTemplateUsePrompt(template);
196}
197
198export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
199
200export function resolveEffectiveInteractionMode(input: {
201 planModeEnabled: boolean;
202 composerInteractionMode: ProviderInteractionMode | null;
203 threadInteractionMode: ProviderInteractionMode | null | undefined;
204}): ProviderInteractionMode {
205 if (!input.planModeEnabled) return "default";
206 return input.composerInteractionMode ?? input.threadInteractionMode ?? "default";
207}
208
209export function shouldDockDraftHeroForSubmission(input: {
210 isDraftHeroState: boolean;
211 activeThreadKey: string | null;
212 submissionIntent: ComposerSubmissionIntent;
213}): boolean {
214 return (
215 input.submissionIntent === "foreground" &&
216 input.isDraftHeroState &&
217 input.activeThreadKey !== null
218 );
219}
220
221export function shouldReleaseTimelineAnchorForToolActivity(input: {
222 anchorMessageId: MessageId | null;
223 liveFollowEnabled: boolean;
224 runningTurnId: RunId | null;
225 timelineEntries: ReadonlyArray<TimelineEntry>;
226}): boolean {
227 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
228 return false;
229 }
230
231 return input.timelineEntries.some((timelineEntry) => {
232 if (timelineEntry.kind !== "work" || timelineEntry.entry.runId !== input.runningTurnId) {
233 return false;
234 }
235
236 const entry = timelineEntry.entry;
237 return (
238 entry.tone === "tool" ||
239 entry.itemType !== undefined ||
240 entry.requestKind !== undefined ||
241 (entry.command?.trim().length ?? 0) > 0
242 );
243 });
244}
245
246export function toolGroupConsumesUpwardNavigation(target: EventTarget | null): boolean {
247 const elementTarget = target instanceof Element ? target : null;
248 const group = elementTarget?.closest<HTMLElement>("[data-tool-group-scroll]");
249 if (!group) return false;
250
251 // A nested result or the group itself can consume an upward scroll.
252 for (let element = elementTarget; element; element = element.parentElement) {
253 if (element.scrollTop > 0) {
254 const overflowY = getComputedStyle(element).overflowY;
255 if (overflowY === "auto" || overflowY === "scroll") return true;
256 }
257 if (element === group) break;
258 }
259 return false;
260}
261
262export function resolveDraftHeroState(input: {
263 isLocalDraftThread: boolean;
264 hasTimelineEntries: boolean;
265 isWorking: boolean;
266 draftHeroDockRequested: boolean;
267 backgroundSubmissionPending: boolean;
268}): boolean {
269 if (input.backgroundSubmissionPending) {
270 return true;
271 }
272 return (
273 input.isLocalDraftThread &&
274 !input.hasTimelineEntries &&
275 !input.isWorking &&
276 !input.draftHeroDockRequested
277 );
278}
279
280export function resolveDraftPromotionNavigationTarget(input: {
281 serverThreadRef: ScopedThreadRef | null;
282 serverThread: Pick<Thread, "latestRun"> | null | undefined;
283 backgroundSubmissionPending: boolean;
284}): ScopedThreadRef | null {
285 if (input.backgroundSubmissionPending) {
286 return null;
287 }
288 const latestRun = input.serverThread?.latestRun ?? null;
289 const runStarted = latestRun?.startedAt != null;
290 const startupStopped =
291 latestRun?.status === "failed" ||
292 latestRun?.status === "interrupted" ||
293 latestRun?.status === "cancelled";
294 // Keep local preparation feedback mounted until the server can render the
295 // running turn or its startup error on the canonical thread route.
296 return runStarted || startupStopped ? input.serverThreadRef : null;
297}
298
299export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
300 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
301 return () => globalThis.clearTimeout(timeoutId);
302}
303
304export function hasEnvironmentReconnectWarningGraceElapsed(
305 activeEnvironmentId: EnvironmentId | null,
306 elapsedEnvironmentId: EnvironmentId | null,
307): boolean {
308 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
309}
310
311export function startNewThreadForProject(
312 projectRef: ScopedProjectRef | null,
313 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
314): boolean {
315 if (projectRef === null) return false;
316 void handleNewThread(projectRef);
317
318 return true;
319}
320
321export function resolveThreadMetadataUpdateForNextTurn(input: {
322 currentModelSelection: ModelSelection;
323 nextModelSelection?: ModelSelection;
324 currentBranch: string | null;
325 nextBranch?: string;
326}): {
327 modelSelection?: ModelSelection;
328 branch?: string;
329 worktreePath?: null;
330} | null {
331 const nextModelSelection = input.nextModelSelection;
332 const modelSelectionChanged =
333 nextModelSelection !== undefined &&
334 (nextModelSelection.model !== input.currentModelSelection.model ||
335 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
336 JSON.stringify(nextModelSelection.options ?? null) !==
337 JSON.stringify(input.currentModelSelection.options ?? null));
338 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
339 if (!modelSelectionChanged && !branchChanged) {
340 return null;
341 }
342 return {
343 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
344 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
345 };
346}
347
348export function buildLocalDraftThread(
349 threadId: ThreadId,
350 draftThread: DraftThreadState,
351 fallbackModelSelection: ModelSelection,
352): Thread {
353 const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
354 return presentThreadShell(draftThread.environmentId, {
355 id: threadId,
356 projectId: draftThread.projectId,
357 title: "New thread",
358 providerInstanceId: fallbackModelSelection.instanceId,
359 modelSelection: fallbackModelSelection,
360 runtimeMode: draftThread.runtimeMode,
361 interactionMode: draftThread.interactionMode,
362 branch: draftThread.branch,
363 worktreePath: draftThread.worktreePath,
364 activeProviderThreadId: null,
365 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
366 forkedFrom: null,
367 createdBy: "user",
368 creationSource: "web",
369 latestRunId: null,
370 activeRunId: null,
371 status: "idle",
372 pendingRuntimeRequest: null,
373 latestVisibleMessage: null,
374 latestUserMessageAt: null,
375 hasActionableProposedPlan: false,
376 itemCount: 0,
377 visibleItemCount: 0,
378 createdAt: timestamp,
379 updatedAt: timestamp,
380 archivedAt: null,
381 settledOverride: null,
382 settledAt: null,
383 deletedAt: null,
384 });
385}
386
387export function shouldWriteThreadErrorToCurrentServerThread(input: {
388 serverThread:
389 | {
390 environmentId: EnvironmentId;
391 id: ThreadId;
392 }
393 | null
394 | undefined;
395 routeThreadRef: ScopedThreadRef;
396 targetThreadId: ThreadId;
397}): boolean {
398 return Boolean(
399 input.serverThread &&
400 input.targetThreadId === input.routeThreadRef.threadId &&
401 input.serverThread.environmentId === input.routeThreadRef.environmentId &&
402 input.serverThread.id === input.targetThreadId,
403 );
404}
405
406/** Use the same enabled instance for the composer, provider status, and chat actions. */
407export function resolveComposerProviderSelection(input: {
408 entries: ReadonlyArray<ProviderInstanceEntry>;
409 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
410 lockedProvider: ProviderDriverKind | null;
411 lockedInstanceId: ProviderInstanceId | null | undefined;
412}) {
413 const requestedInstanceId = input.candidateInstanceIds.find(
414 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
415 );
416 const requestedDriverKind =
417 input.lockedProvider ??
418 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
419 input.entries[0]?.driverKind ??
420 ProviderDriverKind.make("unconfigured");
421 const lockedContinuationGroupKey = input.lockedProvider
422 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
423 ?.continuationGroupKey ?? null)
424 : null;
425 // Missing metadata must not move Antigravity history into another Google profile.
426 const requiresExactInstance =
427 input.lockedProvider === "antigravity" &&
428 input.lockedInstanceId != null &&
429 lockedContinuationGroupKey === null;
430 const compatibleEntries = input.entries.filter(
431 (entry) =>
432 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
433 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
434 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
435 );
436 const selectedProviderEntry =
437 input.candidateInstanceIds
438 .map((candidate) =>
439 compatibleEntries.find(
440 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
441 ),
442 )
443 .find((entry) => entry !== undefined) ??
444 resolveSelectableProviderInstanceEntry(
445 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
446 undefined,
447 ) ??
448 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
449 const unavailableProviderInstanceId = selectedProviderEntry
450 ? undefined
451 : input.lockedProvider
452 ? (input.lockedInstanceId ?? requestedInstanceId)
453 : requestedInstanceId;
454 return {
455 selectedProviderEntry,
456 requestedDriverKind,
457 lockedContinuationGroupKey,
458 unavailableProviderInstanceId,
459 };
460}
461
462/** Keep restored drafts and every plan control on the selected instance's supported mode. */
463export function resolveComposerInteractionMode(input: {
464 planModeEnabled: boolean;
465 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
466 interactionMode: ProviderInteractionMode;
467}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
468 const enabled =
469 input.planModeEnabled &&
470 input.provider != null &&
471 input.provider.showInteractionModeToggle !== false;
472 return {
473 enabled,
474 interactionMode: enabled ? input.interactionMode : "default",
475 };
476}
477
478export function getAntigravitySendBlockReason(
479 provider:
480 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
481 | null
482 | undefined,
483 model: string,
484): string | null {
485 if (provider?.driver !== "antigravity") return null;
486 if (!provider.installed) {
487 return "Install Antigravity in provider settings before sending.";
488 }
489 if (provider.auth.status === "unauthenticated") {
490 return "Sign in to Antigravity in provider settings before sending.";
491 }
492 const slug = model.trim();
493 if (slug.length === 0) return "Choose an Antigravity model before sending.";
494 // A restart clears the account status and catalog. Session startup checks
495 // saved credentials and validates the model before sending the prompt.
496 if (provider.auth.status === "unknown") return null;
497 if (provider.models.length === 0) {
498 return "Refresh Antigravity models in provider settings before sending.";
499 }
500 // A saved model that left the catalog is kept in the picker as unavailable
501 // so the user sees what the thread used. The server rejects it at turn
502 // start, so block here unless the provider is in an error state, where a
503 // retry with the same model is the right move.
504 if (
505 provider.status === "ready" &&
506 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
507 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
508 ) {
509 return "That Antigravity model is no longer available. Choose another model.";
510 }
511 return null;
512}
513
514export function reconcileMountedTerminalThreadIds(input: {
515 currentThreadIds: ReadonlyArray<string>;
516 openThreadIds: ReadonlyArray<string>;
517 activeThreadId: string | null;
518 activeThreadTerminalOpen: boolean;
519 maxHiddenThreadCount?: number;
520}): string[] {
521 return reconcileRetainedMountedThreadIds({
522 currentThreadIds: input.currentThreadIds,
523 openThreadIds: input.openThreadIds,
524 activeThreadId: input.activeThreadId,
525 activeThreadOpen: input.activeThreadTerminalOpen,
526 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
527 });
528}
529
530export function reconcileRetainedMountedThreadIds(input: {
531 currentThreadIds: ReadonlyArray<string>;
532 openThreadIds: ReadonlyArray<string>;
533 activeThreadId: string | null;
534 activeThreadOpen: boolean;
535 maxHiddenThreadCount: number;
536 retainInactiveActiveThread?: boolean;
537}): string[] {
538 const openThreadIdSet = new Set(input.openThreadIds);
539 const hiddenThreadIds = input.currentThreadIds.filter(
540 (threadId) =>
541 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
542 openThreadIdSet.has(threadId),
543 );
544 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
545 const nextThreadIds =
546 hiddenThreadIds.length > maxHiddenThreadCount
547 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
548 : hiddenThreadIds;
549
550 if (
551 input.activeThreadId &&
552 input.activeThreadOpen &&
553 !nextThreadIds.includes(input.activeThreadId)
554 ) {
555 nextThreadIds.push(input.activeThreadId);
556 }
557
558 return nextThreadIds;
559}
560
561export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
562 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
563 return;
564 }
565 URL.revokeObjectURL(previewUrl);
566}
567
568/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
569export async function resolveFileAttachmentUrl(input: {
570 attachment: ChatFileAttachment;
571 environmentId: EnvironmentId;
572 httpBaseUrl: string;
573 createAssetUrl: (input: {
574 environmentId: EnvironmentId;
575 input: AssetCreateUrlInput;
576 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
577}): Promise<string> {
578 const { attachment } = input;
579 const result = await input.createAssetUrl({
580 environmentId: input.environmentId,
581 input: {
582 resource: {
583 _tag: "attachment",
584 attachmentId: attachment.id,
585 fileName: attachment.name,
586 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
587 },
588 },
589 });
590 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
591 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
592 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
593 return url;
594}
595
596export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
597 if (message.role !== "user" || !message.attachments) {
598 return;
599 }
600 for (const attachment of message.attachments) {
601 if (!isImageAttachment(attachment)) {
602 continue;
603 }
604 revokeBlobPreviewUrl(attachment.previewUrl);
605 }
606}
607
608export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
609 if (message.role !== "user" || !message.attachments) {
610 return [];
611 }
612 const previewUrls: string[] = [];
613 for (const attachment of message.attachments) {
614 if (!isImageAttachment(attachment)) continue;
615 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
616 previewUrls.push(attachment.previewUrl);
617 }
618 return previewUrls;
619}
620
621export interface PullRequestDialogState {
622 initialReference: string | null;
623 key: number;
624}
625
626export function readFileAsDataUrl(file: File): Promise<string> {
627 return new Promise((resolve, reject) => {
628 const reader = new FileReader();
629 reader.addEventListener("load", () => {
630 if (typeof reader.result === "string") {
631 resolve(reader.result);
632 return;
633 }
634 reject(new Error("Could not read image data."));
635 });
636 reader.addEventListener("error", () => {
637 reject(reader.error ?? new Error("Failed to read image."));
638 });
639 reader.readAsDataURL(file);
640 });
641}
642
643export function resolveSendEnvMode(input: {
644 requestedEnvMode: DraftThreadEnvMode;
645 isGitRepo: boolean;
646}): DraftThreadEnvMode {
647 return input.isGitRepo ? input.requestedEnvMode : "local";
648}
649
650export function resolveBackgroundDraftWorkspaceOptions(input: {
651 envMode: DraftThreadEnvMode;
652 branch: string | null;
653 startFromOrigin: boolean;
654}): {
655 envMode: DraftThreadEnvMode;
656 branch: string | null;
657 worktreePath: null;
658 startFromOrigin: boolean;
659} {
660 return {
661 envMode: input.envMode,
662 branch: input.branch,
663 worktreePath: null,
664 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
665 };
666}
667
668export function cloneComposerImageForRetry(
669 image: ComposerImageAttachment,
670): ComposerImageAttachment {
671 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
672 return image;
673 }
674 try {
675 return {
676 ...image,
677 previewUrl: URL.createObjectURL(image.file),
678 };
679 } catch {
680 return image;
681 }
682}
683
684export function deriveComposerSendState(options: {
685 prompt: string;
686 imageCount: number;
687 terminalContexts: ReadonlyArray<TerminalContextDraft>;
688 /**
689 * Optional element-pick attachment count. Element contexts contribute to
690 * "sendable content" exactly like images and (text-bearing) terminal
691 * contexts do: a prompt of just element chips is still a valid send.
692 */
693 elementContextCount?: number;
694}): {
695 trimmedPrompt: string;
696 sendableTerminalContexts: TerminalContextDraft[];
697 expiredTerminalContextCount: number;
698 hasSendableContent: boolean;
699} {
700 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
701 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
702 const expiredTerminalContextCount =
703 options.terminalContexts.length - sendableTerminalContexts.length;
704 const elementContextCount = options.elementContextCount ?? 0;
705 return {
706 trimmedPrompt,
707 sendableTerminalContexts,
708 expiredTerminalContextCount,
709 hasSendableContent:
710 trimmedPrompt.length > 0 ||
711 options.imageCount > 0 ||
712 sendableTerminalContexts.length > 0 ||
713 elementContextCount > 0,
714 };
715}
716
717export function buildExpiredTerminalContextToastCopy(
718 expiredTerminalContextCount: number,
719 variant: "omitted" | "empty",
720): { title: string; description: string } {
721 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
722 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
723 if (variant === "empty") {
724 return {
725 title: `${noun} won't be sent`,
726 description: "Remove it or re-add it to include terminal output.",
727 };
728 }
729 return {
730 title: `${noun} omitted from message`,
731 description: "Re-add it if you want that terminal output included.",
732 };
733}
734
735export function branchMismatchKey(
736 threadId: string | null,
737 mismatch: { threadBranch: string; currentBranch: string } | null,
738): string | null {
739 if (!threadId || !mismatch) {
740 return null;
741 }
742 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
743}
744
745// The mismatch banner only matters when the user is about to send: passive
746// reading of an old thread carries no risk (the branch picker tint already
747// covers ambient awareness). Draft content is the intent signal — composer
748// focus is useless here because ChatView autofocuses the composer on every
749// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
750// revealed so it doesn't flicker away when the draft is cleared.
751export function shouldShowBranchMismatchBanner(input: {
752 hasMismatch: boolean;
753 isDismissed: boolean;
754 composerHasContent: boolean;
755 wasShownForCurrentMismatch: boolean;
756}): boolean {
757 if (!input.hasMismatch || input.isDismissed) {
758 return false;
759 }
760 return input.composerHasContent || input.wasShownForCurrentMismatch;
761}
762
763export function shouldShowPlanFollowUpPrompt(input: {
764 pendingUserInputCount: number;
765 interactionMode: ProviderInteractionMode;
766 latestTurnSettled: boolean;
767 hasActionableProposedPlan: boolean;
768 hasComposerAttachments: boolean;
769}): boolean {
770 return (
771 input.pendingUserInputCount === 0 &&
772 input.interactionMode === "plan" &&
773 input.latestTurnSettled &&
774 input.hasActionableProposedPlan &&
775 !input.hasComposerAttachments
776 );
777}
778
779// Session-scoped (module-level so it survives ChatView remounts, e.g. route
780// changes). Durable cross-device dismissal is planned as a server-side ack.
781const sessionDismissedBranchMismatchKeys = new Set<string>();
782
783export function dismissBranchMismatchForSession(key: string): void {
784 sessionDismissedBranchMismatchKeys.add(key);
785}
786
787export function isBranchMismatchDismissedForSession(key: string | null): boolean {
788 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
789}
790
791// Git status for a checkout arrives after the composer paints, and the branch
792// strip mounts on the assumption that a project is a Git repo. Without a
793// memory, a non-Git project would mount the strip and drop it on every visit.
794// Keyed by environment and checkout for the session; never persisted.
795const sessionCheckoutIsRepo = new Map<string, boolean>();
796
797function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
798 return JSON.stringify([environmentId, cwd]);
799}
800
801export function rememberCheckoutIsRepo(
802 environmentId: EnvironmentId,
803 cwd: string,
804 isRepo: boolean,
805): void {
806 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
807}
808
809export function recallCheckoutIsRepo(
810 environmentId: EnvironmentId,
811 cwd: string | null,
812): boolean | undefined {
813 return cwd === null
814 ? undefined
815 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
816}
817
818export function threadHasStarted(thread: Thread | null | undefined): boolean {
819 return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
820}
821
822/**
823 * Whether a thread ran at least one turn, judged from its shell alone.
824 *
825 * `threadHasStarted` needs the detail: a thread whose latest turn was cleared
826 * still has messages, and the loading shell carries none. The shell records
827 * when the last user message landed, which every started thread has.
828 */
829export function threadShellHasStarted(
830 shell:
831 | Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt" | "runtime">
832 | null
833 | undefined,
834): boolean {
835 return Boolean(
836 shell &&
837 (shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null),
838 );
839}
840
841// Imported history has no session until its first prompt. Resolve its instance
842// through the environment's provider catalog before locking to a driver.
843export function deriveLockedProvider(input: {
844 thread: Thread | null | undefined;
845 selectedProvider: string | null;
846 threadProvider: string | null;
847 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
848}): ProviderDriverKind | null {
849 if (!threadHasStarted(input.thread)) {
850 return null;
851 }
852 const sessionProvider = input.thread?.runtime?.providerName ?? null;
853 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
854 return sessionProvider;
855 }
856 // Preserve the existing lock while an instance is missing from the catalog;
857 // a started thread must not silently fall back to a different driver.
858 const threadProvider =
859 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
860 input.threadProvider;
861 const selectedProvider =
862 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
863 input.selectedProvider;
864 const narrowedThreadProvider =
865 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
866 const narrowedSelectedProvider =
867 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
868 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
869}
870
871export function getStartedThreadModelChangeBlockReason(input: {
872 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
873 hasStartedSession: boolean;
874 supportsProviderSwitchingViaHandoff?: boolean;
875 currentModelSelection: ModelSelection;
876 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
877 nextModelSelection: ModelSelection;
878}): { title: string; description: string } | null {
879 if (!input.hasStartedSession) {
880 return null;
881 }
882 const currentModelSelection = {
883 ...input.currentModelSelection,
884 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
885 };
886 if (
887 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
888 currentModelSelection.model === input.nextModelSelection.model
889 ) {
890 return null;
891 }
892 if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
893 if (input.supportsProviderSwitchingViaHandoff === true) {
894 return null;
895 }
896 return {
897 title: "Start a new chat to switch providers",
898 description: "This thread does not support switching providers after it has started.",
899 };
900 }
901 const currentProvider = input.providers.find(
902 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
903 );
904 const nextProvider = input.providers.find(
905 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
906 );
907 if (
908 currentProvider?.requiresNewThreadForModelChange !== true &&
909 nextProvider?.requiresNewThreadForModelChange !== true
910 ) {
911 return null;
912 }
913 return {
914 title: "Start a new chat to change models",
915 description: "This provider does not allow switching models after a conversation has started.",
916 };
917}
918
919export async function waitForStartedServerThread(
920 threadRef: ScopedThreadRef,
921 timeoutMs = 1_000,
922): Promise<boolean> {
923 const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
924 return waitForAtomValue({
925 registry: appAtomRegistry,
926 atom: threadAtom,
927 predicate: threadHasStarted,
928 timeoutMs,
929 });
930}
931
932export interface LocalDispatchSnapshot {
933 startedAt: string;
934 preparingWorktree: boolean;
935 submissionIntent: ComposerSubmissionIntent;
936 latestUserMessageId: ChatMessage["id"] | null;
937 latestRunId: RunId | null;
938 latestRunRequestedAt: string | null;
939 latestRunStartedAt: string | null;
940 latestRunCompletedAt: string | null;
941 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
942 runtimeUpdatedAt: string | null;
943}
944
945export function createLocalDispatchSnapshot(
946 activeThread: Thread | undefined,
947 options?: {
948 preparingWorktree?: boolean;
949 latestUserMessageId?: ChatMessage["id"] | null;
950 submissionIntent?: ComposerSubmissionIntent;
951 },
952): LocalDispatchSnapshot {
953 const latestRun = activeThread?.latestRun ?? null;
954 const runtime = activeThread?.runtime ?? null;
955 return {
956 startedAt: new Date().toISOString(),
957 preparingWorktree: Boolean(options?.preparingWorktree),
958 submissionIntent: options?.submissionIntent ?? "foreground",
959 latestUserMessageId: options?.latestUserMessageId ?? null,
960 latestRunId: latestRun?.runId ?? null,
961 latestRunRequestedAt: latestRun?.requestedAt ?? null,
962 latestRunStartedAt: latestRun?.startedAt ?? null,
963 latestRunCompletedAt: latestRun?.completedAt ?? null,
964 runtimeStatus: runtime?.status ?? null,
965 runtimeUpdatedAt: runtime?.updatedAt ?? null,
966 };
967}
968
969/**
970 * The timeline renders committed user rows from `visibleTurnItems`, but
971 * `message.updated` can land in `projection.messages` one event earlier than
972 * the matching `turn-item.updated`. Basing optimistic eviction on visible user
973 * turn items avoids dropping steer rows in that gap.
974 */
975export function deriveCommittedServerUserMessageIds(
976 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
977): ReadonlySet<ChatMessage["id"]> {
978 return new Set(
979 visibleTurnItems.flatMap((row) =>
980 row.item.type === "user_message" ? [row.item.messageId] : [],
981 ),
982 );
983}
984
985export function hasServerAcknowledgedLocalDispatch(input: {
986 localDispatch: LocalDispatchSnapshot | null;
987 phase: SessionPhase;
988 latestRun: Thread["latestRun"] | null;
989 latestUserMessageId?: ChatMessage["id"] | null;
990 runtime: Thread["runtime"] | null;
991 hasPendingApproval: boolean;
992 hasPendingUserInput: boolean;
993 threadError: string | null | undefined;
994}): boolean {
995 if (!input.localDispatch) {
996 return false;
997 }
998 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
999 return true;
1000 }
1001 if (input.phase === "connecting") {
1002 return false;
1003 }
1004
1005 const latestRun = input.latestRun ?? null;
1006 const runtime = input.runtime ?? null;
1007 const latestUserMessageChanged =
1008 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
1009 const latestRunChanged =
1010 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
1011 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
1012 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
1013 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
1014
1015 if (input.phase === "running") {
1016 if (latestUserMessageChanged) {
1017 return true;
1018 }
1019 if (!latestRunChanged) {
1020 return false;
1021 }
1022 if (latestRun?.startedAt === null || latestRun === null) {
1023 return false;
1024 }
1025 if (
1026 runtime?.activeRunId !== null &&
1027 runtime?.activeRunId !== undefined &&
1028 latestRun?.runId !== runtime.activeRunId
1029 ) {
1030 return false;
1031 }
1032 return true;
1033 }
1034
1035 return (
1036 latestRunChanged ||
1037 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
1038 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
1039 );
1040}
1041
1042// Returning to the window should land the caret in the composer, so the reader can type right
1043// away. The exceptions are places where focus is deliberate: another text field, a terminal in
1044// the drawer or the right panel, or an open dialog or popup. A focused button outside those is
1045// not one of them, so it yields to the composer.
1046export function shouldRefocusComposerOnWindowFocus(
1047 activeElement:
1048 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1049 | null,
1050): boolean {
1051 if (activeElement === null || activeElement.tagName === "BODY") return true;
1052 if (
1053 activeElement.tagName === "INPUT" ||
1054 activeElement.tagName === "TEXTAREA" ||
1055 activeElement.tagName === "SELECT" ||
1056 activeElement.isContentEditable === true ||
1057 activeElement.getAttribute("role") === "textbox"
1058 ) {
1059 return false;
1060 }
1061 return (
1062 activeElement.closest(
1063 '[role="dialog"], [role="alertdialog"], [data-slot$="-popup"], [data-terminal-owner]',
1064 ) === null
1065 );
1066}