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

ChatView.logic.ts

345 lines10.3 KB

1import {
2 type EnvironmentId,
3 ProjectId,
4 type ModelSelection,
5 type ProviderKind,
6 type ScopedThreadRef,
7 type ThreadId,
8 type TurnId,
9} from "@t3tools/contracts";
10import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
11import { randomUUID } from "~/lib/utils";
12import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
13import { Schema } from "effect";
14import { selectThreadByRef, useStore } from "../store";
15import {
16 filterTerminalContextsWithText,
17 stripInlineTerminalContextPlaceholders,
18 type TerminalContextDraft,
19} from "../lib/terminalContext";
20​
21export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
22export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
23const WORKTREE_BRANCH_PREFIX = "t3code";
24​
25export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
26​
27export function buildLocalDraftThread(
28 threadId: ThreadId,
29 draftThread: DraftThreadState,
30 fallbackModelSelection: ModelSelection,
31 error: string | null,
32): Thread {
33 return {
34 id: threadId,
35 environmentId: draftThread.environmentId,
36 codexThreadId: null,
37 projectId: draftThread.projectId,
38 title: "New thread",
39 modelSelection: fallbackModelSelection,
40 runtimeMode: draftThread.runtimeMode,
41 interactionMode: draftThread.interactionMode,
42 session: null,
43 messages: [],
44 error,
45 createdAt: draftThread.createdAt,
46 archivedAt: null,
47 latestTurn: null,
48 branch: draftThread.branch,
49 worktreePath: draftThread.worktreePath,
50 turnDiffSummaries: [],
51 activities: [],
52 proposedPlans: [],
53 };
55​
56export function shouldWriteThreadErrorToCurrentServerThread(input: {
57 serverThread:
58 | {
59 environmentId: EnvironmentId;
60 id: ThreadId;
61 }
62 | null
63 | undefined;
64 routeThreadRef: ScopedThreadRef;
65 targetThreadId: ThreadId;
66}): boolean {
67 return Boolean(
68 input.serverThread &&
69 input.targetThreadId === input.routeThreadRef.threadId &&
70 input.serverThread.environmentId === input.routeThreadRef.environmentId &&
71 input.serverThread.id === input.targetThreadId,
72 );
74​
75export function reconcileMountedTerminalThreadIds(input: {
76 currentThreadIds: ReadonlyArray<string>;
77 openThreadIds: ReadonlyArray<string>;
78 activeThreadId: string | null;
79 activeThreadTerminalOpen: boolean;
80 maxHiddenThreadCount?: number;
81}): string[] {
82 const openThreadIdSet = new Set(input.openThreadIds);
83 const hiddenThreadIds = input.currentThreadIds.filter(
84 (threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
85 );
86 const maxHiddenThreadCount = Math.max(
87 0,
88 input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
89 );
90 const nextThreadIds =
91 hiddenThreadIds.length > maxHiddenThreadCount
92 ? hiddenThreadIds.slice(-maxHiddenThreadCount)
93 : hiddenThreadIds;
94​
95 if (
96 input.activeThreadId &&
97 input.activeThreadTerminalOpen &&
98 !nextThreadIds.includes(input.activeThreadId)
99 ) {
100 nextThreadIds.push(input.activeThreadId);
101 }
102​
103 return nextThreadIds;
105​
106export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
107 if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
108 return;
109 }
110 URL.revokeObjectURL(previewUrl);
112​
113export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
114 if (message.role !== "user" || !message.attachments) {
115 return;
116 }
117 for (const attachment of message.attachments) {
118 if (attachment.type !== "image") {
119 continue;
120 }
121 revokeBlobPreviewUrl(attachment.previewUrl);
122 }
124​
125export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
126 if (message.role !== "user" || !message.attachments) {
127 return [];
128 }
129 const previewUrls: string[] = [];
130 for (const attachment of message.attachments) {
131 if (attachment.type !== "image") continue;
132 if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
133 previewUrls.push(attachment.previewUrl);
134 }
135 return previewUrls;
137​
138export interface PullRequestDialogState {
139 initialReference: string | null;
140 key: number;
142​
143export function readFileAsDataUrl(file: File): Promise<string> {
144 return new Promise((resolve, reject) => {
145 const reader = new FileReader();
146 reader.addEventListener("load", () => {
147 if (typeof reader.result === "string") {
148 resolve(reader.result);
149 return;
150 }
151 reject(new Error("Could not read image data."));
152 });
153 reader.addEventListener("error", () => {
154 reject(reader.error ?? new Error("Failed to read image."));
155 });
156 reader.readAsDataURL(file);
157 });
159​
160export function buildTemporaryWorktreeBranchName(): string {
161 // Keep the 8-hex suffix shape for backend temporary-branch detection.
162 const token = randomUUID().slice(0, 8).toLowerCase();
163 return `${WORKTREE_BRANCH_PREFIX}/${token}`;
165​
166export function cloneComposerImageForRetry(
167 image: ComposerImageAttachment,
168): ComposerImageAttachment {
169 if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
170 return image;
171 }
172 try {
173 return {
174 ...image,
175 previewUrl: URL.createObjectURL(image.file),
176 };
177 } catch {
178 return image;
179 }
181​
182export function deriveComposerSendState(options: {
183 prompt: string;
184 imageCount: number;
185 terminalContexts: ReadonlyArray<TerminalContextDraft>;
186}): {
187 trimmedPrompt: string;
188 sendableTerminalContexts: TerminalContextDraft[];
189 expiredTerminalContextCount: number;
190 hasSendableContent: boolean;
191} {
192 const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
193 const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
194 const expiredTerminalContextCount =
195 options.terminalContexts.length - sendableTerminalContexts.length;
196 return {
197 trimmedPrompt,
198 sendableTerminalContexts,
199 expiredTerminalContextCount,
200 hasSendableContent:
201 trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
202 };
204​
205export function buildExpiredTerminalContextToastCopy(
206 expiredTerminalContextCount: number,
207 variant: "omitted" | "empty",
208): { title: string; description: string } {
209 const count = Math.max(1, Math.floor(expiredTerminalContextCount));
210 const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
211 if (variant === "empty") {
212 return {
213 title: `${noun} won't be sent`,
214 description: "Remove it or re-add it to include terminal output.",
215 };
216 }
217 return {
218 title: `${noun} omitted from message`,
219 description: "Re-add it if you want that terminal output included.",
220 };
222​
223export function threadHasStarted(thread: Thread | null | undefined): boolean {
224 return Boolean(
225 thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
226 );
228​
229export function deriveLockedProvider(input: {
230 thread: Thread | null | undefined;
231 selectedProvider: ProviderKind | null;
232 threadProvider: ProviderKind | null;
233}): ProviderKind | null {
234 if (!threadHasStarted(input.thread)) {
235 return null;
236 }
237 return input.thread?.session?.provider ?? input.threadProvider ?? input.selectedProvider ?? null;
239​
240export async function waitForStartedServerThread(
241 threadRef: ScopedThreadRef,
242 timeoutMs = 1_000,
243): Promise<boolean> {
244 const getThread = () => selectThreadByRef(useStore.getState(), threadRef);
245 const thread = getThread();
246​
247 if (threadHasStarted(thread)) {
248 return true;
249 }
250​
251 return await new Promise<boolean>((resolve) => {
252 let settled = false;
253 let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
254 const finish = (result: boolean) => {
255 if (settled) {
256 return;
257 }
258 settled = true;
259 if (timeoutId !== null) {
260 globalThis.clearTimeout(timeoutId);
261 }
262 unsubscribe();
263 resolve(result);
264 };
265​
266 const unsubscribe = useStore.subscribe((state) => {
267 if (!threadHasStarted(selectThreadByRef(state, threadRef))) {
268 return;
269 }
270 finish(true);
271 });
272​
273 if (threadHasStarted(getThread())) {
274 finish(true);
275 return;
276 }
277​
278 timeoutId = globalThis.setTimeout(() => {
279 finish(false);
280 }, timeoutMs);
281 });
283​
284export interface LocalDispatchSnapshot {
285 startedAt: string;
286 preparingWorktree: boolean;
287 latestTurnTurnId: TurnId | null;
288 latestTurnRequestedAt: string | null;
289 latestTurnStartedAt: string | null;
290 latestTurnCompletedAt: string | null;
291 sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null;
292 sessionUpdatedAt: string | null;
294​
295export function createLocalDispatchSnapshot(
296 activeThread: Thread | undefined,
297 options?: { preparingWorktree?: boolean },
298): LocalDispatchSnapshot {
299 const latestTurn = activeThread?.latestTurn ?? null;
300 const session = activeThread?.session ?? null;
301 return {
302 startedAt: new Date().toISOString(),
303 preparingWorktree: Boolean(options?.preparingWorktree),
304 latestTurnTurnId: latestTurn?.turnId ?? null,
305 latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
306 latestTurnStartedAt: latestTurn?.startedAt ?? null,
307 latestTurnCompletedAt: latestTurn?.completedAt ?? null,
308 sessionOrchestrationStatus: session?.orchestrationStatus ?? null,
309 sessionUpdatedAt: session?.updatedAt ?? null,
310 };
312​
313export function hasServerAcknowledgedLocalDispatch(input: {
314 localDispatch: LocalDispatchSnapshot | null;
315 phase: SessionPhase;
316 latestTurn: Thread["latestTurn"] | null;
317 session: Thread["session"] | null;
318 hasPendingApproval: boolean;
319 hasPendingUserInput: boolean;
320 threadError: string | null | undefined;
321}): boolean {
322 if (!input.localDispatch) {
323 return false;
324 }
325 if (
326 input.phase === "running" ||
327 input.hasPendingApproval ||
328 input.hasPendingUserInput ||
329 Boolean(input.threadError)
330 ) {
331 return true;
332 }
333​
334 const latestTurn = input.latestTurn ?? null;
335 const session = input.session ?? null;
336​
337 return (
338 input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
339 input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
340 input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
341 input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
342 input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
343 input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
344 );