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
@@ -300,6 +300,48 @@ function backendEnv(): NodeJS.ProcessEnv {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveBackendLaunch(backendEntry: string): {
|
||||
command: string;
|
||||
args: string[];
|
||||
env: NodeJS.ProcessEnv;
|
||||
} {
|
||||
const runtimeOverride = process.env.T3CODE_BACKEND_RUNTIME?.trim();
|
||||
if (runtimeOverride && runtimeOverride.length > 0) {
|
||||
if (runtimeOverride === "electron-node") {
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [backendEntry],
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
command: runtimeOverride,
|
||||
args: [backendEntry],
|
||||
env: backendEnv(),
|
||||
};
|
||||
}
|
||||
|
||||
if (isDevelopment) {
|
||||
return {
|
||||
command: "bun",
|
||||
args: [backendEntry],
|
||||
env: backendEnv(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [backendEntry],
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
@@ -322,14 +364,10 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [backendEntry], {
|
||||
const launch = resolveBackendLaunch(backendEntry);
|
||||
const child = spawn(launch.command, launch.args, {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
env: launch.env,
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const LOCAL_APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:local:v1";
|
||||
|
||||
type StorageMap = Map<string, string>;
|
||||
|
||||
function installWindowMock(initialStorage?: StorageMap): StorageMap {
|
||||
const storage = initialStorage ?? new Map<string, string>();
|
||||
|
||||
const localStorageMock = {
|
||||
length: 0,
|
||||
clear: () => {
|
||||
storage.clear();
|
||||
localStorageMock.length = 0;
|
||||
},
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
key: (index: number) => Array.from(storage.keys())[index] ?? null,
|
||||
removeItem: (key: string) => {
|
||||
storage.delete(key);
|
||||
localStorageMock.length = storage.size;
|
||||
},
|
||||
setItem: (key: string, value: string) => {
|
||||
storage.set(key, value);
|
||||
localStorageMock.length = storage.size;
|
||||
},
|
||||
};
|
||||
|
||||
localStorageMock.length = storage.size;
|
||||
|
||||
const windowMock = {
|
||||
localStorage: localStorageMock as Storage,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
};
|
||||
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
value: windowMock,
|
||||
});
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
describe("appSettings", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
Reflect.deleteProperty(globalThis, "window");
|
||||
});
|
||||
|
||||
it("returns a stable snapshot reference when settings have not changed", async () => {
|
||||
installWindowMock();
|
||||
const module = await import("./appSettings");
|
||||
|
||||
const first = module.getAppSettingsSnapshot();
|
||||
const second = module.getAppSettingsSnapshot();
|
||||
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
it("returns a new snapshot reference when local settings change", async () => {
|
||||
const storage = installWindowMock();
|
||||
const module = await import("./appSettings");
|
||||
|
||||
const first = module.getAppSettingsSnapshot();
|
||||
storage.set(LOCAL_APP_SETTINGS_STORAGE_KEY, JSON.stringify({ confirmThreadDelete: false }));
|
||||
const second = module.getAppSettingsSnapshot();
|
||||
|
||||
expect(second).not.toBe(first);
|
||||
expect(second.confirmThreadDelete).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -34,8 +34,11 @@ const DEFAULT_APP_SETTINGS: AppSettings = {
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let cachedBackendSettings: BackendAppSettings = DEFAULT_BACKEND_APP_SETTINGS;
|
||||
let cachedBackendCacheKey = JSON.stringify(DEFAULT_BACKEND_APP_SETTINGS);
|
||||
let cachedLocalSettings = DEFAULT_LOCAL_APP_SETTINGS;
|
||||
let cachedLocalCacheKey: string | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
let cachedSnapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
let backendHydrationPromise: Promise<void> | null = null;
|
||||
let backendHydrated = false;
|
||||
let backendUpdateSequence = 0;
|
||||
@@ -46,6 +49,11 @@ function emitChange(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedBackendSettings(next: BackendAppSettings): void {
|
||||
cachedBackendSettings = next;
|
||||
cachedBackendCacheKey = JSON.stringify(next);
|
||||
}
|
||||
|
||||
function parseLegacySettings(value: string | null): z.infer<typeof legacyAppSettingsSchema> | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
@@ -152,7 +160,7 @@ async function hydrateBackendSettings(): Promise<void> {
|
||||
next = normalizeBackendSettings(await api.appSettings.update(migrationPatch));
|
||||
}
|
||||
|
||||
cachedBackendSettings = next;
|
||||
setCachedBackendSettings(next);
|
||||
backendHydrated = true;
|
||||
|
||||
if (legacySettings) {
|
||||
@@ -178,10 +186,17 @@ async function hydrateBackendSettings(): Promise<void> {
|
||||
|
||||
export function getAppSettingsSnapshot(): AppSettings {
|
||||
const localSettings = readLocalSettingsSnapshot();
|
||||
return appSettingsSchema.parse({
|
||||
const snapshotKey = `${cachedBackendCacheKey}|${cachedLocalCacheKey ?? ""}`;
|
||||
if (snapshotKey === cachedSnapshotKey) {
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
cachedSnapshot = appSettingsSchema.parse({
|
||||
...cachedBackendSettings,
|
||||
...localSettings,
|
||||
});
|
||||
cachedSnapshotKey = snapshotKey;
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
@@ -237,7 +252,7 @@ export function useAppSettings() {
|
||||
...cachedBackendSettings,
|
||||
...backendPatch,
|
||||
});
|
||||
cachedBackendSettings = optimisticNext;
|
||||
setCachedBackendSettings(optimisticNext);
|
||||
backendHydrated = true;
|
||||
didChange = true;
|
||||
|
||||
@@ -248,12 +263,12 @@ export function useAppSettings() {
|
||||
.update(backendPatch)
|
||||
.then((response) => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
cachedBackendSettings = normalizeBackendSettings(response);
|
||||
setCachedBackendSettings(normalizeBackendSettings(response));
|
||||
emitChange();
|
||||
})
|
||||
.catch(() => {
|
||||
if (updateSequence !== backendUpdateSequence) return;
|
||||
cachedBackendSettings = previous;
|
||||
setCachedBackendSettings(previous);
|
||||
emitChange();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -415,6 +415,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
|
||||
const checkpointTurnCountSyncFingerprintRef = useRef(new Map<string, string>());
|
||||
const terminalStateSyncFingerprintRef = useRef(new Map<string, string>());
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === threadId);
|
||||
const diffSearch = useMemo(
|
||||
@@ -763,6 +764,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const hasReachedTerminalLimit =
|
||||
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const activeThreadTerminalSyncId = activeThread?.id;
|
||||
const activeThreadTerminalSyncOpen = activeThread?.terminalOpen;
|
||||
const activeThreadTerminalSyncHeight = activeThread?.terminalHeight;
|
||||
const activeThreadTerminalSyncIds = activeThread?.terminalIds;
|
||||
const activeThreadTerminalSyncActiveId = activeThread?.activeTerminalId;
|
||||
const activeThreadTerminalSyncGroups = activeThread?.terminalGroups;
|
||||
const activeThreadTerminalSyncActiveGroupId = activeThread?.activeTerminalGroupId;
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThread) return;
|
||||
@@ -796,27 +804,49 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}, [activeThread?.id, activeThread?.branch, activeThread?.worktreePath, api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThread) return;
|
||||
if (
|
||||
!api ||
|
||||
!activeThreadTerminalSyncId ||
|
||||
activeThreadTerminalSyncOpen === undefined ||
|
||||
activeThreadTerminalSyncHeight === undefined ||
|
||||
activeThreadTerminalSyncIds === undefined ||
|
||||
activeThreadTerminalSyncActiveId === undefined ||
|
||||
activeThreadTerminalSyncGroups === undefined
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
threadId: activeThreadTerminalSyncId,
|
||||
terminalOpen: activeThreadTerminalSyncOpen,
|
||||
terminalHeight: activeThreadTerminalSyncHeight,
|
||||
terminalIds: activeThreadTerminalSyncIds,
|
||||
activeTerminalId: activeThreadTerminalSyncActiveId,
|
||||
terminalGroups: activeThreadTerminalSyncGroups,
|
||||
...(activeThreadTerminalSyncActiveGroupId !== undefined
|
||||
? { activeTerminalGroupId: activeThreadTerminalSyncActiveGroupId }
|
||||
: {}),
|
||||
};
|
||||
const fingerprint = JSON.stringify(payload);
|
||||
const previousFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
|
||||
if (previousFingerprint === fingerprint) return;
|
||||
terminalStateSyncFingerprintRef.current.set(payload.threadId, fingerprint);
|
||||
void api.threads
|
||||
.updateTerminalState({
|
||||
threadId: activeThread.id,
|
||||
terminalOpen: activeThread.terminalOpen,
|
||||
terminalHeight: activeThread.terminalHeight,
|
||||
terminalIds: activeThread.terminalIds,
|
||||
activeTerminalId: activeThread.activeTerminalId,
|
||||
terminalGroups: activeThread.terminalGroups,
|
||||
activeTerminalGroupId: activeThread.activeTerminalGroupId,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
.updateTerminalState(payload)
|
||||
.catch(() => {
|
||||
const currentFingerprint = terminalStateSyncFingerprintRef.current.get(payload.threadId);
|
||||
if (currentFingerprint === fingerprint) {
|
||||
terminalStateSyncFingerprintRef.current.delete(payload.threadId);
|
||||
}
|
||||
});
|
||||
}, [
|
||||
activeThread?.id,
|
||||
activeThread?.terminalOpen,
|
||||
activeThread?.terminalHeight,
|
||||
activeThread?.terminalIds,
|
||||
activeThread?.activeTerminalId,
|
||||
activeThread?.terminalGroups,
|
||||
activeThread?.activeTerminalGroupId,
|
||||
api,
|
||||
activeThreadTerminalSyncId,
|
||||
activeThreadTerminalSyncOpen,
|
||||
activeThreadTerminalSyncHeight,
|
||||
activeThreadTerminalSyncIds,
|
||||
activeThreadTerminalSyncActiveId,
|
||||
activeThreadTerminalSyncGroups,
|
||||
activeThreadTerminalSyncActiveGroupId,
|
||||
]);
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
|
||||
@@ -252,6 +252,7 @@ function TerminalViewport({
|
||||
),
|
||||
);
|
||||
});
|
||||
let didReceiveRenderableEventSinceOpen = false;
|
||||
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
@@ -279,9 +280,14 @@ function TerminalViewport({
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
});
|
||||
if (disposed) return;
|
||||
activeTerminal.write("\u001bc");
|
||||
if (snapshot.history.length > 0) {
|
||||
activeTerminal.write(snapshot.history);
|
||||
const shouldHydrateFromSnapshot =
|
||||
snapshot.history.length > 0 || !didReceiveRenderableEventSinceOpen;
|
||||
if (shouldHydrateFromSnapshot) {
|
||||
// Avoid clearing output that arrived before open() resolved.
|
||||
activeTerminal.write("\u001bc");
|
||||
if (snapshot.history.length > 0) {
|
||||
activeTerminal.write(snapshot.history);
|
||||
}
|
||||
}
|
||||
if (autoFocus) {
|
||||
window.requestAnimationFrame(() => {
|
||||
@@ -302,6 +308,10 @@ function TerminalViewport({
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
|
||||
if (event.type !== "activity") {
|
||||
didReceiveRenderableEventSinceOpen = true;
|
||||
}
|
||||
|
||||
if (event.type === "output") {
|
||||
activeTerminal.write(event.data);
|
||||
return;
|
||||
|
||||
@@ -550,6 +550,61 @@ describe("store reducer thread continuity", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not clear persisted turn summaries on thread.upsert snapshots", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:01.000Z",
|
||||
files: [{ path: "src/existing.ts", kind: "modified" }],
|
||||
assistantMessageId: "msg-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STATE_EVENT",
|
||||
event: {
|
||||
seq: 1,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-local-1",
|
||||
createdAt: "2026-02-09T00:00:05.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: "thr-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
updatedAt: "2026-02-09T00:00:05.000Z",
|
||||
lastVisitedAt: "2026-02-09T00:00:05.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
});
|
||||
|
||||
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
|
||||
const state = makeState(makeThread({ turnDiffSummaries: [] }));
|
||||
const next = reducer(state, {
|
||||
|
||||
@@ -645,13 +645,15 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
updatedAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})) ?? [];
|
||||
const payloadTurnDiffSummaries = Array.isArray(threadPayload?.turnDiffSummaries)
|
||||
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
|
||||
: undefined;
|
||||
const bootstrapThread: StateBootstrapThread = {
|
||||
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
|
||||
messages: existingStateMessages,
|
||||
turnDiffSummaries:
|
||||
(threadPayload?.turnDiffSummaries as Thread["turnDiffSummaries"] | undefined) ??
|
||||
existing?.turnDiffSummaries ??
|
||||
[],
|
||||
turnDiffSummaries: payloadTurnDiffSummaries
|
||||
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
|
||||
: existing?.turnDiffSummaries ?? [],
|
||||
};
|
||||
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
|
||||
const nextThreads = existing
|
||||
|
||||
Reference in new issue
Block a user