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

ChatView.logic.ts

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