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

ChatView.logic.ts

1,029 lines34.6 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 previousTargetKey !== undefined && 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.previousRunningTurnId !== undefined &&
162 input.previousRunningTurnId !== null &&
163 input.runningTurnId === null &&
164 input.turnCompleted &&
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 reconcileMountedTerminalThreadIds(input: {
511 currentThreadIds: ReadonlyArray<string>;
512 openThreadIds: ReadonlyArray<string>;
513 activeThreadId: string | null;
514 activeThreadTerminalOpen: boolean;
515 maxHiddenThreadCount?: number;
516}): string[] {
517 return reconcileRetainedMountedThreadIds({
518 currentThreadIds: input.currentThreadIds,
519 openThreadIds: input.openThreadIds,
520 activeThreadId: input.activeThreadId,
521 activeThreadOpen: input.activeThreadTerminalOpen,
522 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
523 });
525​
526export function reconcileRetainedMountedThreadIds(input: {
527 currentThreadIds: ReadonlyArray<string>;
528 openThreadIds: ReadonlyArray<string>;
529 activeThreadId: string | null;
530 activeThreadOpen: boolean;
531 maxHiddenThreadCount: number;
532 retainInactiveActiveThread?: boolean;
533}): string[] {
534 const openThreadIdSet = new Set(input.openThreadIds);
535 const hiddenThreadIds = input.currentThreadIds.filter(
536 (threadId) =>
537 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
538 openThreadIdSet.has(threadId),
539 );
540 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
541 const nextThreadIds =
542 hiddenThreadIds.length > maxHiddenThreadCount
543 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
544 : hiddenThreadIds;
545​
546 if (
547 input.activeThreadId &&
548 input.activeThreadOpen &&
549 !nextThreadIds.includes(input.activeThreadId)
550 ) {
551 nextThreadIds.push(input.activeThreadId);
552 }
553​
554 return nextThreadIds;
556​
557export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
558 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
559 return;
560 }
561 URL.revokeObjectURL(previewUrl);
563​
564/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
565export async function resolveFileAttachmentUrl(input: {
566 attachment: ChatFileAttachment;
567 environmentId: EnvironmentId;
568 httpBaseUrl: string;
569 createAssetUrl: (input: {
570 environmentId: EnvironmentId;
571 input: AssetCreateUrlInput;
572 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
573}): Promise<string> {
574 const { attachment } = input;
575 const result = await input.createAssetUrl({
576 environmentId: input.environmentId,
577 input: {
578 resource: {
579 _tag: "attachment",
580 attachmentId: attachment.id,
581 fileName: attachment.name,
582 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
583 },
584 },
585 });
586 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
587 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
588 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
589 return url;
591​
592export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
593 if (message.role !== "user" || !message.attachments) {
594 return;
595 }
596 for (const attachment of message.attachments) {
597 if (!isImageAttachment(attachment)) {
598 continue;
599 }
600 revokeBlobPreviewUrl(attachment.previewUrl);
601 }
603​
604export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
605 if (message.role !== "user" || !message.attachments) {
606 return [];
607 }
608 const previewUrls: string[] = [];
609 for (const attachment of message.attachments) {
610 if (!isImageAttachment(attachment)) continue;
611 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
612 previewUrls.push(attachment.previewUrl);
613 }
614 return previewUrls;
616​
617export interface PullRequestDialogState {
618 initialReference: string | null;
619 key: number;
621​
622export function readFileAsDataUrl(file: File): Promise<string> {
623 return new Promise((resolve, reject) => {
624 const reader = new FileReader();
625 reader.addEventListener("load", () => {
626 if (typeof reader.result === "string") {
627 resolve(reader.result);
628 return;
629 }
630 reject(new Error("Could not read image data."));
631 });
632 reader.addEventListener("error", () => {
633 reject(reader.error ?? new Error("Failed to read image."));
634 });
635 reader.readAsDataURL(file);
636 });
638​
639export function resolveSendEnvMode(input: {
640 requestedEnvMode: DraftThreadEnvMode;
641 isGitRepo: boolean;
642}): DraftThreadEnvMode {
643 return input.isGitRepo ? input.requestedEnvMode : "local";
645​
646export function resolveBackgroundDraftWorkspaceOptions(input: {
647 envMode: DraftThreadEnvMode;
648 branch: string | null;
649 startFromOrigin: boolean;
650}): {
651 envMode: DraftThreadEnvMode;
652 branch: string | null;
653 worktreePath: null;
654 startFromOrigin: boolean;
655} {
656 return {
657 envMode: input.envMode,
658 branch: input.branch,
659 worktreePath: null,
660 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
661 };
663​
664export function cloneComposerImageForRetry(
665 image: ComposerImageAttachment,
666): ComposerImageAttachment {
667 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
668 return image;
669 }
670 try {
671 return {
672 ...image,
673 previewUrl: URL.createObjectURL(image.file),
674 };
675 } catch {
676 return image;
677 }
679​
680export function deriveComposerSendState(options: {
681 prompt: string;
682 imageCount: number;
683 terminalContexts: ReadonlyArray<TerminalContextDraft>;
684 /**
685 * Optional element-pick attachment count. Element contexts contribute to
686 * "sendable content" exactly like images and (text-bearing) terminal
687 * contexts do: a prompt of just element chips is still a valid send.
688 */
689 elementContextCount?: number;
690}): {
691 trimmedPrompt: string;
692 sendableTerminalContexts: TerminalContextDraft[];
693 expiredTerminalContextCount: number;
694 hasSendableContent: boolean;
695} {
696 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
697 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
698 const expiredTerminalContextCount =
699 options.terminalContexts.length - sendableTerminalContexts.length;
700 const elementContextCount = options.elementContextCount ?? 0;
701 return {
702 trimmedPrompt,
703 sendableTerminalContexts,
704 expiredTerminalContextCount,
705 hasSendableContent:
706 trimmedPrompt.length > 0 ||
707 options.imageCount > 0 ||
708 sendableTerminalContexts.length > 0 ||
709 elementContextCount > 0,
710 };
712​
713export function buildExpiredTerminalContextToastCopy(
714 expiredTerminalContextCount: number,
715 variant: "omitted" | "empty",
716): { title: string; description: string } {
717 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
718 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
719 if (variant === "empty") {
720 return {
721 title: `${noun} won't be sent`,
722 description: "Remove it or re-add it to include terminal output.",
723 };
724 }
725 return {
726 title: `${noun} omitted from message`,
727 description: "Re-add it if you want that terminal output included.",
728 };
730​
731export function branchMismatchKey(
732 threadId: string | null,
733 mismatch: { threadBranch: string; currentBranch: string } | null,
734): string | null {
735 if (!threadId || !mismatch) {
736 return null;
737 }
738 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
740​
741// The mismatch banner only matters when the user is about to send: passive
742// reading of an old thread carries no risk (the branch picker tint already
743// covers ambient awareness). Draft content is the intent signal — composer
744// focus is useless here because ChatView autofocuses the composer on every
745// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
746// revealed so it doesn't flicker away when the draft is cleared.
747export function shouldShowBranchMismatchBanner(input: {
748 hasMismatch: boolean;
749 isDismissed: boolean;
750 composerHasContent: boolean;
751 wasShownForCurrentMismatch: boolean;
752}): boolean {
753 if (!input.hasMismatch || input.isDismissed) {
754 return false;
755 }
756 return input.composerHasContent || input.wasShownForCurrentMismatch;
758​
759export function shouldShowPlanFollowUpPrompt(input: {
760 pendingUserInputCount: number;
761 interactionMode: ProviderInteractionMode;
762 latestTurnSettled: boolean;
763 hasActionableProposedPlan: boolean;
764 hasComposerAttachments: boolean;
765}): boolean {
766 return (
767 input.pendingUserInputCount === 0 &&
768 input.interactionMode === "plan" &&
769 input.latestTurnSettled &&
770 input.hasActionableProposedPlan &&
771 !input.hasComposerAttachments
772 );
774​
775// Session-scoped (module-level so it survives ChatView remounts, e.g. route
776// changes). Durable cross-device dismissal is planned as a server-side ack.
777const sessionDismissedBranchMismatchKeys = new Set<string>();
778​
779export function dismissBranchMismatchForSession(key: string): void {
780 sessionDismissedBranchMismatchKeys.add(key);
782​
783export function isBranchMismatchDismissedForSession(key: string | null): boolean {
784 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
786​
787export function threadHasStarted(thread: Thread | null | undefined): boolean {
788 return Boolean(
789 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
790 );
792​
793// Imported history has no session until its first prompt. Resolve its instance
794// through the environment's provider catalog before locking to a driver.
795export function deriveLockedProvider(input: {
796 thread: Thread | null | undefined;
797 selectedProvider: string | null;
798 threadProvider: string | null;
799 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
800}): ProviderDriverKind | null {
801 if (!threadHasStarted(input.thread)) {
802 return null;
803 }
804 const sessionProvider = input.thread?.session?.providerName ?? null;
805 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
806 return sessionProvider;
807 }
808 // Preserve the existing lock while an instance is missing from the catalog;
809 // a started thread must not silently fall back to a different driver.
810 const threadProvider =
811 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
812 input.threadProvider;
813 const selectedProvider =
814 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
815 input.selectedProvider;
816 const narrowedThreadProvider =
817 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
818 const narrowedSelectedProvider =
819 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
820 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
822​
823export function getStartedThreadModelChangeBlockReason(input: {
824 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
825 hasStartedSession: boolean;
826 currentModelSelection: ModelSelection;
827 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
828 nextModelSelection: ModelSelection;
829}): { title: string; description: string } | null {
830 if (!input.hasStartedSession) {
831 return null;
832 }
833 const currentModelSelection = {
834 ...input.currentModelSelection,
835 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
836 };
837 if (
838 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
839 currentModelSelection.model === input.nextModelSelection.model
840 ) {
841 return null;
842 }
843 const currentProvider = input.providers.find(
844 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
845 );
846 const nextProvider = input.providers.find(
847 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
848 );
849 if (
850 currentProvider?.requiresNewThreadForModelChange !== true &&
851 nextProvider?.requiresNewThreadForModelChange !== true
852 ) {
853 return null;
854 }
855 return {
856 title: "Start a new chat to change models",
857 description: "This provider does not allow switching models after a conversation has started.",
858 };
860​
861export async function waitForStartedServerThread(
862 threadRef: ScopedThreadRef,
863 timeoutMs = 1_000,
864): Promise<boolean> {
865 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
866 const getThread = () => appAtomRegistry.get(threadAtom);
867 const thread = getThread();
868​
869 if (threadHasStarted(thread)) {
870 return true;
871 }
872​
873 return await new Promise<boolean>((resolve) => {
874 let settled = false;
875 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
876 const finish = (result: boolean) => {
877 if (settled) {
878 return;
879 }
880 settled = true;
881 if (timeoutId !== null) {
882 globalThis.clearTimeout(timeoutId);
883 }
884 unsubscribe();
885 resolve(result);
886 };
887​
888 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
889 if (!threadHasStarted(thread)) {
890 return;
891 }
892 finish(true);
893 });
894​
895 if (threadHasStarted(getThread())) {
896 finish(true);
897 return;
898 }
899​
900 timeoutId = globalThis.setTimeout(() => {
901 finish(false);
902 }, timeoutMs);
903 });
905​
906export interface LocalDispatchSnapshot {
907 startedAt: string;
908 preparingWorktree: boolean;
909 submissionIntent: ComposerSubmissionIntent;
910 latestUserMessageId: ChatMessage["id"] | null;
911 latestTurnTurnId: TurnId | null;
912 latestTurnRequestedAt: string | null;
913 latestTurnStartedAt: string | null;
914 latestTurnCompletedAt: string | null;
915 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
916 sessionUpdatedAt: string | null;
917 latestTurnStartFailureId: string | null;
919​
920export function latestTurnStartFailureId(
921 activeThread: Thread | undefined,
922 latestUserMessageId: ChatMessage["id"] | null,
923): string | null {
924 if (latestUserMessageId === null) return null;
925 return (
926 activeThread?.activities.findLast((activity) => {
927 if (activity.kind !== "provider.turn.start.failed") return false;
928 const payload =
929 typeof activity.payload === "object" && activity.payload !== null
930 ? (activity.payload as { readonly requestId?: unknown })
931 : null;
932 return payload?.requestId === latestUserMessageId;
933 })?.id ?? null
934 );
936​
937export function createLocalDispatchSnapshot(
938 activeThread: Thread | undefined,
939 options?: {
940 preparingWorktree?: boolean;
941 submissionIntent?: ComposerSubmissionIntent;
942 },
943): LocalDispatchSnapshot {
944 const latestTurn = activeThread?.latestTurn ?? null;
945 const session = activeThread?.session ?? null;
946 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
947 return {
948 startedAt: new Date().toISOString(),
949 preparingWorktree: Boolean(options?.preparingWorktree),
950 submissionIntent: options?.submissionIntent ?? "foreground",
951 latestUserMessageId: latestUserMessage?.id ?? null,
952 latestTurnTurnId: latestTurn?.turnId ?? null,
953 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
954 latestTurnStartedAt: latestTurn?.startedAt ?? null,
955 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
956 sessionStatus: session?.status ?? null,
957 sessionUpdatedAt: session?.updatedAt ?? null,
958 latestTurnStartFailureId: latestTurnStartFailureId(activeThread, latestUserMessage?.id ?? null),
959 };
961​
962export function hasServerAcknowledgedLocalDispatch(input: {
963 localDispatch: LocalDispatchSnapshot | null;
964 phase: SessionPhase;
965 latestTurn: Thread["latestTurn"] | null;
966 latestUserMessageId: ChatMessage["id"] | null;
967 session: Thread["session"] | null;
968 hasPendingApproval: boolean;
969 hasPendingUserInput: boolean;
970 latestTurnStartFailureId?: string | null;
971 threadError: string | null | undefined;
972}): boolean {
973 if (!input.localDispatch) {
974 return false;
975 }
976 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
977 return true;
978 }
979 if (
980 input.latestTurnStartFailureId !== undefined &&
981 input.latestTurnStartFailureId !== null &&
982 input.latestTurnStartFailureId !== input.localDispatch.latestTurnStartFailureId
983 ) {
984 return true;
985 }
986 if (input.phase === "connecting") {
987 return false;
988 }
989​
990 const latestTurn = input.latestTurn ?? null;
991 const session = input.session ?? null;
992 const latestUserMessageChanged =
993 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
994 const latestTurnChanged =
995 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
996 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
997 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
998 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
999​
1000 if (input.phase === "running") {
1001 // Steering adds a user message to the current running turn without
1002 // necessarily changing any of the turn timestamps. Treat that projected
1003 // message as the server acknowledgment so the composer does not remain
1004 // stuck in its local "Sending" state until the turn settles.
1005 if (latestUserMessageChanged) {
1006 return true;
1008 if (!latestTurnChanged) {
1009 return false;
1011 if (latestTurn?.startedAt === null || latestTurn === null) {
1012 return false;
1014 if (
1015 session?.activeTurnId !== null &&
1016 session?.activeTurnId !== undefined &&
1017 latestTurn?.turnId !== session.activeTurnId
1018 ) {
1019 return false;
1021 return true;
1023​
1024 return (
1025 latestTurnChanged ||
1026 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
1027 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
1028 );