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

ChatView.logic.ts

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