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

ChatView.logic.ts

647 lines20.7 KB

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