Type state event payloads across contracts and store

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Cursor AgentandJulius Marminge committed 2026-02-20 09:25:48 +00:00
1 parent 550069f1d1
commit e691b4a176
5 files changed
+282 -229

No files matched your search

+32 -30
View File
@@ -1,4 +1,4 @@
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession, StateEvent, TerminalEvent } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
@@ -566,7 +566,7 @@ describe("store reducer thread continuity", () => {
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: {
event: ({
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-1",
@@ -598,7 +598,7 @@ describe("store reducer thread continuity", () => {
turnDiffSummaries: [],
},
},
},
} as unknown as StateEvent),
});
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
@@ -626,33 +626,35 @@ describe("store reducer thread continuity", () => {
}),
);
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: {
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-1",
createdAt: "2026-02-09T00:00:06.000Z",
payload: {
thread: {
id: "thread-local-1",
codexThreadId: "thr-1",
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
activeTerminalId: "term-2",
activeTerminalGroupId: "group-term-2",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:06.000Z",
lastVisitedAt: "2026-02-09T00:00:06.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [],
},
const malformedStateEvent = ({
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-1",
createdAt: "2026-02-09T00:00:06.000Z",
payload: {
thread: {
id: "thread-local-1",
codexThreadId: "thr-1",
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
activeTerminalId: "term-2",
activeTerminalGroupId: "group-term-2",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:06.000Z",
lastVisitedAt: "2026-02-09T00:00:06.000Z",
branch: null,
worktreePath: null,
turnDiffSummaries: [],
},
},
} as unknown) as StateEvent;
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: malformedStateEvent,
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
@@ -674,7 +676,7 @@ describe("store reducer thread continuity", () => {
const next = reducer(state, {
type: "APPLY_STATE_EVENT",
event: {
event: ({
seq: 1,
eventType: "thread.upsert",
entityId: "thread-local-2",
@@ -696,7 +698,7 @@ describe("store reducer thread continuity", () => {
turnDiffSummaries: [],
},
},
},
} as unknown as StateEvent),
});
const createdThread = next.threads.find((thread) => thread.id === "thread-local-2");
+144 -195
View File
@@ -575,209 +575,158 @@ export function reducer(state: AppState, action: Action): AppState {
}
case "APPLY_STATE_EVENT": {
const payload = asObject(action.event.payload);
const eventType = action.event.eventType;
if (eventType === "project.upsert") {
const project = asObject(payload?.project);
const id = asString(project?.id);
const name = asString(project?.name);
const cwd = asString(project?.cwd);
const scripts = Array.isArray(project?.scripts) ? (project.scripts as ProjectScript[]) : [];
if (!id || !name || !cwd) {
return state;
switch (action.event.eventType) {
case "project.upsert": {
const project = action.event.payload.project;
const previous = state.projects.find((entry) => entry.id === project.id);
const nextProject: Project = {
id: project.id,
name: project.name,
cwd: project.cwd,
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
expanded: previous?.expanded ?? true,
scripts: normalizeProjectScripts(project.scripts),
};
const nextProjects = previous
? state.projects.map((entry) => (entry.id === project.id ? nextProject : entry))
: [...state.projects, nextProject];
return {
...state,
projects: nextProjects,
};
}
const previous = state.projects.find((entry) => entry.id === id);
const nextProject: Project = {
id,
name,
cwd,
model: resolveModelSlug(previous?.model ?? DEFAULT_MODEL),
expanded: previous?.expanded ?? true,
scripts: normalizeProjectScripts(scripts),
};
const nextProjects = previous
? state.projects.map((entry) => (entry.id === id ? nextProject : entry))
: [...state.projects, nextProject];
return {
...state,
projects: nextProjects,
};
}
if (eventType === "project.delete") {
const projectId = asString(payload?.projectId) ?? action.event.entityId;
const projects = state.projects.filter((project) => project.id !== projectId);
const threads = state.threads.filter((thread) => thread.projectId !== projectId);
const diffState = resetDiffTargetIfMissing(state, threads);
return {
...state,
projects,
threads,
...diffState,
};
}
if (eventType === "thread.upsert") {
const threadPayload = asObject(payload?.thread);
const threadId = asString(threadPayload?.id);
const projectId = asString(threadPayload?.projectId);
if (!threadId || !projectId) {
return state;
case "project.delete": {
const projectId = action.event.payload.projectId;
const projects = state.projects.filter((project) => project.id !== projectId);
const threads = state.threads.filter((thread) => thread.projectId !== projectId);
const diffState = resetDiffTargetIfMissing(state, threads);
return {
...state,
projects,
threads,
...diffState,
};
}
if (!state.projects.some((project) => project.id === projectId)) {
return state;
case "thread.upsert": {
const threadPayload = action.event.payload.thread as Partial<StateBootstrapThread> &
Pick<
StateBootstrapThread,
"id" | "projectId" | "title" | "model" | "createdAt" | "updatedAt"
>;
const threadId = threadPayload.id;
const projectId = threadPayload.projectId;
if (!state.projects.some((project) => project.id === projectId)) {
return state;
}
const existing = state.threads.find((thread) => thread.id === threadId);
const existingStateMessages =
existing?.messages.map((message) => ({
id: message.id,
threadId,
role: message.role,
text: message.text,
...(message.attachments
? {
attachments: message.attachments.map((attachment) => ({ ...attachment })),
}
: {}),
createdAt: message.createdAt,
updatedAt: message.createdAt,
streaming: message.streaming,
})) ?? [];
const payloadTurnDiffSummaries = Array.isArray(threadPayload.turnDiffSummaries)
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
: undefined;
const payloadTerminalIds = Array.isArray(threadPayload.terminalIds)
? (threadPayload.terminalIds as string[])
: (existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID]);
const payloadRunningTerminalIds = Array.isArray(threadPayload.runningTerminalIds)
? (threadPayload.runningTerminalIds as string[])
: (existing?.runningTerminalIds ?? []);
const payloadTerminalGroups = Array.isArray(threadPayload.terminalGroups)
? (threadPayload.terminalGroups as ThreadTerminalGroup[])
: (existing?.terminalGroups ?? []);
const bootstrapThread: StateBootstrapThread = {
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
terminalIds: payloadTerminalIds,
runningTerminalIds: payloadRunningTerminalIds,
terminalGroups: payloadTerminalGroups,
messages: existingStateMessages,
turnDiffSummaries: payloadTurnDiffSummaries
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
: existing?.turnDiffSummaries ?? [],
};
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
const nextThreads = existing
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
: [...state.threads, nextThread];
return {
...state,
threads: nextThreads,
};
}
const existing = state.threads.find((thread) => thread.id === threadId);
const existingStateMessages =
existing?.messages.map((message) => ({
id: message.id,
threadId,
role: message.role,
text: message.text,
...(message.attachments
? {
attachments: message.attachments.map((attachment) => ({ ...attachment })),
}
: {}),
createdAt: message.createdAt,
updatedAt: message.createdAt,
streaming: message.streaming,
})) ?? [];
const payloadTurnDiffSummaries = Array.isArray(threadPayload?.turnDiffSummaries)
? (threadPayload.turnDiffSummaries as Thread["turnDiffSummaries"])
: undefined;
const payloadTerminalIds = Array.isArray(threadPayload?.terminalIds)
? (threadPayload.terminalIds as string[])
: (existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID]);
const payloadRunningTerminalIds = Array.isArray(threadPayload?.runningTerminalIds)
? (threadPayload.runningTerminalIds as string[])
: (existing?.runningTerminalIds ?? []);
const payloadTerminalGroups = Array.isArray(threadPayload?.terminalGroups)
? (threadPayload.terminalGroups as ThreadTerminalGroup[])
: (existing?.terminalGroups ?? []);
const bootstrapThread: StateBootstrapThread = {
...(threadPayload as unknown as Omit<StateBootstrapThread, "messages">),
terminalIds: payloadTerminalIds,
runningTerminalIds: payloadRunningTerminalIds,
terminalGroups: payloadTerminalGroups,
messages: existingStateMessages,
turnDiffSummaries: payloadTurnDiffSummaries
? mergeTurnDiffSummaries(existing?.turnDiffSummaries ?? [], payloadTurnDiffSummaries)
: existing?.turnDiffSummaries ?? [],
};
const nextThread = hydrateThreadFromBootstrap(bootstrapThread, existing);
const nextThreads = existing
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
: [...state.threads, nextThread];
return {
...state,
threads: nextThreads,
};
}
if (eventType === "thread.delete") {
const threadId = asString(payload?.threadId) ?? action.event.entityId;
const nextThreads = state.threads.filter((thread) => thread.id !== threadId);
const diffState = resetDiffTargetIfMissing(state, nextThreads);
return {
...state,
threads: nextThreads,
...diffState,
};
}
if (eventType === "message.upsert") {
const threadId = asString(payload?.threadId);
const messagePayload = asObject(payload?.message);
const messageId = asString(messagePayload?.id);
const role = messagePayload?.role === "assistant" ? "assistant" : "user";
const text = typeof messagePayload?.text === "string" ? messagePayload.text : "";
const createdAt = asString(messagePayload?.createdAt);
if (!threadId || !messageId || !createdAt) {
return state;
case "thread.delete": {
const threadId = action.event.payload.threadId;
const nextThreads = state.threads.filter((thread) => thread.id !== threadId);
const diffState = resetDiffTargetIfMissing(state, nextThreads);
return {
...state,
threads: nextThreads,
...diffState,
};
}
const attachments = Array.isArray(messagePayload?.attachments)
? (messagePayload.attachments as Thread["messages"][number]["attachments"])
: undefined;
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
messages: upsertThreadMessage(thread.messages, {
id: messageId,
role,
text,
...(attachments ? { attachments } : {}),
createdAt,
streaming: messagePayload?.streaming === true,
}),
})),
};
}
if (eventType === "message.delete") {
const threadId = asString(payload?.threadId);
const messageId = asString(payload?.messageId);
if (!threadId || !messageId) {
return state;
case "message.upsert": {
const { threadId, message: messagePayload } = action.event.payload;
const attachments = messagePayload.attachments as
| Thread["messages"][number]["attachments"]
| undefined;
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
messages: upsertThreadMessage(thread.messages, {
id: messagePayload.id,
role: messagePayload.role,
text: messagePayload.text,
...(attachments ? { attachments } : {}),
createdAt: messagePayload.createdAt,
streaming: messagePayload.streaming,
}),
})),
};
}
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
messages: thread.messages.filter((message) => message.id !== messageId),
})),
};
}
if (eventType === "turn_summary.upsert") {
const threadId = asString(payload?.threadId);
const summaryPayload = asObject(payload?.turnSummary);
const turnId = asString(summaryPayload?.turnId);
const completedAt = asString(summaryPayload?.completedAt);
if (!threadId || !turnId || !completedAt) {
return state;
case "message.delete": {
const { threadId, messageId } = action.event.payload;
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
messages: thread.messages.filter((message) => message.id !== messageId),
})),
};
}
const summary: Thread["turnDiffSummaries"][number] = {
turnId,
completedAt,
status: asString(summaryPayload?.status),
files: Array.isArray(summaryPayload?.files)
? (summaryPayload.files as Thread["turnDiffSummaries"][number]["files"])
: [],
assistantMessageId: asString(summaryPayload?.assistantMessageId),
checkpointTurnCount:
typeof summaryPayload?.checkpointTurnCount === "number"
? summaryPayload.checkpointTurnCount
: undefined,
};
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
turnDiffSummaries: mergeTurnDiffSummaries(thread.turnDiffSummaries, [summary]),
})),
};
}
if (eventType === "turn_summary.delete") {
const threadId = asString(payload?.threadId);
const turnId = asString(payload?.turnId);
if (!threadId || !turnId) {
return state;
case "turn_summary.upsert": {
const { threadId, turnSummary } = action.event.payload;
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
turnDiffSummaries: mergeTurnDiffSummaries(thread.turnDiffSummaries, [turnSummary]),
})),
};
}
case "turn_summary.delete": {
const { threadId, turnId } = action.event.payload;
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
turnDiffSummaries: thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId),
})),
};
}
return {
...state,
threads: updateThread(state.threads, threadId, (thread) => ({
...thread,
turnDiffSummaries: thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId),
})),
};
}
return state;
}
case "ADD_PROJECT":
+1 -1
View File
@@ -38,7 +38,7 @@
"@effect/sql-sqlite-node": "^4.0.0-beta.6",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "^4.0.0-beta.6",
"node-pty": "^1.1.0",
"node-pty": "1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
},
+25
View File
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
stateBootstrapResultSchema,
stateCatchUpInputSchema,
stateEventSchema,
stateListMessagesInputSchema,
stateListMessagesResultSchema,
stateMessageSchema,
@@ -117,4 +118,28 @@ describe("state schemas", () => {
const catchUp = stateCatchUpInputSchema.parse({});
expect(catchUp.afterSeq).toBe(0);
});
it("validates typed state event payload variants", () => {
const event = stateEventSchema.parse({
seq: 1,
eventType: "project.upsert",
entityId: "project-1",
payload: {
project: {
id: "project-1",
cwd: "/repo",
name: "repo",
scripts: [],
createdAt: "2026-02-19T00:00:00.000Z",
updatedAt: "2026-02-19T00:00:00.000Z",
},
},
createdAt: "2026-02-19T00:00:00.000Z",
});
expect(event.eventType).toBe("project.upsert");
if (event.eventType === "project.upsert") {
expect(event.payload.project.id).toBe("project-1");
}
});
});
+80 -3
View File
@@ -103,14 +103,83 @@ export const stateCatchUpInputSchema = z.object({
afterSeq: z.number().int().min(0).default(0),
});
export const stateEventSchema = z.object({
const stateEventBaseSchema = z.object({
seq: z.number().int().positive(),
eventType: z.string().min(1),
entityId: z.string().min(1),
payload: z.unknown(),
createdAt: z.string().datetime(),
});
export const stateProjectUpsertPayloadSchema = z.object({
project: stateProjectSchema,
});
export const stateProjectDeletePayloadSchema = z.object({
projectId: z.string().min(1),
});
export const stateThreadUpsertPayloadSchema = z.object({
thread: stateThreadSchema,
});
export const stateThreadDeletePayloadSchema = z.object({
threadId: z.string().min(1),
});
export const stateMessageUpsertPayloadSchema = z.object({
threadId: z.string().min(1),
message: stateMessageSchema,
});
export const stateMessageDeletePayloadSchema = z.object({
threadId: z.string().min(1),
messageId: z.string().min(1),
});
export const stateTurnSummaryUpsertPayloadSchema = z.object({
threadId: z.string().min(1),
turnSummary: stateTurnSummarySchema,
});
export const stateTurnSummaryDeletePayloadSchema = z.object({
threadId: z.string().min(1),
turnId: z.string().min(1),
});
export const stateEventSchema = z.discriminatedUnion("eventType", [
stateEventBaseSchema.extend({
eventType: z.literal("project.upsert"),
payload: stateProjectUpsertPayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("project.delete"),
payload: stateProjectDeletePayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("thread.upsert"),
payload: stateThreadUpsertPayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("thread.delete"),
payload: stateThreadDeletePayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("message.upsert"),
payload: stateMessageUpsertPayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("message.delete"),
payload: stateMessageDeletePayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("turn_summary.upsert"),
payload: stateTurnSummaryUpsertPayloadSchema,
}),
stateEventBaseSchema.extend({
eventType: z.literal("turn_summary.delete"),
payload: stateTurnSummaryDeletePayloadSchema,
}),
]);
export const stateCatchUpResultSchema = z.object({
events: z.array(stateEventSchema),
lastStateSeq: z.number().int().min(0),
@@ -204,6 +273,14 @@ export type StateThread = z.infer<typeof stateThreadSchema>;
export type StateBootstrapThread = z.infer<typeof stateBootstrapThreadSchema>;
export type StateBootstrapResult = z.infer<typeof stateBootstrapResultSchema>;
export type StateCatchUpInput = z.input<typeof stateCatchUpInputSchema>;
export type StateProjectUpsertPayload = z.infer<typeof stateProjectUpsertPayloadSchema>;
export type StateProjectDeletePayload = z.infer<typeof stateProjectDeletePayloadSchema>;
export type StateThreadUpsertPayload = z.infer<typeof stateThreadUpsertPayloadSchema>;
export type StateThreadDeletePayload = z.infer<typeof stateThreadDeletePayloadSchema>;
export type StateMessageUpsertPayload = z.infer<typeof stateMessageUpsertPayloadSchema>;
export type StateMessageDeletePayload = z.infer<typeof stateMessageDeletePayloadSchema>;
export type StateTurnSummaryUpsertPayload = z.infer<typeof stateTurnSummaryUpsertPayloadSchema>;
export type StateTurnSummaryDeletePayload = z.infer<typeof stateTurnSummaryDeletePayloadSchema>;
export type StateEvent = z.infer<typeof stateEventSchema>;
export type StateCatchUpResult = z.infer<typeof stateCatchUpResultSchema>;
export type StateListMessagesInput = z.input<typeof stateListMessagesInputSchema>;