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

ChatView.logic.ts

697 lines22.1 KB

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