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

ChatView.logic.ts

306 lines9.4 KB

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