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

ChatView.logic.ts

552 lines18.5 KB

1import {
2 type EnvironmentId,
3 isProviderDriverKind,
4 ProjectId,
5 type ModelSelection,
6 type OrchestrationV2ProjectedTurnItem,
7 type ProviderDriverKind,
8 type ServerProvider,
9 type ScopedProjectRef,
10 type ScopedThreadRef,
11 type ThreadId,
12 type RunId,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
16import { type ChatMessage, type SessionPhase, type Thread } from "../types";
17import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
18import * as Schema from "effect/Schema";
19import { appAtomRegistry } from "../rpc/atomRegistry";
20import { environmentThreadShells } from "../state/threads";
21import { waitForAtomValue } from "../state/waitForAtomValue";
22import {
23 filterTerminalContextsWithText,
24 stripInlineTerminalContextPlaceholders,
25 type TerminalContextDraft,
26} from "../lib/terminalContext";
27import type { DraftThreadEnvMode } from "../composerDraftStore";
28​
29export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
30export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
31export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
32​
33export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
34​
35export function startNewThreadForProject(
36 projectRef: ScopedProjectRef | null,
37 handleNewThread: (projectRef: ScopedProjectRef) => Promise<void>,
38): boolean {
39 if (projectRef === null) return false;
40 void handleNewThread(projectRef);
41​
42 return true;
44​
45export function resolveThreadMetadataUpdateForNextTurn(input: {
46 currentModelSelection: ModelSelection;
47 nextModelSelection?: ModelSelection;
48 currentBranch: string | null;
49 nextBranch?: string;
50}): {
51 modelSelection?: ModelSelection;
52 branch?: string;
53 worktreePath?: null;
54} | null {
55 const nextModelSelection = input.nextModelSelection;
56 const modelSelectionChanged =
57 nextModelSelection !== undefined &&
58 (nextModelSelection.model !== input.currentModelSelection.model ||
59 nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
60 JSON.stringify(nextModelSelection.options ?? null) !==
61 JSON.stringify(input.currentModelSelection.options ?? null));
62 const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
63 if (!modelSelectionChanged && !branchChanged) {
64 return null;
65 }
66 return {
67 ...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
68 ...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
69 };
71​
72export function buildLocalDraftThread(
73 threadId: ThreadId,
74 draftThread: DraftThreadState,
75 fallbackModelSelection: ModelSelection,
76): Thread {
77 const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
78 return presentThreadShell(draftThread.environmentId, {
79 id: threadId,
80 projectId: draftThread.projectId,
81 title: "New thread",
82 providerInstanceId: fallbackModelSelection.instanceId,
83 modelSelection: fallbackModelSelection,
84 runtimeMode: draftThread.runtimeMode,
85 interactionMode: draftThread.interactionMode,
86 branch: draftThread.branch,
87 worktreePath: draftThread.worktreePath,
88 activeProviderThreadId: null,
89 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
90 forkedFrom: null,
91 createdBy: "user",
92 creationSource: "web",
93 latestRunId: null,
94 activeRunId: null,
95 status: "idle",
96 pendingRuntimeRequest: null,
97 latestVisibleMessage: null,
98 latestUserMessageAt: null,
99 hasActionableProposedPlan: false,
100 itemCount: 0,
101 visibleItemCount: 0,
102 createdAt: timestamp,
103 updatedAt: timestamp,
104 archivedAt: null,
105 settledOverride: null,
106 settledAt: null,
107 deletedAt: null,
108 });
110​
111export function shouldWriteThreadErrorToCurrentServerThread(input: {
112 serverThread:
113 | {
114 environmentId: EnvironmentId;
115 id: ThreadId;
116 }
117 | null
118 | undefined;
119 routeThreadRef: ScopedThreadRef;
120 targetThreadId: ThreadId;
121}): boolean {
122 return Boolean(
123 input.serverThread &&
124 input.targetThreadId === input.routeThreadRef.threadId &&
125 input.serverThread.environmentId === input.routeThreadRef.environmentId &&
126 input.serverThread.id === input.targetThreadId,
127 );
129​
130export function reconcileMountedTerminalThreadIds(input: {
131 currentThreadIds: ReadonlyArray<string>;
132 openThreadIds: ReadonlyArray<string>;
133 activeThreadId: string | null;
134 activeThreadTerminalOpen: boolean;
135 maxHiddenThreadCount?: number;
136}): string[] {
137 return reconcileRetainedMountedThreadIds({
138 currentThreadIds: input.currentThreadIds,
139 openThreadIds: input.openThreadIds,
140 activeThreadId: input.activeThreadId,
141 activeThreadOpen: input.activeThreadTerminalOpen,
142 maxHiddenThreadCount: input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
143 });
145​
146export function reconcileRetainedMountedThreadIds(input: {
147 currentThreadIds: ReadonlyArray<string>;
148 openThreadIds: ReadonlyArray<string>;
149 activeThreadId: string | null;
150 activeThreadOpen: boolean;
151 maxHiddenThreadCount: number;
152 retainInactiveActiveThread?: boolean;
153}): string[] {
154 const openThreadIdSet = new Set(input.openThreadIds);
155 const hiddenThreadIds = input.currentThreadIds.filter(
156 (threadId) =>
157 (threadId !== input.activeThreadId || input.retainInactiveActiveThread === true) &&
158 openThreadIdSet.has(threadId),
159 );
160 const maxHiddenThreadCount = Math.max(0, input.maxHiddenThreadCount);
161 const nextThreadIds =
162 hiddenThreadIds.length > maxHiddenThreadCount
163 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
164 : hiddenThreadIds;
165​
166 if (
167 input.activeThreadId &&
168 input.activeThreadOpen &&
169 !nextThreadIds.includes(input.activeThreadId)
170 ) {
171 nextThreadIds.push(input.activeThreadId);
172 }
173​
174 return nextThreadIds;
176​
177export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
178 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
179 return;
180 }
181 URL.revokeObjectURL(previewUrl);
183​
184export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
185 if (message.role !== "user" || !message.attachments) {
186 return;
187 }
188 for (const attachment of message.attachments) {
189 if (attachment.type !== "image") {
190 continue;
191 }
192 revokeBlobPreviewUrl(attachment.previewUrl);
193 }
195​
196export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
197 if (message.role !== "user" || !message.attachments) {
198 return [];
199 }
200 const previewUrls: string[] = [];
201 for (const attachment of message.attachments) {
202 if (attachment.type !== "image") continue;
203 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
204 previewUrls.push(attachment.previewUrl);
205 }
206 return previewUrls;
208​
209export interface PullRequestDialogState {
210 initialReference: string | null;
211 key: number;
213​
214export function readFileAsDataUrl(file: File): Promise<string> {
215 return new Promise((resolve, reject) => {
216 const reader = new FileReader();
217 reader.addEventListener("load", () => {
218 if (typeof reader.result === "string") {
219 resolve(reader.result);
220 return;
221 }
222 reject(new Error("Could not read image data."));
223 });
224 reader.addEventListener("error", () => {
225 reject(reader.error ?? new Error("Failed to read image."));
226 });
227 reader.readAsDataURL(file);
228 });
230​
231export function resolveSendEnvMode(input: {
232 requestedEnvMode: DraftThreadEnvMode;
233 isGitRepo: boolean;
234}): DraftThreadEnvMode {
235 return input.isGitRepo ? input.requestedEnvMode : "local";
237​
238export function shouldShowComposerContextStrip(input: {
239 routeKind: "draft" | "server";
240 isGitRepo: boolean;
241 hasActiveProject: boolean;
242}): boolean {
243 return input.routeKind === "draft" && input.isGitRepo && input.hasActiveProject;
245​
246export function cloneComposerImageForRetry(
247 image: ComposerImageAttachment,
248): ComposerImageAttachment {
249 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
250 return image;
251 }
252 try {
253 return {
254 ...image,
255 previewUrl: URL.createObjectURL(image.file),
256 };
257 } catch {
258 return image;
259 }
261​
262export function deriveComposerSendState(options: {
263 prompt: string;
264 imageCount: number;
265 terminalContexts: ReadonlyArray<TerminalContextDraft>;
266 /**
267 * Optional element-pick attachment count. Element contexts contribute to
268 * "sendable content" exactly like images and (text-bearing) terminal
269 * contexts do: a prompt of just element chips is still a valid send.
270 */
271 elementContextCount?: number;
272}): {
273 trimmedPrompt: string;
274 sendableTerminalContexts: TerminalContextDraft[];
275 expiredTerminalContextCount: number;
276 hasSendableContent: boolean;
277} {
278 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
279 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
280 const expiredTerminalContextCount =
281 options.terminalContexts.length - sendableTerminalContexts.length;
282 const elementContextCount = options.elementContextCount ?? 0;
283 return {
284 trimmedPrompt,
285 sendableTerminalContexts,
286 expiredTerminalContextCount,
287 hasSendableContent:
288 trimmedPrompt.length > 0 ||
289 options.imageCount > 0 ||
290 sendableTerminalContexts.length > 0 ||
291 elementContextCount > 0,
292 };
294​
295export function buildExpiredTerminalContextToastCopy(
296 expiredTerminalContextCount: number,
297 variant: "omitted" | "empty",
298): { title: string; description: string } {
299 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
300 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
301 if (variant === "empty") {
302 return {
303 title: `${noun} won't be sent`,
304 description: "Remove it or re-add it to include terminal output.",
305 };
306 }
307 return {
308 title: `${noun} omitted from message`,
309 description: "Re-add it if you want that terminal output included.",
310 };
312​
313export function branchMismatchKey(
314 threadId: string | null,
315 mismatch: { threadBranch: string; currentBranch: string } | null,
316): string | null {
317 if (!threadId || !mismatch) {
318 return null;
319 }
320 return `${threadId}:${mismatch.threadBranch}:${mismatch.currentBranch}`;
322​
323// The mismatch banner only matters when the user is about to send: passive
324// reading of an old thread carries no risk (the branch picker tint already
325// covers ambient awareness). Draft content is the intent signal — composer
326// focus is useless here because ChatView autofocuses the composer on every
327// thread open. `wasShownForCurrentMismatch` keeps the banner mounted once
328// revealed so it doesn't flicker away when the draft is cleared.
329export function shouldShowBranchMismatchBanner(input: {
330 hasMismatch: boolean;
331 isDismissed: boolean;
332 composerHasContent: boolean;
333 wasShownForCurrentMismatch: boolean;
334}): boolean {
335 if (!input.hasMismatch || input.isDismissed) {
336 return false;
337 }
338 return input.composerHasContent || input.wasShownForCurrentMismatch;
340​
341// Session-scoped (module-level so it survives ChatView remounts, e.g. route
342// changes). Durable cross-device dismissal is planned as a server-side ack.
343const sessionDismissedBranchMismatchKeys = new Set<string>();
344​
345export function dismissBranchMismatchForSession(key: string): void {
346 sessionDismissedBranchMismatchKeys.add(key);
348​
349export function isBranchMismatchDismissedForSession(key: string | null): boolean {
350 return key !== null && sessionDismissedBranchMismatchKeys.has(key);
352​
353export function threadHasStarted(thread: Thread | null | undefined): boolean {
354 return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
356​
357// `threadProvider` is the open branded driver kind carried by the session.
358// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe
359// rollback / fork behavior — the routing layer is the right place to surface
360// "driver not installed" errors, not the lock state.
361//
362// `selectedProvider` takes the same open-string shape because the composer
363// now tracks the picker selection as a `ProviderInstanceId` (e.g.
364// `codex_personal`). Custom instance ids that don't directly match a
365// registered driver resolve to `null` here, which matches the existing
366// "unknown driver -> unlocked" semantics. Callers that want the lock to track
367// a custom instance's underlying driver kind should resolve the instance id
368// upstream and pass the correlated kind.
369export function deriveLockedProvider(input: {
370 thread: Thread | null | undefined;
371 selectedProvider: string | null;
372 threadProvider: string | null;
373}): ProviderDriverKind | null {
374 if (!threadHasStarted(input.thread)) {
375 return null;
376 }
377 const sessionProvider = input.thread?.runtime?.providerName ?? null;
378 if (sessionProvider && isProviderDriverKind(sessionProvider)) {
379 return sessionProvider;
380 }
381 const narrowedThreadProvider =
382 input.threadProvider && isProviderDriverKind(input.threadProvider)
383 ? input.threadProvider
384 : null;
385 const narrowedSelectedProvider =
386 input.selectedProvider && isProviderDriverKind(input.selectedProvider)
387 ? input.selectedProvider
388 : null;
389 return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
391​
392export function getStartedThreadModelChangeBlockReason(input: {
393 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
394 hasStartedSession: boolean;
395 supportsProviderSwitchingViaHandoff?: boolean;
396 currentModelSelection: ModelSelection;
397 currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
398 nextModelSelection: ModelSelection;
399}): { title: string; description: string } | null {
400 if (!input.hasStartedSession) {
401 return null;
402 }
403 const currentModelSelection = {
404 ...input.currentModelSelection,
405 instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
406 };
407 if (
408 currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
409 currentModelSelection.model === input.nextModelSelection.model
410 ) {
411 return null;
412 }
413 if (currentModelSelection.instanceId !== input.nextModelSelection.instanceId) {
414 if (input.supportsProviderSwitchingViaHandoff === true) {
415 return null;
416 }
417 return {
418 title: "Start a new chat to switch providers",
419 description: "This thread does not support switching providers after it has started.",
420 };
421 }
422 const currentProvider = input.providers.find(
423 (snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
424 );
425 const nextProvider = input.providers.find(
426 (snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
427 );
428 if (
429 currentProvider?.requiresNewThreadForModelChange !== true &&
430 nextProvider?.requiresNewThreadForModelChange !== true
431 ) {
432 return null;
433 }
434 return {
435 title: "Start a new chat to change models",
436 description: "This provider does not allow switching models after a conversation has started.",
437 };
439​
440export async function waitForStartedServerThread(
441 threadRef: ScopedThreadRef,
442 timeoutMs = 1_000,
443): Promise<boolean> {
444 const threadAtom = environmentThreadShells.threadShellAtom(threadRef);
445 return waitForAtomValue({
446 registry: appAtomRegistry,
447 atom: threadAtom,
448 predicate: threadHasStarted,
449 timeoutMs,
450 });
452​
453export interface LocalDispatchSnapshot {
454 startedAt: string;
455 preparingWorktree: boolean;
456 latestUserMessageId: ChatMessage["id"] | null;
457 latestRunId: RunId | null;
458 latestRunRequestedAt: string | null;
459 latestRunStartedAt: string | null;
460 latestRunCompletedAt: string | null;
461 runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
462 runtimeUpdatedAt: string | null;
464​
465export function createLocalDispatchSnapshot(
466 activeThread: Thread | undefined,
467 options?: { preparingWorktree?: boolean; latestUserMessageId?: ChatMessage["id"] | null },
468): LocalDispatchSnapshot {
469 const latestRun = activeThread?.latestRun ?? null;
470 const runtime = activeThread?.runtime ?? null;
471 return {
472 startedAt: new Date().toISOString(),
473 preparingWorktree: Boolean(options?.preparingWorktree),
474 latestUserMessageId: options?.latestUserMessageId ?? null,
475 latestRunId: latestRun?.runId ?? null,
476 latestRunRequestedAt: latestRun?.requestedAt ?? null,
477 latestRunStartedAt: latestRun?.startedAt ?? null,
478 latestRunCompletedAt: latestRun?.completedAt ?? null,
479 runtimeStatus: runtime?.status ?? null,
480 runtimeUpdatedAt: runtime?.updatedAt ?? null,
481 };
483​
484/**
485 * The timeline renders committed user rows from `visibleTurnItems`, but
486 * `message.updated` can land in `projection.messages` one event earlier than
487 * the matching `turn-item.updated`. Basing optimistic eviction on visible user
488 * turn items avoids dropping steer rows in that gap.
489 */
490export function deriveCommittedServerUserMessageIds(
491 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
492): ReadonlySet<ChatMessage["id"]> {
493 return new Set(
494 visibleTurnItems.flatMap((row) =>
495 row.item.type === "user_message" ? [row.item.messageId] : [],
496 ),
497 );
499​
500export function hasServerAcknowledgedLocalDispatch(input: {
501 localDispatch: LocalDispatchSnapshot | null;
502 phase: SessionPhase;
503 latestRun: Thread["latestRun"] | null;
504 latestUserMessageId?: ChatMessage["id"] | null;
505 runtime: Thread["runtime"] | null;
506 hasPendingApproval: boolean;
507 hasPendingUserInput: boolean;
508 threadError: string | null | undefined;
509}): boolean {
510 if (!input.localDispatch) {
511 return false;
512 }
513 if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) {
514 return true;
515 }
516​
517 const latestRun = input.latestRun ?? null;
518 const runtime = input.runtime ?? null;
519 const latestUserMessageChanged =
520 input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null);
521 const latestRunChanged =
522 input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
523 input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
524 input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
525 input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
526​
527 if (input.phase === "running") {
528 if (latestUserMessageChanged) {
529 return true;
530 }
531 if (!latestRunChanged) {
532 return false;
533 }
534 if (latestRun?.startedAt === null || latestRun === null) {
535 return false;
536 }
537 if (
538 runtime?.activeRunId !== null &&
539 runtime?.activeRunId !== undefined &&
540 latestRun?.runId !== runtime.activeRunId
541 ) {
542 return false;
543 }
544 return true;
545 }
546​
547 return (
548 latestRunChanged ||
549 input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
550 input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
551 );