Improve persistence and runtime SQLite compatibility
- add a SQLite adapter that works in both Bun and Node/Electron, with tests - persist and backfill `assistantMessageId` on turn summaries to keep thread diffs linked - prevent web state regressions by preserving turn summaries and deduplicating terminal/settings sync updates
This commit is contained in:
1 parent
1332c488ad
commit
78b7070042
13 files changed
+575
-67
No files matched your search
@@ -160,6 +160,7 @@ describe("PersistenceService", () => {
|
||||
]);
|
||||
expect(thread?.messages[1]?.text).toBe("hi there");
|
||||
expect(thread?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
|
||||
expect(thread?.turnDiffSummaries[0]?.assistantMessageId).toBe("assistant-msg-1");
|
||||
|
||||
const catchUp = service.catchUp({ afterSeq: 0 });
|
||||
expect(catchUp.events.length).toBeGreaterThan(0);
|
||||
@@ -207,10 +208,31 @@ describe("PersistenceService", () => {
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
service.ingestProviderEvent({
|
||||
id: "evt-agent-msg-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-19T00:00:01.000Z",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
itemId: "assistant-msg-1",
|
||||
payload: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: "assistant-msg-1",
|
||||
text: "done",
|
||||
},
|
||||
threadId: "runtime-thread-1",
|
||||
turnId: "turn-1",
|
||||
},
|
||||
});
|
||||
|
||||
const snapshot = service.loadSnapshot();
|
||||
const summary = snapshot.threads[0]?.turnDiffSummaries[0];
|
||||
expect(summary?.turnId).toBe("turn-1");
|
||||
expect(summary?.checkpointTurnCount).toBe(1);
|
||||
expect(summary?.assistantMessageId).toBe("assistant-msg-1");
|
||||
expect(summary?.files[0]?.path).toBe("src/app.ts");
|
||||
expect(summary?.files[0]?.additions).toBe(2);
|
||||
expect(summary?.files[0]?.deletions).toBe(1);
|
||||
|
||||
@@ -171,6 +171,13 @@ 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);
|
||||
@@ -710,7 +717,22 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
const parsedThread = this.parseJson(row.data_json, stateThreadSchema);
|
||||
if (!parsedThread) continue;
|
||||
const messages = this.listMessagesForThread(parsedThread.id);
|
||||
const turnDiffSummaries = this.listTurnSummariesForThread(parsedThread.id);
|
||||
const turnDiffSummaries = this.listTurnSummariesForThread(parsedThread.id).map((summary) => {
|
||||
if (summary.assistantMessageId) {
|
||||
return summary;
|
||||
}
|
||||
const assistantMessageId = this.findAssistantMessageIdForTurn({
|
||||
turnId: summary.turnId,
|
||||
runtimeThreadId: parsedThread.codexThreadId,
|
||||
});
|
||||
if (!assistantMessageId) {
|
||||
return summary;
|
||||
}
|
||||
return stateTurnSummarySchema.parse({
|
||||
...summary,
|
||||
assistantMessageId,
|
||||
});
|
||||
});
|
||||
threads.push({
|
||||
...parsedThread,
|
||||
turnDiffSummaries,
|
||||
@@ -1068,29 +1090,58 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
if (event.method === "item/completed") {
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) === "agentMessage") {
|
||||
if (normalizeProviderItemType(asString(item?.type)) === "agentmessage") {
|
||||
const messageId = asString(item?.id);
|
||||
if (messageId) {
|
||||
const existing = this.getMessageById(nextThread.id, messageId);
|
||||
const fullText = asString(item?.text) ?? existing?.text ?? "";
|
||||
const message = stateMessageSchema.parse({
|
||||
id: messageId,
|
||||
threadId: nextThread.id,
|
||||
role: "assistant",
|
||||
text: fullText,
|
||||
createdAt: existing?.createdAt ?? event.createdAt,
|
||||
updatedAt: event.createdAt,
|
||||
streaming: false,
|
||||
});
|
||||
this.upsertMessageDocument(nextThread, message);
|
||||
this.appendStateEvent(
|
||||
pendingEvents,
|
||||
"message.upsert",
|
||||
`${nextThread.id}:${message.id}`,
|
||||
{ threadId: nextThread.id, message },
|
||||
message.updatedAt,
|
||||
);
|
||||
if (!messageId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = this.getMessageById(nextThread.id, messageId);
|
||||
const fullText = asString(item?.text) ?? existing?.text ?? "";
|
||||
const message = stateMessageSchema.parse({
|
||||
id: messageId,
|
||||
threadId: nextThread.id,
|
||||
role: "assistant",
|
||||
text: fullText,
|
||||
createdAt: existing?.createdAt ?? event.createdAt,
|
||||
updatedAt: event.createdAt,
|
||||
streaming: false,
|
||||
});
|
||||
this.upsertMessageDocument(nextThread, message);
|
||||
this.appendStateEvent(
|
||||
pendingEvents,
|
||||
"message.upsert",
|
||||
`${nextThread.id}:${message.id}`,
|
||||
{ threadId: nextThread.id, message },
|
||||
message.updatedAt,
|
||||
);
|
||||
|
||||
const completedTurnId = parseTurnIdFromEvent(event) ?? nextThread.latestTurnId;
|
||||
if (!completedTurnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingSummary = this.getTurnSummaryByTurnId(nextThread.id, completedTurnId);
|
||||
if (!existingSummary || existingSummary.assistantMessageId === messageId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const summary = this.upsertTurnSummary(
|
||||
nextThread,
|
||||
completedTurnId,
|
||||
{
|
||||
completedAt: existingSummary.completedAt,
|
||||
assistantMessageId: messageId,
|
||||
},
|
||||
"merge",
|
||||
);
|
||||
this.appendStateEvent(
|
||||
pendingEvents,
|
||||
"turn_summary.upsert",
|
||||
`${nextThread.id}:${summary.turnId}`,
|
||||
{ threadId: nextThread.id, turnSummary: summary },
|
||||
summary.completedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1123,12 +1174,19 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
);
|
||||
|
||||
if (completedTurnId) {
|
||||
const assistantMessageId =
|
||||
this.findAssistantMessageIdForTurn({
|
||||
sessionId: event.sessionId,
|
||||
turnId: completedTurnId,
|
||||
runtimeThreadId,
|
||||
}) ?? this.findLatestAssistantMessageIdForThread(nextThread.id);
|
||||
const summary = this.upsertTurnSummary(
|
||||
nextThread,
|
||||
completedTurnId,
|
||||
{
|
||||
completedAt: event.createdAt,
|
||||
...(turnStatus ? { status: turnStatus } : {}),
|
||||
...(assistantMessageId ? { assistantMessageId } : {}),
|
||||
},
|
||||
"merge",
|
||||
);
|
||||
@@ -1164,12 +1222,19 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
const turnId = parseTurnIdFromEvent(event);
|
||||
const diff = asString(asObject(event.payload)?.diff);
|
||||
if (turnId && diff) {
|
||||
const assistantMessageId =
|
||||
this.findAssistantMessageIdForTurn({
|
||||
sessionId: event.sessionId,
|
||||
turnId,
|
||||
runtimeThreadId,
|
||||
}) ?? this.findLatestAssistantMessageIdForThread(nextThread.id);
|
||||
const summary = this.upsertTurnSummary(
|
||||
nextThread,
|
||||
turnId,
|
||||
{
|
||||
completedAt: event.createdAt,
|
||||
files: summarizeUnifiedDiff(diff),
|
||||
...(assistantMessageId ? { assistantMessageId } : {}),
|
||||
},
|
||||
"merge",
|
||||
);
|
||||
@@ -1212,6 +1277,12 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
}
|
||||
|
||||
this.withTransaction((pendingEvents) => {
|
||||
const assistantMessageId =
|
||||
this.findAssistantMessageIdForTurn({
|
||||
sessionId: input.sessionId,
|
||||
turnId,
|
||||
runtimeThreadId: input.runtimeThreadId,
|
||||
}) ?? this.findLatestAssistantMessageIdForThread(thread.id);
|
||||
const summary = this.upsertTurnSummary(
|
||||
thread,
|
||||
turnId,
|
||||
@@ -1220,6 +1291,7 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
...(input.status ? { status: input.status } : {}),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
files: summarizeUnifiedDiff(input.diff),
|
||||
...(assistantMessageId ? { assistantMessageId } : {}),
|
||||
},
|
||||
"replace",
|
||||
);
|
||||
@@ -1575,6 +1647,83 @@ export class PersistenceService extends EventEmitter<PersistenceServiceEvents> {
|
||||
return this.parseJson(row.data_json, stateTurnSummarySchema);
|
||||
}
|
||||
|
||||
private findAssistantMessageIdForTurn(input: {
|
||||
turnId: string;
|
||||
sessionId?: string;
|
||||
runtimeThreadId?: string | null;
|
||||
}): string | undefined {
|
||||
const queries: Array<{ sql: string; params: unknown[] }> = [];
|
||||
if (input.sessionId) {
|
||||
queries.push({
|
||||
sql: `SELECT item_id, payload_json
|
||||
FROM provider_events
|
||||
WHERE session_id = ? AND turn_id = ? AND method = 'item/completed'
|
||||
ORDER BY created_at DESC;`,
|
||||
params: [input.sessionId, input.turnId],
|
||||
});
|
||||
}
|
||||
if (input.runtimeThreadId) {
|
||||
queries.push({
|
||||
sql: `SELECT item_id, payload_json
|
||||
FROM provider_events
|
||||
WHERE thread_id = ? AND turn_id = ? AND method = 'item/completed'
|
||||
ORDER BY created_at DESC;`,
|
||||
params: [input.runtimeThreadId, input.turnId],
|
||||
});
|
||||
}
|
||||
queries.push({
|
||||
sql: `SELECT item_id, payload_json
|
||||
FROM provider_events
|
||||
WHERE turn_id = ? AND method = 'item/completed'
|
||||
ORDER BY created_at DESC;`,
|
||||
params: [input.turnId],
|
||||
});
|
||||
|
||||
for (const query of queries) {
|
||||
const rows = this.db.prepare(query.sql).all(...query.params) as Array<{
|
||||
item_id: string | null;
|
||||
payload_json: string | null;
|
||||
}>;
|
||||
for (const row of rows) {
|
||||
const payload = row.payload_json ? this.tryParseJson(row.payload_json) : null;
|
||||
const item = asObject(asObject(payload)?.item);
|
||||
const itemType = normalizeProviderItemType(asString(item?.type));
|
||||
if (itemType !== "agentmessage") {
|
||||
continue;
|
||||
}
|
||||
const messageId = asString(item?.id) ?? (row.item_id ?? undefined);
|
||||
if (messageId) {
|
||||
return messageId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private findLatestAssistantMessageIdForThread(threadId: string): string | undefined {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT data_json
|
||||
FROM documents
|
||||
WHERE kind = 'message' AND thread_id = ?
|
||||
ORDER BY sort_key DESC, updated_at DESC;`,
|
||||
)
|
||||
.all(threadId) as Array<{ data_json: string }>;
|
||||
|
||||
for (const row of rows) {
|
||||
const message = this.parseJson(row.data_json, stateMessageSchema);
|
||||
if (!message) {
|
||||
continue;
|
||||
}
|
||||
if (message.role === "assistant") {
|
||||
return message.id;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private listMessagesForThread(threadId: string): StateMessage[] {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { openSqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
describe("sqliteAdapter", () => {
|
||||
it("opens a database and runs basic statements", () => {
|
||||
const db = openSqliteDatabase(":memory:");
|
||||
db.exec("CREATE TABLE sample (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL);");
|
||||
|
||||
const insertResult = db.prepare("INSERT INTO sample (value) VALUES (?);").run("hello") as {
|
||||
changes?: number;
|
||||
lastInsertRowid?: number;
|
||||
};
|
||||
expect(insertResult.changes).toBe(1);
|
||||
|
||||
const row = db.prepare("SELECT value FROM sample WHERE id = ?;").get(1) as
|
||||
| { value?: string }
|
||||
| undefined;
|
||||
expect(row?.value).toBe("hello");
|
||||
|
||||
const rows = db.prepare("SELECT value FROM sample ORDER BY id ASC;").all() as Array<{
|
||||
value?: string;
|
||||
}>;
|
||||
expect(rows.map((entry) => entry.value)).toEqual(["hello"]);
|
||||
|
||||
db.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
|
||||
export interface SqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
export interface SqliteDatabase {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
interface NodeSqliteModule {
|
||||
DatabaseSync: new (filename: string) => {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => SqliteStatement;
|
||||
close: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
interface BunSqliteStatement {
|
||||
run: (...params: unknown[]) => unknown;
|
||||
get: (...params: unknown[]) => unknown;
|
||||
all: (...params: unknown[]) => unknown[];
|
||||
}
|
||||
|
||||
interface BunSqliteModule {
|
||||
Database: new (filename: string) => {
|
||||
exec: (sql: string) => unknown;
|
||||
query: (sql: string) => BunSqliteStatement;
|
||||
close: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
function openNodeSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
const nodeSqlite = requireFn("node:sqlite") as NodeSqliteModule;
|
||||
const db = new nodeSqlite.DatabaseSync(dbPath);
|
||||
return {
|
||||
exec: (sql) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
prepare: (sql) => db.prepare(sql),
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function openBunSqliteDatabase(
|
||||
requireFn: ReturnType<typeof createRequire>,
|
||||
dbPath: string,
|
||||
): SqliteDatabase {
|
||||
const bunSqlite = requireFn("bun:sqlite") as BunSqliteModule;
|
||||
const db = new bunSqlite.Database(dbPath);
|
||||
return {
|
||||
exec: (sql) => {
|
||||
db.exec(sql);
|
||||
},
|
||||
prepare: (sql) => {
|
||||
const statement = db.query(sql);
|
||||
return {
|
||||
run: (...params: unknown[]) => statement.run(...params),
|
||||
get: (...params: unknown[]) => statement.get(...params),
|
||||
all: (...params: unknown[]) => statement.all(...params),
|
||||
};
|
||||
},
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function openSqliteDatabase(dbPath: string): SqliteDatabase {
|
||||
const requireFn = createRequire(path.join(process.cwd(), "t3code-sqlite-adapter.cjs"));
|
||||
|
||||
if (process.versions.bun) {
|
||||
// Development mode runs in Bun, so use Bun's SQLite adapter
|
||||
return openBunSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
|
||||
return openNodeSqliteDatabase(requireFn, dbPath);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
|
||||
import { openSqliteDatabase, type SqliteDatabase } from "./sqliteAdapter";
|
||||
import { runStateMigrations } from "./stateMigrations";
|
||||
|
||||
export interface StateDbOptions {
|
||||
@@ -10,12 +10,12 @@ export interface StateDbOptions {
|
||||
|
||||
export class StateDb {
|
||||
readonly dbPath: string;
|
||||
readonly db: DatabaseSync;
|
||||
readonly db: SqliteDatabase;
|
||||
|
||||
constructor(options: StateDbOptions) {
|
||||
this.dbPath = path.resolve(options.dbPath);
|
||||
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
|
||||
this.db = new DatabaseSync(this.dbPath);
|
||||
this.db = openSqliteDatabase(this.dbPath);
|
||||
runStateMigrations(this.db);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { SqliteDatabase } from "./sqliteAdapter";
|
||||
|
||||
export const STATE_DB_SCHEMA_VERSION = 1;
|
||||
|
||||
export function applyStateDbPragmas(db: DatabaseSync): void {
|
||||
export function applyStateDbPragmas(db: SqliteDatabase): void {
|
||||
db.exec("PRAGMA journal_mode=WAL;");
|
||||
db.exec("PRAGMA synchronous=FULL;");
|
||||
db.exec("PRAGMA busy_timeout=5000;");
|
||||
db.exec("PRAGMA foreign_keys=ON;");
|
||||
}
|
||||
|
||||
function readUserVersion(db: DatabaseSync): number {
|
||||
function readUserVersion(db: SqliteDatabase): number {
|
||||
const row = db.prepare("PRAGMA user_version;").get() as { user_version?: number } | undefined;
|
||||
const value = row?.user_version;
|
||||
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
|
||||
@@ -18,7 +18,7 @@ function readUserVersion(db: DatabaseSync): number {
|
||||
return value;
|
||||
}
|
||||
|
||||
function migrationV1(db: DatabaseSync): void {
|
||||
function migrationV1(db: SqliteDatabase): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -74,7 +74,7 @@ function migrationV1(db: DatabaseSync): void {
|
||||
`);
|
||||
}
|
||||
|
||||
export function runStateMigrations(db: DatabaseSync): void {
|
||||
export function runStateMigrations(db: SqliteDatabase): void {
|
||||
applyStateDbPragmas(db);
|
||||
|
||||
const userVersion = readUserVersion(db);
|
||||
|
||||
Reference in new issue
Block a user