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

ChatView.logic.ts

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