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

ChatView.logic.ts

817 lines26.6 KB

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