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

ChatView.logic.ts

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