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

ChatView.logic.ts

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