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

ChatView.logic.ts

708 lines22.5 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 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 );
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 );
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 });
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 );
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;
118​
119export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void {
120 const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS);
121 return () => globalThis.clearTimeout(timeoutId);
123​
124export function hasEnvironmentReconnectWarningGraceElapsed(
125 activeEnvironmentId: EnvironmentId | null,
126 elapsedEnvironmentId: EnvironmentId | null,
127): boolean {
128 return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId;
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;
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 };
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 };
197​
198export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
199 return {
200 ...shell,
201 messages: [],
202 proposedPlans: [],
203 activities: [],
204 checkpoints: [],
205 deletedAt: null,
206 };
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 );
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 };
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 });
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;
285​
286export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
287 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
288 return;
289 }
290 URL.revokeObjectURL(previewUrl);
292​
293export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
294 if (message.role !== "user" || !message.attachments) {
295 return;
296 }
297 for (const attachment of message.attachments) {
298 if (!isImageAttachment(attachment)) {
299 continue;
300 }
301 revokeBlobPreviewUrl(attachment.previewUrl);
302 }
304​
305export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
306 if (message.role !== "user" || !message.attachments) {
307 return [];
308 }
309 const previewUrls: string[] = [];
310 for (const attachment of message.attachments) {
311 if (!isImageAttachment(attachment)) continue;
312 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
313 previewUrls.push(attachment.previewUrl);
314 }
315 return previewUrls;
317​
318export interface PullRequestDialogState {
319 initialReference: string | null;
320 key: number;
322​
323export function readFileAsDataUrl(file: File): Promise<string> {
324 return new Promise((resolve, reject) => {
325 const reader = new FileReader();
326 reader.addEventListener("load", () => {
327 if (typeof reader.result === "string") {
328 resolve(reader.result);
329 return;
330 }
331 reject(new Error("Could not read image data."));
332 });
333 reader.addEventListener("error", () => {
334 reject(reader.error ?? new Error("Failed to read image."));
335 });
336 reader.readAsDataURL(file);
337 });
339​
340export function resolveSendEnvMode(input: {
341 requestedEnvMode: DraftThreadEnvMode;
342 isGitRepo: boolean;
343}): DraftThreadEnvMode {
344 return input.isGitRepo ? input.requestedEnvMode : "local";
346​
347export function resolveBackgroundDraftWorkspaceOptions(input: {
348 envMode: DraftThreadEnvMode;
349 branch: string | null;
350 startFromOrigin: boolean;
351}): {
352 envMode: DraftThreadEnvMode;
353 branch: string | null;
354 worktreePath: null;
355 startFromOrigin: boolean;
356} {
357 return {
358 envMode: input.envMode,
359 branch: input.branch,
360 worktreePath: null,
361 startFromOrigin: input.envMode === "worktree" && input.startFromOrigin,
362 };
364​
365export function cloneComposerImageForRetry(
366 image: ComposerImageAttachment,
367): ComposerImageAttachment {
368 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
369 return image;
370 }
371 try {
372 return {
373 ...image,
374 previewUrl: URL.createObjectURL(image.file),
375 };
376 } catch {
377 return image;
378 }
380​
381export function deriveComposerSendState(options: {
382 prompt: string;
383 imageCount: number;
384 terminalContexts: ReadonlyArray<TerminalContextDraft>;
385 /**
386 * Optional element-pick attachment count. Element contexts contribute to
387 * "sendable content" exactly like images and (text-bearing) terminal
388 * contexts do: a prompt of just element chips is still a valid send.
389 */
390 elementContextCount?: number;
391}): {
392 trimmedPrompt: string;
393 sendableTerminalContexts: TerminalContextDraft[];
394 expiredTerminalContextCount: number;
395 hasSendableContent: boolean;
396} {
397 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
398 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
399 const expiredTerminalContextCount =
400 options.terminalContexts.length - sendableTerminalContexts.length;
401 const elementContextCount = options.elementContextCount ?? 0;
402 return {
403 trimmedPrompt,
404 sendableTerminalContexts,
405 expiredTerminalContextCount,
406 hasSendableContent:
407 trimmedPrompt.length > 0 ||
408 options.imageCount > 0 ||
409 sendableTerminalContexts.length > 0 ||
410 elementContextCount > 0,
411 };
413​
414export function buildExpiredTerminalContextToastCopy(
415 expiredTerminalContextCount: number,
416 variant: "omitted" | "empty",
417): { title: string; description: string } {
418 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
419 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
420 if (variant === "empty") {
421 return {
422 title: `${noun} won't be sent`,
423 description: "Remove it or re-add it to include terminal output.",
424 };
425 }
426 return {
427 title: `${noun} omitted from message`,
428 description: "Re-add it if you want that terminal output included.",
429 };
431​
432export function branchMismatchKey(
433 threadId: string | null,
434 mismatch: { threadBranch: string; currentBranch: string } | null,
435): string | null {
436 if (!threadId || !mismatch) {
437 return null;
438 }
439 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
441​
442// The mismatch banner only matters when the user is about to send: passive
443// reading of an old thread carries no risk (the branch picker tint already
444// covers ambient awareness). Draft content is the intent signal — composer
445// focus is useless here because ChatView autofocuses the composer on every
446// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
447// revealed so it doesn't flicker away when the draft is cleared.
448export function shouldShowBranchMismatchBanner(input: {
449 hasMismatch: boolean;
450 isDismissed: boolean;
451 composerHasContent: boolean;
452 wasShownForCurrentMismatch: boolean;
453}): boolean {
454 if (!input.hasMismatch || input.isDismissed) {
455 return false;
456 }
457 return input.composerHasContent || input.wasShownForCurrentMismatch;
459​
460export function shouldShowPlanFollowUpPrompt(input: {
461 pendingUserInputCount: number;
462 interactionMode: ProviderInteractionMode;
463 latestTurnSettled: boolean;
464 hasActionableProposedPlan: boolean;
465 hasComposerAttachments: boolean;
466}): boolean {
467 return (
468 input.pendingUserInputCount === 0 &&
469 input.interactionMode === "plan" &&
470 input.latestTurnSettled &&
471 input.hasActionableProposedPlan &&
472 !input.hasComposerAttachments
473 );
475​
476// Session-scoped (module-level so it survives ChatView remounts, e.g. route
477// changes). Durable cross-device dismissal is planned as a server-side ack.
478const sessionDismissedBranchMismatchKeys = new Set<string>();
479​
480export function dismissBranchMismatchForSession(key: string): void {
481 sessionDismissedBranchMismatchKeys.add(key);
483​
484export function isBranchMismatchDismissedForSession(key: string | null): boolean {
485 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
487​
488export function threadHasStarted(thread: Thread | null | undefined): boolean {
489 return Boolean(
490 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
491 );
493​
494// `threadProvider` is the open branded driver kind carried by the session.
495// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe
496// rollback / fork behavior — the routing layer is the right place to surface
497// "driver not installed" errors, not the lock state.
498//
499// `selectedProvider` takes the same open-string shape because the composer
500// now tracks the picker selection as a `ProviderInstanceId` (e.g.
501// `codex_personal`). Custom instance ids that don't directly match a
502// registered driver resolve to `null` here, which matches the existing
503// "unknown driver -> unlocked" semantics. Callers that want the lock to track
504// a custom instance's underlying driver kind should resolve the instance id
505// upstream and pass the correlated kind.
506export function deriveLockedProvider(input: {
507 thread: Thread | null | undefined;
508 selectedProvider: string | null;
509 threadProvider: string | null;
510}): ProviderDriverKind | null {
511 if (!threadHasStarted(input.thread)) {
512 return null;
513 }
514 const sessionProvider = input.thread?.session?.providerName ?? null;
515 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
516 return sessionProvider;
517 }
518 const narrowedThreadProvider =
519 input.threadProvider && isProviderDriverKind(input.threadProvider)
520 ? input.threadProvider
521 : null;
522 const narrowedSelectedProvider =
523 input.selectedProvider && isProviderDriverKind(input.selectedProvider)
524 ? input.selectedProvider
525 : null;
526 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
528​
529export function getStartedThreadModelChangeBlockReason(input: {
530 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
531 hasStartedSession: boolean;
532 currentModelSelection: ModelSelection;
533 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
534 nextModelSelection: ModelSelection;
535}): { title: string; description: string } | null {
536 if (!input.hasStartedSession) {
537 return null;
538 }
539 const currentModelSelection = {
540 ...input.currentModelSelection,
541 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
542 };
543 if (
544 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
545 currentModelSelection.model === input.nextModelSelection.model
546 ) {
547 return null;
548 }
549 const currentProvider = input.providers.find(
550 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
551 );
552 const nextProvider = input.providers.find(
553 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
554 );
555 if (
556 currentProvider?.requiresNewThreadForModelChange !== true &&
557 nextProvider?.requiresNewThreadForModelChange !== true
558 ) {
559 return null;
560 }
561 return {
562 title: "Start a new chat to change models",
563 description: "This provider does not allow switching models after a conversation has started.",
564 };
566​
567export async function waitForStartedServerThread(
568 threadRef: ScopedThreadRef,
569 timeoutMs = 1_000,
570): Promise<boolean> {
571 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
572 const getThread = () => appAtomRegistry.get(threadAtom);
573 const thread = getThread();
574​
575 if (threadHasStarted(thread)) {
576 return true;
577 }
578​
579 return await new Promise<boolean>((resolve) => {
580 let settled = false;
581 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
582 const finish = (result: boolean) => {
583 if (settled) {
584 return;
585 }
586 settled = true;
587 if (timeoutId !== null) {
588 globalThis.clearTimeout(timeoutId);
589 }
590 unsubscribe();
591 resolve(result);
592 };
593​
594 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
595 if (!threadHasStarted(thread)) {
596 return;
597 }
598 finish(true);
599 });
600​
601 if (threadHasStarted(getThread())) {
602 finish(true);
603 return;
604 }
605​
606 timeoutId = globalThis.setTimeout(() => {
607 finish(false);
608 }, timeoutMs);
609 });
611​
612export interface LocalDispatchSnapshot {
613 startedAt: string;
614 preparingWorktree: boolean;
615 submissionIntent: ComposerSubmissionIntent;
616 latestUserMessageId: ChatMessage["id"] | null;
617 latestTurnTurnId: TurnId | null;
618 latestTurnRequestedAt: string | null;
619 latestTurnStartedAt: string | null;
620 latestTurnCompletedAt: string | null;
621 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
622 sessionUpdatedAt: string | null;
624​
625export function createLocalDispatchSnapshot(
626 activeThread: Thread | undefined,
627 options?: {
628 preparingWorktree?: boolean;
629 submissionIntent?: ComposerSubmissionIntent;
630 },
631): LocalDispatchSnapshot {
632 const latestTurn = activeThread?.latestTurn ?? null;
633 const session = activeThread?.session ?? null;
634 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
635 return {
636 startedAt: new Date().toISOString(),
637 preparingWorktree: Boolean(options?.preparingWorktree),
638 submissionIntent: options?.submissionIntent ?? "foreground",
639 latestUserMessageId: latestUserMessage?.id ?? null,
640 latestTurnTurnId: latestTurn?.turnId ?? null,
641 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
642 latestTurnStartedAt: latestTurn?.startedAt ?? null,
643 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
644 sessionStatus: session?.status ?? null,
645 sessionUpdatedAt: session?.updatedAt ?? null,
646 };
648​
649export function hasServerAcknowledgedLocalDispatch(input: {
650 localDispatch: LocalDispatchSnapshot | null;
651 phase: SessionPhase;
652 latestTurn: Thread["latestTurn"] | null;
653 latestUserMessageId: ChatMessage["id"] | null;
654 session: Thread["session"] | null;
655 hasPendingApproval: boolean;
656 hasPendingUserInput: boolean;
657 threadError: string | null | undefined;
658}): boolean {
659 if (!input.localDispatch) {
660 return false;
661 }
662 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
663 return true;
664 }
665 if (input.phase === "connecting") {
666 return false;
667 }
668​
669 const latestTurn = input.latestTurn ?? null;
670 const session = input.session ?? null;
671 const latestUserMessageChanged =
672 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
673 const latestTurnChanged =
674 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
675 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
676 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
677 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
678​
679 if (input.phase === "running") {
680 // Steering adds a user message to the current running turn without
681 // necessarily changing any of the turn timestamps. Treat that projected
682 // message as the server acknowledgment so the composer does not remain
683 // stuck in its local "Sending" state until the turn settles.
684 if (latestUserMessageChanged) {
685 return true;
686 }
687 if (!latestTurnChanged) {
688 return false;
689 }
690 if (latestTurn?.startedAt === null || latestTurn === null) {
691 return false;
692 }
693 if (
694 session?.activeTurnId !== null &&
695 session?.activeTurnId !== undefined &&
696 latestTurn?.turnId !== session.activeTurnId
697 ) {
698 return false;
699 }
700 return true;
701 }
702​
703 return (
704 latestTurnChanged ||
705 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
706 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
707 );