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

ChatView.logic.ts

1,250 lines42.2 KB

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