From 40d49f10359f65fdda0781c61d4535c0105e2f8d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Feb 2026 10:09:22 +0000 Subject: [PATCH] Extract persistence domain helpers and add turn summary tests Co-authored-by: Julius Marminge --- .../src/persistence/domain/appSettings.ts | 25 ++ .../server/src/persistence/domain/messages.ts | 39 ++ .../server/src/persistence/domain/projects.ts | 24 ++ .../persistence/domain/providerProjection.ts | 42 ++ .../src/persistence/domain/stateSync.ts | 41 ++ apps/server/src/persistence/domain/threads.ts | 117 ++++++ .../persistence/domain/turnSummaries.test.ts | 46 +++ .../src/persistence/domain/turnSummaries.ts | 115 ++++++ apps/server/src/persistenceService.ts | 370 ++---------------- 9 files changed, 484 insertions(+), 335 deletions(-) create mode 100644 apps/server/src/persistence/domain/appSettings.ts create mode 100644 apps/server/src/persistence/domain/messages.ts create mode 100644 apps/server/src/persistence/domain/projects.ts create mode 100644 apps/server/src/persistence/domain/providerProjection.ts create mode 100644 apps/server/src/persistence/domain/stateSync.ts create mode 100644 apps/server/src/persistence/domain/threads.ts create mode 100644 apps/server/src/persistence/domain/turnSummaries.test.ts create mode 100644 apps/server/src/persistence/domain/turnSummaries.ts diff --git a/apps/server/src/persistence/domain/appSettings.ts b/apps/server/src/persistence/domain/appSettings.ts new file mode 100644 index 0000000000..ee3470acf8 --- /dev/null +++ b/apps/server/src/persistence/domain/appSettings.ts @@ -0,0 +1,25 @@ +import { + type AppSettings, + type AppSettingsUpdateInput, + appSettingsSchema, + appSettingsUpdateInputSchema, +} from "@t3tools/contracts"; + +export function resolveAppSettings(metadataValue: unknown): AppSettings { + const parsed = appSettingsSchema.safeParse(metadataValue); + if (parsed.success) { + return parsed.data; + } + return appSettingsSchema.parse({}); +} + +export function buildUpdatedAppSettings( + current: AppSettings, + rawPatch: AppSettingsUpdateInput, +): AppSettings { + const patch = appSettingsUpdateInputSchema.parse(rawPatch); + return appSettingsSchema.parse({ + ...current, + ...patch, + }); +} diff --git a/apps/server/src/persistence/domain/messages.ts b/apps/server/src/persistence/domain/messages.ts new file mode 100644 index 0000000000..28dc6161e4 --- /dev/null +++ b/apps/server/src/persistence/domain/messages.ts @@ -0,0 +1,39 @@ +import { + type ProviderSendTurnInput, + type StateMessage, + stateMessageSchema, +} from "@t3tools/contracts"; + +export function messageDocId(threadId: string, messageId: string): string { + return `message:${threadId}:${messageId}`; +} + +export function buildUserTurnMessage(input: { + turn: ProviderSendTurnInput; + threadId: string; + messageId: string; + createdAt: string; +}): StateMessage { + const text = input.turn.clientMessageText ?? input.turn.input ?? ""; + const inputAttachments = input.turn.attachments ?? []; + const attachments = + inputAttachments.length > 0 + ? inputAttachments.map((attachment, index) => ({ + type: "image" as const, + id: `${input.messageId}:image:${index + 1}`, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + })) + : undefined; + return stateMessageSchema.parse({ + id: input.messageId, + threadId: input.threadId, + role: "user", + text, + ...(attachments ? { attachments } : {}), + createdAt: input.createdAt, + updatedAt: input.createdAt, + streaming: false, + }); +} diff --git a/apps/server/src/persistence/domain/projects.ts b/apps/server/src/persistence/domain/projects.ts new file mode 100644 index 0000000000..09b94f00a0 --- /dev/null +++ b/apps/server/src/persistence/domain/projects.ts @@ -0,0 +1,24 @@ +import fs from "node:fs"; +import path from "node:path"; + +export function normalizeCwd(rawCwd: string): string { + const resolved = path.resolve(rawCwd.trim()); + const normalized = path.normalize(resolved); + if (process.platform === "win32") { + return normalized.toLowerCase(); + } + return normalized; +} + +export function isDirectory(cwd: string): boolean { + try { + return fs.statSync(cwd).isDirectory(); + } catch { + return false; + } +} + +export function inferProjectName(cwd: string): string { + const name = path.basename(cwd); + return name.length > 0 ? name : "project"; +} diff --git a/apps/server/src/persistence/domain/providerProjection.ts b/apps/server/src/persistence/domain/providerProjection.ts new file mode 100644 index 0000000000..db8bdb62a3 --- /dev/null +++ b/apps/server/src/persistence/domain/providerProjection.ts @@ -0,0 +1,42 @@ +import type { ProviderEvent } from "@t3tools/contracts"; + +export function asObject(value: unknown): Record | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + return value as Record; +} + +export function asString(value: unknown): string | undefined { + return typeof value === "string" && value.length > 0 ? value : undefined; +} + +export function normalizeProviderItemType(value: string | undefined): string | undefined { + if (!value) return undefined; + const normalized = value.trim(); + if (normalized.length === 0) return undefined; + return normalized.replace(/[_\-\s]+/g, "").toLowerCase(); +} + +export function parseThreadIdFromEventPayload(payload: unknown): string | null { + const record = asObject(payload); + const threadId = asString(record?.threadId) ?? asString(record?.thread_id); + if (threadId) return threadId; + const thread = asObject(record?.thread); + return asString(thread?.id) ?? null; +} + +export function parseTurnIdFromEvent(event: ProviderEvent): string | null { + if (event.turnId) return event.turnId; + const payload = asObject(event.payload); + const turn = asObject(payload?.turn); + return asString(turn?.id) ?? null; +} + +export function parseAssistantItemId(event: ProviderEvent): string | null { + const payload = asObject(event.payload); + const item = asObject(payload?.item); + const itemType = asString(item?.type); + if (itemType !== "agentMessage") return null; + return asString(item?.id) ?? event.itemId ?? null; +} diff --git a/apps/server/src/persistence/domain/stateSync.ts b/apps/server/src/persistence/domain/stateSync.ts new file mode 100644 index 0000000000..7bd6e870fd --- /dev/null +++ b/apps/server/src/persistence/domain/stateSync.ts @@ -0,0 +1,41 @@ +import { + type StateBootstrapResult, + type StateBootstrapThread, + type StateCatchUpResult, + type StateEvent, + type StateListMessagesResult, + type StateMessage, + type StateProject, + stateBootstrapResultSchema, + stateCatchUpResultSchema, + stateListMessagesResultSchema, +} from "@t3tools/contracts"; + +export function buildStateBootstrapResult(input: { + projects: StateProject[]; + threads: StateBootstrapThread[]; + lastStateSeq: number; +}): StateBootstrapResult { + return stateBootstrapResultSchema.parse(input); +} + +export function buildStateCatchUpResult(input: { + events: StateEvent[]; + lastStateSeq: number; +}): StateCatchUpResult { + return stateCatchUpResultSchema.parse(input); +} + +export function buildStateListMessagesResult(input: { + messages: StateMessage[]; + total: number; + offset: number; + pageSize: number; +}): StateListMessagesResult { + const nextOffset = input.offset + input.pageSize; + return stateListMessagesResultSchema.parse({ + messages: input.messages, + total: input.total, + nextOffset: nextOffset < input.total ? nextOffset : null, + }); +} diff --git a/apps/server/src/persistence/domain/threads.ts b/apps/server/src/persistence/domain/threads.ts new file mode 100644 index 0000000000..4c8f6a75fa --- /dev/null +++ b/apps/server/src/persistence/domain/threads.ts @@ -0,0 +1,117 @@ +import type { StateThread } from "@t3tools/contracts"; + +const MAX_TERMINAL_COUNT = 4; +const DEFAULT_TERMINAL_ID = "default"; + +export function normalizeTerminalIds(ids: readonly string[]): string[] { + const normalized = [ + ...new Set(ids.map((id) => id.trim()).filter((id) => id.length > 0)), + ].slice(0, MAX_TERMINAL_COUNT); + if (normalized.length > 0) { + return normalized; + } + return [DEFAULT_TERMINAL_ID]; +} + +function normalizeRunningTerminalIds( + runningTerminalIds: readonly string[], + terminalIds: readonly string[], +): string[] { + if (runningTerminalIds.length === 0) { + return []; + } + + const validTerminalIds = new Set(terminalIds); + return [...new Set(runningTerminalIds)] + .map((id) => id.trim()) + .filter((id) => id.length > 0 && validTerminalIds.has(id)) + .slice(0, MAX_TERMINAL_COUNT); +} + +export function fallbackGroupId(terminalId: string): string { + return `group-${terminalId}`; +} + +function assignUniqueGroupId(groupId: string, usedGroupIds: Set): string { + if (!usedGroupIds.has(groupId)) { + usedGroupIds.add(groupId); + return groupId; + } + + let suffix = 2; + while (usedGroupIds.has(`${groupId}-${suffix}`)) { + suffix += 1; + } + const uniqueGroupId = `${groupId}-${suffix}`; + usedGroupIds.add(uniqueGroupId); + return uniqueGroupId; +} + +function normalizeTerminalGroups( + groups: StateThread["terminalGroups"], + terminalIds: readonly string[], +): StateThread["terminalGroups"] { + const validTerminalIds = new Set(terminalIds); + const assignedTerminalIds = new Set(); + const usedGroupIds = new Set(); + const normalizedGroups: StateThread["terminalGroups"] = []; + + for (const group of groups) { + const groupTerminalIds = [ + ...new Set(group.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)), + ].filter((terminalId) => { + if (!validTerminalIds.has(terminalId)) return false; + if (assignedTerminalIds.has(terminalId)) return false; + return true; + }); + if (groupTerminalIds.length === 0) continue; + for (const terminalId of groupTerminalIds) { + assignedTerminalIds.add(terminalId); + } + const baseGroupId = + group.id.trim().length > 0 + ? group.id.trim() + : fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_TERMINAL_ID); + normalizedGroups.push({ + id: assignUniqueGroupId(baseGroupId, usedGroupIds), + terminalIds: groupTerminalIds, + }); + } + + for (const terminalId of terminalIds) { + if (assignedTerminalIds.has(terminalId)) continue; + normalizedGroups.push({ + id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds), + terminalIds: [terminalId], + }); + } + + if (normalizedGroups.length > 0) { + return normalizedGroups; + } + + return [{ id: fallbackGroupId(DEFAULT_TERMINAL_ID), terminalIds: [DEFAULT_TERMINAL_ID] }]; +} + +export function normalizeThread(thread: StateThread): StateThread { + const terminalIds = normalizeTerminalIds(thread.terminalIds); + const runningTerminalIds = normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds); + const activeTerminalId = terminalIds.includes(thread.activeTerminalId) + ? thread.activeTerminalId + : (terminalIds[0] ?? DEFAULT_TERMINAL_ID); + const terminalGroups = normalizeTerminalGroups(thread.terminalGroups, terminalIds); + const activeGroupId = + terminalGroups.find((group) => group.id === thread.activeTerminalGroupId)?.id ?? + terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? + terminalGroups[0]?.id ?? + fallbackGroupId(activeTerminalId); + + return { + ...thread, + terminalIds, + runningTerminalIds, + activeTerminalId, + terminalGroups, + activeTerminalGroupId: activeGroupId, + }; +} diff --git a/apps/server/src/persistence/domain/turnSummaries.test.ts b/apps/server/src/persistence/domain/turnSummaries.test.ts new file mode 100644 index 0000000000..a115913cb6 --- /dev/null +++ b/apps/server/src/persistence/domain/turnSummaries.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, test } from "vitest"; + +import { mergeTurnSummaryFiles, summarizeUnifiedDiff } from "./turnSummaries"; + +describe("turnSummaries domain helpers", () => { + test("summarizeUnifiedDiff returns per-file diff stats", () => { + const diff = [ + "diff --git a/src/example.ts b/src/example.ts", + "index 1111111..2222222 100644", + "--- a/src/example.ts", + "+++ b/src/example.ts", + "@@ -1,2 +1,3 @@", + " line1", + "-line2", + "+line2-updated", + "+line3", + "", + ].join("\n"); + + expect(summarizeUnifiedDiff(diff)).toEqual([ + { + path: "src/example.ts", + kind: "change", + additions: 2, + deletions: 1, + }, + ]); + }); + + test("mergeTurnSummaryFiles merges by path while preserving prior fields", () => { + const existing = [ + { path: "a.ts", kind: "modified" as const, additions: 1, deletions: 2 }, + { path: "b.ts", kind: "deleted" as const, additions: 0, deletions: 4 }, + ]; + const incoming = [ + { path: "a.ts", additions: 3, deletions: 5 }, + { path: "c.ts", kind: "added" as const, additions: 7, deletions: 0 }, + ]; + + expect(mergeTurnSummaryFiles(existing, incoming)).toEqual([ + { path: "a.ts", kind: "modified", additions: 3, deletions: 5 }, + { path: "b.ts", kind: "deleted", additions: 0, deletions: 4 }, + { path: "c.ts", kind: "added", additions: 7, deletions: 0 }, + ]); + }); +}); diff --git a/apps/server/src/persistence/domain/turnSummaries.ts b/apps/server/src/persistence/domain/turnSummaries.ts new file mode 100644 index 0000000000..ea6a6a052d --- /dev/null +++ b/apps/server/src/persistence/domain/turnSummaries.ts @@ -0,0 +1,115 @@ +import { parsePatchFiles } from "@pierre/diffs"; +import type { StateTurnDiffFileChange } from "@t3tools/contracts"; + +function parsePathFromDiff(diff: string): string | null { + const normalized = diff.replace(/\r\n/g, "\n"); + const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m); + if (bPath?.[1]) return bPath[1]; + const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m); + if (gitHeader?.[1]) return gitHeader[1]; + const direct = normalized.match(/^\+\+\+ (.+)$/m); + if (!direct?.[1] || direct[1] === "/dev/null") { + return null; + } + return direct[1]; +} + +function splitUnifiedDiffByFile(diff: string): Map { + const normalized = diff.replace(/\r\n/g, "\n"); + const byPath = new Map(); + const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)]; + + if (headerMatches.length === 0) { + const pathFromDiff = parsePathFromDiff(normalized); + if (pathFromDiff) { + byPath.set(pathFromDiff, normalized.trim()); + } + return byPath; + } + + for (let index = 0; index < headerMatches.length; index += 1) { + const match = headerMatches[index]; + if (!match) continue; + const start = match.index ?? 0; + const end = headerMatches[index + 1]?.index ?? normalized.length; + const segment = normalized.slice(start, end).trim(); + const pathFromDiff = parsePathFromDiff(segment); + if (!pathFromDiff || segment.length === 0) continue; + byPath.set(pathFromDiff, segment); + } + + return byPath; +} + +function countDiffStat(patch: string): { additions: number; deletions: number } { + let additions = 0; + let deletions = 0; + for (const line of patch.replace(/\r\n/g, "\n").split("\n")) { + if (line.startsWith("+++ ") || line.startsWith("--- ")) continue; + if (line.startsWith("+")) { + additions += 1; + continue; + } + if (line.startsWith("-")) { + deletions += 1; + } + } + return { additions, deletions }; +} + +export function summarizeUnifiedDiff(diff: string): StateTurnDiffFileChange[] { + try { + const parsedPatches = parsePatchFiles(diff, "state-turn-summary", false); + const files: StateTurnDiffFileChange[] = []; + for (const patch of parsedPatches) { + for (const file of patch.files) { + const additions = file.hunks.reduce((sum, hunk) => sum + hunk.additionLines, 0); + const deletions = file.hunks.reduce((sum, hunk) => sum + hunk.deletionLines, 0); + files.push({ + path: file.name, + kind: file.type, + additions, + deletions, + }); + } + } + if (files.length > 0) { + return files.toSorted((a, b) => a.path.localeCompare(b.path)); + } + } catch { + // Fallback below. + } + + const fileDiffsByPath = splitUnifiedDiffByFile(diff); + const fallback: StateTurnDiffFileChange[] = []; + for (const [filePath, fileDiff] of fileDiffsByPath) { + const stat = countDiffStat(fileDiff); + fallback.push({ + path: filePath, + additions: stat.additions, + deletions: stat.deletions, + }); + } + return fallback.toSorted((a, b) => a.path.localeCompare(b.path)); +} + +export function mergeTurnSummaryFiles( + existing: StateTurnDiffFileChange[], + incoming: StateTurnDiffFileChange[], +): StateTurnDiffFileChange[] { + const byPath = new Map(existing.map((file) => [file.path, { ...file }] as const)); + for (const file of incoming) { + const previous = byPath.get(file.path); + if (!previous) { + byPath.set(file.path, { ...file }); + continue; + } + byPath.set(file.path, { + ...previous, + ...(file.kind !== undefined ? { kind: file.kind } : {}), + ...(file.additions !== undefined ? { additions: file.additions } : {}), + ...(file.deletions !== undefined ? { deletions: file.deletions } : {}), + }); + } + return Array.from(byPath.values()).toSorted((a, b) => a.path.localeCompare(b.path)); +} diff --git a/apps/server/src/persistenceService.ts b/apps/server/src/persistenceService.ts index 08ba4a9fbb..0246834654 100644 --- a/apps/server/src/persistenceService.ts +++ b/apps/server/src/persistenceService.ts @@ -5,13 +5,10 @@ import path from "node:path"; import * as Effect from "effect/Effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; -import { parsePatchFiles } from "@pierre/diffs"; import { DEFAULT_MODEL, type AppSettings, type AppSettingsUpdateInput, - appSettingsSchema, - appSettingsUpdateInputSchema, type ProjectAddInput, type ProjectAddResult, type ProjectListResult, @@ -46,12 +43,9 @@ import { projectRemoveInputSchema, projectScriptsSchema, projectUpdateScriptsInputSchema, - stateBootstrapResultSchema, stateCatchUpInputSchema, - stateCatchUpResultSchema, stateEventSchema, stateListMessagesInputSchema, - stateListMessagesResultSchema, stateMessageSchema, stateProjectSchema, stateThreadSchema, @@ -100,12 +94,36 @@ import { readMetadataValue as readMetadataValueEffect, writeMetadataValue as writeMetadataValueEffect, } from "./persistence/metadataRepo"; +import { + buildUpdatedAppSettings, + resolveAppSettings, +} from "./persistence/domain/appSettings"; +import { buildUserTurnMessage, messageDocId } from "./persistence/domain/messages"; +import { + inferProjectName, + isDirectory, + normalizeCwd, +} from "./persistence/domain/projects"; +import { + asObject, + asString, + normalizeProviderItemType, + parseAssistantItemId, + parseThreadIdFromEventPayload, + parseTurnIdFromEvent, +} from "./persistence/domain/providerProjection"; +import { + buildStateBootstrapResult, + buildStateCatchUpResult, + buildStateListMessagesResult, +} from "./persistence/domain/stateSync"; +import { fallbackGroupId, normalizeTerminalIds, normalizeThread } from "./persistence/domain/threads"; +import { mergeTurnSummaryFiles, summarizeUnifiedDiff } from "./persistence/domain/turnSummaries"; import { openSqliteDatabase, type EffectSqliteDatabaseAdapter, type SqliteDatabase } from "./sqliteAdapter"; import { runStateMigrations } from "./stateMigrations"; const METADATA_KEY_PROJECTS_JSON_IMPORTED = "migration.projects_json_imported"; const METADATA_KEY_APP_SETTINGS = "app.settings.v1"; -const MAX_TERMINAL_COUNT = 4; const DEFAULT_TERMINAL_ID = "default"; const DEFAULT_TERMINAL_HEIGHT = 280; @@ -160,182 +178,6 @@ function toSafeInteger(value: unknown, fallback = 0): number { return fallback; } -function normalizeCwd(rawCwd: string): string { - const resolved = path.resolve(rawCwd.trim()); - const normalized = path.normalize(resolved); - if (process.platform === "win32") { - return normalized.toLowerCase(); - } - return normalized; -} - -function isDirectory(cwd: string): boolean { - try { - return fs.statSync(cwd).isDirectory(); - } catch { - return false; - } -} - -function inferProjectName(cwd: string): string { - const name = path.basename(cwd); - return name.length > 0 ? name : "project"; -} - -function asObject(value: unknown): Record | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - return value as Record; -} - -function asString(value: unknown): string | undefined { - return typeof value === "string" && value.length > 0 ? value : undefined; -} - -function normalizeProviderItemType(value: string | undefined): string | undefined { - if (!value) return undefined; - const normalized = value.trim(); - if (normalized.length === 0) return undefined; - return normalized.replace(/[_\-\s]+/g, "").toLowerCase(); -} - -function parseThreadIdFromEventPayload(payload: unknown): string | null { - const record = asObject(payload); - const threadId = asString(record?.threadId) ?? asString(record?.thread_id); - if (threadId) return threadId; - const thread = asObject(record?.thread); - return asString(thread?.id) ?? null; -} - -function parseTurnIdFromEvent(event: ProviderEvent): string | null { - if (event.turnId) return event.turnId; - const payload = asObject(event.payload); - const turn = asObject(payload?.turn); - return asString(turn?.id) ?? null; -} - -function parseAssistantItemId(event: ProviderEvent): string | null { - const payload = asObject(event.payload); - const item = asObject(payload?.item); - const itemType = asString(item?.type); - if (itemType !== "agentMessage") return null; - return asString(item?.id) ?? event.itemId ?? null; -} - -function normalizeTerminalIds(ids: readonly string[]): string[] { - const normalized = [ - ...new Set(ids.map((id) => id.trim()).filter((id) => id.length > 0)), - ].slice(0, MAX_TERMINAL_COUNT); - if (normalized.length > 0) { - return normalized; - } - return [DEFAULT_TERMINAL_ID]; -} - -function normalizeRunningTerminalIds( - runningTerminalIds: readonly string[], - terminalIds: readonly string[], -): string[] { - if (runningTerminalIds.length === 0) { - return []; - } - - const validTerminalIds = new Set(terminalIds); - return [...new Set(runningTerminalIds)] - .map((id) => id.trim()) - .filter((id) => id.length > 0 && validTerminalIds.has(id)) - .slice(0, MAX_TERMINAL_COUNT); -} - -function fallbackGroupId(terminalId: string): string { - return `group-${terminalId}`; -} - -function assignUniqueGroupId(groupId: string, usedGroupIds: Set): string { - if (!usedGroupIds.has(groupId)) { - usedGroupIds.add(groupId); - return groupId; - } - - let suffix = 2; - while (usedGroupIds.has(`${groupId}-${suffix}`)) { - suffix += 1; - } - const uniqueGroupId = `${groupId}-${suffix}`; - usedGroupIds.add(uniqueGroupId); - return uniqueGroupId; -} - -function normalizeTerminalGroups( - groups: StateThread["terminalGroups"], - terminalIds: readonly string[], -): StateThread["terminalGroups"] { - const validTerminalIds = new Set(terminalIds); - const assignedTerminalIds = new Set(); - const usedGroupIds = new Set(); - const normalizedGroups: StateThread["terminalGroups"] = []; - - for (const group of groups) { - const groupTerminalIds = [ - ...new Set(group.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)), - ].filter((terminalId) => { - if (!validTerminalIds.has(terminalId)) return false; - if (assignedTerminalIds.has(terminalId)) return false; - return true; - }); - if (groupTerminalIds.length === 0) continue; - for (const terminalId of groupTerminalIds) { - assignedTerminalIds.add(terminalId); - } - const baseGroupId = - group.id.trim().length > 0 - ? group.id.trim() - : fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_TERMINAL_ID); - normalizedGroups.push({ - id: assignUniqueGroupId(baseGroupId, usedGroupIds), - terminalIds: groupTerminalIds, - }); - } - - for (const terminalId of terminalIds) { - if (assignedTerminalIds.has(terminalId)) continue; - normalizedGroups.push({ - id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds), - terminalIds: [terminalId], - }); - } - - if (normalizedGroups.length > 0) { - return normalizedGroups; - } - - return [{ id: fallbackGroupId(DEFAULT_TERMINAL_ID), terminalIds: [DEFAULT_TERMINAL_ID] }]; -} - -function normalizeThread(thread: StateThread): StateThread { - const terminalIds = normalizeTerminalIds(thread.terminalIds); - const runningTerminalIds = normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds); - const activeTerminalId = terminalIds.includes(thread.activeTerminalId) - ? thread.activeTerminalId - : (terminalIds[0] ?? DEFAULT_TERMINAL_ID); - const terminalGroups = normalizeTerminalGroups(thread.terminalGroups, terminalIds); - const activeGroupId = - terminalGroups.find((group) => group.id === thread.activeTerminalGroupId)?.id ?? - terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? - terminalGroups[0]?.id ?? - fallbackGroupId(activeTerminalId); - - return { - ...thread, - terminalIds, - runningTerminalIds, - activeTerminalId, - terminalGroups, - activeTerminalGroupId: activeGroupId, - }; -} - function projectDocId(projectId: string): string { return `project:${projectId}`; } @@ -344,127 +186,10 @@ function threadDocId(threadId: string): string { return `thread:${threadId}`; } -function messageDocId(threadId: string, messageId: string): string { - return `message:${threadId}:${messageId}`; -} - function turnSummaryDocId(threadId: string, turnId: string): string { return `turn_summary:${threadId}:${turnId}`; } -function parsePathFromDiff(diff: string): string | null { - const normalized = diff.replace(/\r\n/g, "\n"); - const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m); - if (bPath?.[1]) return bPath[1]; - const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m); - if (gitHeader?.[1]) return gitHeader[1]; - const direct = normalized.match(/^\+\+\+ (.+)$/m); - if (!direct?.[1] || direct[1] === "/dev/null") { - return null; - } - return direct[1]; -} - -function splitUnifiedDiffByFile(diff: string): Map { - const normalized = diff.replace(/\r\n/g, "\n"); - const byPath = new Map(); - const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)]; - - if (headerMatches.length === 0) { - const pathFromDiff = parsePathFromDiff(normalized); - if (pathFromDiff) { - byPath.set(pathFromDiff, normalized.trim()); - } - return byPath; - } - - for (let index = 0; index < headerMatches.length; index += 1) { - const match = headerMatches[index]; - if (!match) continue; - const start = match.index ?? 0; - const end = headerMatches[index + 1]?.index ?? normalized.length; - const segment = normalized.slice(start, end).trim(); - const pathFromDiff = parsePathFromDiff(segment); - if (!pathFromDiff || segment.length === 0) continue; - byPath.set(pathFromDiff, segment); - } - - return byPath; -} - -function countDiffStat(patch: string): { additions: number; deletions: number } { - let additions = 0; - let deletions = 0; - for (const line of patch.replace(/\r\n/g, "\n").split("\n")) { - if (line.startsWith("+++ ") || line.startsWith("--- ")) continue; - if (line.startsWith("+")) { - additions += 1; - continue; - } - if (line.startsWith("-")) { - deletions += 1; - } - } - return { additions, deletions }; -} - -function summarizeUnifiedDiff(diff: string): StateTurnDiffFileChange[] { - try { - const parsedPatches = parsePatchFiles(diff, "state-turn-summary", false); - const files: StateTurnDiffFileChange[] = []; - for (const patch of parsedPatches) { - for (const file of patch.files) { - const additions = file.hunks.reduce((sum, hunk) => sum + hunk.additionLines, 0); - const deletions = file.hunks.reduce((sum, hunk) => sum + hunk.deletionLines, 0); - files.push({ - path: file.name, - kind: file.type, - additions, - deletions, - }); - } - } - if (files.length > 0) { - return files.toSorted((a, b) => a.path.localeCompare(b.path)); - } - } catch { - // Fallback below. - } - - const fileDiffsByPath = splitUnifiedDiffByFile(diff); - const fallback: StateTurnDiffFileChange[] = []; - for (const [filePath, fileDiff] of fileDiffsByPath) { - const stat = countDiffStat(fileDiff); - fallback.push({ - path: filePath, - additions: stat.additions, - deletions: stat.deletions, - }); - } - return fallback.toSorted((a, b) => a.path.localeCompare(b.path)); -} - -function mergeTurnSummaryFiles( - existing: StateTurnDiffFileChange[], - incoming: StateTurnDiffFileChange[], -): StateTurnDiffFileChange[] { - const byPath = new Map(existing.map((file) => [file.path, { ...file }] as const)); - for (const file of incoming) { - const previous = byPath.get(file.path); - if (!previous) { - byPath.set(file.path, { ...file }); - continue; - } - byPath.set(file.path, { - ...previous, - ...(file.kind !== undefined ? { kind: file.kind } : {}), - ...(file.additions !== undefined ? { additions: file.additions } : {}), - ...(file.deletions !== undefined ? { deletions: file.deletions } : {}), - }); - } - return Array.from(byPath.values()).toSorted((a, b) => a.path.localeCompare(b.path)); -} - export class PersistenceService extends EventEmitter { private readonly db: SqliteDatabase; private readonly sessionThreadIds = new Map(); @@ -495,20 +220,11 @@ export class PersistenceService extends EventEmitter { } getAppSettings(): AppSettings { - const metadataValue = this.readMetadata(METADATA_KEY_APP_SETTINGS); - const parsed = appSettingsSchema.safeParse(metadataValue); - if (parsed.success) { - return parsed.data; - } - return appSettingsSchema.parse({}); + return resolveAppSettings(this.readMetadata(METADATA_KEY_APP_SETTINGS)); } updateAppSettings(raw: AppSettingsUpdateInput): AppSettings { - const patch = appSettingsUpdateInputSchema.parse(raw); - const next = appSettingsSchema.parse({ - ...this.getAppSettings(), - ...patch, - }); + const next = buildUpdatedAppSettings(this.getAppSettings(), raw); this.writeMetadata(METADATA_KEY_APP_SETTINGS, next); return next; } @@ -788,7 +504,7 @@ export class PersistenceService extends EventEmitter { } const lastStateSeq = this.readLastStateSeq(); - return stateBootstrapResultSchema.parse({ + return buildStateBootstrapResult({ projects, threads, lastStateSeq, @@ -823,7 +539,7 @@ export class PersistenceService extends EventEmitter { }, ); - return stateCatchUpResultSchema.parse({ + return buildStateCatchUpResult({ events, lastStateSeq: this.readLastStateSeq(), }); @@ -861,11 +577,11 @@ export class PersistenceService extends EventEmitter { } } - const nextOffset = input.offset + payloads.length; - return stateListMessagesResultSchema.parse({ + return buildStateListMessagesResult({ messages, total, - nextOffset: nextOffset < total ? nextOffset : null, + offset: input.offset, + pageSize: payloads.length, }); } @@ -900,28 +616,12 @@ export class PersistenceService extends EventEmitter { } const messageId = input.clientMessageId ?? randomUUID(); - const text = input.clientMessageText ?? input.input ?? ""; const createdAt = nowIso(); - const inputAttachments = input.attachments ?? []; - const attachments = - inputAttachments.length > 0 - ? inputAttachments.map((attachment, index) => ({ - type: "image" as const, - id: `${messageId}:image:${index + 1}`, - name: attachment.name, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - })) - : undefined; - const message = stateMessageSchema.parse({ - id: messageId, + const message = buildUserTurnMessage({ + turn: input, threadId, - role: "user", - text, - ...(attachments ? { attachments } : {}), + messageId, createdAt, - updatedAt: createdAt, - streaming: false, }); this.withTransaction((pendingEvents) => {