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

ChatView.logic.ts

1,337 lines46.3 KB

1import * as Option from "effect/Option";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import {
4 ANTIGRAVITY_DEFAULT_MODEL,
5 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6 type AssetCreateUrlInput,
7 type AssetCreateUrlResult,
8 type ChatFileAttachment,
9 type CommandId,
10 type EnvironmentId,
11 isProviderDriverKind,
12 ProjectId,
13 type MessageId,
14 type ModelSelection,
15 type OrchestrationV2ProjectedTurnItem,
16 type PreviewAnnotationPayload,
17 type ProviderInteractionMode,
18 ProviderDriverKind,
19 type ProviderInstanceId,
20 type ServerProvider,
21 type ScopedProjectRef,
22 type ScopedThreadRef,
23 type ThreadContextRecord,
24 type ThreadId,
25 type ThreadLinkedPullRequest,
26 type RunId,
27 type WorktreeSetupSnapshot,
28} from "@t3tools/contracts";
29import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
30import * as DateTime from "effect/DateTime";
31import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
32import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
33import {
34 squashAtomCommandFailure,
35 type AtomCommandResult,
36} from "@t3tools/client-runtime/state/runtime";
37import { videoMimeType } from "@t3tools/shared/video";
38import {
39 appendCodexArtifactTemplateUsePrompt,
40 codexArtifactTemplateUsePrompt,
41 type CodexArtifactTemplate,
42} from "@t3tools/shared/codexArtifactTemplates";
43import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
44import {
45 type ChatMessage,
46 isImageAttachment,
47 type SessionPhase,
48 type Thread,
49 type TurnDiffSummary,
50} from "../types";
51import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
52import * as Schema from "effect/Schema";
53import { appAtomRegistry } from "../rpc/atomRegistry";
54import { environmentThreadShells, environmentThreadDetails } from "../state/threads";
55import { waitForAtomValue } from "../state/waitForAtomValue";
56import { filterTerminalContextsWithText, type TerminalContextDraft } from "../lib/terminalContext";
57import { stripInlineContextReferences } from "~/lib/composerContextReferences";
58import type { DraftThreadEnvMode } from "../composerDraftStore";
59import { collapseExpandedComposerCursor, type ComposerSubmissionIntent } from "../composer-logic";
60import type { ReviewCommentContext } from "../reviewCommentContext";
61import { derivePhase, type TimelineEntry } from "../session-logic";
62import type { PreviewMiniPlayerSource } from "../previewMiniPlayerStore";
63import type { DesktopPreviewOverlay } from "../previewStateStore";
64import type { RightPanelSurface } from "../rightPanelStore";
65import {
66 NO_PROVIDER_MODEL_SELECTION,
67 resolveSelectableProviderInstanceEntry,
68 type ProviderInstanceEntry,
69} from "../providerInstances";
70​
71export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
72export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
73​
74const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
75​
76export function agentControlledBrowserCloseConfirmation(
77 surfaces: readonly RightPanelSurface[],
78 desktopByTabId: Readonly<Record<string, Pick<DesktopPreviewOverlay, "controller"> | undefined>>,
79): string | null {
80 const activeBrowserCount = surfaces.filter(
81 (surface) =>
82 surface.kind === "preview" &&
83 surface.resourceId !== null &&
84 desktopByTabId[surface.resourceId]?.controller === "agent",
85 ).length;
86 if (activeBrowserCount === 0) return null;
87 if (activeBrowserCount === 1) {
88 return [
89 "Close browser while the agent is using it?",
90 "The agent is actively controlling this browser. Closing it may interrupt the current browser action.",
91 ].join("\n");
92 }
93 return [
94 `Close ${activeBrowserCount} browsers while the agent is using them?`,
95 "The agent is actively controlling these browsers. Closing them may interrupt the current browser actions.",
96 ].join("\n");
98​
99export function shouldRenderPreviewMiniPlayer(
100 source: PreviewMiniPlayerSource | null,
101 renderedRightPanelSurface: RightPanelSurface | null,
102): boolean {
103 if (source === null) return false;
104 if (source.kind === "browser") {
105 return !(
106 renderedRightPanelSurface?.kind === "preview" &&
107 renderedRightPanelSurface.resourceId === source.tabId
108 );
109 }
110 return !(
111 renderedRightPanelSurface?.kind === "device" &&
112 renderedRightPanelSurface.target?.hostId === source.hostId &&
113 renderedRightPanelSurface.target.deviceId === source.deviceId
114 );
116​
117export function shouldOpenProactivePullRequest(
118 previousTargetKey: string | null | undefined,
119 targetKey: string | null,
120): boolean {
121 return targetKey !== null && targetKey !== previousTargetKey;
123​
124interface ProactivePanelObservation {
125 threadKey: string;
126 runningTurnId: RunId | null | undefined;
127 targetKey: string | null | undefined;
128 userActionTurnId: RunId | null;
129 userActionRevision: number;
131​
132export function observeProactivePanelUserChoice(
133 previous: ProactivePanelObservation | null,
134 input: { threadKey: string; runningTurnId: RunId | null; userActionRevision: number },
135): ProactivePanelObservation {
136 const sameThread = previous?.threadKey === input.threadKey;
137 const newTurn =
138 sameThread && input.runningTurnId !== null && input.runningTurnId !== previous.userActionTurnId;
139 return {
140 threadKey: input.threadKey,
141 runningTurnId: sameThread ? previous.runningTurnId : undefined,
142 targetKey: sameThread ? previous.targetKey : undefined,
143 userActionTurnId: input.runningTurnId ?? (sameThread ? previous.userActionTurnId : null),
144 userActionRevision:
145 !sameThread || newTurn ? input.userActionRevision : previous.userActionRevision,
146 };
148​
149export function shouldRetargetThreadPullRequestPanel(
150 previous: ThreadLinkedPullRequest | null,
151 current: ThreadLinkedPullRequest | null,
152 surface: RightPanelSurface | null,
153): boolean {
154 if (previous === null || current === null || surface?.kind !== "pull-request") return false;
155 const previousRepository = previous.repository.toLowerCase();
156 return (
157 (previous.projectId !== current.projectId ||
158 previousRepository !== current.repository.toLowerCase() ||
159 previous.number !== current.number) &&
160 surface.projectId === previous.projectId &&
161 surface.repository.toLowerCase() === previousRepository &&
162 surface.number === previous.number
163 );
165​
166export function shouldOpenProactiveTurnDiff(input: {
167 previousRunningTurnId: RunId | null | undefined;
168 runningTurnId: RunId | null;
169 settledTurnId: RunId | null;
170 turnCompleted: boolean;
171}): boolean {
172 return (
173 input.runningTurnId === null &&
174 input.turnCompleted &&
175 input.settledTurnId !== null &&
176 (input.previousRunningTurnId === undefined ||
177 input.settledTurnId === input.previousRunningTurnId)
178 );
180​
181export function resolveProactiveTurnDiffAction(input: {
182 checkpoint: Pick<TurnDiffSummary, "status" | "files"> | undefined;
183 isGitRepo: boolean | undefined;
184}): "defer" | "ignore" | "open" {
185 if (input.checkpoint === undefined || input.checkpoint.status === "missing") return "defer";
186 if (input.isGitRepo === undefined) return "defer";
187 if (
188 !input.isGitRepo ||
189 input.checkpoint.status !== "ready" ||
190 input.checkpoint.files.length === 0
191 ) {
192 return "ignore";
193 }
194 const changedLines = input.checkpoint.files.reduce(
195 (total, file) => total + file.additions + file.deletions,
196 0,
197 );
198 return input.checkpoint.files.length >= 3 || changedLines >= 50 ? "open" : "ignore";
200​
201/**
202 * Clicking back to an existing Diff tab resumes the review in progress, so the
203 * generic-open reset to Changes must skip it. A diff that is already active is
204 * left unmarked: the reset never runs for it, and the marker would linger into
205 * the next generic open.
206 */
207export function resolveExplicitDiffOpenOnActivate(input: {
208 readonly surfaceKind: RightPanelSurface["kind"];
209 readonly diffOpen: boolean;
210 readonly activeThreadRef: ScopedThreadRef;
211}): ScopedThreadRef | null {
212 return input.surfaceKind === "diff" && !input.diffOpen ? input.activeThreadRef : null;
214​
215export function codexArtifactTemplatePromptToAppend(
216 currentDraft: string,
217 template: CodexArtifactTemplate,
218): string | null {
219 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
220 ? null
221 : codexArtifactTemplateUsePrompt(template);
223​
224export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
225​
226export function shouldDockDraftHeroForSubmission(input: {
227 isDraftHeroState: boolean;
228 activeThreadKey: string | null;
229 submissionIntent: ComposerSubmissionIntent;
230}): boolean {
231 return (
232 input.submissionIntent === "foreground" &&
233 input.isDraftHeroState &&
234 input.activeThreadKey !== null
235 );
237​
238export function shouldReleaseTimelineAnchorForToolActivity(input: {
239 anchorMessageId: MessageId | null;
240 liveFollowEnabled: boolean;
241 runningTurnId: RunId | null;
242 timelineEntries: ReadonlyArray<TimelineEntry>;
243}): boolean {
244 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
245 return false;
246 }
247​
248 return input.timelineEntries.some((timelineEntry) => {
249 if (timelineEntry.kind !== "work" || timelineEntry.entry.runId !== input.runningTurnId) {
250 return false;
251 }
252​
253 const entry = timelineEntry.entry;
254 return (
255 entry.tone === "tool" ||
256 entry.itemType !== undefined ||
257 entry.requestKind !== undefined ||
258 (entry.command?.trim().length ?? 0) > 0
259 );
260 });
262​
263export {
264 findRecordedWorktreeSetup,
265 resolveVisibleWorktreeSetup,
266} from "@t3tools/client-runtime/worktree-setup";
267​
268export function resolveWorktreeSetupProgress(input: {
269 threadId: ThreadId;
270 localPreparing: boolean;
271 runStatus: NonNullable<Thread["latestRun"]>["status"] | undefined;
272 latest: WorktreeSetupSnapshot | null | undefined;
273 held: WorktreeSetupSnapshot | null;
274}) {
275 const latest = input.latest?.threadId === input.threadId ? input.latest : null;
276 const held = input.held?.threadId === input.threadId ? input.held : null;
277 const snapshot = latest && (!held || latest.sequence >= held.sequence) ? latest : held;
278 return {
279 snapshot,
280 isPreparingWorktree:
281 input.localPreparing ||
282 input.runStatus === "preparing" ||
283 (snapshot?.phase === "running" && !worktreeSetupAgentStarted(snapshot)),
284 };
286​
287export function resolveDraftHeroState(input: {
288 isLocalDraftThread: boolean;
289 hasTimelineEntries: boolean;
290 isWorking: boolean;
291 draftHeroDockRequested: boolean;
292 backgroundSubmissionPending: boolean;
293 hasWorktreeSetupCard?: boolean;
294}): boolean {
295 if (input.hasWorktreeSetupCard) {
296 return false;
297 }
298 if (input.backgroundSubmissionPending) {
299 return true;
300 }
301 return (
302 input.isLocalDraftThread &&
303 !input.hasTimelineEntries &&
304 !input.isWorking &&
305 !input.draftHeroDockRequested
306 );
308​
309/**
310 * Remounting LegendList (or handing it an empty first paint) punches a hole
311 * through the chat pane — white in light mode — so cmd+1/2/3 spam flashes even
312 * when the destination is already cached.
313 */
314export type HeldThreadTimeline<T extends readonly unknown[]> = {
315 threadKey: string | null;
316 entries: T;
317 markdownCwd?: string | null;
318 workspaceRoot?: string | null;
319};
320​
321const MAX_REMEMBERED_THREAD_TIMELINES = 16;
322​
323let rememberedThreadTimelines = new Map<string, HeldThreadTimeline<readonly unknown[]>>();
324let rememberedThreadTimelineOrder: string[] = [];
325let lastReadyThreadKey: string | null = null;
326​
327function rememberThreadTimelineEntries(held: HeldThreadTimeline<readonly unknown[]>): void {
328 if (held.threadKey === null) {
329 return;
330 }
331 rememberedThreadTimelines.set(held.threadKey, held);
332 rememberedThreadTimelineOrder = [
333 ...rememberedThreadTimelineOrder.filter((key) => key !== held.threadKey),
334 held.threadKey,
335 ];
336 while (rememberedThreadTimelineOrder.length > MAX_REMEMBERED_THREAD_TIMELINES) {
337 const evicted = rememberedThreadTimelineOrder.shift();
338 if (evicted !== undefined) {
339 rememberedThreadTimelines.delete(evicted);
340 }
341 }
342 lastReadyThreadKey = held.threadKey;
344​
345export function rememberReadyThreadTimeline<T extends readonly unknown[]>(
346 held: HeldThreadTimeline<T>,
347): void {
348 if (held.threadKey === null || held.entries.length === 0) {
349 return;
350 }
351 rememberThreadTimelineEntries(held);
353​
354export function peekRememberedThreadTimeline<T extends readonly unknown[]>(
355 threadKey: string | null,
356): T | null {
357 if (threadKey === null) {
358 return null;
359 }
360 return (rememberedThreadTimelines.get(threadKey)?.entries as T | undefined) ?? null;
362​
363export function peekHeldThreadTimeline<
364 T extends readonly unknown[],
365>(): HeldThreadTimeline<T> | null {
366 if (lastReadyThreadKey === null) {
367 return null;
368 }
369 const held = rememberedThreadTimelines.get(lastReadyThreadKey);
370 if (held === undefined || held.entries.length === 0) {
371 return null;
372 }
373 return held as HeldThreadTimeline<T>;
375​
376export function resetHeldThreadTimeline(): void {
377 rememberedThreadTimelines = new Map();
378 rememberedThreadTimelineOrder = [];
379 lastReadyThreadKey = null;
381​
382export function threadKeysShareEnvironment(left: string | null, right: string | null): boolean {
383 if (left === null || right === null) {
384 return false;
385 }
386 const leftRef = parseScopedThreadKey(left);
387 const rightRef = parseScopedThreadKey(right);
388 return leftRef !== null && rightRef !== null && leftRef.environmentId === rightRef.environmentId;
390​
391export function isPaintOnlyThreadTimeline(
392 displayThreadKey: string | null,
393 activeThreadKey: string | null,
394): boolean {
395 return (
396 displayThreadKey !== null && activeThreadKey !== null && displayThreadKey !== activeThreadKey
397 );
399​
400export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input: {
401 loading: boolean;
402 activeThreadKey: string | null;
403 nextEntries: T;
404 rememberedForActive?: T | null;
405 lastReady?: HeldThreadTimeline<T> | null;
406}): { entries: T; displayThreadKey: string | null } {
407 if (input.nextEntries.length > 0) {
408 return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
409 }
410​
411 const rememberedForActive =
412 input.rememberedForActive ?? peekRememberedThreadTimeline<T>(input.activeThreadKey);
413 if (input.loading && rememberedForActive !== null && rememberedForActive.length > 0) {
414 return { entries: rememberedForActive, displayThreadKey: input.activeThreadKey };
415 }
416​
417 return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
419​
420export function resolveDraftPromotionNavigationTarget(input: {
421 serverThreadRef: ScopedThreadRef | null;
422 serverThread: Pick<Thread, "latestRun" | "latestUserMessageAt"> | null | undefined;
423 backgroundSubmissionPending: boolean;
424}): ScopedThreadRef | null {
425 if (input.backgroundSubmissionPending) {
426 return null;
427 }
428 const latestRun = input.serverThread?.latestRun ?? null;
429 const runStarted = latestRun?.startedAt != null;
430 const startupStopped =
431 latestRun?.status === "failed" ||
432 latestRun?.status === "interrupted" ||
433 latestRun?.status === "cancelled";
434 const messagePersisted = input.serverThread?.latestUserMessageAt != null;
435 return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;
437​
438export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
439 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
440 return () => globalThis.clearTimeout(timeoutId);
442​
443export function hasEnvironmentReconnectWarningGraceElapsed(
444 activeEnvironmentId: EnvironmentId | null,
445 elapsedEnvironmentId: EnvironmentId | null,
446): boolean {
447 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
449​
450export function startNewThreadForProject(
451 projectRef: ScopedProjectRef | null,
452 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
453): boolean {
454 if (projectRef === null) return false;
455 void handleNewThread(projectRef);
456​
457 return true;
459​
460export function resolveThreadMetadataUpdateForNextTurn(input: {
461 currentModelSelection: ModelSelection;
462 nextModelSelection?: ModelSelection;
463 currentBranch: string | null;
464 nextBranch?: string;
465}): {
466 modelSelection?: ModelSelection;
467 branch?: string;
468 worktreePath?: null;
469} | null {
470 const nextModelSelection = input.nextModelSelection;
471 const modelSelectionChanged =
472 nextModelSelection !== undefined &&
473 (nextModelSelection.model !== input.currentModelSelection.model ||
474 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
475 JSON.stringify(nextModelSelection.options ?? null) !==
476 JSON.stringify(input.currentModelSelection.options ?? null));
477 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
478 if (!modelSelectionChanged && !branchChanged) {
479 return null;
480 }
481 return {
482 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
483 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
484 };
486​
487export function buildLocalDraftThread(
488 threadId: ThreadId,
489 draftThread: DraftThreadState,
490 fallbackModelSelection: ModelSelection,
491): Thread {
492 const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
493 return presentThreadShell(draftThread.environmentId, {
494 id: threadId,
495 projectId: draftThread.projectId,
496 title: "New thread",
497 providerInstanceId: fallbackModelSelection.instanceId,
498 modelSelection: fallbackModelSelection,
499 runtimeMode: draftThread.runtimeMode,
500 interactionMode: draftThread.interactionMode,
501 branch: draftThread.branch,
502 worktreePath: draftThread.worktreePath,
503 activeProviderThreadId: null,
504 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
505 forkedFrom: null,
506 createdBy: "user",
507 creationSource: "web",
508 latestRunId: null,
509 activeRunId: null,
510 status: "idle",
511 pendingRuntimeRequest: null,
512 latestVisibleMessage: null,
513 latestUserMessageAt: null,
514 hasActionableProposedPlan: false,
515 itemCount: 0,
516 visibleItemCount: 0,
517 createdAt: timestamp,
518 updatedAt: timestamp,
519 archivedAt: null,
520 settledOverride: null,
521 settledAt: null,
522 deletedAt: null,
523 });
525​
526export function resolveComposerProviderSelection(input: {
527 entries: ReadonlyArray<ProviderInstanceEntry>;
528 candidateInstanceIds: ReadonlyArray<ProviderInstanceId | null | undefined>;
529 lockedProvider: ProviderDriverKind | null;
530 lockedInstanceId: ProviderInstanceId | null | undefined;
531}) {
532 const requestedInstanceId = input.candidateInstanceIds.find(
533 (candidate) => candidate != null && candidate !== NO_PROVIDER_MODEL_SELECTION.instanceId,
534 );
535 const requestedDriverKind =
536 input.lockedProvider ??
537 input.entries.find((entry) => entry.instanceId === requestedInstanceId)?.driverKind ??
538 input.entries[0]?.driverKind ??
539 ProviderDriverKind.make("unconfigured");
540 const lockedContinuationGroupKey = input.lockedProvider
541 ? (input.entries.find((entry) => entry.instanceId === input.lockedInstanceId)
542 ?.continuationGroupKey ?? null)
543 : null;
544 // Missing metadata must not move Antigravity history into another Google profile.
545 const requiresExactInstance =
546 input.lockedProvider === "antigravity" &&
547 input.lockedInstanceId != null &&
548 lockedContinuationGroupKey === null;
549 const compatibleEntries = input.entries.filter(
550 (entry) =>
551 (!input.lockedProvider || entry.driverKind === input.lockedProvider) &&
552 (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey) &&
553 (!requiresExactInstance || entry.instanceId === input.lockedInstanceId),
554 );
555 const selectedProviderEntry =
556 input.candidateInstanceIds
557 .map((candidate) =>
558 compatibleEntries.find(
559 (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
560 ),
561 )
562 .find((entry) => entry !== undefined) ??
563 resolveSelectableProviderInstanceEntry(
564 compatibleEntries.filter((entry) => entry.driverKind === requestedDriverKind),
565 undefined,
566 ) ??
567 resolveSelectableProviderInstanceEntry(compatibleEntries, undefined);
568 const unavailableProviderInstanceId = selectedProviderEntry
569 ? undefined
570 : input.lockedProvider
571 ? (input.lockedInstanceId ?? requestedInstanceId)
572 : requestedInstanceId;
573 return {
574 selectedProviderEntry,
575 requestedDriverKind,
576 lockedContinuationGroupKey,
577 unavailableProviderInstanceId,
578 };
580​
581export function resolveComposerInteractionMode(input: {
582 planModeEnabled: boolean;
583 provider: Pick<ServerProvider, "showInteractionModeToggle"> | null | undefined;
584 interactionMode: ProviderInteractionMode;
585}): { enabled: boolean; interactionMode: ProviderInteractionMode } {
586 const enabled =
587 input.planModeEnabled &&
588 input.provider != null &&
589 input.provider.showInteractionModeToggle !== false;
590 return {
591 enabled,
592 interactionMode: enabled ? input.interactionMode : "default",
593 };
595​
596export function getAntigravitySendBlockReason(
597 provider:
598 | Pick<ServerProvider, "driver" | "installed" | "auth" | "models" | "status">
599 | null
600 | undefined,
601 model: string,
602): string | null {
603 if (provider?.driver !== "antigravity") return null;
604 if (!provider.installed) {
605 return "Install Antigravity in provider settings before sending.";
606 }
607 if (provider.auth.status === "unauthenticated") {
608 return "Sign in to Antigravity in provider settings before sending.";
609 }
610 const slug = model.trim();
611 if (slug.length === 0) return "Choose an Antigravity model before sending.";
612 if (provider.auth.status === "unknown") return null;
613 if (provider.models.length === 0) {
614 return "Refresh Antigravity models in provider settings before sending.";
615 }
616 if (
617 provider.status === "ready" &&
618 slug !== ANTIGRAVITY_DEFAULT_MODEL &&
619 !provider.models.some((entry) => entry.slug === slug || entry.aliases?.includes(slug))
620 ) {
621 return "That Antigravity model is no longer available. Choose another model.";
622 }
623 return null;
625​
626export function reconcileMountedTerminalThreadIds(input: {
627 currentThreadIds: ReadonlyArray<string>;
628 openThreadIds: ReadonlyArray<string>;
629 activeThreadId: string | null;
630 activeThreadTerminalOpen: boolean;
631 maxHiddenThreadCount?: number;
632}): string[] {
633 const openThreadIdSet = new Set(input.openThreadIds);
634 const hiddenThreadIds = input.currentThreadIds.filter(
635 (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
636 );
637 const maxHiddenThreadCount = Math.max(
638 0,
639 input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
640 );
641 const nextThreadIds =
642 hiddenThreadIds.length > maxHiddenThreadCount
643 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
644 : hiddenThreadIds;
645​
646 if (
647 input.activeThreadId &&
648 input.activeThreadTerminalOpen &&
649 !nextThreadIds.includes(input.activeThreadId)
650 ) {
651 nextThreadIds.push(input.activeThreadId);
652 }
653​
654 return nextThreadIds;
656​
657// Null identifies the project checkout when a launch or session is known.
658export function resolveTerminalWorktreePath(input: {
659 launchContext: { readonly worktreePath: string | null } | null;
660 summary: { readonly worktreePath: string | null } | null;
661 threadWorktreePath: string | null;
662}): string | null {
663 if (input.launchContext !== null) return input.launchContext.worktreePath;
664 if (input.summary !== null) return input.summary.worktreePath;
665 return input.threadWorktreePath;
667​
668export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
669 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
670 return;
671 }
672 URL.revokeObjectURL(previewUrl);
674​
675export async function resolveFileAttachmentUrl(input: {
676 attachment: ChatFileAttachment;
677 environmentId: EnvironmentId;
678 httpBaseUrl: string;
679 createAssetUrl: (input: {
680 environmentId: EnvironmentId;
681 input: AssetCreateUrlInput;
682 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
683}): Promise<string> {
684 const { attachment } = input;
685 const result = await input.createAssetUrl({
686 environmentId: input.environmentId,
687 input: {
688 resource: {
689 _tag: "attachment",
690 attachmentId: attachment.id,
691 fileName: attachment.name,
692 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
693 },
694 },
695 });
696 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
697 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
698 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
699 return url;
701​
702export async function prepareRevertedMessageAttachments(input: {
703 message: ChatMessage;
704 environmentId: EnvironmentId;
705 httpBaseUrl: string;
706 createAssetUrl: Parameters<typeof resolveFileAttachmentUrl>[0]["createAssetUrl"];
707}): Promise<File[]> {
708 return Promise.all(
709 (input.message.attachments ?? []).map(async (attachment) => {
710 if (attachment.type !== "image" && attachment.type !== "file") {
711 throw new Error("This message has an attachment that cannot be restored.");
712 }
713 const result = await input.createAssetUrl({
714 environmentId: input.environmentId,
715 input: {
716 resource: {
717 _tag: "attachment",
718 attachmentId: attachment.id,
719 fileName: attachment.name,
720 mimeType: attachment.mimeType,
721 },
722 },
723 });
724 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
725 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
726 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
727 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
728 if (!response.ok) throw new Error(`Could not restore attachment: ${attachment.name}`);
729 return new File([await response.blob()], attachment.name, { type: attachment.mimeType });
730 }),
731 );
733​
734export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
735 if (message.role !== "user" || !message.attachments) {
736 return;
737 }
738 for (const attachment of message.attachments) {
739 if (!isImageAttachment(attachment)) {
740 continue;
741 }
742 revokeBlobPreviewUrl(attachment.previewUrl);
743 }
745​
746export function timelineHasEphemeralPreviewUrls(
747 entries: ReadonlyArray<Pick<TimelineEntry, "kind"> & { message?: ChatMessage }>,
748): boolean {
749 return entries.some(
750 (entry) =>
751 entry.kind === "message" &&
752 entry.message !== undefined &&
753 collectUserMessageBlobPreviewUrls(entry.message).length > 0,
754 );
756​
757export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
758 if (message.role !== "user" || !message.attachments) {
759 return [];
760 }
761 const previewUrls: string[] = [];
762 for (const attachment of message.attachments) {
763 if (!isImageAttachment(attachment)) continue;
764 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
765 previewUrls.push(attachment.previewUrl);
766 }
767 return previewUrls;
769​
770export { readFileAsDataUrl } from "../lib/imageCompression";
771​
772export { resolveSendEnvMode } from "@t3tools/shared/projectSettings";
773​
774export function resolveBackgroundDraftWorkspaceOptions(input: {
775 envMode: DraftThreadEnvMode;
776 branch: string | null;
777 startFromOrigin: boolean;
778}): {
779 envMode: DraftThreadEnvMode;
780 branch: string | null;
781 worktreePath: null;
782 startFromOrigin: boolean;
783} {
784 return {
785 envMode: input.envMode,
786 branch: input.branch,
787 worktreePath: null,
788 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
789 };
791​
792export function cloneComposerImageForRetry(
793 image: ComposerImageAttachment,
794): ComposerImageAttachment {
795 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
796 return image;
797 }
798 try {
799 return {
800 ...image,
801 previewUrl: URL.createObjectURL(image.file),
802 };
803 } catch {
804 return image;
805 }
807​
808export function deriveComposerSendState(options: {
809 prompt: string;
810 imageCount: number;
811 terminalContexts: ReadonlyArray<TerminalContextDraft>;
812 elementContextCount?: number;
813}): {
814 trimmedPrompt: string;
815 sendableTerminalContexts: TerminalContextDraft[];
816 expiredTerminalContextCount: number;
817 hasSendableContent: boolean;
818} {
819 const trimmedPrompt = stripInlineContextReferences(options.prompt).trim();
820 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
821 const expiredTerminalContextCount =
822 options.terminalContexts.length - sendableTerminalContexts.length;
823 const elementContextCount = options.elementContextCount ?? 0;
824 return {
825 trimmedPrompt,
826 sendableTerminalContexts,
827 expiredTerminalContextCount,
828 hasSendableContent:
829 trimmedPrompt.length > 0 ||
830 options.imageCount > 0 ||
831 sendableTerminalContexts.length > 0 ||
832 elementContextCount > 0,
833 };
835​
836export function buildExpiredTerminalContextToastCopy(
837 expiredTerminalContextCount: number,
838 variant: "omitted" | "empty",
839): { title: string; description: string } {
840 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
841 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
842 if (variant === "empty") {
843 return {
844 title: `${noun} won't be sent`,
845 description: "Remove it or re-add it to include terminal output.",
846 };
847 }
848 return {
849 title: `${noun} omitted from message`,
850 description: "Re-add it if you want that terminal output included.",
851 };
853​
854export function branchMismatchKey(
855 threadId: string | null,
856 mismatch: { threadBranch: string; currentBranch: string } | null,
857): string | null {
858 if (!threadId || !mismatch) {
859 return null;
860 }
861 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
863​
864// Draft content is the intent signal — composer focus is useless here because
865// ChatView autofocuses the composer on every thread open.
866export function shouldShowBranchMismatchBanner(input: {
867 hasMismatch: boolean;
868 isDismissed: boolean;
869 composerHasContent: boolean;
870 wasShownForCurrentMismatch: boolean;
871}): boolean {
872 if (!input.hasMismatch || input.isDismissed) {
873 return false;
874 }
875 return input.composerHasContent || input.wasShownForCurrentMismatch;
877​
878export function shouldShowPlanFollowUpPrompt(input: {
879 pendingUserInputCount: number;
880 interactionMode: ProviderInteractionMode;
881 latestTurnSettled: boolean;
882 hasActionableProposedPlan: boolean;
883 hasComposerAttachments: boolean;
884}): boolean {
885 return (
886 input.pendingUserInputCount === 0 &&
887 input.interactionMode === "plan" &&
888 input.latestTurnSettled &&
889 input.hasActionableProposedPlan &&
890 !input.hasComposerAttachments
891 );
893​
894const sessionDismissedBranchMismatchKeys = new Set<string>();
895​
896export function dismissBranchMismatchForSession(key: string): void {
897 sessionDismissedBranchMismatchKeys.add(key);
899​
900export function isBranchMismatchDismissedForSession(key: string | null): boolean {
901 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
903​
904// Git status for a checkout arrives after the composer paints, and the branch
905// strip mounts on the assumption that a project is a Git repo. Without a
906// memory, a non-Git project would mount the strip and drop it on every visit.
907const sessionCheckoutIsRepo = new Map<string, boolean>();
908​
909function checkoutIsRepoKey(environmentId: EnvironmentId, cwd: string): string {
910 return JSON.stringify([environmentId, cwd]);
912​
913export function rememberCheckoutIsRepo(
914 environmentId: EnvironmentId,
915 cwd: string,
916 isRepo: boolean,
917): void {
918 sessionCheckoutIsRepo.set(checkoutIsRepoKey(environmentId, cwd), isRepo);
920​
921export function recallCheckoutIsRepo(
922 environmentId: EnvironmentId,
923 cwd: string | null,
924): boolean | undefined {
925 return cwd === null
926 ? undefined
927 : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
929​
930export function threadHasStarted(thread: Thread | null | undefined): boolean {
931 return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
933​
934export function threadShellHasStarted(
935 shell:
936 | Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt" | "runtime">
937 | null
938 | undefined,
939): boolean {
940 return Boolean(
941 shell &&
942 (shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null),
943 );
945​
946// Imported history has no session until its first prompt. Resolve its instance
947// through the environment's provider catalog before locking to a driver.
948export function deriveLockedProvider(input: {
949 thread: Thread | null | undefined;
950 selectedProvider: string | null;
951 threadProvider: string | null;
952 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver">>;
953}): ProviderDriverKind | null {
954 if (!threadHasStarted(input.thread)) {
955 return null;
956 }
957 const sessionProvider = input.thread?.runtime?.providerName ?? null;
958 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
959 return sessionProvider;
960 }
961 // Preserve the existing lock while an instance is missing from the catalog;
962 // a started thread must not silently fall back to a different driver.
963 const threadProvider =
964 input.providers.find((provider) => provider.instanceId === input.threadProvider)?.driver ??
965 input.threadProvider;
966 const selectedProvider =
967 input.providers.find((provider) => provider.instanceId === input.selectedProvider)?.driver ??
968 input.selectedProvider;
969 const narrowedThreadProvider =
970 threadProvider && isProviderDriverKind(threadProvider) ? threadProvider : null;
971 const narrowedSelectedProvider =
972 selectedProvider && isProviderDriverKind(selectedProvider) ? selectedProvider : null;
973 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
975​
976export function getStartedThreadModelChangeBlockReason(input: {
977 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
978 hasStartedSession: boolean;
979 supportsProviderSwitchingViaHandoff?: boolean;
980 currentModelSelection: ModelSelection;
981 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
982 nextModelSelection: ModelSelection;
983}): { title: string; description: string } | null {
984 if (!input.hasStartedSession) {
985 return null;
986 }
987 const currentModelSelection = {
988 ...input.currentModelSelection,
989 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
990 };
991 if (
992 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
993 currentModelSelection.model === input.nextModelSelection.model
994 ) {
995 return null;
996 }
997 if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
998 if (input.supportsProviderSwitchingViaHandoff === true) {
999 return null;
1001 return {
1002 title: "Start a new chat to switch providers",
1003 description: "This thread does not support switching providers after it has started.",
1004 };
1006 const currentProvider = input.providers.find(
1007 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
1008 );
1009 const nextProvider = input.providers.find(
1010 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
1011 );
1012 if (
1013 currentProvider?.requiresNewThreadForModelChange !== true &&
1014 nextProvider?.requiresNewThreadForModelChange !== true
1015 ) {
1016 return null;
1018 return {
1019 title: "Start a new chat to change models",
1020 description: "This provider does not allow switching models after a conversation has started.",
1021 };
1023​
1024export async function waitForStartedServerThread(
1025 threadRef: ScopedThreadRef,
1026 timeoutMs = 1_000,
1027): Promise<boolean> {
1028 const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
1029 return waitForAtomValue({
1030 registry: appAtomRegistry,
1031 atom: threadAtom,
1032 predicate: threadHasStarted,
1033 timeoutMs,
1034 });
1036​
1037export async function waitForRevertedMessage(
1038 threadRef: ScopedThreadRef,
1039 turnCount: number,
1040 requestId: CommandId,
1041 revert: () => Promise<void>,
1042 timeoutMs = 120_000,
1043): Promise<void> {
1044 const threadAtom = environmentThreadDetails.stateAtom(threadRef);
1045 const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);
1046 const initial = readProjection();
1047 const providerThreadId = initial?.thread.activeProviderThreadId;
1048 const initialProviderThread = initial?.providerThreads.find(
1049 (providerThread) => providerThread.id === providerThreadId,
1050 );
1051 const initialProviderThreadIds = new Set(initial?.providerThreads.map((thread) => thread.id));
1052 // Paging can omit the source run. Rollback commits the entire settled suffix atomically.
1053 const witness = initial?.runs.reduce<(typeof initial.runs)[number] | undefined>((latest, run) => {
1054 if (
1055 run.ordinal <= turnCount ||
1056 (run.status !== "completed" &&
1057 run.status !== "interrupted" &&
1058 run.status !== "failed" &&
1059 run.status !== "cancelled")
1061 return latest;
1062 return latest === undefined || run.ordinal > latest.ordinal ? run : latest;
1063 }, undefined);
1064 if (witness === undefined) {
1065 throw new Error("The thread has changed. Select a message to rewind again.");
1067 return new Promise<void>((resolve, reject) => {
1068 let settled = false;
1069 let accepted = false;
1070 let unsubscribe = () => {};
1071 let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;
1072 const finish = (error?: unknown) => {
1073 if (settled) return;
1074 settled = true;
1075 if (timeout !== undefined) globalThis.clearTimeout(timeout);
1076 unsubscribe();
1077 if (error !== undefined) reject(error);
1078 else resolve();
1079 };
1080 const inspect = () => {
1081 const thread = readProjection();
1082 if (!thread) return;
1083 const failure = thread.thread.rollbackFailure;
1084 if (failure?.requestId === requestId) {
1085 finish(new Error(failure.message));
1086 return;
1088 if (
1089 accepted &&
1090 thread.providerThreads.some(
1091 (providerThread) =>
1092 (providerThread.id === providerThreadId ||
1093 // Claude resets to a fresh root session when rewinding to thread start.
1094 (turnCount === 0 &&
1095 providerThread.ownerNodeId === null &&
1096 providerThread.appThreadId === initial?.thread.id &&
1097 providerThread.providerInstanceId === initialProviderThread?.providerInstanceId &&
1098 !initialProviderThreadIds.has(providerThread.id))) &&
1099 providerThread.lastRunOrdinal === (turnCount === 0 ? null : turnCount),
1100 ) &&
1101 thread.runs.some((run) => run.id === witness.id && run.status === "rolled_back")
1103 finish();
1104 };
1105 unsubscribe = appAtomRegistry.subscribe(threadAtom, inspect);
1106 timeout = globalThis.setTimeout(() => {
1107 finish(new Error("Timed out waiting for the thread to rewind."));
1108 }, timeoutMs);
1109 Promise.resolve()
1110 .then(revert)
1111 .then(() => {
1112 accepted = true;
1113 inspect();
1114 }, finish);
1115 });
1117​
1118export interface LocalDispatchSnapshot {
1119 startedAt: string;
1120 preparingWorktree: boolean;
1121 submissionIntent: ComposerSubmissionIntent;
1122 latestUserMessageId: ChatMessage["id"] | null;
1123 latestRunId: RunId | null;
1124 latestRunRequestedAt: string | null;
1125 latestRunStartedAt: string | null;
1126 latestRunCompletedAt: string | null;
1127 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
1128 runtimeUpdatedAt: string | null;
1130​
1131export function createLocalDispatchSnapshot(
1132 activeThread: Thread | undefined,
1133 options?: {
1134 preparingWorktree?: boolean;
1135 latestUserMessageId?: ChatMessage["id"] | null;
1136 submissionIntent?: ComposerSubmissionIntent;
1137 },
1138): LocalDispatchSnapshot {
1139 const latestRun = activeThread?.latestRun ?? null;
1140 const runtime = activeThread?.runtime ?? null;
1141 return {
1142 startedAt: new Date().toISOString(),
1143 preparingWorktree: Boolean(options?.preparingWorktree),
1144 submissionIntent: options?.submissionIntent ?? "foreground",
1145 latestUserMessageId: options?.latestUserMessageId ?? null,
1146 latestRunId: latestRun?.runId ?? null,
1147 latestRunRequestedAt: latestRun?.requestedAt ?? null,
1148 latestRunStartedAt: latestRun?.startedAt ?? null,
1149 latestRunCompletedAt: latestRun?.completedAt ?? null,
1150 runtimeStatus: runtime?.status ?? null,
1151 runtimeUpdatedAt: runtime?.updatedAt ?? null,
1152 };
1154​
1155/**
1156 * The timeline renders committed user rows from `visibleTurnItems`, but
1157 * `message.updated` can land in `projection.messages` one event earlier than
1158 * the matching `turn-item.updated`. Basing optimistic eviction on visible user
1159 * turn items avoids dropping steer rows in that gap.
1160 */
1161export function deriveCommittedServerUserMessageIds(
1162 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1163): ReadonlySet<ChatMessage["id"]> {
1164 return new Set(
1165 visibleTurnItems.flatMap((row) =>
1166 row.item.type === "user_message" ? [row.item.messageId] : [],
1167 ),
1168 );
1170​
1171export function hasServerAcknowledgedLocalDispatch(input: {
1172 localDispatch: LocalDispatchSnapshot | null;
1173 phase: SessionPhase;
1174 latestRun: Thread["latestRun"] | null;
1175 latestUserMessageId?: ChatMessage["id"] | null;
1176 runtime: Thread["runtime"] | null;
1177 hasPendingApproval: boolean;
1178 hasPendingUserInput: boolean;
1179 threadError: string | null | undefined;
1180}): boolean {
1181 if (!input.localDispatch) {
1182 return false;
1184 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
1185 return true;
1187 if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") {
1188 return false;
1190​
1191 const latestRun = input.latestRun ?? null;
1192 const runtime = input.runtime ?? null;
1193 const latestUserMessageChanged =
1194 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
1195 const latestRunChanged =
1196 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
1197 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
1198 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
1199 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
1200​
1201 if (input.phase === "running") {
1202 if (latestUserMessageChanged) {
1203 return true;
1205 if (!latestRunChanged) {
1206 return false;
1208 if (latestRun?.startedAt === null || latestRun === null) {
1209 return false;
1211 if (
1212 runtime?.activeRunId !== null &&
1213 runtime?.activeRunId !== undefined &&
1214 latestRun?.runId !== runtime.activeRunId
1215 ) {
1216 return false;
1218 return true;
1220​
1221 return (
1222 latestRunChanged ||
1223 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
1224 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
1225 );
1227​
1228export function shouldRefocusComposerOnWindowFocus(
1229 activeElement:
1230 | (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })
1231 | null,
1232): boolean {
1233 if (activeElement === null || activeElement.tagName === "BODY") return true;
1234 if (
1235 activeElement.tagName === "INPUT" ||
1236 activeElement.tagName === "TEXTAREA" ||
1237 activeElement.tagName === "SELECT" ||
1238 activeElement.tagName === "IFRAME" ||
1239 activeElement.tagName === "WEBVIEW" ||
1240 activeElement.isContentEditable === true ||
1241 activeElement.getAttribute("role") === "textbox"
1242 ) {
1243 return false;
1245 return (
1246 activeElement.closest(
1247 '[role="dialog"], [role="alertdialog"], [role="application"], [data-slot$="-popup"], [data-terminal-owner]',
1248 ) === null
1249 );
1251​
1252export interface PlanFollowUpComposerSnapshot {
1253 readonly prompt: string;
1254 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
1255 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
1256 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1257 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
1259​
1260/**
1261 * The caller clears the composer before awaiting the send, so every field it
1262 * held has to be written back here: a dropped field silently discards user
1263 * context.
1264 */
1265export function restorePlanFollowUpComposer(input: {
1266 readonly snapshot: PlanFollowUpComposerSnapshot;
1267 readonly writePrompt: (prompt: string) => void;
1268 readonly writeTerminalContexts: (contexts: ReadonlyArray<TerminalContextDraft>) => void;
1269 readonly writeReviewComments: (comments: ReadonlyArray<ReviewCommentContext>) => void;
1270 readonly writePreviewAnnotations: (annotations: ReadonlyArray<PreviewAnnotationPayload>) => void;
1271 readonly writeThreadContexts: (records: ReadonlyArray<ThreadContextRecord>) => void;
1272 readonly resetCursor: (options: {
1273 cursor: number;
1274 prompt: string;
1275 detectTrigger: boolean;
1276 }) => void;
1277}): void {
1278 input.writePrompt(input.snapshot.prompt);
1279 input.writeTerminalContexts(input.snapshot.terminalContexts);
1280 input.writeReviewComments(input.snapshot.reviewComments);
1281 input.writePreviewAnnotations(input.snapshot.previewAnnotations);
1282 input.writeThreadContexts(input.snapshot.threadContexts);
1283 input.resetCursor({
1284 cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length),
1285 prompt: input.snapshot.prompt,
1286 detectTrigger: true,
1287 });
1289​
1290/**
1291 * Adds a directly sent preview annotation to the composer's images and
1292 * annotations. Its screenshot rides along only while the turn has room for
1293 * another attachment; over the cap the server rejects the whole turn.
1294 */
1295export function mergeDirectPreviewAnnotation(input: {
1296 readonly images: ReadonlyArray<ComposerImageAttachment>;
1297 readonly fileCount: number;
1298 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1299 readonly direct:
1300 | {
1301 readonly annotation: PreviewAnnotationPayload;
1302 readonly image: ComposerImageAttachment | null;
1304 | undefined;
1305}): {
1306 readonly images: ReadonlyArray<ComposerImageAttachment>;
1307 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1308} {
1309 const { direct } = input;
1310 if (!direct) return { images: input.images, previewAnnotations: input.previewAnnotations };
1311 const imageAlreadyAttached =
1312 direct.image !== null && input.images.some((image) => image.id === direct.image?.id);
1313 const imageAppended =
1314 direct.image !== null &&
1315 !imageAlreadyAttached &&
1316 input.images.length + input.fileCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
1317 const images = direct.image && imageAppended ? [...input.images, direct.image] : input.images;
1318 const previewAnnotations = input.previewAnnotations.some(
1319 (annotation) => annotation.id === direct.annotation.id,
1321 ? input.previewAnnotations
1322 : [
1323 ...input.previewAnnotations,
1325 ...direct.annotation,
1326 // Claim an attached crop only when the screenshot really rides
1327 // along; a cap-dropped image must not produce a lying prompt.
1328 screenshot:
1329 direct.annotation.screenshot && (imageAppended || imageAlreadyAttached)
1330 ? { ...direct.annotation.screenshot, dataUrl: "" }
1331 : null,
1332 },
1333 ];
1334 return { images, previewAnnotations };
1336​
1337export { isThreadWokeUnseen } from "@t3tools/client-runtime/state/thread-settled";