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

persistenceSchema.ts

360 lines11.5 KB

1import { z } from "zod";
2import { projectScriptSchema } from "@t3tools/contracts";
3​
4import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
5import {
6 DEFAULT_THREAD_TERMINAL_HEIGHT,
7 DEFAULT_THREAD_TERMINAL_ID,
8 DEFAULT_RUNTIME_MODE,
9 type Project,
10 type RuntimeMode,
11 type Thread,
12 type ThreadTerminalGroup,
13} from "./types";
14​
15const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
16​
17const persistedProjectSchema = z.object({
18 id: z.string().min(1),
19 name: z.string().min(1),
20 cwd: z.string().min(1),
21 model: z.string().min(1),
22 expanded: z.boolean(),
23 scripts: z.array(projectScriptSchema).default([]),
24});
25​
26const persistedMessageSchema = z.object({
27 id: z.string().min(1),
28 role: z.enum(["user", "assistant"]),
29 text: z.string(),
30 attachments: z
31 .array(
32 z.object({
33 type: z.literal("image"),
34 id: z.string().min(1),
35 name: z.string().min(1),
36 mimeType: z.string().min(1),
37 sizeBytes: z.number().int().min(1),
38 }),
39 )
40 .optional(),
41 createdAt: z.string().min(1),
42 streaming: z.boolean(),
43});
44​
45const persistedTerminalGroupSchema = z.object({
46 id: z.string().trim().min(1),
47 terminalIds: z.array(z.string().trim().min(1)),
48});
49​
50const persistedThreadSchema = z.object({
51 id: z.string().min(1),
52 codexThreadId: z.string().min(1).nullable().default(null),
53 projectId: z.string().min(1),
54 title: z.string().min(1),
55 model: z.string().min(1),
56 terminalOpen: z.boolean().default(false),
57 terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
58 terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
59 activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
60 terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
61 activeTerminalGroupId: z.string().trim().min(1).optional(),
62 // Legacy v6 and older fields retained for migration.
63 terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
64 splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
65 messages: z.array(persistedMessageSchema),
66 createdAt: z.string().min(1),
67 lastVisitedAt: z.string().min(1).optional(),
68 branch: z.string().min(1).nullable().optional(),
69 worktreePath: z.string().min(1).nullable().optional(),
70});
71​
72const persistedStateBodySchema = z.object({
73 projects: z.array(persistedProjectSchema),
74 threads: z.array(persistedThreadSchema),
75 activeThreadId: z.string().min(1).nullable(),
76});
77​
78const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
79​
80export const persistedStateV1Schema = persistedStateBodySchema.extend({
81 version: z.literal(1).optional(),
82});
83​
84export const persistedStateV2Schema = persistedStateBodySchema.extend({
85 version: z.literal(2).optional(),
86});
87​
88export const persistedStateV3Schema = persistedStateBodySchema.extend({
89 runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
90 version: z.literal(3).optional(),
91});
92​
93export const persistedStateV4Schema = persistedStateBodySchema.extend({
94 runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
95 version: z.literal(4).optional(),
96});
97​
98export const persistedStateV6Schema = persistedStateBodySchema.extend({
99 runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
100 version: z.literal(6).optional(),
101});
102​
103export const persistedStateV7Schema = persistedStateBodySchema.extend({
104 runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
105 version: z.literal(7).optional(),
106});
107​
108export const persistedStateV5Schema = persistedStateBodySchema.extend({
109 runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
110 version: z.literal(5).optional(),
111});
112​
113const persistedStateSchema = z.union([
114 persistedStateV7Schema,
115 persistedStateV6Schema,
116 persistedStateV5Schema,
117 persistedStateV4Schema,
118 persistedStateV3Schema,
119 persistedStateV2Schema,
120 persistedStateV1Schema,
121]);
122​
123export interface PersistedStoreSnapshot {
124 projects: Project[];
125 threads: Thread[];
126 activeThreadId: string | null;
127 runtimeMode: RuntimeMode;
129​
130function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
131 if (!isLegacyPayload) {
132 return model;
133 }
134​
135 return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
137​
138function hydrateProject(
139 project: z.infer<typeof persistedProjectSchema>,
140 isLegacyPayload: boolean,
141): Project {
142 return {
143 ...project,
144 model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
145 scripts: project.scripts,
146 };
148​
149function hydrateThread(
150 thread: z.infer<typeof persistedThreadSchema>,
151 isLegacyPayload: boolean,
152): Thread {
153 const terminalIds = [
154 ...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
155 ];
156 const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
157 const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
158 ? thread.activeTerminalId
159 : (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
160 const safeTerminalIdSet = new Set(safeTerminalIds);
161 const assignedTerminalIds = new Set<string>();
162 const usedGroupIds = new Set<string>();
163 const normalizedGroups: ThreadTerminalGroup[] = [];
164 const assignUniqueGroupId = (groupId: string): string => {
165 if (!usedGroupIds.has(groupId)) {
166 usedGroupIds.add(groupId);
167 return groupId;
168 }
169 let suffix = 2;
170 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
171 suffix += 1;
172 }
173 const uniqueGroupId = `${groupId}-${suffix}`;
174 usedGroupIds.add(uniqueGroupId);
175 return uniqueGroupId;
176 };
177​
178 for (const terminalGroup of thread.terminalGroups) {
179 const nextTerminalIds = [
180 ...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
181 ].filter((terminalId) => {
182 if (!safeTerminalIdSet.has(terminalId)) return false;
183 if (assignedTerminalIds.has(terminalId)) return false;
184 return true;
185 });
186 if (nextTerminalIds.length === 0) continue;
187 for (const terminalId of nextTerminalIds) {
188 assignedTerminalIds.add(terminalId);
189 }
190 const baseGroupId =
191 terminalGroup.id.trim().length > 0
192 ? terminalGroup.id.trim()
193 : `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
194 normalizedGroups.push({
195 id: assignUniqueGroupId(baseGroupId),
196 terminalIds: nextTerminalIds,
197 });
198 }
199​
200 if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
201 const splitTerminalIds = [
202 ...new Set(
203 (thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
204 ),
205 ].filter((terminalId) => safeTerminalIdSet.has(terminalId));
206 if (splitTerminalIds.length >= 2) {
207 const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
208 for (const terminalId of splitGroupTerminalIds) {
209 assignedTerminalIds.add(terminalId);
210 }
211 normalizedGroups.push({
212 id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
213 terminalIds: splitGroupTerminalIds,
214 });
215 }
216 }
217​
218 for (const terminalId of safeTerminalIds) {
219 if (assignedTerminalIds.has(terminalId)) continue;
220 normalizedGroups.push({
221 id: assignUniqueGroupId(`group-${terminalId}`),
222 terminalIds: [terminalId],
223 });
224 }
225​
226 const activeGroupIndexFromId = normalizedGroups.findIndex(
227 (terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
228 );
229 const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
230 terminalGroup.terminalIds.includes(activeTerminalId),
231 );
232 const activeGroupIndex =
233 activeGroupIndexFromId >= 0
234 ? activeGroupIndexFromId
235 : activeGroupIndexFromTerminal >= 0
236 ? activeGroupIndexFromTerminal
237 : 0;
238 const activeTerminalGroupId =
239 normalizedGroups[activeGroupIndex]?.id ??
240 normalizedGroups[0]?.id ??
241 `group-${DEFAULT_THREAD_TERMINAL_ID}`;
242​
243 return {
244 id: thread.id,
245 codexThreadId: thread.codexThreadId,
246 projectId: thread.projectId,
247 title: thread.title,
248 model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
249 terminalOpen: thread.terminalOpen ?? false,
250 terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
251 terminalIds: safeTerminalIds,
252 runningTerminalIds: [],
253 activeTerminalId,
254 terminalGroups: normalizedGroups,
255 activeTerminalGroupId,
256 session: null,
257 messages: thread.messages.map((message) => {
258 const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
259 return {
260 id: message.id,
261 role: message.role,
262 text: message.text,
263 ...(hydratedAttachments && hydratedAttachments.length > 0
264 ? { attachments: hydratedAttachments }
265 : {}),
266 createdAt: message.createdAt,
267 streaming: false,
268 };
269 }),
270 events: [],
271 error: null,
272 createdAt: thread.createdAt,
273 lastVisitedAt: thread.lastVisitedAt,
274 branch: thread.branch ?? null,
275 worktreePath: thread.worktreePath ?? null,
276 };
278​
279export function hydratePersistedState(
280 raw: string,
281 isLegacyPayload: boolean,
282): PersistedStoreSnapshot | null {
283 let parsedJson: unknown;
284 try {
285 parsedJson = JSON.parse(raw);
286 } catch {
287 return null;
288 }
289​
290 const parsedState = persistedStateSchema.safeParse(parsedJson);
291 if (!parsedState.success) {
292 return null;
293 }
294​
295 const projects = parsedState.data.projects.map((project) =>
296 hydrateProject(project, isLegacyPayload),
297 );
298 const projectIds = new Set(projects.map((project) => project.id));
299 const threads = parsedState.data.threads
300 .map((thread) => hydrateThread(thread, isLegacyPayload))
301 .filter((thread) => projectIds.has(thread.projectId));
302 const hasActiveThread = Boolean(
303 parsedState.data.activeThreadId &&
304 threads.some((thread) => thread.id === parsedState.data.activeThreadId),
305 );
306​
307 return {
308 projects,
309 threads,
310 activeThreadId: hasActiveThread ? parsedState.data.activeThreadId : (threads[0]?.id ?? null),
311 runtimeMode:
312 "runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
313 };
315​
316export function toPersistedState(
317 state: PersistedStoreSnapshot,
318): z.infer<typeof persistedStateV7Schema> {
319 return {
320 version: 7,
321 projects: state.projects,
322 threads: state.threads.map((thread) => ({
323 id: thread.id,
324 codexThreadId: thread.codexThreadId,
325 projectId: thread.projectId,
326 title: thread.title,
327 model: thread.model,
328 terminalOpen: thread.terminalOpen,
329 terminalHeight: thread.terminalHeight,
330 terminalIds: thread.terminalIds,
331 activeTerminalId: thread.activeTerminalId,
332 terminalGroups: thread.terminalGroups,
333 activeTerminalGroupId: thread.activeTerminalGroupId,
334 messages: thread.messages.map((message) => ({
335 id: message.id,
336 role: message.role,
337 text: message.text,
338 ...(message.attachments && message.attachments.length > 0
339 ? {
340 attachments: message.attachments.map((attachment) => ({
341 type: attachment.type,
342 id: attachment.id,
343 name: attachment.name,
344 mimeType: attachment.mimeType,
345 sizeBytes: attachment.sizeBytes,
346 })),
347 }
348 : {}),
349 createdAt: message.createdAt,
350 streaming: message.streaming,
351 })),
352 createdAt: thread.createdAt,
353 ...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
354 branch: thread.branch,
355 worktreePath: thread.worktreePath,
356 })),
357 activeThreadId: state.activeThreadId,
358 runtimeMode: state.runtimeMode,
359 };