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

ChatView.logic.ts

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