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

ChatView.logic.ts

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