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