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

ChatView.logic.ts

504 lines16.4 KB

1import {
2 type EnvironmentId,
3 isProviderDriverKind,
4 ProjectId,
5 type ModelSelection,
6 type ProviderDriverKind,
7 type ServerProvider,
8 type ScopedThreadRef,
9 type ThreadId,
10 type TurnId,
11} from "@t3tools/contracts";
12import { type ChatMessage, type SessionPhase, type Thread } from "../types";
13import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
14import * as Schema from "effect/Schema";
15import { appAtomRegistry } from "../rpc/atomRegistry";
16import { environmentThreadDetails } from "../state/threads";
17import {
18 filterTerminalContextsWithText,
19 stripInlineTerminalContextPlaceholders,
20 type TerminalContextDraft,
21} from "../lib/terminalContext";
22import type { DraftThreadEnvMode } from "../composerDraftStore";
23​
24export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
25export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
26export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
27​
28export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
29​
30export function resolveThreadMetadataUpdateForNextTurn(input: {
31 currentModelSelection: ModelSelection;
32 nextModelSelection?: ModelSelection;
33 currentBranch: string | null;
34 nextBranch?: string;
35}): {
36 modelSelection?: ModelSelection;
37 branch?: string;
38 worktreePath?: null;
39} | null {
40 const nextModelSelection = input.nextModelSelection;
41 const modelSelectionChanged =
42 nextModelSelection !== undefined &&
43 (nextModelSelection.model !== input.currentModelSelection.model ||
44 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
45 JSON.stringify(nextModelSelection.options ?? null) !==
46 JSON.stringify(input.currentModelSelection.options ?? null));
47 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
48 if (!modelSelectionChanged && !branchChanged) {
49 return null;
50 }
51 return {
52 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
53 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
54 };
56​
57export function buildLocalDraftThread(
58 threadId: ThreadId,
59 draftThread: DraftThreadState,
60 fallbackModelSelection: ModelSelection,
61): Thread {
62 return {
63 id: threadId,
64 environmentId: draftThread.environmentId,
65 projectId: draftThread.projectId,
66 title: "New thread",
67 modelSelection: fallbackModelSelection,
68 runtimeMode: draftThread.runtimeMode,
69 interactionMode: draftThread.interactionMode,
70 session: null,
71 messages: [],
72 createdAt: draftThread.createdAt,
73 updatedAt: draftThread.createdAt,
74 archivedAt: null,
75 settledOverride: null,
76 settledAt: null,
77 deletedAt: null,
78 latestTurn: null,
79 branch: draftThread.branch,
80 worktreePath: draftThread.worktreePath,
81 checkpoints: [],
82 activities: [],
83 proposedPlans: [],
84 };
86​
87export function shouldWriteThreadErrorToCurrentServerThread(input: {
88 serverThread:
89 | {
90 environmentId: EnvironmentId;
91 id: ThreadId;
92 }
93 | null
94 | undefined;
95 routeThreadRef: ScopedThreadRef;
96 targetThreadId: ThreadId;
97}): boolean {
98 return Boolean(
99 input.serverThread &&
100 input.targetThreadId === input.routeThreadRef.threadId &&
101 input.serverThread.environmentId === input.routeThreadRef.environmentId &&
102 input.serverThread.id === input.targetThreadId,
103 );
105​
106export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
107 threadId: ThreadId;
108 turnId?: TurnId;
109} {
110 const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
111 return {
112 threadId: thread.id,
113 ...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
114 };
116​
117export function reconcileMountedTerminalThreadIds(input: {
118 currentThreadIds: ReadonlyArray<string>;
119 openThreadIds: ReadonlyArray<string>;
120 activeThreadId: string | null;
121 activeThreadTerminalOpen: boolean;
122 maxHiddenThreadCount?: number;
123}): string[] {
124 return reconcileRetainedMountedThreadIds({
125 currentThreadIds: input.currentThreadIds,
126 openThreadIds: input.openThreadIds,
127 activeThreadId: input.activeThreadId,
128 activeThreadOpen: input.activeThreadTerminalOpen,
129 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
130 });
132​
133export function reconcileRetainedMountedThreadIds(input: {
134 currentThreadIds: ReadonlyArray<string>;
135 openThreadIds: ReadonlyArray<string>;
136 activeThreadId: string | null;
137 activeThreadOpen: boolean;
138 maxHiddenThreadCount: number;
139 retainInactiveActiveThread?: boolean;
140}): string[] {
141 const openThreadIdSet = new Set(input.openThreadIds);
142 const hiddenThreadIds = input.currentThreadIds.filter(
143 (threadId) =>
144 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
145 openThreadIdSet.has(threadId),
146 );
147 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
148 const nextThreadIds =
149 hiddenThreadIds.length > maxHiddenThreadCount
150 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
151 : hiddenThreadIds;
152​
153 if (
154 input.activeThreadId &&
155 input.activeThreadOpen &&
156 !nextThreadIds.includes(input.activeThreadId)
157 ) {
158 nextThreadIds.push(input.activeThreadId);
159 }
160​
161 return nextThreadIds;
163​
164export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
165 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
166 return;
167 }
168 URL.revokeObjectURL(previewUrl);
170​
171export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
172 if (message.role !== "user" || !message.attachments) {
173 return;
174 }
175 for (const attachment of message.attachments) {
176 if (attachment.type !== "image") {
177 continue;
178 }
179 revokeBlobPreviewUrl(attachment.previewUrl);
180 }
182​
183export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
184 if (message.role !== "user" || !message.attachments) {
185 return [];
186 }
187 const previewUrls: string[] = [];
188 for (const attachment of message.attachments) {
189 if (attachment.type !== "image") continue;
190 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
191 previewUrls.push(attachment.previewUrl);
192 }
193 return previewUrls;
195​
196export interface PullRequestDialogState {
197 initialReference: string | null;
198 key: number;
200​
201export function readFileAsDataUrl(file: File): Promise<string> {
202 return new Promise((resolve, reject) => {
203 const reader = new FileReader();
204 reader.addEventListener("load", () => {
205 if (typeof reader.result === "string") {
206 resolve(reader.result);
207 return;
208 }
209 reject(new Error("Could not read image data."));
210 });
211 reader.addEventListener("error", () => {
212 reject(reader.error ?? new Error("Failed to read image."));
213 });
214 reader.readAsDataURL(file);
215 });
217​
218export function resolveSendEnvMode(input: {
219 requestedEnvMode: DraftThreadEnvMode;
220 isGitRepo: boolean;
221}): DraftThreadEnvMode {
222 return input.isGitRepo ? input.requestedEnvMode : "local";
224​
225export function cloneComposerImageForRetry(
226 image: ComposerImageAttachment,
227): ComposerImageAttachment {
228 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
229 return image;
230 }
231 try {
232 return {
233 ...image,
234 previewUrl: URL.createObjectURL(image.file),
235 };
236 } catch {
237 return image;
238 }
240​
241export function deriveComposerSendState(options: {
242 prompt: string;
243 imageCount: number;
244 terminalContexts: ReadonlyArray<TerminalContextDraft>;
245 /**
246 * Optional element-pick attachment count. Element contexts contribute to
247 * "sendable content" exactly like images and (text-bearing) terminal
248 * contexts do: a prompt of just element chips is still a valid send.
249 */
250 elementContextCount?: number;
251}): {
252 trimmedPrompt: string;
253 sendableTerminalContexts: TerminalContextDraft[];
254 expiredTerminalContextCount: number;
255 hasSendableContent: boolean;
256} {
257 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
258 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
259 const expiredTerminalContextCount =
260 options.terminalContexts.length - sendableTerminalContexts.length;
261 const elementContextCount = options.elementContextCount ?? 0;
262 return {
263 trimmedPrompt,
264 sendableTerminalContexts,
265 expiredTerminalContextCount,
266 hasSendableContent:
267 trimmedPrompt.length > 0 ||
268 options.imageCount > 0 ||
269 sendableTerminalContexts.length > 0 ||
270 elementContextCount > 0,
271 };
273​
274export function buildExpiredTerminalContextToastCopy(
275 expiredTerminalContextCount: number,
276 variant: "omitted" | "empty",
277): { title: string; description: string } {
278 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
279 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
280 if (variant === "empty") {
281 return {
282 title: `${noun} won't be sent`,
283 description: "Remove it or re-add it to include terminal output.",
284 };
285 }
286 return {
287 title: `${noun} omitted from message`,
288 description: "Re-add it if you want that terminal output included.",
289 };
291​
292export function threadHasStarted(thread: Thread | null | undefined): boolean {
293 return Boolean(
294 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
295 );
297​
298// `threadProvider` is the open branded driver kind carried by the session.
299// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe
300// rollback / fork behavior — the routing layer is the right place to surface
301// "driver not installed" errors, not the lock state.
302//
303// `selectedProvider` takes the same open-string shape because the composer
304// now tracks the picker selection as a `ProviderInstanceId` (e.g.
305// `codex_personal`). Custom instance ids that don't directly match a
306// registered driver resolve to `null` here, which matches the existing
307// "unknown driver -> unlocked" semantics. Callers that want the lock to track
308// a custom instance's underlying driver kind should resolve the instance id
309// upstream and pass the correlated kind.
310export function deriveLockedProvider(input: {
311 thread: Thread | null | undefined;
312 selectedProvider: string | null;
313 threadProvider: string | null;
314}): ProviderDriverKind | null {
315 if (!threadHasStarted(input.thread)) {
316 return null;
317 }
318 const sessionProvider = input.thread?.session?.providerName ?? null;
319 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
320 return sessionProvider;
321 }
322 const narrowedThreadProvider =
323 input.threadProvider && isProviderDriverKind(input.threadProvider)
324 ? input.threadProvider
325 : null;
326 const narrowedSelectedProvider =
327 input.selectedProvider && isProviderDriverKind(input.selectedProvider)
328 ? input.selectedProvider
329 : null;
330 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
332​
333export function getStartedThreadModelChangeBlockReason(input: {
334 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
335 hasStartedSession: boolean;
336 currentModelSelection: ModelSelection;
337 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
338 nextModelSelection: ModelSelection;
339}): { title: string; description: string } | null {
340 if (!input.hasStartedSession) {
341 return null;
342 }
343 const currentModelSelection = {
344 ...input.currentModelSelection,
345 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
346 };
347 if (
348 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
349 currentModelSelection.model === input.nextModelSelection.model
350 ) {
351 return null;
352 }
353 const currentProvider = input.providers.find(
354 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
355 );
356 const nextProvider = input.providers.find(
357 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
358 );
359 if (
360 currentProvider?.requiresNewThreadForModelChange !== true &&
361 nextProvider?.requiresNewThreadForModelChange !== true
362 ) {
363 return null;
364 }
365 return {
366 title: "Start a new chat to change models",
367 description: "This provider does not allow switching models after a conversation has started.",
368 };
370​
371export async function waitForStartedServerThread(
372 threadRef: ScopedThreadRef,
373 timeoutMs = 1_000,
374): Promise<boolean> {
375 const threadAtom = environmentThreadDetails.detailAtom(threadRef);
376 const getThread = () => appAtomRegistry.get(threadAtom);
377 const thread = getThread();
378​
379 if (threadHasStarted(thread)) {
380 return true;
381 }
382​
383 return await new Promise<boolean>((resolve) => {
384 let settled = false;
385 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
386 const finish = (result: boolean) => {
387 if (settled) {
388 return;
389 }
390 settled = true;
391 if (timeoutId !== null) {
392 globalThis.clearTimeout(timeoutId);
393 }
394 unsubscribe();
395 resolve(result);
396 };
397​
398 const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => {
399 if (!threadHasStarted(thread)) {
400 return;
401 }
402 finish(true);
403 });
404​
405 if (threadHasStarted(getThread())) {
406 finish(true);
407 return;
408 }
409​
410 timeoutId = globalThis.setTimeout(() => {
411 finish(false);
412 }, timeoutMs);
413 });
415​
416export interface LocalDispatchSnapshot {
417 startedAt: string;
418 preparingWorktree: boolean;
419 latestUserMessageId: ChatMessage["id"] | null;
420 latestTurnTurnId: TurnId | null;
421 latestTurnRequestedAt: string | null;
422 latestTurnStartedAt: string | null;
423 latestTurnCompletedAt: string | null;
424 sessionStatus: NonNullable<Thread["session"]>["status"] | null;
425 sessionUpdatedAt: string | null;
427​
428export function createLocalDispatchSnapshot(
429 activeThread: Thread | undefined,
430 options?: { preparingWorktree?: boolean },
431): LocalDispatchSnapshot {
432 const latestTurn = activeThread?.latestTurn ?? null;
433 const session = activeThread?.session ?? null;
434 const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
435 return {
436 startedAt: new Date().toISOString(),
437 preparingWorktree: Boolean(options?.preparingWorktree),
438 latestUserMessageId: latestUserMessage?.id ?? null,
439 latestTurnTurnId: latestTurn?.turnId ?? null,
440 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
441 latestTurnStartedAt: latestTurn?.startedAt ?? null,
442 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
443 sessionStatus: session?.status ?? null,
444 sessionUpdatedAt: session?.updatedAt ?? null,
445 };
447​
448export function hasServerAcknowledgedLocalDispatch(input: {
449 localDispatch: LocalDispatchSnapshot | null;
450 phase: SessionPhase;
451 latestTurn: Thread["latestTurn"] | null;
452 latestUserMessageId: ChatMessage["id"] | null;
453 session: Thread["session"] | null;
454 hasPendingApproval: boolean;
455 hasPendingUserInput: boolean;
456 threadError: string | null | undefined;
457}): boolean {
458 if (!input.localDispatch) {
459 return false;
460 }
461 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
462 return true;
463 }
464​
465 const latestTurn = input.latestTurn ?? null;
466 const session = input.session ?? null;
467 const latestUserMessageChanged =
468 input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
469 const latestTurnChanged =
470 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
471 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
472 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
473 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
474​
475 if (input.phase === "running") {
476 // Steering adds a user message to the current running turn without
477 // necessarily changing any of the turn timestamps. Treat that projected
478 // message as the server acknowledgment so the composer does not remain
479 // stuck in its local "Sending" state until the turn settles.
480 if (latestUserMessageChanged) {
481 return true;
482 }
483 if (!latestTurnChanged) {
484 return false;
485 }
486 if (latestTurn?.startedAt === null || latestTurn === null) {
487 return false;
488 }
489 if (
490 session?.activeTurnId !== null &&
491 session?.activeTurnId !== undefined &&
492 latestTurn?.turnId !== session.activeTurnId
493 ) {
494 return false;
495 }
496 return true;
497 }
498​
499 return (
500 latestTurnChanged ||
501 input.localDispatch.sessionStatus !== (session?.status ?? null) ||
502 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
503 );