Project mirrored state events into LiveStore parity snapshot
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
fa39092505
commit
dae7ab8359
2 files changed
+352
-1
No files matched your search
@@ -0,0 +1,197 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { StateBootstrapResult, StateEvent } from "@t3tools/contracts";
|
||||
import { diffStateSnapshots, isStateSnapshotInParity } from "./parity";
|
||||
import { LiveStoreStateMirror } from "./liveStoreEngine";
|
||||
|
||||
function makeEvent(input: StateEvent): StateEvent {
|
||||
return input;
|
||||
}
|
||||
|
||||
function makeExpectedSnapshot(): StateBootstrapResult {
|
||||
return {
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
cwd: "/workspace/project",
|
||||
name: "project",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
updatedAt: "2026-02-20T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "thread-1",
|
||||
codexThreadId: null,
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
updatedAt: "2026-02-20T00:00:02.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-20T00:00:04.000Z",
|
||||
files: [],
|
||||
},
|
||||
],
|
||||
messages: [
|
||||
{
|
||||
id: "message-1",
|
||||
threadId: "thread-1",
|
||||
role: "user",
|
||||
text: "hello",
|
||||
createdAt: "2026-02-20T00:00:03.000Z",
|
||||
updatedAt: "2026-02-20T00:00:03.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
lastStateSeq: 4,
|
||||
};
|
||||
}
|
||||
|
||||
describe("LiveStoreStateMirror", () => {
|
||||
it("projects mirrored state events into a parity snapshot", async () => {
|
||||
const mirror = new LiveStoreStateMirror({ storeId: "shadow-parity-test" });
|
||||
const events: StateEvent[] = [
|
||||
makeEvent({
|
||||
seq: 1,
|
||||
eventType: "project.upsert",
|
||||
entityId: "project-1",
|
||||
createdAt: "2026-02-20T00:00:01.000Z",
|
||||
payload: {
|
||||
project: {
|
||||
id: "project-1",
|
||||
cwd: "/workspace/project",
|
||||
name: "project",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
updatedAt: "2026-02-20T00:00:01.000Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
seq: 2,
|
||||
eventType: "thread.upsert",
|
||||
entityId: "thread-1",
|
||||
createdAt: "2026-02-20T00:00:02.000Z",
|
||||
payload: {
|
||||
thread: {
|
||||
id: "thread-1",
|
||||
codexThreadId: null,
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
updatedAt: "2026-02-20T00:00:02.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
seq: 3,
|
||||
eventType: "message.upsert",
|
||||
entityId: "thread-1:message-1",
|
||||
createdAt: "2026-02-20T00:00:03.000Z",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
message: {
|
||||
id: "message-1",
|
||||
threadId: "thread-1",
|
||||
role: "user",
|
||||
text: "hello",
|
||||
createdAt: "2026-02-20T00:00:03.000Z",
|
||||
updatedAt: "2026-02-20T00:00:03.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
seq: 4,
|
||||
eventType: "turn_summary.upsert",
|
||||
entityId: "thread-1:turn-1",
|
||||
createdAt: "2026-02-20T00:00:04.000Z",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnSummary: {
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-20T00:00:04.000Z",
|
||||
files: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
for (const event of events) {
|
||||
await mirror.mirrorStateEvent(event);
|
||||
}
|
||||
|
||||
const expected = makeExpectedSnapshot();
|
||||
const actual = mirror.debugReadSnapshot();
|
||||
expect(diffStateSnapshots(expected, actual)).toEqual([]);
|
||||
expect(isStateSnapshotInParity(expected, actual)).toBe(true);
|
||||
} finally {
|
||||
await mirror.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("handles delete events in mirrored projections", async () => {
|
||||
const mirror = new LiveStoreStateMirror({ storeId: "shadow-delete-test" });
|
||||
try {
|
||||
await mirror.mirrorStateEvent(
|
||||
makeEvent({
|
||||
seq: 1,
|
||||
eventType: "project.upsert",
|
||||
entityId: "project-1",
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
payload: {
|
||||
project: {
|
||||
id: "project-1",
|
||||
cwd: "/workspace/project",
|
||||
name: "project",
|
||||
scripts: [],
|
||||
createdAt: "2026-02-20T00:00:00.000Z",
|
||||
updatedAt: "2026-02-20T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
await mirror.mirrorStateEvent(
|
||||
makeEvent({
|
||||
seq: 2,
|
||||
eventType: "project.delete",
|
||||
entityId: "project-1",
|
||||
createdAt: "2026-02-20T00:00:01.000Z",
|
||||
payload: { projectId: "project-1" },
|
||||
}),
|
||||
);
|
||||
|
||||
const snapshot = mirror.debugReadSnapshot();
|
||||
expect(snapshot.projects).toEqual([]);
|
||||
expect(snapshot.threads).toEqual([]);
|
||||
expect(snapshot.lastStateSeq).toBe(2);
|
||||
} finally {
|
||||
await mirror.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,14 @@
|
||||
import { makeAdapter } from "@livestore/adapter-node";
|
||||
import { createStorePromise } from "@livestore/livestore";
|
||||
import type { StateEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
stateBootstrapResultSchema,
|
||||
stateMessageSchema,
|
||||
stateProjectSchema,
|
||||
stateThreadSchema,
|
||||
stateTurnSummarySchema,
|
||||
type StateBootstrapResult,
|
||||
type StateEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { createLogger } from "../logger";
|
||||
import type { StateEventMirror } from "../stateSyncEngineShadow";
|
||||
import { liveStoreShadowSchema } from "./materializers";
|
||||
@@ -17,6 +25,17 @@ interface LiveStoreShadowStore {
|
||||
shutdownPromise?: () => Promise<void>;
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
export class LiveStoreStateMirror implements StateEventMirror {
|
||||
private readonly enabled: boolean;
|
||||
private readonly storeId: string;
|
||||
@@ -25,6 +44,16 @@ export class LiveStoreStateMirror implements StateEventMirror {
|
||||
private storePromise: Promise<LiveStoreShadowStore> | null = null;
|
||||
private lastMirroredSeq = 0;
|
||||
private disposed = false;
|
||||
private readonly projectsById = new Map<string, StateBootstrapResult["projects"][number]>();
|
||||
private readonly threadsById = new Map<string, StateBootstrapResult["threads"][number]>();
|
||||
private readonly threadMessagesByThreadId = new Map<
|
||||
string,
|
||||
Map<string, StateBootstrapResult["threads"][number]["messages"][number]>
|
||||
>();
|
||||
private readonly turnSummariesByThreadId = new Map<
|
||||
string,
|
||||
Map<string, StateBootstrapResult["threads"][number]["turnDiffSummaries"][number]>
|
||||
>();
|
||||
|
||||
constructor(options: LiveStoreStateMirrorOptions = {}) {
|
||||
this.enabled = options.enabled ?? true;
|
||||
@@ -54,6 +83,7 @@ export class LiveStoreStateMirror implements StateEventMirror {
|
||||
createdAt: event.createdAt,
|
||||
}, "shadow"),
|
||||
);
|
||||
this.applyProjection(event);
|
||||
this.lastMirroredSeq = event.seq;
|
||||
} catch (error) {
|
||||
this.logger.warn("failed to commit mirrored state event", {
|
||||
@@ -73,6 +103,10 @@ export class LiveStoreStateMirror implements StateEventMirror {
|
||||
this.store = null;
|
||||
this.storePromise = null;
|
||||
this.lastMirroredSeq = 0;
|
||||
this.projectsById.clear();
|
||||
this.threadsById.clear();
|
||||
this.threadMessagesByThreadId.clear();
|
||||
this.turnSummariesByThreadId.clear();
|
||||
if (!store) {
|
||||
return;
|
||||
}
|
||||
@@ -130,4 +164,124 @@ export class LiveStoreStateMirror implements StateEventMirror {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
debugReadSnapshot(): StateBootstrapResult {
|
||||
const projects = Array.from(this.projectsById.values());
|
||||
const threads = Array.from(this.threadsById.values()).map((thread) => {
|
||||
const messagesById = this.threadMessagesByThreadId.get(thread.id);
|
||||
const turnSummariesByTurnId = this.turnSummariesByThreadId.get(thread.id);
|
||||
return {
|
||||
...thread,
|
||||
messages: messagesById
|
||||
? Array.from(messagesById.values()).toSorted((a, b) => {
|
||||
if (a.createdAt === b.createdAt) {
|
||||
return a.id.localeCompare(b.id);
|
||||
}
|
||||
return a.createdAt.localeCompare(b.createdAt);
|
||||
})
|
||||
: [],
|
||||
turnDiffSummaries: turnSummariesByTurnId
|
||||
? Array.from(turnSummariesByTurnId.values()).toSorted((a, b) =>
|
||||
b.completedAt.localeCompare(a.completedAt),
|
||||
)
|
||||
: [],
|
||||
};
|
||||
});
|
||||
|
||||
return stateBootstrapResultSchema.parse({
|
||||
projects,
|
||||
threads,
|
||||
lastStateSeq: this.lastMirroredSeq,
|
||||
});
|
||||
}
|
||||
|
||||
private applyProjection(event: StateEvent): void {
|
||||
const payload = asObject(event.payload);
|
||||
|
||||
if (event.eventType === "project.upsert") {
|
||||
const candidate = stateProjectSchema.safeParse(payload?.project);
|
||||
if (candidate.success) {
|
||||
this.projectsById.set(candidate.data.id, candidate.data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "project.delete") {
|
||||
const projectId = asString(payload?.projectId) ?? event.entityId;
|
||||
this.projectsById.delete(projectId);
|
||||
for (const [threadId, thread] of this.threadsById.entries()) {
|
||||
if (thread.projectId !== projectId) {
|
||||
continue;
|
||||
}
|
||||
this.threadsById.delete(threadId);
|
||||
this.threadMessagesByThreadId.delete(threadId);
|
||||
this.turnSummariesByThreadId.delete(threadId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "thread.upsert") {
|
||||
const candidate = stateThreadSchema.safeParse(payload?.thread);
|
||||
if (!candidate.success) {
|
||||
return;
|
||||
}
|
||||
this.threadsById.set(candidate.data.id, {
|
||||
...candidate.data,
|
||||
messages: [],
|
||||
turnDiffSummaries: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "thread.delete") {
|
||||
const threadId = asString(payload?.threadId) ?? event.entityId;
|
||||
this.threadsById.delete(threadId);
|
||||
this.threadMessagesByThreadId.delete(threadId);
|
||||
this.turnSummariesByThreadId.delete(threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "message.upsert") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const messageCandidate = stateMessageSchema.safeParse(payload?.message);
|
||||
if (!threadId || !messageCandidate.success) {
|
||||
return;
|
||||
}
|
||||
const byId = this.threadMessagesByThreadId.get(threadId) ?? new Map();
|
||||
byId.set(messageCandidate.data.id, messageCandidate.data);
|
||||
this.threadMessagesByThreadId.set(threadId, byId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "message.delete") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const messageId = asString(payload?.messageId);
|
||||
if (!threadId || !messageId) {
|
||||
return;
|
||||
}
|
||||
this.threadMessagesByThreadId.get(threadId)?.delete(messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "turn_summary.upsert") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const summaryCandidate = stateTurnSummarySchema.safeParse(payload?.turnSummary);
|
||||
if (!threadId || !summaryCandidate.success) {
|
||||
return;
|
||||
}
|
||||
const byTurnId = this.turnSummariesByThreadId.get(threadId) ?? new Map();
|
||||
byTurnId.set(summaryCandidate.data.turnId, summaryCandidate.data);
|
||||
this.turnSummariesByThreadId.set(threadId, byTurnId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.eventType === "turn_summary.delete") {
|
||||
const threadId = asString(payload?.threadId);
|
||||
const turnId = asString(payload?.turnId);
|
||||
if (!threadId || !turnId) {
|
||||
return;
|
||||
}
|
||||
this.turnSummariesByThreadId.get(threadId)?.delete(turnId);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user