@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,671 lines 59.7 KB
Raw
1 import { toServerClock } from "@t3tools/client-runtime/clock";
2 import { msg } from "gt-react";
3 import { m, type MessageResolver } from "../i18n/messages";
4 import { type OrchestrationV2ProviderTurn, type RunAttemptId } from "@t3tools/contracts";
5 import {
6 deriveLatestThreadRun,
7 deriveThreadRuntime,
8 } from "@t3tools/client-runtime/state/thread-execution";
9 import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints";
10 import { COMPACT_COMMAND_PATTERN } from "@t3tools/client-runtime/state/context-window";
11 import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
12 import {
13 latestUnheldRun,
14 usageLimitRunPresentedAsLatest,
15 } from "@t3tools/shared/orchestrationV2ThreadError";
16 import * as Option from "effect/Option";
17 import type { SetStateAction } from "react";
18 import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model";
19 import { getProviderModelCapabilities } from "../providerModels";
20 import { sanitizeThreadErrorMessage, thrownErrorMessage } from "@t3tools/client-runtime/errors";
21 import type { EnvironmentThread, ThreadStructure } from "@t3tools/client-runtime/state/shell";
22 import {
23 ANTIGRAVITY_DEFAULT_MODEL,
24 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
25 type AssetCreateUrlInput,
26 type AssetCreateUrlResult,
27 type ChatFileAttachment,
28 type CommandId,
29 type EnvironmentId,
30 isProviderDriverKind,
31 ProjectId,
32 type MessageId,
33 type ModelSelection,
34 type OrchestrationMessageContext,
35 type PreviewAnnotationPayload,
36 ProviderDriverKind,
37 type ProviderInstanceId,
38 type ProviderThreadId,
39 type ServerProvider,
40 type ScopedProjectRef,
41 type ScopedThreadRef,
42 type ThreadContextRecord,
43 type EnvironmentContextRecord,
44 type ResponseContextRecord,
45 type ThreadId,
46 type ThreadLinkedPullRequest,
47 type RunId,
48 type WorktreeSetupSnapshot,
49 } from "@t3tools/contracts";
50 import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
51 import * as DateTime from "effect/DateTime";
52 import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
53 import {
54 squashAtomCommandFailure,
55 type AtomCommandResult,
56 } from "@t3tools/client-runtime/state/runtime";
57 import { readComposerImageBytes } from "./chat/composerAttachmentFiles";
58 import { videoMimeType } from "@t3tools/shared/video";
59 import {
60 appendCodexArtifactTemplateUsePrompt,
61 codexArtifactTemplateUsePrompt,
62 type CodexArtifactTemplate,
63 } from "@t3tools/shared/codexArtifactTemplates";
64 import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
65 import {
66 type ChatMessage,
67 isImageAttachment,
68 type SessionPhase,
69 type Thread,
70 type TurnDiffSummary,
71 } from "../types";
72 import {
73 type ComposerFileAttachment,
74 type ComposerImageAttachment,
75 type DraftId,
76 type DraftThreadState,
77 } from "../composerDraftStore";
78 import * as Schema from "effect/Schema";
79 import { threadHasStarted } from "../lib/chatThreadActions";
80 import { appAtomRegistry } from "../rpc/atomRegistry";
81 import { environmentThreadDetails } from "../state/threads";
82 import {
83 filterTerminalContextsWithText,
84 formatTerminalContextLabel,
85 type TerminalContextDraft,
86 } from "../lib/terminalContext";
87 import {
88 removeInlineContextReference,
89 stripInlineContextReferences,
90 } from "~/lib/composerContextReferences";
91 import {
92 previewAnnotationContextLabel,
93 reviewCommentContextLabel,
94 terminalContextReference,
95 } from "../lib/composerContextRecords";
96 import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
97 import type { DraftThreadEnvMode } from "../composerDraftStore";
98 import { type ComposerSubmissionIntent } from "../composer-logic";
99 import type { ReviewCommentContext } from "../reviewCommentContext";
100 import { derivePhase, type TimelineEntry } from "../session-logic";
101 import type { PreviewMiniPlayerSource } from "../previewMiniPlayerStore";
102 import type { DesktopPreviewOverlay } from "../previewStateStore";
103 import type { RightPanelSurface } from "../rightPanelStore";
104 import {
105 NO_PROVIDER_MODEL_SELECTION,
106 resolveSelectableProviderInstanceEntry,
107 type ProviderInstanceEntry,
108 } from "../providerInstances";
109
110 type ThreadProjection = EnvironmentThread["projection"];
111 type ThreadStructureRow = ThreadStructure["visibleTurnItems"][number];
112
113 export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
114 export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
115
116 export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
117
118 export function agentControlledBrowserCloseConfirmation(
119 surfaces: readonly RightPanelSurface[],
120 desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
121 resolve: MessageResolver = m,
122 ): string | null {
123 const activeBrowserCount = surfaces.filter(
124 (surface) =>
125 surface.kind === "preview" &&
126 surface.resourceId !== null &&
127 desktopByTabId[surface.resourceId]?.controller === "agent",
128 ).length;
129 if (activeBrowserCount === 0) return null;
130 if (activeBrowserCount === 1) {
131 return [
132 resolve(msg("Close browser while the agent is using it?")),
133 resolve(
134 msg(
135 "The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
136 ),
137 ),
138 ].join("\n");
139 }
140 return [
141 resolve(
142 msg(
143 "{count, plural, one {Close {count} browsers while the agent is using them?} other {Close {count} browsers while the agent is using them?}}",
144 { count: activeBrowserCount },
145 ),
146 ),
147 resolve(
148 msg(
149 "The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
150 ),
151 ),
152 ].join("\n");
153 }
154
155 export function shouldRenderPreviewMiniPlayer(
156 source: PreviewMiniPlayerSource | null,
157 renderedRightPanelSurface: RightPanelSurface | null,
158 ): boolean {
159 if (source === null) return false;
160 if (source.kind === "browser") {
161 return !(
162 renderedRightPanelSurface?.kind === "preview" &&
163 renderedRightPanelSurface.resourceId === source.tabId
164 );
165 }
166 return !(
167 renderedRightPanelSurface?.kind === "device" &&
168 renderedRightPanelSurface.target?.hostId === source.hostId &&
169 renderedRightPanelSurface.target.deviceId === source.deviceId
170 );
171 }
172
173 export function shouldOpenProactivePullRequest(
174 previousTargetKey: string | null | undefined,
175 targetKey: string | null,
176 ): boolean {
177 return targetKey !== null && targetKey !== previousTargetKey;
178 }
179
180 interface ProactivePanelObservation {
181 threadKey: string;
182 runningTurnId: RunId | null | undefined;
183 targetKey: string | null | undefined;
184 userActionTurnId: RunId | null;
185 userActionRevision: number;
186 }
187
188 export function observeProactivePanelUserChoice(
189 previous: ProactivePanelObservation | null,
190 input: { threadKey: string; runningTurnId: RunId | null; userActionRevision: number },
191 ): ProactivePanelObservation {
192 const sameThread = previous?.threadKey === input.threadKey;
193 const newTurn =
194 sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;
195 return {
196 threadKey: input.threadKey,
197 runningTurnId: sameThread ? previous.runningTurnId : undefined,
198 targetKey: sameThread ? previous.targetKey : undefined,
199 userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),
200 userActionRevision:
201 !sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,
202 };
203 }
204
205 export function shouldRetargetThreadPullRequestPanel(
206 previous: ThreadLinkedPullRequest | null,
207 current: ThreadLinkedPullRequest | null,
208 surface: RightPanelSurface | null,
209 ): boolean {
210 if (previous === null || current === null || surface?.kind !== "pull-request") return false;
211 const previousRepository = previous.repository.toLowerCase();
212 return (
213 (previous.projectId !== current.projectId ||
214 previousRepository !== current.repository.toLowerCase() ||
215 previous.number !== current.number) &&
216 surface.projectId === previous.projectId &&
217 surface.repository.toLowerCase() === previousRepository &&
218 surface.number === previous.number
219 );
220 }
221
222 export function shouldOpenProactiveTurnDiff(input: {
223 previousRunningTurnId: RunId | null | undefined;
224 runningTurnId: RunId | null;
225 settledTurnId: RunId | null;
226 turnCompleted: boolean;
227 }): boolean {
228 return (
229 input.runningTurnId === null &&
230 input.turnCompleted &&
231 input.settledTurnId !== null &&
232 (input.previousRunningTurnId === undefined ||
233 input.settledTurnId === input.previousRunningTurnId)
234 );
235 }
236
237 export function resolveProactiveTurnDiffAction(input: {
238 checkpoint: Pick<TurnDiffSummary, "status" | "files" | "filesTotal"> | undefined;
239 isGitRepo: boolean | undefined;
240 }): "defer" | "ignore" | "open" {
241 if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
242 if (input.isGitRepo === undefined) return "defer";
243 if (
244 !input.isGitRepo ||
245 input.checkpoint.status !== "ready" ||
246 input.checkpoint.files.length === 0
247 ) {
248 return "ignore";
249 }
250 const totals = checkpointFileTotals(input.checkpoint);
251 return totals.count >= 3 || totals.additions + totals.deletions >= 50 ? "open" : "ignore";
252 }
253
254 export function codexArtifactTemplatePromptToAppend(
255 currentDraft: string,
256 template: CodexArtifactTemplate,
257 ): string | null {
258 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
259 ? null
260 : codexArtifactTemplateUsePrompt(template);
261 }
262
263 export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
264
265 export function shouldDockDraftHeroForSubmission(input: {
266 isDraftHeroState: boolean;
267 activeThreadKey: string | null;
268 submissionIntent: ComposerSubmissionIntent;
269 }): boolean {
270 return (
271 input.submissionIntent === "foreground" &&
272 input.isDraftHeroState &&
273 input.activeThreadKey !== null
274 );
275 }
276
277 export function shouldReleaseTimelineAnchorForToolActivity(input: {
278 anchorMessageId: MessageId | null;
279 liveFollowEnabled: boolean;
280 runningTurnId: RunId | null;
281 timelineEntries: ReadonlyArray<TimelineEntry>;
282 }): boolean {
283 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
284 return false;
285 }
286
287 return input.timelineEntries.some((timelineEntry) => {
288 if (timelineEntry.kind !== "work" || timelineEntry.entry.runId !== input.runningTurnId) {
289 return false;
290 }
291
292 const entry = timelineEntry.entry;
293 return (
294 entry.tone === "tool" ||
295 entry.itemType !== undefined ||
296 entry.requestKind !== undefined ||
297 (entry.command?.trim().length ?? 0) > 0
298 );
299 });
300 }
301
302 export { resolveVisibleWorktreeSetup } from "@t3tools/client-runtime/worktree-setup";
303
304 export function resolveWorktreeSetupProgress(input: {
305 threadId: ThreadId;
306 localPreparing: boolean;
307 runStatus: NonNullable<Thread["latestRun"]>["status"] | undefined;
308 latest: WorktreeSetupSnapshot | null | undefined;
309 held: WorktreeSetupSnapshot | null;
310 }) {
311 const latest = input.latest?.threadId === input.threadId ? input.latest : null;
312 const held = input.held?.threadId === input.threadId ? input.held : null;
313 const snapshot = latest && (!held || latest.sequence >= held.sequence) ? latest : held;
314 return {
315 snapshot,
316 isPreparingWorktree:
317 input.localPreparing ||
318 input.runStatus === "preparing" ||
319 (snapshot?.phase === "running" && !worktreeSetupAgentStarted(snapshot)),
320 };
321 }
322
323 export function resolveDraftHeroState(input: {
324 isLocalDraftThread: boolean;
325 hasTimelineEntries: boolean;
326 isWorking: boolean;
327 draftHeroDockRequested: boolean;
328 backgroundSubmissionPending: boolean;
329 hasWorktreeSetupCard?: boolean;
330 }): boolean {
331 if (input.hasWorktreeSetupCard) {
332 return false;
333 }
334 if (input.backgroundSubmissionPending) {
335 return true;
336 }
337 return (
338 input.isLocalDraftThread &&
339 !input.hasTimelineEntries &&
340 !input.isWorking &&
341 !input.draftHeroDockRequested
342 );
343 }
344
345 /** Remounting or initially emptying LegendList flashes the chat pane, even for cached threads. */
346 export type HeldThreadTimeline<T extends readonly unknown[]> = {
347 threadKey: string | null;
348 entries: T;
349 };
350
351 const MAX_REMEMBERED_THREAD_TIMELINES = 16;
352
353 let rememberedThreadTimelines = new Map<string, HeldThreadTimeline<readonly unknown[]>>();
354 let rememberedThreadTimelineOrder: string[] = [];
355
356 function rememberThreadTimelineEntries(held: HeldThreadTimeline<readonly unknown[]>): void {
357 if (held.threadKey === null) {
358 return;
359 }
360 rememberedThreadTimelines.set(held.threadKey, held);
361 rememberedThreadTimelineOrder = [
362 ...rememberedThreadTimelineOrder.filter((key) => key !== held.threadKey),
363 held.threadKey,
364 ];
365 while (rememberedThreadTimelineOrder.length > MAX_REMEMBERED_THREAD_TIMELINES) {
366 const evicted = rememberedThreadTimelineOrder.shift();
367 if (evicted !== undefined) {
368 rememberedThreadTimelines.delete(evicted);
369 }
370 }
371 }
372
373 export function rememberReadyThreadTimeline<T extends readonly unknown[]>(
374 held: HeldThreadTimeline<T>,
375 ): void {
376 if (held.threadKey === null || held.entries.length === 0) {
377 return;
378 }
379 rememberThreadTimelineEntries(held);
380 }
381
382 export function peekRememberedThreadTimeline<T extends readonly unknown[]>(
383 threadKey: string | null,
384 ): T | null {
385 if (threadKey === null) {
386 return null;
387 }
388 return (rememberedThreadTimelines.get(threadKey)?.entries as T | undefined) ?? null;
389 }
390
391 export function resetHeldThreadTimeline(): void {
392 rememberedThreadTimelines = new Map();
393 rememberedThreadTimelineOrder = [];
394 }
395
396 export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input: {
397 loading: boolean;
398 activeThreadKey: string | null;
399 nextEntries: T;
400 rememberedForActive?: T | null;
401 }): T {
402 if (input.nextEntries.length > 0) {
403 return input.nextEntries;
404 }
405
406 const rememberedForActive =
407 input.rememberedForActive ?? peekRememberedThreadTimeline<T>(input.activeThreadKey);
408 if (input.loading && rememberedForActive !== null && rememberedForActive.length > 0) {
409 return rememberedForActive;
410 }
411
412 return input.nextEntries;
413 }
414
415 export function startNewThreadForProject(
416 projectRef: ScopedProjectRef | null,
417 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
418 ): boolean {
419 if (projectRef === null) return false;
420 void handleNewThread(projectRef);
421
422 return true;
423 }
424
425 export function resolveThreadMetadataUpdateForNextTurn(input: {
426 currentModelSelection: ModelSelection;
427 nextModelSelection?: ModelSelection;
428 currentBranch: string | null;
429 nextBranch?: string;
430 }): {
431 modelSelection?: ModelSelection;
432 branch?: string;
433 worktreePath?: null;
434 } | null {
435 const nextModelSelection = input.nextModelSelection;
436 const modelSelectionChanged =
437 nextModelSelection !== undefined &&
438 (nextModelSelection.model !== input.currentModelSelection.model ||
439 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
440 JSON.stringify(nextModelSelection.options ?? null) !==
441 JSON.stringify(input.currentModelSelection.options ?? null));
442 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
443 if (!modelSelectionChanged && !branchChanged) {
444 return null;
445 }
446 return {
447 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
448 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
449 };
450 }
451
452 export function buildLocalDraftThread(
453 threadId: ThreadId,
454 draftThread: DraftThreadState,
455 fallbackModelSelection: ModelSelection,
456 resolve: MessageResolver = m,
457 ): Thread {
458 const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
459 return presentThreadShell(draftThread.environmentId, {
460 id: threadId,
461 projectId: draftThread.projectId,
462 title: resolve(msg("New thread")),
463 providerInstanceId: fallbackModelSelection.instanceId,
464 modelSelection: fallbackModelSelection,
465 runtimeMode: draftThread.runtimeMode,
466 interactionMode: draftThread.interactionMode,
467 branch: draftThread.branch,
468 worktreePath: draftThread.worktreePath,
469 activeProviderThreadId: null,
470 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
471 forkedFrom: null,
472 createdBy: "user",
473 creationSource: "web",
474 latestRunId: null,
475 activeRunId: null,
476 status: "idle",
477 pendingRuntimeRequest: null,
478 latestVisibleMessage: null,
479 latestUserMessageAt: null,
480 hasActionableProposedPlan: false,
481 itemCount: 0,
482 visibleItemCount: 0,
483 createdAt: timestamp,
484 updatedAt: timestamp,
485 archivedAt: null,
486 settledOverride: null,
487 settledAt: null,
488 deletedAt: null,
489 });
490 }
491
492 export function resolveComposerProviderSelection(input: {
493 entries: ReadonlyArray<ProviderInstanceEntry>;
494 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
495 lockedProvider: ProviderDriverKind | null;
496 lockedInstanceId: ProviderInstanceId | null | undefined;
497 }) {
498 const requestedInstanceId = input.candidateInstanceIds.find(
499 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
500 );
501 const requestedDriverKind =
502 input.lockedProvider ??
503 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
504 input.entries[0]?.driverKind ??
505 ProviderDriverKind.make("unconfigured");
506 const lockedContinuationGroupKey = input.lockedProvider
507 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
508 ?.continuationGroupKey ?? null)
509 : null;
510 // Missing metadata must not move Antigravity history into another Google profile.
511 const requiresExactInstance =
512 input.lockedProvider === "antigravity" &&
513 input.lockedInstanceId != null &&
514 lockedContinuationGroupKey === null;
515 const compatibleEntries = input.entries.filter(
516 (entry) =>
517 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
518 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
519 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
520 );
521 const selectedProviderEntry =
522 input.candidateInstanceIds
523 .map((candidate) =>
524 compatibleEntries.find(
525 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
526 ),
527 )
528 .find((entry) => entry !== undefined) ??
529 resolveSelectableProviderInstanceEntry(
530 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
531 undefined,
532 ) ??
533 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
534 const unavailableProviderInstanceId = selectedProviderEntry
535 ? undefined
536 : input.lockedProvider
537 ? (input.lockedInstanceId ?? requestedInstanceId)
538 : requestedInstanceId;
539 return {
540 selectedProviderEntry,
541 requestedInstanceId,
542 requestedDriverKind,
543 lockedContinuationGroupKey,
544 unavailableProviderInstanceId,
545 };
546 }
547
548 export function getAntigravitySendBlockReason(
549 provider:
550 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
551 | null
552 | undefined,
553 model: string,
554 resolve: MessageResolver = m,
555 ): string | null {
556 if (provider?.driver !== "antigravity") return null;
557 if (!provider.installed) {
558 return resolve(msg("Install Antigravity in provider settings before sending."));
559 }
560 if (provider.auth.status === "unauthenticated") {
561 return resolve(msg("Sign in to Antigravity in provider settings before sending."));
562 }
563 const slug = model.trim();
564 if (slug.length === 0) return resolve(msg("Choose an Antigravity model before sending."));
565 if (provider.auth.status === "unknown") return null;
566 if (provider.models.length === 0) {
567 return resolve(msg("Refresh Antigravity models in provider settings before sending."));
568 }
569 if (
570 provider.status === "ready" &&
571 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
572 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
573 ) {
574 return resolve(msg("That Antigravity model is no longer available. Choose another model."));
575 }
576 return null;
577 }
578
579 export function reconcileMountedTerminalThreadIds(input: {
580 currentThreadIds: ReadonlyArray<string>;
581 openThreadIds: ReadonlyArray<string>;
582 activeThreadId: string | null;
583 activeThreadTerminalOpen: boolean;
584 maxHiddenThreadCount?: number;
585 }): string[] {
586 const openThreadIdSet = new Set(input.openThreadIds);
587 const hiddenThreadIds = input.currentThreadIds.filter(
588 (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
589 );
590 const maxHiddenThreadCount = Math.max(
591 0,
592 input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
593 );
594 const nextThreadIds =
595 hiddenThreadIds.length > maxHiddenThreadCount
596 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
597 : hiddenThreadIds;
598
599 if (
600 input.activeThreadId &&
601 input.activeThreadTerminalOpen &&
602 !nextThreadIds.includes(input.activeThreadId)
603 ) {
604 nextThreadIds.push(input.activeThreadId);
605 }
606
607 return nextThreadIds;
608 }
609
610 // Null identifies the project checkout when a launch or session is known.
611 export function resolveTerminalWorktreePath(input: {
612 launchContext: { readonly worktreePath: string | null } | null;
613 summary: { readonly worktreePath: string | null } | null;
614 threadWorktreePath: string | null;
615 }): string | null {
616 if (input.launchContext !== null) return input.launchContext.worktreePath;
617 if (input.summary !== null) return input.summary.worktreePath;
618 return input.threadWorktreePath;
619 }
620
621 export async function resolveFileAttachmentUrl(input: {
622 attachment: ChatFileAttachment;
623 environmentId: EnvironmentId;
624 httpBaseUrl: string;
625 createAssetUrl: (input: {
626 environmentId: EnvironmentId;
627 input: AssetCreateUrlInput;
628 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
629 }): Promise<string> {
630 const { attachment } = input;
631 const result = await input.createAssetUrl({
632 environmentId: input.environmentId,
633 input: {
634 resource: {
635 _tag: "attachment",
636 attachmentId: attachment.id,
637 fileName: attachment.name,
638 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
639 },
640 },
641 });
642 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
643 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
644 if (url === null) throw new Error(m(msg("The environment returned an invalid attachment URL.")));
645 return url;
646 }
647
648 export async function prepareRevertedMessageAttachments(input: {
649 message: ChatMessage;
650 environmentId: EnvironmentId;
651 httpBaseUrl: string;
652 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
653 }): Promise<File[]> {
654 return Promise.all(
655 (input.message.attachments ?? []).map(async (attachment) => {
656 if (attachment.type !== "image" && attachment.type !== "file") {
657 throw new Error(m(msg("This message has an attachment that cannot be restored.")));
658 }
659 const result = await input.createAssetUrl({
660 environmentId: input.environmentId,
661 input: {
662 resource: {
663 _tag: "attachment",
664 attachmentId: attachment.id,
665 fileName: attachment.name,
666 mimeType: attachment.mimeType,
667 },
668 },
669 });
670 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
671 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
672 if (url === null)
673 throw new Error(m(msg("The environment returned an invalid attachment URL.")));
674 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
675 if (!response.ok)
676 throw new Error(m(msg("Could not restore attachment: {name}", { name: attachment.name })));
677 const file = new File([await response.blob()], attachment.name, {
678 type: attachment.mimeType,
679 });
680 if (attachment.type === "image") await readComposerImageBytes(file);
681 return file;
682 }),
683 );
684 }
685
686 export function timelineHasEphemeralPreviewUrls(
687 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
688 ): boolean {
689 return entries.some(
690 (entry) =>
691 entry.kind === "message" &&
692 entry.message !== undefined &&
693 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
694 );
695 }
696
697 export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
698 if (message.role !== "user" || !message.attachments) {
699 return [];
700 }
701 const previewUrls: string[] = [];
702 for (const attachment of message.attachments) {
703 if (!isImageAttachment(attachment)) continue;
704 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
705 previewUrls.push(attachment.previewUrl);
706 }
707 return previewUrls;
708 }
709
710 export { readFileAsDataUrl } from "../lib/imageCompression";
711
712 export { resolveSendEnvMode } from "@t3tools/shared/projectSettings";
713
714 export function resolveBackgroundDraftWorkspaceOptions(input: {
715 envMode: DraftThreadEnvMode;
716 branch: string | null;
717 startFromOrigin: boolean;
718 }): {
719 envMode: DraftThreadEnvMode;
720 branch: string | null;
721 worktreePath: null;
722 startFromOrigin: boolean;
723 } {
724 return {
725 envMode: input.envMode,
726 branch: input.branch,
727 worktreePath: null,
728 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
729 };
730 }
731
732 export function cloneComposerImageForRetry(
733 image: ComposerImageAttachment,
734 ): ComposerImageAttachment {
735 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
736 return image;
737 }
738 try {
739 return {
740 ...image,
741 previewUrl: URL.createObjectURL(image.file),
742 };
743 } catch {
744 return image;
745 }
746 }
747
748 export function deriveComposerSendState(options: {
749 prompt: string;
750 imageCount: number;
751 existingAttachmentCount?: number;
752 terminalContexts: ReadonlyArray<TerminalContextDraft>;
753 elementContextCount?: number;
754 }): {
755 trimmedPrompt: string;
756 sendableTerminalContexts: TerminalContextDraft[];
757 expiredTerminalContextCount: number;
758 hasSendableContent: boolean;
759 } {
760 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
761 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
762 const expiredTerminalContextCount =
763 options.terminalContexts.length - sendableTerminalContexts.length;
764 const elementContextCount = options.elementContextCount ?? 0;
765 return {
766 trimmedPrompt,
767 sendableTerminalContexts,
768 expiredTerminalContextCount,
769 hasSendableContent:
770 trimmedPrompt.length > 0 ||
771 options.imageCount > 0 ||
772 (options.existingAttachmentCount ?? 0) > 0 ||
773 sendableTerminalContexts.length > 0 ||
774 elementContextCount > 0,
775 };
776 }
777
778 export function buildExpiredTerminalContextToastCopy(
779 expiredTerminalContextCount: number,
780 variant: "omitted" | "empty",
781 resolve: MessageResolver = m,
782 ): { title: string; description: string } {
783 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
784 if (variant === "empty") {
785 return {
786 title: resolve(
787 msg(
788 "{count, plural, =1 {Expired terminal context won't be sent} other {Expired terminal contexts won't be sent}}",
789 { count },
790 ),
791 ),
792 description: resolve(
793 msg(
794 "{count, plural, =1 {Remove it or re-add it to include terminal output.} other {Remove them or re-add them to include terminal output.}}",
795 { count },
796 ),
797 ),
798 };
799 }
800 return {
801 title: resolve(
802 msg(
803 "{count, plural, =1 {Expired terminal context omitted from message} other {Expired terminal contexts omitted from message}}",
804 { count },
805 ),
806 ),
807 description: resolve(
808 msg(
809 "{count, plural, =1 {Re-add it if you want that terminal output included.} other {Re-add them if you want that terminal output included.}}",
810 { count },
811 ),
812 ),
813 };
814 }
815
816 export function branchMismatchKey(
817 threadId: string | null,
818 mismatch: { threadBranch: string; currentBranch: string } | null,
819 ): string | null {
820 if (!threadId || !mismatch) {
821 return null;
822 }
823 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
824 }
825
826 // Composer autofocus makes focus unreliable as draft intent.
827 export function shouldShowBranchMismatchBanner(input: {
828 hasMismatch: boolean;
829 isDismissed: boolean;
830 composerHasContent: boolean;
831 wasShownForCurrentMismatch: boolean;
832 }): boolean {
833 if (!input.hasMismatch || input.isDismissed) {
834 return false;
835 }
836 return input.composerHasContent || input.wasShownForCurrentMismatch;
837 }
838
839 const sessionDismissedBranchMismatchKeys = new Set<string>();
840
841 export function dismissBranchMismatchForSession(key: string): void {
842 sessionDismissedBranchMismatchKeys.add(key);
843 }
844
845 export function isBranchMismatchDismissedForSession(key: string | null): boolean {
846 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
847 }
848
849 // Remember non-Git checkouts to avoid flashing the branch strip before delayed Git status arrives.
850 const sessionCheckoutIsRepo = new Map<string, boolean>();
851
852 function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
853 return JSON.stringify([environmentId, cwd]);
854 }
855
856 export function rememberCheckoutIsRepo(
857 environmentId: EnvironmentId,
858 cwd: string,
859 isRepo: boolean,
860 ): void {
861 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
862 }
863
864 export function recallCheckoutIsRepo(
865 environmentId: EnvironmentId,
866 cwd: string | null,
867 ): boolean | undefined {
868 return cwd === null
869 ? undefined
870 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
871 }
872
873 // Imported history lacks a session until its first prompt; resolve its instance before locking the driver.
874 export function deriveLockedProvider(input: {
875 thread: Thread | null | undefined;
876 selectedProvider: string | null;
877 threadProvider: string | null;
878 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
879 }): ProviderDriverKind | null {
880 if (!threadHasStarted(input.thread)) {
881 return null;
882 }
883 const sessionProvider = input.thread?.runtime?.providerName ?? null;
884 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
885 return sessionProvider;
886 }
887 // Missing catalog entries must not switch a started thread's driver.
888 const threadProvider =
889 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
890 input.threadProvider;
891 const selectedProvider =
892 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
893 input.selectedProvider;
894 const narrowedThreadProvider =
895 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
896 const narrowedSelectedProvider =
897 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
898 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
899 }
900
901 export function getStartedThreadModelChangeBlockReason(
902 input: {
903 hasStartedSession: boolean;
904 supportsProviderSwitchingViaHandoff?: boolean;
905 currentModelSelection: ModelSelection;
906 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
907 nextModelSelection: ModelSelection;
908 },
909 resolve: MessageResolver = m,
910 ): { title: string; description: string } | null {
911 if (!input.hasStartedSession) {
912 return null;
913 }
914 const currentModelSelection = {
915 ...input.currentModelSelection,
916 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
917 };
918 if (
919 currentModelSelection.instanceId === input.nextModelSelection.instanceId ||
920 input.supportsProviderSwitchingViaHandoff === true
921 ) {
922 return null;
923 }
924 return {
925 title: resolve(msg("Start a new chat to switch providers")),
926 description: resolve(
927 msg("This thread does not support switching providers after it has started."),
928 ),
929 };
930 }
931
932 export async function waitForRevertedMessage(
933 threadRef: ScopedThreadRef,
934 turnCount: number,
935 requestId: CommandId,
936 revert: () => Promise<void>,
937 timeoutMs = 120_000,
938 ): Promise<void> {
939 const threadAtom = environmentThreadDetails.stateAtom(threadRef);
940 const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);
941 const initial = readProjection();
942 const providerThreadId = initial?.thread.activeProviderThreadId;
943 const initialProviderThread = initial?.providerThreads.find(
944 (providerThread) => providerThread.id === providerThreadId,
945 );
946 const initialProviderThreadIds = new Set(initial?.providerThreads.map((thread) => thread.id));
947 // Paging can omit the source run. Rollback commits the entire settled suffix atomically.
948 const witness = initial?.runs.reduce<(typeof initial.runs)[number] | undefined>((latest, run) => {
949 if (
950 run.ordinal <= turnCount ||
951 (run.status !== "completed" &&
952 run.status !== "interrupted" &&
953 run.status !== "failed" &&
954 run.status !== "cancelled")
955 )
956 return latest;
957 return latest === undefined || run.ordinal > latest.ordinal ? run : latest;
958 }, undefined);
959 if (witness === undefined) {
960 throw new Error(m(msg("The thread has changed. Select a message to rewind again.")));
961 }
962 return new Promise<void>((resolve, reject) => {
963 let settled = false;
964 let accepted = false;
965 let unsubscribe = () => {};
966 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
967 const finish = (error?: unknown) => {
968 if (settled) return;
969 settled = true;
970 if (timeout !== undefined) globalThis.clearTimeout(timeout);
971 unsubscribe();
972 if (error !== undefined) reject(error);
973 else resolve();
974 };
975 const inspect = () => {
976 const thread = readProjection();
977 if (!thread) return;
978 const failure = thread.thread.rollbackFailure;
979 if (failure?.requestId === requestId) {
980 finish(new Error(failure.message));
981 return;
982 }
983 if (
984 accepted &&
985 thread.providerThreads.some(
986 (providerThread) =>
987 (providerThread.id === providerThreadId ||
988 // Claude resets to a fresh root session when rewinding to thread start.
989 (turnCount === 0 &&
990 providerThread.ownerNodeId === null &&
991 providerThread.appThreadId === initial?.thread.id &&
992 providerThread.providerInstanceId === initialProviderThread?.providerInstanceId &&
993 !initialProviderThreadIds.has(providerThread.id))) &&
994 providerThread.lastRunOrdinal === (turnCount === 0 ? null : turnCount),
995 ) &&
996 thread.runs.some((run) => run.id === witness.id && run.status === "rolled_back")
997 )
998 finish();
999 };
1000 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1001 timeout = globalThis.setTimeout(() => {
1002 finish(new Error(m(msg("Timed out waiting for the thread to rewind."))));
1003 }, timeoutMs);
1004 Promise.resolve()
1005 .then(revert)
1006 .then(() => {
1007 accepted = true;
1008 inspect();
1009 }, finish);
1010 });
1011 }
1012
1013 export interface LocalDispatchSnapshot {
1014 startedAt: string;
1015 preparingWorktree: boolean;
1016 submissionIntent: ComposerSubmissionIntent;
1017 latestUserMessageId: ChatMessage["id"] | null;
1018 latestRunId: RunId | null;
1019 latestRunRequestedAt: string | null;
1020 latestRunStartedAt: string | null;
1021 latestRunCompletedAt: string | null;
1022 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
1023 runtimeUpdatedAt: string | null;
1024 }
1025
1026 export function createLocalDispatchSnapshot(
1027 activeThread: Thread | undefined,
1028 options?: {
1029 environmentId?: EnvironmentId;
1030 preparingWorktree?: boolean;
1031 latestUserMessageId?: ChatMessage["id"] | null;
1032 submissionIntent?: ComposerSubmissionIntent;
1033 },
1034 ): LocalDispatchSnapshot {
1035 const environmentId = options?.environmentId ?? activeThread?.environmentId;
1036 const latestRun = activeThread?.latestRun ?? null;
1037 const runtime = activeThread?.runtime ?? null;
1038 return {
1039 startedAt: new Date(
1040 environmentId === undefined ? Date.now() : toServerClock(environmentId, Date.now()),
1041 ).toISOString(),
1042 preparingWorktree: Boolean(options?.preparingWorktree),
1043 submissionIntent: options?.submissionIntent ?? "foreground",
1044 latestUserMessageId: options?.latestUserMessageId ?? null,
1045 latestRunId: latestRun?.runId ?? null,
1046 latestRunRequestedAt: latestRun?.requestedAt ?? null,
1047 latestRunStartedAt: latestRun?.startedAt ?? null,
1048 latestRunCompletedAt: latestRun?.completedAt ?? null,
1049 runtimeStatus: runtime?.status ?? null,
1050 runtimeUpdatedAt: runtime?.updatedAt ?? null,
1051 };
1052 }
1053
1054 /** Projection messages can precede visible turn items by one event; evict optimistic rows only when
1055 * visible. */
1056 export function deriveCommittedServerUserMessageIds(
1057 visibleTurnItems: ReadonlyArray<ThreadStructureRow>,
1058 ): ReadonlySet<ChatMessage["id"]> {
1059 return new Set(
1060 visibleTurnItems.flatMap((row) =>
1061 row.item.type === "user_message" ? [row.item.messageId] : [],
1062 ),
1063 );
1064 }
1065
1066 /**
1067 * The server checks the full history, but the first page of an
1068 * agent-started thread or a long turn can hold no user message.
1069 */
1070 export function hasCompactableConversation(input: {
1071 readonly visibleTurnItems: ReadonlyArray<ThreadStructureRow>;
1072 readonly hasMoreHistory: boolean;
1073 readonly latestUserMessageAt: string | null;
1074 }): boolean {
1075 return (
1076 input.visibleTurnItems.some(
1077 ({ item }) =>
1078 item.type === "user_message" &&
1079 (item.text.trim().toLowerCase() !== "/compact" || item.attachments.length > 0),
1080 ) ||
1081 (input.hasMoreHistory && input.latestUserMessageAt !== null)
1082 );
1083 }
1084
1085 export function hasServerAcknowledgedLocalDispatch(input: {
1086 localDispatch: LocalDispatchSnapshot | null;
1087 phase: SessionPhase;
1088 latestRun: Thread["latestRun"] | null;
1089 latestUserMessageId?: ChatMessage["id"] | null;
1090 runtime: Thread["runtime"] | null;
1091 hasPendingApproval: boolean;
1092 hasPendingUserInput: boolean;
1093 threadError: string | null | undefined;
1094 }): boolean {
1095 if (!input.localDispatch) {
1096 return false;
1097 }
1098 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1099 return true;
1100 }
1101 const latestUserMessageChanged =
1102 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
1103 if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") {
1104 // A message queued behind other work, such as an idle compaction the shell hides, has landed.
1105 return input.runtime?.status === "queued" && latestUserMessageChanged;
1106 }
1107
1108 const latestRun = input.latestRun ?? null;
1109 const runtime = input.runtime ?? null;
1110 const latestRunChanged =
1111 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
1112 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
1113 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
1114 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
1115
1116 if (input.phase === "running") {
1117 if (latestUserMessageChanged) {
1118 return true;
1119 }
1120 if (!latestRunChanged) {
1121 return false;
1122 }
1123 if (latestRun?.startedAt === null || latestRun === null) {
1124 return false;
1125 }
1126 if (
1127 runtime?.activeRunId !== null &&
1128 runtime?.activeRunId !== undefined &&
1129 latestRun?.runId !== runtime.activeRunId
1130 ) {
1131 return false;
1132 }
1133 return true;
1134 }
1135
1136 return (
1137 latestRunChanged ||
1138 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
1139 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
1140 );
1141 }
1142
1143 // Window return puts the caret in the composer unless focus or a selection is deliberate: another
1144 // text field, a terminal, an open dialog, menu, or popup, a region, timeline, or sidebar row reached
1145 // from the keyboard, a region with its own keys (aria-keyshortcuts), or selected text the composer
1146 // would clear. A plain focused button or a clicked row yields to the composer.
1147 export function shouldRefocusComposerOnWindowFocus(
1148 activeElement:
1149 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1150 | null,
1151 selection: Pick<Selection, "isCollapsed"> | null,
1152 ): boolean {
1153 if (selection !== null && !selection.isCollapsed) return false;
1154 if (activeElement === null || activeElement.tagName === "BODY") return true;
1155 if (
1156 activeElement.tagName === "INPUT" ||
1157 activeElement.tagName === "TEXTAREA" ||
1158 activeElement.tagName === "SELECT" ||
1159 activeElement.tagName === "IFRAME" ||
1160 activeElement.tagName === "WEBVIEW" ||
1161 activeElement.isContentEditable === true ||
1162 activeElement.getAttribute("role") === "textbox"
1163 ) {
1164 return false;
1165 }
1166 return (
1167 activeElement.closest(
1168 '[data-workspace-keyboard-focus], [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner], [aria-keyshortcuts]',
1169 ) === null
1170 );
1171 }
1172
1173 /** Includes the annotation screenshot only within the attachment cap; exceeding it rejects the whole turn. */
1174 export function mergeDirectPreviewAnnotation(input: {
1175 readonly images: ReadonlyArray<ComposerImageAttachment>;
1176 readonly fileCount: number;
1177 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1178 readonly direct:
1179 | {
1180 readonly annotation: PreviewAnnotationPayload;
1181 readonly image: ComposerImageAttachment | null;
1182 }
1183 | undefined;
1184 }): {
1185 readonly images: ReadonlyArray<ComposerImageAttachment>;
1186 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1187 } {
1188 const { direct } = input;
1189 if (!direct) return { images: input.images, previewAnnotations: input.previewAnnotations };
1190 const imageAlreadyAttached =
1191 direct.image !== null && input.images.some((image) => image.id === direct.image?.id);
1192 const imageAppended =
1193 direct.image !== null &&
1194 !imageAlreadyAttached &&
1195 input.images.length + input.fileCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
1196 const images = direct.image && imageAppended ? [...input.images, direct.image] : input.images;
1197 const previewAnnotations = input.previewAnnotations.some(
1198 (annotation) => annotation.id === direct.annotation.id,
1199 )
1200 ? input.previewAnnotations
1201 : [
1202 ...input.previewAnnotations,
1203 {
1204 ...direct.annotation,
1205 screenshot:
1206 direct.annotation.screenshot && (imageAppended || imageAlreadyAttached)
1207 ? { ...direct.annotation.screenshot, dataUrl: "" }
1208 : null,
1209 },
1210 ];
1211 return { images, previewAnnotations };
1212 }
1213
1214 export { isThreadWokeUnseen } from "@t3tools/client-runtime/state/thread-settled";
1215
1216 export function formatOutgoingPrompt(params: {
1217 provider: ProviderDriverKind;
1218 model: string | null;
1219 models: ReadonlyArray<ServerProvider["models"][number]>;
1220 effort: string | null;
1221 text: string;
1222 }): string {
1223 const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
1224 const promptEffort = resolvePromptInjectedEffort(caps, params.effort);
1225 return applyClaudePromptEffortPrefix(params.text, promptEffort);
1226 }
1227
1228 export function isCompactCommandMessage(message: ChatMessage): boolean {
1229 const text = message.text.trim().toLowerCase();
1230 return message.role === "user" && text === "/compact" && !message.attachments?.length;
1231 }
1232
1233 // Errors surface through two maps (draft-keyed and thread-keyed) whose entries
1234 // can race around promotion, so each write carries its time to let the latest
1235 // one win when they collide.
1236 export type LocalThreadErrorEntry = {
1237 readonly message: string | null;
1238 readonly at: number;
1239 };
1240
1241 export function chatActionErrorMessage(error: unknown, resolve: MessageResolver = m): string {
1242 return thrownErrorMessage(error, resolve) ?? resolve(msg("An error occurred."));
1243 }
1244
1245 /** A local copy of the runtime's error shares the runtime's key, so one dismissal covers both. */
1246 export function threadErrorIsServerRuntime(input: {
1247 readonly isServerThread: boolean;
1248 readonly localServerError: string | null;
1249 readonly runtimeError: string | null;
1250 }): boolean {
1251 return (
1252 input.isServerThread &&
1253 (input.localServerError === null || input.localServerError === input.runtimeError)
1254 );
1255 }
1256
1257 export function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | null }>(
1258 current: T,
1259 ): T {
1260 return current.messageId === null ? current : { ...current, messageId: null };
1261 }
1262
1263 // The factories below build functions ChatView calls during render, or hands
1264 // to ChatComposer, which can call them after an await. They live outside the
1265 // component so each closure keeps only its inputs, not a whole render scope
1266 // (see useStableCallback), while still acting on the render that made them.
1267
1268 /** Records a thread error in local state, keyed by the route the making render saw. */
1269 export function makeThreadErrorSetter(input: {
1270 readonly routeThreadRef: ScopedThreadRef;
1271 readonly routeThreadKey: string;
1272 readonly draftId: DraftId | null;
1273 readonly serverThreadRef: ScopedThreadRef | null;
1274 readonly setLocalServerErrorsByThreadKey: (
1275 update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1276 ) => void;
1277 readonly setLocalDraftErrorsByDraftId: (
1278 update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1279 ) => void;
1280 }) {
1281 return (targetThreadId: ThreadId | null, error: string | null) => {
1282 if (!targetThreadId) return;
1283 const nextError = sanitizeThreadErrorMessage(error);
1284 const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
1285 const { routeThreadRef, serverThreadRef } = input;
1286 if (
1287 serverThreadRef &&
1288 targetThreadId === routeThreadRef.threadId &&
1289 serverThreadRef.environmentId === routeThreadRef.environmentId &&
1290 serverThreadRef.threadId === targetThreadId
1291 ) {
1292 input.setLocalServerErrorsByThreadKey((existing) => {
1293 if ((existing[input.routeThreadKey]?.message ?? null) === nextError) {
1294 return existing;
1295 }
1296 return { ...existing, [input.routeThreadKey]: nextEntry };
1297 });
1298 return;
1299 }
1300 const localDraftErrorKey = input.draftId ?? targetThreadId;
1301 input.setLocalDraftErrorsByDraftId((existing) => {
1302 if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
1303 return existing;
1304 }
1305 return { ...existing, [localDraftErrorKey]: nextEntry };
1306 });
1307 };
1308 }
1309
1310 /** Why the model picker should disable a model, or null when it can be chosen. */
1311 export function makeModelDisabledReason(
1312 context: Omit<
1313 Parameters<typeof getStartedThreadModelChangeBlockReason>[0],
1314 "nextModelSelection"
1315 > | null,
1316 resolve: MessageResolver = m,
1317 ) {
1318 return (instanceId: ProviderInstanceId, model: string): string | null => {
1319 if (!context) return null;
1320 const reason = getStartedThreadModelChangeBlockReason(
1321 { ...context, nextModelSelection: { instanceId, model } },
1322 resolve,
1323 );
1324 return reason
1325 ? resolve(
1326 msg("{reason} Start a new thread to use this model.", { reason: reason.description }),
1327 )
1328 : null;
1329 };
1330 }
1331
1332 /** What the composer held when the user pressed send, after a direct annotation merged in. */
1333 export interface ComposerSendContents {
1334 readonly prompt: string;
1335 readonly images: ReadonlyArray<ComposerImageAttachment>;
1336 readonly files: ReadonlyArray<ComposerFileAttachment>;
1337 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1338 readonly sendableTerminalContexts: ReadonlyArray<TerminalContextDraft>;
1339 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1340 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1341 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
1342 readonly environmentContexts: ReadonlyArray<EnvironmentContextRecord>;
1343 /** The response the message replies to. `prompt` already leads with its reference. */
1344 readonly replyTo: ResponseContextRecord | null;
1345 }
1346
1347 /**
1348 * Copies the composer contents a send dispatches, so a failed send can put the
1349 * same draft back. Terminal contexts that lost their text are dropped from both
1350 * the contexts and the prompt's inline references.
1351 */
1352 export function snapshotComposerSend(contents: ComposerSendContents) {
1353 const images = [...contents.images];
1354 const files = [...contents.files];
1355 const terminalContexts = [...contents.sendableTerminalContexts];
1356 const messageText = contents.terminalContexts
1357 .filter((context) => !terminalContexts.includes(context))
1358 .reduce(
1359 (text, context) =>
1360 removeInlineContextReference(text, terminalContextReference(context).contextId).prompt,
1361 contents.prompt,
1362 )
1363 .trim();
1364 return {
1365 images,
1366 files,
1367 attachments: [...images, ...files],
1368 terminalContexts,
1369 previewAnnotations: [...contents.previewAnnotations],
1370 reviewComments: [...contents.reviewComments],
1371 threadContexts: [...contents.threadContexts],
1372 environmentContexts: [...contents.environmentContexts],
1373 replyTo: contents.replyTo,
1374 messageText,
1375 /** What a failed send puts back in the composer: the reply returns above it, not in the text. */
1376 draftText: contents.replyTo
1377 ? removeInlineContextReference(messageText, contents.replyTo.contextId).prompt.trimStart()
1378 : messageText,
1379 };
1380 }
1381
1382 export type ComposerSendSnapshot = ReturnType<typeof snapshotComposerSend>;
1383
1384 /** Derived from the persisted run phase, so a starting run still reads as work after a reload. */
1385 export function deriveTimelineWorking(input: {
1386 readonly phase: SessionPhase;
1387 readonly isSendBusy: boolean;
1388 readonly isCompacting: boolean;
1389 readonly runlessWorkStartedAt: string | null;
1390 }): boolean {
1391 return (
1392 input.phase === "connecting" ||
1393 input.phase === "running" ||
1394 input.isSendBusy ||
1395 input.isCompacting ||
1396 input.runlessWorkStartedAt !== null
1397 );
1398 }
1399
1400 /** How a composer send dispatches: where it runs and whether it waits behind other work. */
1401 export function planComposerTurn(input: {
1402 readonly messageText: string;
1403 readonly sendQueuesBehindSetup: boolean;
1404 readonly isServerThread: boolean;
1405 readonly activeMessageCount: number;
1406 readonly sendEnvMode: DraftThreadEnvMode;
1407 readonly worktreePath: string | null;
1408 readonly activeThreadBranch: string | null;
1409 /** The server launches a No project worktree request at its root, so it needs no base. */
1410 readonly isScratchProject: boolean;
1411 readonly resumeCompactionTokens: number | null;
1412 readonly keepFullHistory: boolean;
1413 readonly phase: SessionPhase;
1414 readonly dispatchMode: ComposerDispatchMode;
1415 /** The turn starts a new provider session, so it neither compacts first nor steers. */
1416 readonly freshContext: boolean;
1417 }) {
1418 const isFirstMessage =
1419 !input.sendQueuesBehindSetup && (!input.isServerThread || input.activeMessageCount === 0);
1420 const shouldCreateWorktree =
1421 isFirstMessage && input.sendEnvMode === "worktree" && !input.worktreePath;
1422 // A stale Claude session compacts before this message so the turn does not re-read the
1423 // old history. The message queues behind the /compact run, since steering into it is
1424 // rejected.
1425 const compactBeforeSend =
1426 !input.freshContext &&
1427 input.resumeCompactionTokens !== null &&
1428 !input.keepFullHistory &&
1429 !COMPACT_COMMAND_PATTERN.test(input.messageText);
1430 const dispatchMode =
1431 input.freshContext && (input.dispatchMode === "steer" || input.dispatchMode === "restart")
1432 ? "queue"
1433 : input.dispatchMode;
1434 return {
1435 // In worktree mode, require an explicit base branch so we don't silently
1436 // fall back to local execution when branch selection is missing.
1437 missingWorktreeBaseBranch:
1438 shouldCreateWorktree && !input.activeThreadBranch && !input.isScratchProject,
1439 baseBranchForWorktree: shouldCreateWorktree ? input.activeThreadBranch : null,
1440 compactBeforeSend,
1441 turnDispatchMode:
1442 compactBeforeSend || (input.sendQueuesBehindSetup && dispatchMode !== "steer")
1443 ? ("queue" as const)
1444 : dispatchMode,
1445 shouldQueueBehindActiveRun:
1446 compactBeforeSend ||
1447 input.sendQueuesBehindSetup ||
1448 (input.phase === "running" && dispatchMode === "queue"),
1449 };
1450 }
1451
1452 /**
1453 * The attachment ids a message's context records bind to: the upload id the
1454 * server returned, or the local id on the data-URL path.
1455 */
1456 export function boundAttachmentIds(
1457 turnAttachments: ReadonlyArray<{ readonly id?: string | undefined }>,
1458 attachments: ReadonlyArray<{ readonly id: string }>,
1459 ): string[] {
1460 return turnAttachments.map((attachment, index) =>
1461 "id" in attachment && attachment.id !== undefined ? attachment.id : attachments[index]!.id,
1462 );
1463 }
1464
1465 export function withMessageContext(input: {
1466 readonly text: string;
1467 readonly context: OrchestrationMessageContext | undefined;
1468 }): { readonly text: string; readonly context?: OrchestrationMessageContext } {
1469 const { text, context } = input;
1470 if (context === undefined) return { text };
1471 return { text, context };
1472 }
1473
1474 /** The attachments the optimistic user row shows before the server echoes the message. */
1475 export function optimisticMessageAttachments(
1476 attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
1477 ) {
1478 return attachments.map((attachment) =>
1479 attachment.type === "image"
1480 ? {
1481 type: "image" as const,
1482 id: attachment.id,
1483 name: attachment.name,
1484 mimeType: attachment.mimeType,
1485 sizeBytes: attachment.sizeBytes,
1486 previewUrl: attachment.previewUrl,
1487 ...(attachment.source ? { source: attachment.source } : {}),
1488 }
1489 : {
1490 type: "file" as const,
1491 id: attachment.id,
1492 name: attachment.name,
1493 mimeType: attachment.mimeType,
1494 sizeBytes: attachment.sizeBytes,
1495 downloadable: false,
1496 ...(attachment.source ? { source: attachment.source } : {}),
1497 },
1498 );
1499 }
1500
1501 /** Fallback title sources for a message with no text of its own. */
1502 export function sendTitleFallbackLabels(
1503 snapshot: ComposerSendSnapshot,
1504 resolve: MessageResolver = m,
1505 ) {
1506 const terminalContext = snapshot.terminalContexts[0];
1507 const reviewComment = snapshot.reviewComments[0];
1508 const previewAnnotation = snapshot.previewAnnotations[0];
1509 return [
1510 terminalContext ? formatTerminalContextLabel(terminalContext) : undefined,
1511 reviewComment
1512 ? resolve(
1513 msg("Review: {label}", {
1514 label: reviewCommentContextLabel(reviewComment, resolve),
1515 $context: "title seed for a new thread started from a review comment",
1516 }),
1517 )
1518 : undefined,
1519 previewAnnotation ? previewAnnotationContextLabel(previewAnnotation, resolve) : undefined,
1520 ];
1521 }
1522
1523 /**
1524 * A thread shell built from its loaded detail, for direct links that hydrate the detail first.
1525 * `updatedAt` and `lastVisitedAt` are passed live: the thread structure leaves them out.
1526 */
1527 export function presentThreadShellFromProjection(
1528 environmentId: EnvironmentId,
1529 threadId: ThreadId,
1530 projection: ThreadStructure,
1531 live: {
1532 readonly updatedAt: ThreadProjection["updatedAt"];
1533 readonly lastVisitedAt: ThreadProjection["thread"]["lastVisitedAt"];
1534 },
1535 ) {
1536 const { updatedAt, lastVisitedAt } = live;
1537 const latestRun = deriveLatestThreadRun(projection);
1538 const runtime = deriveThreadRuntime({ ...projection, updatedAt });
1539 const pendingRuntimeRequest =
1540 projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null;
1541 // Direct links can hydrate detail before the thread enters the shell index.
1542 return {
1543 ...presentThreadShell(environmentId, {
1544 ...projection.thread,
1545 lastVisitedAt,
1546 latestRunId: latestRun?.runId ?? null,
1547 activeRunId: runtime?.activeRunId ?? null,
1548 status: runtime?.status ?? "idle",
1549 pendingRuntimeRequest,
1550 latestVisibleMessage: null,
1551 latestUserMessageAt:
1552 projection.messages.findLast((message) => message.role === "user")?.updatedAt ?? null,
1553 hasActionableProposedPlan: projection.plans.some(
1554 (plan) => plan.kind === "proposed_plan" && plan.status === "active",
1555 ),
1556 providerInstanceHistory: [
1557 ...new Set(
1558 projection.providerThreads
1559 .filter((thread) => thread.appThreadId === threadId && thread.ownerNodeId === null)
1560 .map((thread) => thread.providerInstanceId),
1561 ),
1562 ],
1563 goal:
1564 projection.providerThreads.find(
1565 (thread) => thread.id === projection.thread.activeProviderThreadId,
1566 )?.goal ?? null,
1567 itemCount: projection.turnItems.length,
1568 visibleItemCount: projection.visibleTurnItems.length,
1569 updatedAt,
1570 }),
1571 latestRun,
1572 runtime,
1573 };
1574 }
1575
1576 // Excludes `waiting`: that is post-terminal checkpoint drain, so its agent turn is over.
1577 const LIVE_RUN_STATUSES = new Set(["queued", "preparing", "starting", "running"]);
1578
1579 /**
1580 * Background work the provider still runs after an earlier run ended. It
1581 * stays listed while a later run is live; that live run's own items are its
1582 * foreground work, so they never count as background. The provider roster is
1583 * not run-tied, so it drops entries naming a live run's item by native id.
1584 */
1585 export function deriveThreadPendingBackgroundTasks(projection: ThreadStructure | null) {
1586 if (projection === null) return [];
1587 const sessionError =
1588 projection.providerSessions.findLast(
1589 (session) => session.providerInstanceId === projection.thread.providerInstanceId,
1590 )?.lastError ?? null;
1591 const liveRunIds = new Set(
1592 projection.runs.filter((run) => LIVE_RUN_STATUSES.has(run.status)).map((run) => run.id),
1593 );
1594 const foregroundTaskIds = new Set<string>();
1595 for (const item of projection.turnItems) {
1596 if (item.runId === null || !liveRunIds.has(item.runId)) continue;
1597 if (item.nativeItemRef?.nativeId) foregroundTaskIds.add(item.nativeItemRef.nativeId);
1598 }
1599 const latestRun =
1600 usageLimitRunPresentedAsLatest(projection.runs, projection.turnItems, sessionError) ??
1601 latestUnheldRun(projection.runs.filter((run) => !liveRunIds.has(run.id)));
1602 return [
1603 ...derivePendingBackgroundWork({
1604 latestRun,
1605 providerThreads: projection.providerThreads.map((thread) => ({
1606 ...thread,
1607 pendingBackgroundTasks: thread.pendingBackgroundTasks?.filter(
1608 (task) => !foregroundTaskIds.has(task.taskId),
1609 ),
1610 })),
1611 turnItems: projection.turnItems.filter(
1612 (item) => item.runId === null || !liveRunIds.has(item.runId),
1613 ),
1614 activeProviderThreadId: projection.thread.activeProviderThreadId,
1615 hasActiveRun: false,
1616 runs: projection.runs,
1617 pullRequests: projection.thread.pullRequests,
1618 }),
1619 ];
1620 }
1621
1622 /**
1623 * Run ordinals the conversation can be reverted to: those whose provider turn belongs to the
1624 * active provider thread, plus 0 for the thread start. Empty without a live provider session
1625 * on the thread's selected instance.
1626 */
1627 export function deriveAvailableRevertTurnCounts(projection: ThreadStructure | null) {
1628 const available = new Set<number>();
1629 const providerThread = projection?.providerThreads.find(
1630 (candidate) => candidate.id === projection.thread.activeProviderThreadId,
1631 );
1632 if (
1633 !providerThread?.providerSessionId ||
1634 providerThread.providerInstanceId !== projection?.thread.modelSelection.instanceId
1635 )
1636 return available;
1637 available.add(0);
1638 const attemptsById = new Map(projection.attempts.map((attempt) => [attempt.id, attempt]));
1639 const providerTurnsById = new Map<
1640 OrchestrationV2ProviderTurn["id"],
1641 OrchestrationV2ProviderTurn
1642 >();
1643 const latestTurnByAttempt = new Map<RunAttemptId, OrchestrationV2ProviderTurn>();
1644 for (const turn of projection.providerTurns) {
1645 providerTurnsById.set(turn.id, turn);
1646 if (turn.runAttemptId === null) continue;
1647 const latest = latestTurnByAttempt.get(turn.runAttemptId);
1648 if (latest === undefined || turn.ordinal > latest.ordinal) {
1649 latestTurnByAttempt.set(turn.runAttemptId, turn);
1650 }
1651 }
1652 for (const run of projection.runs) {
1653 if (run.activeAttemptId === null) continue;
1654 const attempt = attemptsById.get(run.activeAttemptId);
1655 const providerTurn =
1656 latestTurnByAttempt.get(run.activeAttemptId) ??
1657 (attempt?.providerTurnId == null ? undefined : providerTurnsById.get(attempt.providerTurnId));
1658 // A ready file checkpoint alone cannot restore the provider conversation.
1659 if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal);
1660 }
1661 return available;
1662 }
1663
1664 /** An imported native session is bound before it has messages or runs, and its cwd is fixed. */
1665 export function isThreadEnvironmentLocked(input: {
1666 readonly messageCount: number;
1667 readonly hasRuntime: boolean;
1668 readonly activeProviderThreadId: ProviderThreadId | null;
1669 }): boolean {
1670 return input.messageCount > 0 || input.hasRuntime || input.activeProviderThreadId !== null;
1671 }