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

ChatView.logic.ts

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