Open History to see the last commit
1import {
2 type AssetCreateUrlInput,
3 type AssetCreateUrlResult,
4 type ChatFileAttachment,
5 type EnvironmentId,
6 isProviderDriverKind,
7 ProjectId,
8 type MessageId,
9 type ModelSelection,
10 type ProviderInteractionMode,
11 type ProviderDriverKind,
12 type ServerProvider,
13 type ScopedProjectRef,
14 type ScopedThreadRef,
15 type ThreadId,
16 type TurnId,
17} from "@t3tools/contracts";
18import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
19import {
20 squashAtomCommandFailure,
21 type AtomCommandResult,
22} from "@t3tools/client-runtime/state/runtime";
23import { videoMimeType } from "@t3tools/shared/video";
24import {
25 appendCodexArtifactTemplateUsePrompt,
26 codexArtifactTemplateUsePrompt,
27 type CodexArtifactTemplate,
28} from "@t3tools/client-runtime/codex-artifact-templates";
29import {
30 type ChatMessage,
31 isImageAttachment,
32 type SessionPhase,
33 type Thread,
34 type ThreadShell,
35} from "../types";
36import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
37import * as Schema from "effect/Schema";
38import { appAtomRegistry } from "../rpc/atomRegistry";
39import { environmentThreadDetails } from "../state/threads";
40import {
41 filterTerminalContextsWithText,
42 stripInlineTerminalContextPlaceholders,
43 type TerminalContextDraft,
44} from "../lib/terminalContext";
45import type { DraftThreadEnvMode } from "../composerDraftStore";
46import type { ComposerSubmissionIntent } from "../composer-logic";
47import type { TimelineEntry } from "../session-logic";
48
49export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
50export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
51export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
52export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000;
53
54export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
55
56export function codexArtifactTemplatePromptToAppend(
57 currentDraft: string,
58 template: CodexArtifactTemplate,
59): string | null {
60 return appendCodexArtifactTemplateUsePrompt(currentDraft, template) === currentDraft
61 ? null
62 : codexArtifactTemplateUsePrompt(template);
63}
64
65export function shouldDockDraftHeroForSubmission(input: {
66 isDraftHeroState: boolean;
67 activeThreadKey: string | null;
68 submissionIntent: ComposerSubmissionIntent;
69}): boolean {
70 return (
71 input.submissionIntent === "foreground" &&
72 input.isDraftHeroState &&
73 input.activeThreadKey !== null
74 );
75}
76
77export function shouldReleaseTimelineAnchorForToolActivity(input: {
78 anchorMessageId: MessageId | null;
79 liveFollowEnabled: boolean;
80 runningTurnId: TurnId | null;
81 timelineEntries: ReadonlyArray<TimelineEntry>;
82}): boolean {
83 if (input.anchorMessageId === null || !input.liveFollowEnabled || input.runningTurnId === null) {
84 return false;
85 }
86
87 return input.timelineEntries.some((timelineEntry) => {
88 if (timelineEntry.kind !== "work" || timelineEntry.entry.turnId !== input.runningTurnId) {
89 return false;
90 }
91
92 const entry = timelineEntry.entry;
93 return (
94 entry.tone === "tool" ||
95 entry.itemType !== undefined ||
96 entry.requestKind !== undefined ||
97 (entry.command?.trim().length ?? 0) > 0
98 );
99 });
100}
101
102export function toolGroupConsumesUpwardNavigation(target: EventTarget | null): boolean {
103 const elementTarget = target instanceof Element ? target : null;
104 const group = elementTarget?.closest<HTMLElement>("[data-tool-group-scroll]");
105 if (!group) return false;
106
107 // A nested result or the group itself can consume an upward scroll.
108 for (let element = elementTarget; element; element = element.parentElement) {
109 if (element.scrollTop > 0) {
110 const overflowY = getComputedStyle(element).overflowY;
111 if (overflowY === "auto" || overflowY === "scroll") return true;
112 }
113 if (element === group) break;
114 }
115 return false;
116}
117
118export function resolveDraftHeroState(input: {
119 isLocalDraftThread: boolean;
120 hasTimelineEntries: boolean;
121 isWorking: boolean;
122 draftHeroDockRequested: boolean;
123 backgroundSubmissionPending: boolean;
124}): boolean {
125 if (input.backgroundSubmissionPending) {
126 return true;
127 }
128 return (
129 input.isLocalDraftThread &&
130 !input.hasTimelineEntries &&
131 !input.isWorking &&
132 !input.draftHeroDockRequested
133 );
134}
135
136export function resolveDraftPromotionNavigationTarget(input: {
137 serverThreadRef: ScopedThreadRef | null;
138 serverThread: Pick<Thread, "latestTurn" | "session"> | null | undefined;
139 backgroundSubmissionPending: boolean;
140}): ScopedThreadRef | null {
141 if (input.backgroundSubmissionPending) {
142 return null;
143 }
144 const sessionStatus = input.serverThread?.session?.status;
145 const turnStarted = input.serverThread?.latestTurn?.startedAt != null;
146 const startupStopped =
147 sessionStatus === "error" || sessionStatus === "stopped" || sessionStatus === "interrupted";
148 // Keep local preparation feedback mounted until the server can render the
149 // running turn or its startup error on the canonical thread route.
150 return turnStarted || startupStopped ? input.serverThreadRef : null;
151}
152
153export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
154 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
155 return () => globalThis.clearTimeout(timeoutId);
156}
157
158export function hasEnvironmentReconnectWarningGraceElapsed(
159 activeEnvironmentId: EnvironmentId | null,
160 elapsedEnvironmentId: EnvironmentId | null,
161): boolean {
162 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
163}
164
165export function startNewThreadForProject(
166 projectRef: ScopedProjectRef | null,
167 handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
168): boolean {
169 if (projectRef === null) return false;
170 void handleNewThread(projectRef);
171
172 return true;
173}
174
175export function resolveThreadMetadataUpdateForNextTurn(input: {
176 currentModelSelection: ModelSelection;
177 nextModelSelection?: ModelSelection;
178 currentBranch: string | null;
179 nextBranch?: string;
180}): {
181 modelSelection?: ModelSelection;
182 branch?: string;
183 worktreePath?: null;
184} | null {
185 const nextModelSelection = input.nextModelSelection;
186 const modelSelectionChanged =
187 nextModelSelection !== undefined &&
188 (nextModelSelection.model !== input.currentModelSelection.model ||
189 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
190 JSON.stringify(nextModelSelection.options ?? null) !==
191 JSON.stringify(input.currentModelSelection.options ?? null));
192 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
193 if (!modelSelectionChanged && !branchChanged) {
194 return null;
195 }
196 return {
197 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
198 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
199 };
200}
201
202export function buildLocalDraftThread(
203 threadId: ThreadId,
204 draftThread: DraftThreadState,
205 fallbackModelSelection: ModelSelection,
206): Thread {
207 return {
208 id: threadId,
209 environmentId: draftThread.environmentId,
210 projectId: draftThread.projectId,
211 title: "New thread",
212 modelSelection: fallbackModelSelection,
213 runtimeMode: draftThread.runtimeMode,
214 interactionMode: draftThread.interactionMode,
215 session: null,
216 messages: [],
217 createdAt: draftThread.createdAt,
218 updatedAt: draftThread.createdAt,
219 archivedAt: null,
220 settledOverride: null,
221 settledAt: null,
222 deletedAt: null,
223 latestTurn: null,
224 branch: draftThread.branch,
225 worktreePath: draftThread.worktreePath,
226 checkpoints: [],
227 activities: [],
228 proposedPlans: [],
229 };
230}
231
232export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
233 return {
234 ...shell,
235 messages: [],
236 proposedPlans: [],
237 activities: [],
238 checkpoints: [],
239 deletedAt: null,
240 };
241}
242
243export function shouldWriteThreadErrorToCurrentServerThread(input: {
244 activeServerThread:
245 | {
246 environmentId: EnvironmentId;
247 id: ThreadId;
248 }
249 | null
250 | undefined;
251 routeThreadRef: ScopedThreadRef;
252 targetThreadId: ThreadId;
253}): boolean {
254 return Boolean(
255 input.activeServerThread &&
256 input.targetThreadId === input.routeThreadRef.threadId &&
257 input.activeServerThread.environmentId === input.routeThreadRef.environmentId &&
258 input.activeServerThread.id === input.targetThreadId,
259 );
260}
261
262export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
263 threadId: ThreadId;
264 turnId?: TurnId;
265} {
266 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
267 return {
268 threadId: thread.id,
269 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
270 };
271}
272
273export function reconcileMountedTerminalThreadIds(input: {
274 currentThreadIds: ReadonlyArray<string>;
275 openThreadIds: ReadonlyArray<string>;
276 activeThreadId: string | null;
277 activeThreadTerminalOpen: boolean;
278 maxHiddenThreadCount?: number;
279}): string[] {
280 return reconcileRetainedMountedThreadIds({
281 currentThreadIds: input.currentThreadIds,
282 openThreadIds: input.openThreadIds,
283 activeThreadId: input.activeThreadId,
284 activeThreadOpen: input.activeThreadTerminalOpen,
285 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
286 });
287}
288
289export function reconcileRetainedMountedThreadIds(input: {
290 currentThreadIds: ReadonlyArray<string>;
291 openThreadIds: ReadonlyArray<string>;
292 activeThreadId: string | null;
293 activeThreadOpen: boolean;
294 maxHiddenThreadCount: number;
295 retainInactiveActiveThread?: boolean;
296}): string[] {
297 const openThreadIdSet = new Set(input.openThreadIds);
298 const hiddenThreadIds = input.currentThreadIds.filter(
299 (threadId) =>
300 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
301 openThreadIdSet.has(threadId),
302 );
303 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
304 const nextThreadIds =
305 hiddenThreadIds.length > maxHiddenThreadCount
306 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
307 : hiddenThreadIds;
308
309 if (
310 input.activeThreadId &&
311 input.activeThreadOpen &&
312 !nextThreadIds.includes(input.activeThreadId)
313 ) {
314 nextThreadIds.push(input.activeThreadId);
315 }
316
317 return nextThreadIds;
318}
319
320export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
321 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
322 return;
323 }
324 URL.revokeObjectURL(previewUrl);
325}
326
327/** Signs an attachment URL without reading its bytes, so video playback can request byte ranges. */
328export async function resolveFileAttachmentUrl(input: {
329 attachment: ChatFileAttachment;
330 environmentId: EnvironmentId;
331 httpBaseUrl: string;
332 createAssetUrl: (input: {
333 environmentId: EnvironmentId;
334 input: AssetCreateUrlInput;
335 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
336}): Promise<string> {
337 const { attachment } = input;
338 const result = await input.createAssetUrl({
339 environmentId: input.environmentId,
340 input: {
341 resource: {
342 _tag: "attachment",
343 attachmentId: attachment.id,
344 fileName: attachment.name,
345 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
346 },
347 },
348 });
349 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
350 const url = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
351 if (url === null) throw new Error("The environment returned an invalid attachment URL.");
352 return url;
353}
354
355export function isVideoPreviewRequestCurrent(
356 requestThreadKey: string,
357 currentThreadKey: string,
358 requestId: number,
359 currentRequestId: number,
360): boolean {
361 return requestThreadKey === currentThreadKey && requestId === currentRequestId;
362}
363
364export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
365 if (message.role !== "user" || !message.attachments) {
366 return;
367 }
368 for (const attachment of message.attachments) {
369 if (!isImageAttachment(attachment)) {
370 continue;
371 }
372 revokeBlobPreviewUrl(attachment.previewUrl);
373 }
374}
375
376export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
377 if (message.role !== "user" || !message.attachments) {
378 return [];
379 }
380 const previewUrls: string[] = [];
381 for (const attachment of message.attachments) {
382 if (!isImageAttachment(attachment)) continue;
383 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
384 previewUrls.push(attachment.previewUrl);
385 }
386 return previewUrls;
387}
388
389export interface PullRequestDialogState {
390 initialReference: string | null;
391 key: number;
392}
393
394export function readFileAsDataUrl(file: File): Promise<string> {
395 return new Promise((resolve, reject) => {
396 const reader = new FileReader();
397 reader.addEventListener("load", () => {
398 if (typeof reader.result === "string") {
399 resolve(reader.result);
400 return;
401 }
402 reject(new Error("Could not read image data."));
403 });
404 reader.addEventListener("error", () => {
405 reject(reader.error ?? new Error("Failed to read image."));
406 });
407 reader.readAsDataURL(file);
408 });
409}
410
411export function resolveSendEnvMode(input: {
412 requestedEnvMode: DraftThreadEnvMode;
413 isGitRepo: boolean;
414}): DraftThreadEnvMode {
415 return input.isGitRepo ? input.requestedEnvMode : "local";
416}
417
418export function resolveBackgroundDraftWorkspaceOptions(input: {
419 envMode: DraftThreadEnvMode;
420 branch: string | null;
421 startFromOrigin: boolean;
422}): {
423 envMode: DraftThreadEnvMode;
424 branch: string | null;
425 worktreePath: null;
426 startFromOrigin: boolean;
427} {
428 return {
429 envMode: input.envMode,
430 branch: input.branch,
431 worktreePath: null,
432 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
433 };
434}
435
436export function cloneComposerImageForRetry(
437 image: ComposerImageAttachment,
438): ComposerImageAttachment {
439 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
440 return image;
441 }
442 try {
443 return {
444 ...image,
445 previewUrl: URL.createObjectURL(image.file),
446 };
447 } catch {
448 return image;
449 }
450}
451
452export function deriveComposerSendState(options: {
453 prompt: string;
454 imageCount: number;
455 terminalContexts: ReadonlyArray<TerminalContextDraft>;
456 /**
457 * Optional element-pick attachment count. Element contexts contribute to
458 * "sendable content" exactly like images and (text-bearing) terminal
459 * contexts do: a prompt of just element chips is still a valid send.
460 */
461 elementContextCount?: number;
462}): {
463 trimmedPrompt: string;
464 sendableTerminalContexts: TerminalContextDraft[];
465 expiredTerminalContextCount: number;
466 hasSendableContent: boolean;
467} {
468 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
469 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
470 const expiredTerminalContextCount =
471 options.terminalContexts.length - sendableTerminalContexts.length;
472 const elementContextCount = options.elementContextCount ?? 0;
473 return {
474 trimmedPrompt,
475 sendableTerminalContexts,
476 expiredTerminalContextCount,
477 hasSendableContent:
478 trimmedPrompt.length > 0 ||
479 options.imageCount > 0 ||
480 sendableTerminalContexts.length > 0 ||
481 elementContextCount > 0,
482 };
483}
484
485export function buildExpiredTerminalContextToastCopy(
486 expiredTerminalContextCount: number,
487 variant: "omitted" | "empty",
488): { title: string; description: string } {
489 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
490 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
491 if (variant === "empty") {
492 return {
493 title: `${noun} won't be sent`,
494 description: "Remove it or re-add it to include terminal output.",
495 };
496 }
497 return {
498 title: `${noun} omitted from message`,
499 description: "Re-add it if you want that terminal output included.",
500 };
501}
502
503export function branchMismatchKey(
504 threadId: string | null,
505 mismatch: { threadBranch: string; currentBranch: string } | null,
506): string | null {
507 if (!threadId || !mismatch) {
508 return null;
509 }
510 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
511}
512
513// The mismatch banner only matters when the user is about to send: passive
514// reading of an old thread carries no risk (the branch picker tint already
515// covers ambient awareness). Draft content is the intent signal — composer
516// focus is useless here because ChatView autofocuses the composer on every
517// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
518// revealed so it doesn't flicker away when the draft is cleared.
519export function shouldShowBranchMismatchBanner(input: {
520 hasMismatch: boolean;
521 isDismissed: boolean;
522 composerHasContent: boolean;
523 wasShownForCurrentMismatch: boolean;
524}): boolean {
525 if (!input.hasMismatch || input.isDismissed) {
526 return false;
527 }
528 return input.composerHasContent || input.wasShownForCurrentMismatch;
529}
530
531export function shouldShowPlanFollowUpPrompt(input: {
532 pendingUserInputCount: number;
533 interactionMode: ProviderInteractionMode;
534 latestTurnSettled: boolean;
535 hasActionableProposedPlan: boolean;
536 hasComposerAttachments: boolean;
537}): boolean {
538 return (
539 input.pendingUserInputCount === 0 &&
540 input.interactionMode === "plan" &&
541 input.latestTurnSettled &&
542 input.hasActionableProposedPlan &&
543 !input.hasComposerAttachments
544 );
545}
546
547// Session-scoped (module-level so it survives ChatView remounts, e.g. route
548// changes). Durable cross-device dismissal is planned as a server-side ack.
549const sessionDismissedBranchMismatchKeys = new Set<string>();
550
551export function dismissBranchMismatchForSession(key: string): void {
552 sessionDismissedBranchMismatchKeys.add(key);
553}
554
555export function isBranchMismatchDismissedForSession(key: string | null): boolean {
556 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
557}
558
559export function threadHasStarted(thread: Thread | null | undefined): boolean {
560 return Boolean(
561 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
562 );
563}
564
565// `threadProvider` is the open branded driver kind carried by the session.
566// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe
567// rollback / fork behavior — the routing layer is the right place to surface
568// "driver not installed" errors, not the lock state.
569//
570// `selectedProvider` takes the same open-string shape because the composer
571// now tracks the picker selection as a `ProviderInstanceId` (e.g.
572// `codex_personal`). Custom instance ids that don't directly match a
573// registered driver resolve to `null` here, which matches the existing
574// "unknown driver -> unlocked" semantics. Callers that want the lock to track
575// a custom instance's underlying driver kind should resolve the instance id
576// upstream and pass the correlated kind.
577export function deriveLockedProvider(input: {
578 thread: Thread | null | undefined;
579 selectedProvider: string | null;
580 threadProvider: string | null;
581}): ProviderDriverKind | null {
582 if (!threadHasStarted(input.thread)) {
583 return null;
584 }
585 const sessionProvider = input.thread?.session?.providerName ?? null;
586 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
587 return sessionProvider;
588 }
589 const narrowedThreadProvider =
590 input.threadProvider && isProviderDriverKind(input.threadProvider)
591 ? input.threadProvider
592 : null;
593 const narrowedSelectedProvider =
594 input.selectedProvider && isProviderDriverKind(input.selectedProvider)
595 ? input.selectedProvider
596 : null;
597 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
598}
599
600export function getStartedThreadModelChangeBlockReason(input: {
601 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
602 hasStartedSession: boolean;
603 currentModelSelection: ModelSelection;
604 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
605 nextModelSelection: ModelSelection;
606}): { title: string; description: string } | null {
607 if (!input.hasStartedSession) {
608 return null;
609 }
610 const currentModelSelection = {
611 ...input.currentModelSelection,
612 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
613 };
614 if (
615 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
616 currentModelSelection.model === input.nextModelSelection.model
617 ) {
618 return null;
619 }
620 const currentProvider = input.providers.find(
621 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
622 );
623 const nextProvider = input.providers.find(
624 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
625 );
626 if (
627 currentProvider?.requiresNewThreadForModelChange !== true &&
628 nextProvider?.requiresNewThreadForModelChange !== true
629 ) {
630 return null;
631 }
632 return {
633 title: "Start a new chat to change models",
634 description: "This provider does not allow switching models after a conversation has started.",
635 };
636}
637
638export async function waitForStartedServerThread(
639 threadRef: ScopedThreadRef,
640 timeoutMs = 1_000,
641): Promise<boolean> {
642 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
643 const getThread = () => appAtomRegistry.get(threadAtom);
644 const thread = getThread();
645
646 if (threadHasStarted(thread)) {
647 return true;
648 }
649
650 return await new Promise<boolean>((resolve) => {
651 let settled = false;
652 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
653 const finish = (result: boolean) => {
654 if (settled) {
655 return;
656 }
657 settled = true;
658 if (timeoutId !== null) {
659 globalThis.clearTimeout(timeoutId);
660 }
661 unsubscribe();
662 resolve(result);
663 };
664
665 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
666 if (!threadHasStarted(thread)) {
667 return;
668 }
669 finish(true);
670 });
671
672 if (threadHasStarted(getThread())) {
673 finish(true);
674 return;
675 }
676
677 timeoutId = globalThis.setTimeout(() => {
678 finish(false);
679 }, timeoutMs);
680 });
681}
682
683export interface LocalDispatchSnapshot {
684 startedAt: string;
685 preparingWorktree: boolean;
686 submissionIntent: ComposerSubmissionIntent;
687 latestUserMessageId: ChatMessage["id"] | null;
688 latestTurnTurnId: TurnId | null;
689 latestTurnRequestedAt: string | null;
690 latestTurnStartedAt: string | null;
691 latestTurnCompletedAt: string | null;
692 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
693 sessionUpdatedAt: string | null;
694}
695
696export function createLocalDispatchSnapshot(
697 activeThread: Thread | undefined,
698 options?: {
699 preparingWorktree?: boolean;
700 submissionIntent?: ComposerSubmissionIntent;
701 },
702): LocalDispatchSnapshot {
703 const latestTurn = activeThread?.latestTurn ?? null;
704 const session = activeThread?.session ?? null;
705 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
706 return {
707 startedAt: new Date().toISOString(),
708 preparingWorktree: Boolean(options?.preparingWorktree),
709 submissionIntent: options?.submissionIntent ?? "foreground",
710 latestUserMessageId: latestUserMessage?.id ?? null,
711 latestTurnTurnId: latestTurn?.turnId ?? null,
712 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
713 latestTurnStartedAt: latestTurn?.startedAt ?? null,
714 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
715 sessionStatus: session?.status ?? null,
716 sessionUpdatedAt: session?.updatedAt ?? null,
717 };
718}
719
720export function hasServerAcknowledgedLocalDispatch(input: {
721 localDispatch: LocalDispatchSnapshot | null;
722 phase: SessionPhase;
723 latestTurn: Thread["latestTurn"] | null;
724 latestUserMessageId: ChatMessage["id"] | null;
725 session: Thread["session"] | null;
726 hasPendingApproval: boolean;
727 hasPendingUserInput: boolean;
728 threadError: string | null | undefined;
729}): boolean {
730 if (!input.localDispatch) {
731 return false;
732 }
733 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
734 return true;
735 }
736 if (input.phase === "connecting") {
737 return false;
738 }
739
740 const latestTurn = input.latestTurn ?? null;
741 const session = input.session ?? null;
742 const latestUserMessageChanged =
743 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
744 const latestTurnChanged =
745 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
746 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
747 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
748 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
749
750 if (input.phase === "running") {
751 // Steering adds a user message to the current running turn without
752 // necessarily changing any of the turn timestamps. Treat that projected
753 // message as the server acknowledgment so the composer does not remain
754 // stuck in its local "Sending" state until the turn settles.
755 if (latestUserMessageChanged) {
756 return true;
757 }
758 if (!latestTurnChanged) {
759 return false;
760 }
761 if (latestTurn?.startedAt === null || latestTurn === null) {
762 return false;
763 }
764 if (
765 session?.activeTurnId !== null &&
766 session?.activeTurnId !== undefined &&
767 latestTurn?.turnId !== session.activeTurnId
768 ) {
769 return false;
770 }
771 return true;
772 }
773
774 return (
775 latestTurnChanged ||
776 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
777 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
778 );
779}