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

persistenceSchema.ts

357 lines11.3 KB

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