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