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

ChatView.logic.ts

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