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

ChatView.logic.ts

710 lines23.3 KB

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