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

ChatView.logic.ts

680 lines21.6 KB

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