Compare commits

..
Author SHA1 Message Date
Julius MarmingeandClaude Opus 4.5 ac44561caf Move persistence to server-side with Effect and SQLite
- Add @t3tools/core package with Effect-based domain model
- Add @t3tools/infra-sqlite package for SQLite persistence
- Add CoreRuntime to server integrating the new packages
- Remove client-side persistence (persistenceSchema.ts, store.test.ts)
- Simplify web store by delegating persistence to server
- Update contracts with new IPC and WebSocket message types

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-21 17:09:07 -08:00
51 changed files with 4227 additions and 2198 deletions

No files matched your search

+2 -2
View File
@@ -106,12 +106,12 @@ T3 Code has a global runtime mode switch in the chat toolbar:
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
+3 -1
View File
@@ -17,7 +17,9 @@
"test": "vitest run"
},
"dependencies": {
"effect": "^3.19.19",
"@t3tools/core": "workspace:*",
"@t3tools/infra-sqlite": "workspace:*",
"effect": "^3.18.4",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
+108
View File
@@ -0,0 +1,108 @@
import path from "node:path";
import crypto from "node:crypto";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { EffectFanout, OrchestrationEngine, QueueProjector, type AppViewState } from "@t3tools/core";
import { createSqliteStores } from "@t3tools/infra-sqlite";
import type { ProviderManager } from "./providerManager";
import type { TerminalManager } from "./terminalManager";
function nowIso(): string {
return new Date().toISOString();
}
export class CoreRuntime {
private readonly fanout = new EffectFanout();
private readonly stores;
private readonly projector: QueueProjector;
private readonly engine: OrchestrationEngine;
constructor(dbDir: string) {
const dbPath = path.join(dbDir, "event-store.sqlite");
this.stores = createSqliteStores(dbPath);
this.projector = new QueueProjector(this.stores.projectionStore, this.fanout);
this.engine = new OrchestrationEngine(this.stores.eventStore, this.stores.projectionStore, this.projector);
}
async start(cwd: string, projectName: string): Promise<void> {
await this.engine.start();
await this.engine.execute({
id: crypto.randomUUID(),
type: "app.bootstrap",
issuedAt: nowIso(),
payload: { cwd, projectName },
});
}
async stop(): Promise<void> {
await this.engine.stop();
this.stores.db.close();
}
async state(): Promise<AppViewState> {
return this.engine.currentState();
}
async dispatch(command: Parameters<OrchestrationEngine["execute"]>[0]): Promise<AppViewState> {
return this.engine.execute(command);
}
subscribe() {
return this.fanout.subscribe();
}
bindProviderEvents(providerManager: ProviderManager): void {
providerManager.on("event", (event: ProviderEvent) => {
void this.ingestProviderEvent(event);
});
}
bindTerminalEvents(terminalManager: TerminalManager): void {
terminalManager.on("event", (event: TerminalEvent) => {
if (event.type !== "activity" && event.type !== "error" && event.type !== "exited") return;
void this.dispatch({
id: crypto.randomUUID(),
type: "thread.setTerminalActivity",
issuedAt: event.createdAt,
payload: {
threadId: event.threadId,
terminalId: event.terminalId,
running: event.type === "activity" ? event.hasRunningSubprocess : false,
},
});
});
}
async bindProviderSession(threadId: string, session: ProviderSession): Promise<void> {
await this.dispatch({
id: crypto.randomUUID(),
type: "thread.updateProviderSession",
issuedAt: nowIso(),
payload: { threadId, session },
});
}
async clearProviderSession(threadId: string): Promise<void> {
await this.dispatch({
id: crypto.randomUUID(),
type: "thread.updateProviderSession",
issuedAt: nowIso(),
payload: { threadId, session: null },
});
}
async ingestProviderEvent(event: ProviderEvent): Promise<void> {
const state = await this.state();
const target = state.threads.find((thread) => thread.session?.sessionId === event.sessionId);
if (!target) return;
await this.dispatch({
id: crypto.randomUUID(),
type: "thread.recordProviderEvent",
issuedAt: event.createdAt,
payload: {
threadId: target.id,
event,
},
});
}
}
+1 -1
View File
@@ -118,10 +118,10 @@ async function main() {
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
stateDir,
staticDir,
devUrl,
projectRegistry,
stateDir,
authToken,
});
await server.start();
@@ -1,313 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { OrchestrationEngine } from "./engine";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("OrchestrationEngine", () => {
it("replays to the same deterministic snapshot", async () => {
const stateDir = makeTempDir("t3code-orchestration-");
const createdAt = new Date().toISOString();
const projectId = "project-1";
const threadId = "thread-1";
const engineA = new OrchestrationEngine(stateDir);
await engineA.start();
await engineA.dispatch({
type: "project.create",
commandId: "cmd-1",
projectId,
name: "demo",
cwd: "/tmp/demo",
model: "gpt-5-codex",
createdAt,
});
await engineA.dispatch({
type: "thread.create",
commandId: "cmd-2",
threadId,
projectId,
title: "Thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
});
await engineA.dispatch({
type: "message.send",
commandId: "cmd-3",
threadId,
messageId: "msg-1",
role: "user",
text: "hello",
streaming: false,
createdAt,
});
const snapshotA = engineA.getSnapshot();
await engineA.stop();
const engineB = new OrchestrationEngine(stateDir);
await engineB.start();
const snapshotB = engineB.getSnapshot();
expect(snapshotB).toEqual(snapshotA);
await engineB.stop();
});
it("fans out read-model updates to subscribers", async () => {
const stateDir = makeTempDir("t3code-orchestration-fanout-");
const engine = new OrchestrationEngine(stateDir);
await engine.start();
const updates: number[] = [];
const unsubscribe = engine.subscribeToReadModel((snapshot) => {
updates.push(snapshot.sequence);
});
await engine.dispatch({
type: "project.create",
commandId: "cmd-project",
projectId: "project-2",
name: "fanout",
cwd: "/tmp/fanout",
model: "gpt-5-codex",
createdAt: new Date().toISOString(),
});
unsubscribe();
expect(updates.length).toBeGreaterThan(0);
await engine.stop();
});
it("replays append-only events from sequence", async () => {
const stateDir = makeTempDir("t3code-orchestration-replay-");
const engine = new OrchestrationEngine(stateDir);
await engine.start();
await engine.dispatch({
type: "project.create",
commandId: "cmd-a",
projectId: "project-replay",
name: "replay",
cwd: "/tmp/replay",
model: "gpt-5-codex",
createdAt: new Date().toISOString(),
});
await engine.dispatch({
type: "project.delete",
commandId: "cmd-b",
projectId: "project-replay",
createdAt: new Date().toISOString(),
});
const events = await engine.replayEvents(0);
expect(events.length).toBe(2);
expect(events[0]?.type).toBe("project.created");
expect(events[1]?.type).toBe("project.deleted");
await engine.stop();
});
it("stores completed turn summaries even when no files changed", async () => {
const stateDir = makeTempDir("t3code-orchestration-turn-diff-");
const engine = new OrchestrationEngine(stateDir);
const completedAt = new Date().toISOString();
await engine.start();
await engine.dispatch({
type: "project.create",
commandId: "cmd-project-turn-diff",
projectId: "project-turn-diff",
name: "turn-diff",
cwd: "/tmp/turn-diff",
model: "gpt-5-codex",
createdAt: completedAt,
});
await engine.dispatch({
type: "thread.create",
commandId: "cmd-thread-turn-diff",
threadId: "thread-turn-diff",
projectId: "project-turn-diff",
title: "Turn diff thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: completedAt,
});
await engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-diff-complete",
threadId: "thread-turn-diff",
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
createdAt: completedAt,
});
const firstThread = engine.getSnapshot().threads.find((thread) => thread.id === "thread-turn-diff");
expect(firstThread?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
},
]);
await engine.stop();
const restartedEngine = new OrchestrationEngine(stateDir);
await restartedEngine.start();
const restartedThread = restartedEngine
.getSnapshot()
.threads.find((thread) => thread.id === "thread-turn-diff");
expect(restartedThread?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
},
]);
await restartedEngine.stop();
});
it("reverts thread messages and turn summaries to a checkpoint", async () => {
const stateDir = makeTempDir("t3code-orchestration-revert-");
const engine = new OrchestrationEngine(stateDir);
const createdAt = new Date().toISOString();
await engine.start();
await engine.dispatch({
type: "project.create",
commandId: "cmd-project-revert",
projectId: "project-revert",
name: "revert",
cwd: "/tmp/revert",
model: "gpt-5-codex",
createdAt,
});
await engine.dispatch({
type: "thread.create",
commandId: "cmd-thread-revert",
threadId: "thread-revert",
projectId: "project-revert",
title: "Revert thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
});
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-1-user",
threadId: "thread-revert",
messageId: "user-1",
role: "user",
text: "first",
streaming: false,
createdAt,
});
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-1-assistant",
threadId: "thread-revert",
messageId: "assistant:turn-1",
role: "assistant",
text: "first-response",
streaming: false,
createdAt,
});
await engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-1-complete",
threadId: "thread-revert",
turnId: "turn-1",
completedAt: createdAt,
status: "completed",
files: [],
assistantMessageId: "assistant:turn-1",
checkpointTurnCount: 1,
createdAt,
});
const createdAtSecond = new Date(Date.now() + 1_000).toISOString();
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-2-user",
threadId: "thread-revert",
messageId: "user-2",
role: "user",
text: "second",
streaming: false,
createdAt: createdAtSecond,
});
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-2-assistant",
threadId: "thread-revert",
messageId: "assistant:turn-2",
role: "assistant",
text: "second-response",
streaming: false,
createdAt: createdAtSecond,
});
await engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-2-complete",
threadId: "thread-revert",
turnId: "turn-2",
completedAt: createdAtSecond,
status: "completed",
files: [],
assistantMessageId: "assistant:turn-2",
checkpointTurnCount: 2,
createdAt: createdAtSecond,
});
await engine.dispatch({
type: "thread.revert",
commandId: "cmd-thread-revert-apply",
threadId: "thread-revert",
turnCount: 1,
messageCount: 2,
createdAt: createdAtSecond,
});
const thread = engine.getSnapshot().threads.find((entry) => entry.id === "thread-revert");
expect(thread?.messages.map((message) => message.id)).toEqual(["user-1", "assistant:turn-1"]);
expect(thread?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
expect(thread?.latestTurnId).toBe("turn-1");
await engine.stop();
const restarted = new OrchestrationEngine(stateDir);
await restarted.start();
const restartedThread = restarted
.getSnapshot()
.threads.find((entry) => entry.id === "thread-revert");
expect(restartedThread?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant:turn-1",
]);
expect(restartedThread?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
await restarted.stop();
});
it("allows stop to be called multiple times", async () => {
const stateDir = makeTempDir("t3code-orchestration-stop-");
const engine = new OrchestrationEngine(stateDir);
await engine.start();
await engine.stop();
await expect(engine.stop()).resolves.toBeUndefined();
});
});
-308
View File
@@ -1,308 +0,0 @@
import path from "node:path";
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { OrchestrationCommandSchema } from "@t3tools/contracts";
import { Queue, Schema, Stream, Effect, Fiber, Runtime, Either } from "effect";
import { createLogger } from "../logger";
import { SqliteEventStore } from "./eventStore";
import { createEmptyReadModel, reduceEvent } from "./reducer";
import { UI_ENTITY_CONTRACTS } from "./uiContractInventory";
type CommandEnvelope = {
command: OrchestrationCommand;
resolve: (result: { sequence: number }) => void;
reject: (error: Error) => void;
};
function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEvent, "sequence"> {
const eventId = crypto.randomUUID();
switch (command.type) {
case "project.create":
return {
eventId,
type: "project.created",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.projectId,
name: command.name,
cwd: command.cwd,
model: command.model,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
case "project.delete":
return {
eventId,
type: "project.deleted",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.projectId,
deletedAt: command.createdAt,
},
};
case "thread.create":
return {
eventId,
type: "thread.created",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.threadId,
projectId: command.projectId,
title: command.title,
model: command.model,
branch: command.branch,
worktreePath: command.worktreePath,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
case "thread.delete":
return {
eventId,
type: "thread.deleted",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.threadId,
deletedAt: command.createdAt,
},
};
case "thread.meta.update":
return {
eventId,
type: "thread.meta-updated",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: command.createdAt,
},
};
case "message.send":
return {
eventId,
type: "message.sent",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.messageId,
role: command.role,
text: command.text,
threadId: command.threadId,
createdAt: command.createdAt,
streaming: command.streaming === true,
},
};
case "thread.session":
return {
eventId,
type: "thread.session-set",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
session: command.session,
},
};
case "git.readModel.upsert":
return {
eventId,
type: "git.read-model-upsert",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
projectId: command.projectId,
branch: command.branch,
hasWorkingTreeChanges: command.hasWorkingTreeChanges,
aheadCount: command.aheadCount,
behindCount: command.behindCount,
updatedAt: command.createdAt,
},
};
case "thread.turnDiff.complete":
return {
eventId,
type: "thread.turn-diff-completed",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
turnId: command.turnId,
completedAt: command.completedAt,
...(command.status !== undefined ? { status: command.status } : {}),
files: command.files,
...(command.assistantMessageId !== undefined
? { assistantMessageId: command.assistantMessageId }
: {}),
...(command.checkpointTurnCount !== undefined
? { checkpointTurnCount: command.checkpointTurnCount }
: {}),
},
};
case "thread.revert":
return {
eventId,
type: "thread.reverted",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
turnCount: command.turnCount,
messageCount: command.messageCount,
},
};
}
}
export class OrchestrationEngine {
private readonly logger = createLogger("orchestration");
private readonly runtime = Runtime.defaultRuntime;
private readonly eventStore: SqliteEventStore;
private readModel: OrchestrationReadModel;
private commandQueue: Queue.Queue<CommandEnvelope>;
private workerFiber: Fiber.RuntimeFiber<void, unknown> | null = null;
private readonly readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>();
private readonly domainEventListeners = new Set<(event: OrchestrationEvent) => void>();
constructor(stateDir: string) {
const dbPath = path.join(stateDir, "orchestration.sqlite");
this.eventStore = new SqliteEventStore(dbPath);
this.readModel = createEmptyReadModel(new Date().toISOString());
this.commandQueue = Runtime.runSync(this.runtime)(Queue.unbounded<CommandEnvelope>());
}
async start(): Promise<void> {
const existingEvents = await Runtime.runPromise(this.runtime)(this.eventStore.readAll());
for (const event of existingEvents) {
this.readModel = reduceEvent(this.readModel, event);
}
const worker = Stream.fromQueue(this.commandQueue).pipe(
Stream.runForEach((envelope) =>
Effect.tryPromise({
try: async () => {
const eventBase = mapCommandToEvent(envelope.command);
const savedEvent = await Runtime.runPromise(this.runtime)(
this.eventStore.append(eventBase),
);
this.readModel = reduceEvent(this.readModel, savedEvent);
for (const listener of this.domainEventListeners) {
listener(savedEvent);
}
for (const listener of this.readModelListeners) {
listener(this.readModel);
}
envelope.resolve({ sequence: savedEvent.sequence });
},
catch: (error) => {
const message =
error instanceof Error ? error.message : "Unknown command processing error";
envelope.reject(new Error(message));
return undefined;
},
}),
),
);
this.workerFiber = Runtime.runFork(this.runtime)(worker);
this.logger.info("orchestration engine started", {
sequence: this.readModel.sequence,
contracts: UI_ENTITY_CONTRACTS.length,
});
}
async stop(): Promise<void> {
if (this.workerFiber) {
await Runtime.runPromise(this.runtime)(Fiber.interrupt(this.workerFiber));
this.workerFiber = null;
}
this.eventStore.close();
}
getSnapshot(): OrchestrationReadModel {
return this.readModel;
}
async replayEvents(fromSequenceExclusive: number): Promise<OrchestrationEvent[]> {
return Runtime.runPromise(this.runtime)(
this.eventStore.readFromSequence(fromSequenceExclusive),
);
}
async dispatchUnknown(command: unknown): Promise<{ sequence: number }> {
const decode = Schema.decodeUnknownEither(OrchestrationCommandSchema);
let payload: unknown = command;
if (typeof command === "string") {
try {
payload = JSON.parse(command) as unknown;
} catch {
throw new Error("Invalid orchestration command: payload is not valid JSON");
}
}
const decoded = decode(payload);
if (Either.isLeft(decoded)) {
const issues = decoded.left.toString();
throw new Error(`Invalid orchestration command: ${issues}`);
}
return this.dispatch(decoded.right);
}
async dispatch(command: OrchestrationCommand): Promise<{ sequence: number }> {
return new Promise<{ sequence: number }>((resolve, reject) => {
Runtime.runPromise(this.runtime)(
Queue.offer(this.commandQueue, { command, resolve, reject }),
).catch((error) => {
const message = error instanceof Error ? error.message : "Queue offer failed";
reject(new Error(message));
});
});
}
subscribeToReadModel(callback: (snapshot: OrchestrationReadModel) => void): () => void {
this.readModelListeners.add(callback);
return () => {
this.readModelListeners.delete(callback);
};
}
subscribeToDomainEvents(callback: (event: OrchestrationEvent) => void): () => void {
this.domainEventListeners.add(callback);
return () => {
this.domainEventListeners.delete(callback);
};
}
}
-146
View File
@@ -1,146 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync, StatementSync } from "node:sqlite";
import type { SQLOutputValue } from "node:sqlite";
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Effect } from "effect";
interface EventRow {
sequence: number;
event_id: string;
event_type: string;
aggregate_type: string;
aggregate_id: string;
occurred_at: string;
command_id: string | null;
payload_json: string;
}
function readRequiredString(
row: Record<string, SQLOutputValue>,
column: keyof EventRow,
): string {
const value = row[column];
if (typeof value !== "string") {
throw new Error(`Invalid SQLite value for ${String(column)}: expected string`);
}
return value;
}
function readOptionalString(
row: Record<string, SQLOutputValue>,
column: keyof EventRow,
): string | null {
const value = row[column];
if (value === null) return null;
if (typeof value !== "string") {
throw new Error(`Invalid SQLite value for ${String(column)}: expected string or null`);
}
return value;
}
function readRequiredNumber(
row: Record<string, SQLOutputValue>,
column: keyof EventRow,
): number {
const value = row[column];
if (typeof value === "number") return value;
if (typeof value === "bigint") return Number(value);
throw new Error(`Invalid SQLite value for ${String(column)}: expected number`);
}
export class SqliteEventStore {
private readonly db: DatabaseSync;
private readonly insertStatement: StatementSync;
private closed = false;
constructor(dbPath: string) {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec("PRAGMA journal_mode = WAL;");
this.db.exec("PRAGMA foreign_keys = ON;");
this.migrate();
this.insertStatement = this.db.prepare(`
INSERT INTO orchestration_events (
event_id, event_type, aggregate_type, aggregate_id, occurred_at, command_id, payload_json
)
VALUES (?, ?, ?, ?, ?, ?, ?)
`);
}
private migrate(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS orchestration_events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
event_type TEXT NOT NULL,
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
occurred_at TEXT NOT NULL,
command_id TEXT,
payload_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_orch_events_aggregate
ON orchestration_events(aggregate_type, aggregate_id, sequence);
`);
}
append(event: Omit<OrchestrationEvent, "sequence">): Effect.Effect<OrchestrationEvent> {
return Effect.sync(() => {
const result = this.insertStatement.run(
event.eventId,
event.type,
event.aggregateType,
event.aggregateId,
event.occurredAt,
event.commandId,
JSON.stringify(event.payload),
);
return {
...event,
sequence: Number(result.lastInsertRowid),
};
});
}
readFromSequence(sequenceExclusive: number, limit = 1_000): Effect.Effect<OrchestrationEvent[]> {
return Effect.sync(() => {
const rows = this.db
.prepare(
`
SELECT sequence, event_id, event_type, aggregate_type, aggregate_id, occurred_at, command_id, payload_json
FROM orchestration_events
WHERE sequence > ?
ORDER BY sequence ASC
LIMIT ?
`,
)
.all(sequenceExclusive, limit);
return rows.map((row) => ({
sequence: readRequiredNumber(row, "sequence"),
eventId: readRequiredString(row, "event_id"),
type: readRequiredString(row, "event_type"),
aggregateType: readRequiredString(row, "aggregate_type"),
aggregateId: readRequiredString(row, "aggregate_id"),
occurredAt: readRequiredString(row, "occurred_at"),
commandId: readOptionalString(row, "command_id"),
payload: JSON.parse(readRequiredString(row, "payload_json")) as unknown,
}));
});
}
readAll(): Effect.Effect<OrchestrationEvent[]> {
return this.readFromSequence(0, Number.MAX_SAFE_INTEGER);
}
close(): void {
if (this.closed) {
return;
}
this.closed = true;
this.db.close();
}
}
-322
View File
@@ -1,322 +0,0 @@
import type {
OrchestrationEvent,
OrchestrationGitReadModel,
OrchestrationMessage,
OrchestrationProject,
OrchestrationReadModel,
OrchestrationSession,
OrchestrationThread,
} from "@t3tools/contracts";
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: string,
patch: ThreadPatch,
): OrchestrationThread[] {
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
}
function asObject(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object") return null;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
return {
sequence: 0,
projects: [],
threads: [],
gitByProjectId: {},
updatedAt: nowIso,
};
}
export function reduceEvent(
model: OrchestrationReadModel,
event: OrchestrationEvent,
): OrchestrationReadModel {
const payload = asObject(event.payload);
const nextBase: OrchestrationReadModel = {
...model,
sequence: event.sequence,
updatedAt: event.occurredAt,
};
switch (event.type) {
case "project.created": {
if (!payload) return nextBase;
const project: OrchestrationProject = {
id: asString(payload.id) ?? event.aggregateId,
name: asString(payload.name) ?? "project",
cwd: asString(payload.cwd) ?? "",
model: asString(payload.model) ?? "gpt-5-codex",
createdAt: asString(payload.createdAt) ?? event.occurredAt,
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
};
const existing = nextBase.projects.find((entry) => entry.id === project.id);
return {
...nextBase,
projects: existing
? nextBase.projects.map((entry) => (entry.id === project.id ? project : entry))
: [...nextBase.projects, project],
};
}
case "project.deleted":
return {
...nextBase,
projects: nextBase.projects.filter((project) => project.id !== event.aggregateId),
threads: nextBase.threads.filter((thread) => thread.projectId !== event.aggregateId),
};
case "thread.created": {
if (!payload) return nextBase;
const thread: OrchestrationThread = {
id: asString(payload.id) ?? event.aggregateId,
projectId: asString(payload.projectId) ?? "",
title: asString(payload.title) ?? "New thread",
model: asString(payload.model) ?? "gpt-5-codex",
branch: asString(payload.branch),
worktreePath: asString(payload.worktreePath),
createdAt: asString(payload.createdAt) ?? event.occurredAt,
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
latestTurnId: null,
latestTurnStartedAt: null,
latestTurnCompletedAt: null,
latestTurnDurationMs: null,
messages: [],
session: null,
turnDiffSummaries: [],
error: null,
};
const existing = nextBase.threads.find((entry) => entry.id === thread.id);
return {
...nextBase,
threads: existing
? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
: [...nextBase.threads, thread],
};
}
case "thread.deleted":
return {
...nextBase,
threads: nextBase.threads.filter((thread) => thread.id !== event.aggregateId),
};
case "thread.meta-updated": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
if (!thread) return nextBase;
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
...(asString(payload.title) !== null ? { title: asString(payload.title) ?? thread.title } : {}),
...(asString(payload.model) !== null ? { model: asString(payload.model) ?? thread.model } : {}),
...(payload.branch !== undefined ? { branch: asString(payload.branch) } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: asString(payload.worktreePath) } : {}),
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
}),
};
}
case "message.sent": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const message: OrchestrationMessage = {
id: asString(payload.id) ?? crypto.randomUUID(),
role: (asString(payload.role) as OrchestrationMessage["role"] | null) ?? "user",
text: asString(payload.text) ?? "",
createdAt: asString(payload.createdAt) ?? event.occurredAt,
streaming: payload.streaming === true,
};
const targetThread = nextBase.threads.find((thread) => thread.id === threadId);
if (!targetThread) return nextBase;
const existingMessage = targetThread.messages.find((entry) => entry.id === message.id);
const nextMessages = existingMessage
? targetThread.messages.map((entry) =>
entry.id === message.id
? {
...entry,
text:
message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
createdAt: message.createdAt,
}
: entry,
)
: [...targetThread.messages, message];
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
messages: nextMessages,
updatedAt: event.occurredAt,
}),
};
}
case "thread.session-set": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
if (!thread) return nextBase;
const sessionPayload = asObject(payload.session);
if (!sessionPayload) return nextBase;
const session: OrchestrationSession = {
sessionId: asString(sessionPayload.sessionId) ?? crypto.randomUUID(),
status:
(asString(sessionPayload.status) as OrchestrationSession["status"] | null) ?? "connecting",
provider:
(asString(sessionPayload.provider) as OrchestrationSession["provider"] | null) ?? "codex",
threadId,
activeTurnId: asString(sessionPayload.activeTurnId),
createdAt: asString(sessionPayload.createdAt) ?? event.occurredAt,
updatedAt: asString(sessionPayload.updatedAt) ?? event.occurredAt,
lastError: asString(sessionPayload.lastError),
};
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
session,
updatedAt: event.occurredAt,
error: session.lastError,
}),
};
}
case "thread.turn-diff-completed": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
const turnId = asString(payload.turnId);
if (!thread || !turnId) return nextBase;
const files = asArray(payload.files).flatMap((filePayload) => {
const file = asObject(filePayload);
const filePath = asString(file?.path);
if (!filePath) {
return [];
}
const nextFile: {
path: string;
kind?: string;
additions?: number;
deletions?: number;
} = { path: filePath };
const kind = asString(file?.kind);
if (kind !== null) {
nextFile.kind = kind;
}
const additions = asNumber(file?.additions);
if (additions !== null) {
nextFile.additions = additions;
}
const deletions = asNumber(file?.deletions);
if (deletions !== null) {
nextFile.deletions = deletions;
}
return [nextFile];
});
const nextSummary = {
turnId,
completedAt: asString(payload.completedAt) ?? event.occurredAt,
...(asString(payload.status) !== null ? { status: asString(payload.status) ?? undefined } : {}),
files,
...(asString(payload.assistantMessageId) !== null
? { assistantMessageId: asString(payload.assistantMessageId) ?? undefined }
: {}),
...(asNumber(payload.checkpointTurnCount) !== null
? { checkpointTurnCount: asNumber(payload.checkpointTurnCount) ?? undefined }
: {}),
};
const turnDiffSummaries = [...thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId), nextSummary]
.toSorted((left, right) => left.completedAt.localeCompare(right.completedAt));
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
latestTurnId: turnId,
latestTurnCompletedAt: nextSummary.completedAt,
turnDiffSummaries,
updatedAt: event.occurredAt,
}),
};
}
case "thread.reverted": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
if (!thread) return nextBase;
const targetTurnCount = Math.max(0, Math.floor(asNumber(payload.turnCount) ?? 0));
const targetMessageCount = Math.max(0, Math.floor(asNumber(payload.messageCount) ?? 0));
const sortedSummaries = [...thread.turnDiffSummaries].toSorted((left, right) =>
left.completedAt.localeCompare(right.completedAt),
);
const inferredTurnCountByTurnId = new Map<string, number>();
for (let index = 0; index < sortedSummaries.length; index += 1) {
const summary = sortedSummaries[index];
if (!summary) continue;
inferredTurnCountByTurnId.set(summary.turnId, index + 1);
}
const turnDiffSummaries = thread.turnDiffSummaries
.filter((summary) => {
const checkpointTurnCount =
summary.checkpointTurnCount ?? inferredTurnCountByTurnId.get(summary.turnId) ?? 0;
return checkpointTurnCount <= targetTurnCount;
})
.toSorted((left, right) => left.completedAt.localeCompare(right.completedAt));
const latestSummary =
turnDiffSummaries.length > 0 ? turnDiffSummaries[turnDiffSummaries.length - 1] : null;
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
messages: thread.messages.slice(0, Math.min(targetMessageCount, thread.messages.length)),
turnDiffSummaries,
latestTurnId: latestSummary?.turnId ?? null,
latestTurnStartedAt: null,
latestTurnCompletedAt: latestSummary?.completedAt ?? null,
latestTurnDurationMs: null,
updatedAt: event.occurredAt,
}),
};
}
case "git.read-model-upsert": {
if (!payload) return nextBase;
const projectId = asString(payload.projectId) ?? event.aggregateId;
const gitReadModel: OrchestrationGitReadModel = {
projectId,
branch: asString(payload.branch),
hasWorkingTreeChanges: payload.hasWorkingTreeChanges === true,
aheadCount: asNumber(payload.aheadCount) ?? 0,
behindCount: asNumber(payload.behindCount) ?? 0,
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
};
return {
...nextBase,
gitByProjectId: {
...nextBase.gitByProjectId,
[projectId]: gitReadModel,
},
};
}
default:
return nextBase;
}
}
@@ -1,66 +0,0 @@
export interface UiEntityContract {
entity: string;
requiredFields: string[];
consumedBy: string[];
}
// Explicit UI inventory used to keep server read models aligned
// with what the current frontend renders.
export const UI_ENTITY_CONTRACTS: UiEntityContract[] = [
{
entity: "Project",
requiredFields: ["id", "name", "cwd", "model"],
consumedBy: ["apps/web/src/components/Sidebar.tsx"],
},
{
entity: "Thread",
requiredFields: [
"id",
"projectId",
"title",
"model",
"branch",
"worktreePath",
"createdAt",
"latestTurnId",
"latestTurnStartedAt",
"latestTurnCompletedAt",
"latestTurnDurationMs",
"error",
],
consumedBy: [
"apps/web/src/components/Sidebar.tsx",
"apps/web/src/components/ChatView.tsx",
"apps/web/src/components/BranchToolbar.tsx",
],
},
{
entity: "Message",
requiredFields: ["id", "role", "text", "createdAt", "streaming"],
consumedBy: ["apps/web/src/components/ChatView.tsx"],
},
{
entity: "ProviderSession",
requiredFields: [
"sessionId",
"provider",
"status",
"threadId",
"activeTurnId",
"createdAt",
"updatedAt",
"lastError",
],
consumedBy: ["apps/web/src/components/ChatView.tsx", "apps/web/src/components/Sidebar.tsx"],
},
{
entity: "TurnDiffSummary",
requiredFields: ["turnId", "completedAt", "status", "files"],
consumedBy: ["apps/web/src/components/DiffPanel.tsx", "apps/web/src/components/ChatView.tsx"],
},
{
entity: "GitReadModel",
requiredFields: ["projectId", "branch", "hasWorkingTreeChanges", "aheadCount", "behindCount"],
consumedBy: ["apps/web/src/components/GitActionsControl.tsx", "apps/web/src/components/BranchToolbar.tsx"],
},
];
+1 -14
View File
@@ -298,14 +298,12 @@ describe("ProviderManager", () => {
it("emits checkpoint/captured after turn completion checkpoint capture", async () => {
const manager = new ProviderManager();
const events: Array<{ method: string; payload?: unknown; threadId?: string; turnId?: string }> =
[];
const events: Array<{ method: string; payload?: unknown; threadId?: string }> = [];
manager.on("event", (event) => {
events.push({
method: event.method,
...(event.payload !== undefined ? { payload: event.payload } : {}),
...(event.threadId ? { threadId: event.threadId } : {}),
...(event.turnId ? { turnId: event.turnId } : {}),
});
});
@@ -318,8 +316,6 @@ describe("ProviderManager", () => {
createdAt: string;
method: string;
threadId: string;
turnId?: string;
payload?: unknown;
}) => void;
codex: {
hasSession: (sessionId: string) => boolean;
@@ -355,12 +351,6 @@ describe("ProviderManager", () => {
createdAt: "2026-02-19T00:00:00.000Z",
method: "turn/completed",
threadId: "thr_1",
turnId: "turn_1",
payload: {
turn: {
status: "completed",
},
},
});
await vi.waitFor(() => {
@@ -374,12 +364,9 @@ describe("ProviderManager", () => {
const checkpointCapturedEvent = events.find((event) => event.method === "checkpoint/captured");
expect(checkpointCapturedEvent?.threadId).toBe("thr_1");
expect(checkpointCapturedEvent?.turnId).toBe("turn_1");
expect(checkpointCapturedEvent?.payload).toEqual({
threadId: "thr_1",
turnCount: 1,
turnId: "turn_1",
status: "completed",
});
manager.dispose();
+3 -31
View File
@@ -130,12 +130,6 @@ function summarizeTurn(turn: CodexThreadTurnSnapshot): {
};
}
function readTurnCompletionStatus(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.status);
}
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
const checkpoints: ProviderCheckpoint[] = [];
let messageCount = 0;
@@ -481,7 +475,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
return;
}
const turnStatus = readTurnCompletionStatus(event);
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
if (!checkpointCwd) {
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId)
@@ -490,13 +483,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
return;
}
const snapshot = await this.codex.readThread(event.sessionId);
this.emitCheckpointCaptured(
event.sessionId,
snapshot.threadId,
snapshot.turns.length,
event.turnId,
turnStatus,
);
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
})
.catch((error) => {
const message =
@@ -517,26 +504,14 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
this.emitCheckpointCaptured(
event.sessionId,
snapshot.threadId,
snapshot.turns.length,
event.turnId,
turnStatus,
);
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
}).catch((error) => {
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
}
private emitCheckpointCaptured(
sessionId: string,
threadId: string,
turnCount: number,
turnId?: string,
status?: string,
): void {
private emitCheckpointCaptured(sessionId: string, threadId: string, turnCount: number): void {
this.emit("event", {
id: randomUUID(),
kind: "notification",
@@ -545,12 +520,9 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
createdAt: new Date().toISOString(),
method: "checkpoint/captured",
threadId,
...(turnId ? { turnId } : {}),
payload: {
threadId,
turnCount,
...(turnId ? { turnId } : {}),
...(status ? { status } : {}),
},
});
}
+21 -17
View File
@@ -621,8 +621,7 @@ describe("WebSocket Server", () => {
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome + initial orchestration snapshot pushes
await waitForMessage(ws);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, "nonexistent.method");
@@ -630,6 +629,23 @@ describe("WebSocket Server", () => {
expect(response.error!.message).toContain("Unknown method");
});
it("responds to providers.listSessions with empty array", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.providersListSessions);
expect(response.error).toBeUndefined();
expect(response.result).toEqual([]);
});
it("returns unknown-session errors for checkpoint RPCs without an active provider session", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
@@ -784,21 +800,9 @@ describe("WebSocket Server", () => {
// Send garbage
ws.send("not json at all");
let response: WsResponse | null = null;
for (let attempt = 0; attempt < 5; attempt += 1) {
const message = (await waitForMessage(ws)) as Record<string, unknown>;
if (typeof message.id === "string" && message.id === "unknown") {
response = message as WsResponse;
break;
}
if (message.error) {
response = message as WsResponse;
break;
}
}
expect(response).toBeDefined();
expect(response!.error).toBeDefined();
expect(response!.error!.message).toContain("Invalid request format");
const response = (await waitForMessage(ws)) as WsResponse;
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Invalid request format");
});
it("supports projects list/add/dedupe/remove", async () => {
+184 -266
View File
@@ -3,15 +3,13 @@ import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import type { Duplex } from "node:stream";
import {
EDITORS,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
WS_CHANNELS,
WS_METHODS,
type OrchestrationReadModelPush,
type TerminalEvent,
type WsPush,
type WsRequest,
@@ -36,7 +34,7 @@ import {
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { OrchestrationEngine } from "./orchestration/engine";
import { CoreRuntime } from "./coreRuntime";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -57,11 +55,11 @@ export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
stateDir?: string | undefined;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
stateDir?: string | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
@@ -75,29 +73,16 @@ function parseBooleanEnv(value: string | undefined): boolean | undefined {
return undefined;
}
function asObject(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object") return null;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
export function createServer(options: ServerOptions) {
const {
port,
host,
cwd,
stateDir,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
stateDir,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
authToken,
@@ -107,11 +92,12 @@ export function createServer(options: ServerOptions) {
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const gitManager = providedGitManager ?? new GitManager();
const orchestrationEngine = new OrchestrationEngine(
stateDir ?? path.join(os.homedir(), ".t3", "userdata"),
);
const runtimeStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
const coreRuntime = new CoreRuntime(runtimeStateDir);
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
@@ -125,15 +111,7 @@ export function createServer(options: ServerOptions) {
});
}
const unsubscribeReadModel = orchestrationEngine.subscribeToReadModel((snapshot) => {
const push: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: snapshot.sequence,
snapshot,
} satisfies OrchestrationReadModelPush,
};
function broadcastPush(push: WsPush): void {
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
@@ -143,134 +121,31 @@ export function createServer(options: ServerOptions) {
}
}
logOutgoingPush(push, recipients);
});
const unsubscribeDomainEvents = orchestrationEngine.subscribeToDomainEvents((event) => {
const push: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
});
// Forward provider events to all connected WebSocket clients
providerManager.on("event", (event) => {
void (async () => {
const snapshot = orchestrationEngine.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.session?.sessionId === event.sessionId);
if (!thread) return;
const now = event.createdAt;
if (event.method === "turn/started" || event.method === "turn/completed") {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: event.method === "turn/started" ? "running" : "ready",
threadId: thread.id,
activeTurnId: event.method === "turn/started" ? (event.turnId ?? null) : null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: null,
},
createdAt: now,
});
}
if (event.textDelta && event.textDelta.length > 0) {
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
await orchestrationEngine.dispatch({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: event.textDelta,
streaming: true,
createdAt: now,
});
}
if (event.method === "turn/completed") {
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
await orchestrationEngine.dispatch({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: "",
streaming: false,
createdAt: now,
});
}
if (event.method === "checkpoint/captured") {
const payload = asObject(event.payload);
const turnId = event.turnId ?? asString(payload?.turnId);
if (turnId) {
await orchestrationEngine.dispatch({
type: "thread.turnDiff.complete",
commandId: crypto.randomUUID(),
threadId: thread.id,
turnId,
completedAt: now,
...(asString(payload?.status) !== null ? { status: asString(payload?.status) ?? undefined } : {}),
files: [],
assistantMessageId: `assistant:${turnId}`,
...(asNumber(payload?.turnCount) !== null
? { checkpointTurnCount: asNumber(payload?.turnCount) ?? undefined }
: {}),
createdAt: now,
});
}
}
if (event.kind === "error" && event.message) {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: "error",
threadId: thread.id,
activeTurnId: event.turnId ?? null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: event.message,
},
createdAt: now,
});
}
})().catch(() => undefined);
});
}
const onTerminalEvent = (event: TerminalEvent) => {
const push: WsPush = {
broadcastPush({
type: "push",
channel: WS_CHANNELS.terminalEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
});
if (event.type === "activity" || event.type === "exited" || event.type === "error") {
void coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "thread.setTerminalActivity",
issuedAt: event.createdAt,
payload: {
threadId: event.threadId,
terminalId: event.terminalId,
running: event.type === "activity" ? event.hasRunningSubprocess : false,
},
});
}
logOutgoingPush(push, recipients);
};
terminalManager.on("event", onTerminalEvent);
coreRuntime.bindProviderEvents(providerManager);
let stateStreamStopped = false;
let stateStreamTask: Promise<void> | null = null;
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer((req, res) => {
@@ -368,10 +243,6 @@ export function createServer(options: ServerOptions) {
wss.on("connection", (ws) => {
clients.add(ws);
// Send welcome message with project info
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
const welcome: WsPush = {
type: "push",
channel: WS_CHANNELS.serverWelcome,
@@ -380,17 +251,6 @@ export function createServer(options: ServerOptions) {
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
const snapshotPush: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: orchestrationEngine.getSnapshot().sequence,
snapshot: orchestrationEngine.getSnapshot(),
} satisfies OrchestrationReadModelPush,
};
logOutgoingPush(snapshotPush, 1);
ws.send(JSON.stringify(snapshotPush));
ws.on("message", (raw) => {
void handleMessage(ws, raw);
});
@@ -433,12 +293,44 @@ export function createServer(options: ServerOptions) {
}
async function routeRequest(request: WsRequest): Promise<unknown> {
switch (request.method) {
case WS_METHODS.providersStartSession:
return providerManager.startSession(request.params as never);
const requestNow = new Date().toISOString();
const paramsObj = (request.params ?? {}) as Record<string, unknown>;
const state = await coreRuntime.state();
const findThreadBySessionId = (sessionId: string | undefined) =>
sessionId
? state.threads.find((thread) => thread.session?.sessionId === sessionId)
: undefined;
case WS_METHODS.providersSendTurn:
switch (request.method) {
case WS_METHODS.providersStartSession: {
const session = await providerManager.startSession(request.params as never);
const uiThreadId = typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
if (uiThreadId) {
await coreRuntime.bindProviderSession(uiThreadId, session);
}
return session;
}
case WS_METHODS.providersSendTurn: {
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
const uiThreadId = typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
const targetThread = uiThreadId ? state.threads.find((thread) => thread.id === uiThreadId) : findThreadBySessionId(sessionId);
const inputText = typeof paramsObj.input === "string" ? paramsObj.input : undefined;
if (targetThread && inputText && inputText.trim().length > 0) {
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "thread.addUserMessage",
issuedAt: requestNow,
payload: {
threadId: targetThread.id,
messageId: crypto.randomUUID(),
text: inputText,
createdAt: requestNow,
},
});
}
return providerManager.sendTurn(request.params as never);
}
case WS_METHODS.providersInterruptTurn:
return providerManager.interruptTurn(request.params as never);
@@ -447,10 +339,18 @@ export function createServer(options: ServerOptions) {
return providerManager.respondToRequest(request.params as never);
case WS_METHODS.providersStopSession: {
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
const boundThread = findThreadBySessionId(sessionId);
providerManager.stopSession(request.params as never);
if (boundThread) {
await coreRuntime.clearProviderSession(boundThread.id);
}
return undefined;
}
case WS_METHODS.providersListSessions:
return providerManager.listSessions();
case WS_METHODS.providersListCheckpoints:
return providerManager.listCheckpoints(request.params as never);
@@ -458,78 +358,57 @@ export function createServer(options: ServerOptions) {
return providerManager.getCheckpointDiff(request.params as never);
case WS_METHODS.providersRevertToCheckpoint:
{
const result = await providerManager.revertToCheckpoint(request.params as never);
const params = request.params as { sessionId?: string };
const sessionId = params.sessionId;
if (typeof sessionId === "string") {
const snapshot = orchestrationEngine.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.session?.sessionId === sessionId);
if (thread) {
const now = new Date().toISOString();
await orchestrationEngine.dispatch({
type: "thread.revert",
commandId: crypto.randomUUID(),
threadId: thread.id,
turnCount: result.turnCount,
messageCount: result.messageCount,
createdAt: now,
});
if (thread.session) {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
...thread.session,
status: "ready",
activeTurnId: null,
updatedAt: now,
lastError: null,
},
createdAt: now,
});
}
}
}
return result;
}
return providerManager.revertToCheckpoint(request.params as never);
case WS_METHODS.projectsList:
return projectRegistry.list();
case WS_METHODS.projectsAdd:
{
const result = await projectRegistry.add(request.params as never);
await orchestrationEngine.dispatch({
type: "project.create",
commandId: crypto.randomUUID(),
projectId: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: "gpt-5-codex",
createdAt: new Date().toISOString(),
const result = projectRegistry.add(request.params as never);
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "project.add",
issuedAt: requestNow,
payload: {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: "gpt-5-codex",
scripts: result.project.scripts,
},
});
return result;
}
case WS_METHODS.projectsRemove:
{
const params = request.params as { id: string };
projectRegistry.remove(request.params as never);
await orchestrationEngine.dispatch({
type: "project.delete",
commandId: crypto.randomUUID(),
projectId: params.id,
createdAt: new Date().toISOString(),
});
return undefined;
const projectId = typeof paramsObj.id === "string" ? paramsObj.id : undefined;
if (projectId) {
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "project.remove",
issuedAt: requestNow,
payload: { id: projectId },
});
}
projectRegistry.remove(request.params as never);
return undefined;
}
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
case WS_METHODS.projectsUpdateScripts:
return projectRegistry.updateScripts(request.params as never);
{
const result = projectRegistry.updateScripts(request.params as never);
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "project.updateScripts",
issuedAt: requestNow,
payload: { id: result.project.id, scripts: result.project.scripts },
});
return result;
}
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
@@ -576,24 +455,7 @@ export function createServer(options: ServerOptions) {
}
case WS_METHODS.gitStatus:
{
const params = request.params as { cwd: string };
const status = await gitManager.status(request.params as never);
const project = projectRegistry.list().find((entry) => entry.cwd === params.cwd);
if (project) {
await orchestrationEngine.dispatch({
type: "git.readModel.upsert",
commandId: crypto.randomUUID(),
projectId: project.id,
branch: status.branch,
hasWorkingTreeChanges: status.hasWorkingTreeChanges,
aheadCount: status.aheadCount,
behindCount: status.behindCount,
createdAt: new Date().toISOString(),
});
}
return status;
}
return gitManager.status(request.params as never);
case WS_METHODS.gitPull:
return pullGitBranch(request.params as never);
@@ -652,33 +514,68 @@ export function createServer(options: ServerOptions) {
keybindings: keybindingsConfig,
};
case ORCHESTRATION_WS_METHODS.getSnapshot:
return orchestrationEngine.getSnapshot();
case WS_METHODS.stateGetSnapshot:
return coreRuntime.state();
case ORCHESTRATION_WS_METHODS.dispatchCommand:
return orchestrationEngine.dispatchUnknown(request.params);
case WS_METHODS.stateCreateThread: {
const params = request.params as {
id: string;
projectId: string;
title: string;
model: string;
createdAt: string;
branch: string | null;
worktreePath: string | null;
};
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "thread.create",
issuedAt: requestNow,
payload: params,
});
return coreRuntime.state();
}
case ORCHESTRATION_WS_METHODS.replayEvents:
return orchestrationEngine.replayEvents(
Math.max(
0,
Math.floor(
Number(
(request.params as { fromSequenceExclusive?: number } | undefined)
?.fromSequenceExclusive ?? 0,
),
),
),
);
case WS_METHODS.stateDeleteThread: {
const params = request.params as { id: string };
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "thread.delete",
issuedAt: requestNow,
payload: params,
});
return coreRuntime.state();
}
case WS_METHODS.stateMarkThreadVisited: {
const params = request.params as { threadId: string; visitedAt?: string };
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "thread.markVisited",
issuedAt: requestNow,
payload: { threadId: params.threadId, visitedAt: params.visitedAt ?? requestNow },
});
return undefined;
}
case WS_METHODS.stateSetRuntimeMode: {
const params = request.params as { mode: "approval-required" | "full-access" };
await coreRuntime.dispatch({
id: crypto.randomUUID(),
type: "runtime.setMode",
issuedAt: requestNow,
payload: { mode: params.mode },
});
return coreRuntime.state();
}
default:
throw new Error(`Unknown method: ${request.method}`);
}
}
async function start() {
await orchestrationEngine.start();
await new Promise<void>((resolve, reject) => {
function start() {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
reject(error);
@@ -686,7 +583,26 @@ export function createServer(options: ServerOptions) {
httpServer.once("error", onError);
const onListening = () => {
httpServer.off("error", onError);
resolve();
void (async () => {
try {
await coreRuntime.start(cwd, projectName);
stateStreamStopped = false;
stateStreamTask = (async () => {
const iterable = await coreRuntime.subscribe();
for await (const update of iterable) {
if (stateStreamStopped) break;
broadcastPush({
type: "push",
channel: WS_CHANNELS.stateUpdated,
data: update.state,
});
}
})();
resolve();
} catch (error) {
reject(error as Error);
}
})();
};
if (host) {
httpServer.listen(port, host, onListening);
@@ -697,9 +613,7 @@ export function createServer(options: ServerOptions) {
}
async function stop(): Promise<void> {
unsubscribeReadModel();
unsubscribeDomainEvents();
await orchestrationEngine.stop();
stateStreamStopped = true;
terminalManager.off("event", onTerminalEvent);
providerManager.stopAll();
providerManager.dispose();
@@ -739,6 +653,10 @@ export function createServer(options: ServerOptions) {
});
});
if (stateStreamTask) {
await Promise.race([stateStreamTask, Promise.resolve()]);
}
await coreRuntime.stop();
await Promise.all([closeWebSocketServer, closeHttpServer]);
}
+1 -21
View File
@@ -92,23 +92,13 @@ export default function BranchToolbar({
});
if (!activeThreadId || !syncedBranch) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch, api]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
@@ -130,16 +120,6 @@ export default function BranchToolbar({
if (sessionId && worktreePath !== activeWorktreePath) {
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
}
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch,
worktreePath,
createdAt: new Date().toISOString(),
});
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
+161 -64
View File
@@ -57,6 +57,7 @@ import {
derivePhase,
deriveTurnDiffFilesFromUnifiedDiff,
deriveTimelineEntries,
type TurnDiffSummary,
type PendingApproval,
deriveWorkLogEntries,
formatDuration,
@@ -71,7 +72,6 @@ import {
MAX_THREAD_TERMINAL_COUNT,
type ChatImageAttachment,
type TurnDiffFileChange,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
@@ -414,6 +414,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
const checkpointTurnCountSyncFingerprintRef = useRef(new Map<string, string>());
const activeThread = state.threads.find((t) => t.id === threadId);
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
@@ -431,13 +433,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
const phase = derivePhase(activeThread?.session ?? null);
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const workLogEntries = useMemo(() => deriveWorkLogEntries([], undefined), []);
const latestTurnWorkEntries = useMemo(
() => deriveWorkLogEntries([], activeThread?.latestTurnId),
[activeThread?.latestTurnId],
const workLogEntries = useMemo(
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
[activeThread?.events],
);
const pendingApprovals = useMemo(() => derivePendingApprovals([]), []);
const assistantCompletionByItemId = useMemo(() => new Map<string, string>(), []);
const latestTurnWorkEntries = useMemo(
() => deriveWorkLogEntries(activeThread?.events ?? [], activeThread?.latestTurnId),
[activeThread?.events, activeThread?.latestTurnId],
);
const pendingApprovals = useMemo(
() => derivePendingApprovals(activeThread?.events ?? []),
[activeThread?.events],
);
const assistantCompletionByItemId = useMemo(() => {
const map = new Map<string, string>();
const ordered = [...(activeThread?.events ?? [])].toReversed();
for (const event of ordered) {
if (event.method !== "item/completed") continue;
if (!event.itemId) continue;
map.set(event.itemId, event.createdAt);
}
return map;
}, [activeThread?.events]);
const timelineEntries = useMemo(
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
[activeThread?.messages, workLogEntries],
@@ -548,6 +565,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
return byUserMessageId;
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
useEffect(() => {
if (!activeThreadId || turnDiffSummaries.length === 0) {
return;
}
const inferredMissingTurnCounts = turnDiffSummaries.reduce<Record<string, number>>(
(acc, summary) => {
if (typeof summary.checkpointTurnCount === "number") {
return acc;
}
const inferredTurnCount = inferredCheckpointTurnCountByTurnId[summary.turnId];
if (typeof inferredTurnCount !== "number") {
return acc;
}
acc[summary.turnId] = inferredTurnCount;
return acc;
},
{},
);
if (Object.keys(inferredMissingTurnCounts).length === 0) {
return;
}
dispatch({
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
threadId: activeThreadId,
checkpointTurnCountByTurnId: inferredMissingTurnCounts,
});
}, [activeThreadId, dispatch, inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
const completionSummary = useMemo(() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
@@ -1027,6 +1074,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
dispatch({ type: "SET_RUNTIME_MODE", mode });
scheduleComposerFocus();
if (!api) return;
await api.state.setRuntimeMode({ mode });
const sessionIds = state.threads
.map((t) => t.session)
@@ -1403,6 +1451,53 @@ export default function ChatView({ threadId }: ChatViewProps) {
focusComposer();
};
const syncCheckpointTurnCounts = useCallback(
async (input: {
threadId: string;
sessionId: string;
threadRuntimeId: string | null;
}): Promise<void> => {
if (!api || turnDiffSummaries.length === 0) {
return;
}
const turnIds = turnDiffSummaries.map((summary) => summary.turnId);
if (turnIds.length === 0) {
return;
}
const syncKey = `${input.threadId}:${input.sessionId}:${input.threadRuntimeId ?? "none"}`;
const turnFingerprint = turnIds.join(",");
if (checkpointTurnCountSyncFingerprintRef.current.get(syncKey) === turnFingerprint) {
return;
}
checkpointTurnCountSyncFingerprintRef.current.set(syncKey, turnFingerprint);
try {
const result = await api.providers.listCheckpoints({
sessionId: input.sessionId,
});
const turnIdSet = new Set(turnIds);
const checkpointTurnCountByTurnId = Object.fromEntries(
result.checkpoints
.filter((checkpoint) => checkpoint.turnCount > 0 && turnIdSet.has(checkpoint.id))
.map((checkpoint) => [checkpoint.id, checkpoint.turnCount] as const),
);
if (Object.keys(checkpointTurnCountByTurnId).length === 0) {
return;
}
dispatch({
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
threadId: input.threadId,
checkpointTurnCountByTurnId,
});
} catch {
checkpointTurnCountSyncFingerprintRef.current.delete(syncKey);
}
},
[api, dispatch, turnDiffSummaries],
);
const ensureSession = useCallback(
async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
if (!api || !activeThread || !activeProject) return null;
@@ -1414,6 +1509,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
: sessionThreadId === activeThread.codexThreadId
? "resumed"
: "fallback_new";
await syncCheckpointTurnCounts({
threadId: activeThread.id,
sessionId: activeThread.session.sessionId,
threadRuntimeId: sessionThreadId,
});
return {
sessionId: activeThread.session.sessionId,
resolvedThreadId: sessionThreadId,
@@ -1425,6 +1525,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsConnecting(true);
try {
const session = await api.providers.startSession({
uiThreadId: activeThread.id,
provider: "codex",
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
model: selectedModel || undefined,
@@ -1434,21 +1535,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
approvalPolicy: runtimeApprovalPolicy,
sandboxMode: runtimeSandboxMode,
});
await api.orchestration.dispatchCommand({
type: "thread.session",
commandId: crypto.randomUUID(),
dispatch({
type: "UPDATE_SESSION",
threadId: activeThread.id,
session: {
sessionId: session.sessionId,
provider: session.provider,
status: session.status,
threadId: session.threadId ?? activeThread.id,
activeTurnId: session.activeTurnId ?? null,
createdAt: session.createdAt,
updatedAt: session.updatedAt,
lastError: session.lastError ?? null,
},
createdAt: new Date().toISOString(),
session,
});
const resolvedThreadId = session.threadId ?? null;
const continuityState: SessionContinuityState =
@@ -1457,6 +1547,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
: resolvedThreadId === priorCodexThreadId
? "resumed"
: "fallback_new";
await syncCheckpointTurnCounts({
threadId: activeThread.id,
sessionId: session.sessionId,
threadRuntimeId: resolvedThreadId,
});
return {
sessionId: session.sessionId,
resolvedThreadId,
@@ -1479,9 +1574,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
api,
codexBinaryPath,
codexHomePath,
dispatch,
runtimeApprovalPolicy,
runtimeSandboxMode,
selectedModel,
syncCheckpointTurnCounts,
],
);
@@ -1547,10 +1644,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!sessionInfo) {
return;
}
await api.providers.revertToCheckpoint({
const result = await api.providers.revertToCheckpoint({
sessionId: sessionInfo.sessionId,
turnCount,
});
dispatch({
type: "REVERT_TO_CHECKPOINT",
threadId: activeThread.id,
sessionId: sessionInfo.sessionId,
threadRuntimeId: result.threadId,
turnCount: result.turnCount,
messageCount: result.messageCount,
});
dispatch({
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
threadId: activeThread.id,
checkpointTurnCountByTurnId: Object.fromEntries(
result.checkpoints
.filter((entry) => entry.turnCount > 0)
.map((entry) => [entry.id, entry.turnCount] as const),
),
});
} catch (err) {
setThreadError(
activeThread.id,
@@ -1597,16 +1711,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
newBranch,
});
sessionCwd = result.worktree.path;
if (api) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
void runProjectScript(setupScript, {
@@ -1633,15 +1743,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
if (api) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
title,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_TITLE",
threadId: activeThread.id,
title,
});
}
setThreadError(activeThread.id, null);
@@ -1653,19 +1759,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
const userMessageId = crypto.randomUUID();
if (api) {
await api.orchestration.dispatchCommand({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
messageId: userMessageId,
role: "user",
text: trimmed,
streaming: false,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
const previousMessages = activeThread.messages;
promptRef.current = "";
setPrompt("");
@@ -1701,6 +1801,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
).text
: trimmed || undefined;
await api.providers.sendTurn({
uiThreadId: activeThread.id,
sessionId: sessionInfo.sessionId,
...(input ? { input } : {}),
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
@@ -1754,18 +1855,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onModelSelect = useCallback(
(model: ModelSlug) => {
if (!activeThread) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
model: resolveModelSlug(model),
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
scheduleComposerFocus();
},
[activeThread, api, scheduleComposerFocus],
[activeThread, dispatch, scheduleComposerFocus],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
+46 -52
View File
@@ -7,6 +7,7 @@ import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { type Thread } from "../types";
@@ -15,6 +16,7 @@ import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { toastManager } from "./ui/toast";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { createThread } from "../threadFactory";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
@@ -129,37 +131,42 @@ export default function Sidebar() {
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => new Map<string, boolean>(), []);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<string, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(
async (
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
if (!api) return;
const threadId = crypto.randomUUID();
const createdAt = new Date().toISOString();
const model = state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
void api.orchestration.dispatchCommand({
type: "thread.create",
commandId: crypto.randomUUID(),
threadId,
projectId,
title: "New thread",
model,
const thread = createThread(projectId, {
model: state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
createdAt,
});
await api?.state.createThread({
id: thread.id,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
createdAt: thread.createdAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
});
void navigate({
to: "/$threadId",
params: { threadId },
params: { threadId: thread.id },
});
},
[api, dispatch, navigate, state.projects],
[api, navigate, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
@@ -188,30 +195,26 @@ export default function Sidebar() {
setIsAddingProject(true);
try {
if (!api) return;
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
if (isElectron && api) {
const result = await api.projects.add({ cwd });
const existingByCwd = state.projects.find((p) => p.cwd === result.project.cwd);
const resolvedProjectId = existingByCwd?.id ?? result.project.id;
const projectId = crypto.randomUUID();
const now = new Date().toISOString();
const name = inferProjectName(cwd);
if (isElectron) {
// Keep project registry in sync for desktop integrations.
await api.projects.add({ cwd });
if (result.created) {
await handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
if (!api) return;
const result = await api.projects.add({ cwd });
await handleNewThread(result.project.id);
}
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: crypto.randomUUID(),
projectId,
name,
cwd,
model: DEFAULT_MODEL,
createdAt: now,
});
handleNewThread(projectId);
} finally {
setIsAddingProject(false);
setNewCwd("");
@@ -302,12 +305,7 @@ export default function Sidebar() {
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: crypto.randomUUID(),
threadId,
createdAt: new Date().toISOString(),
});
await api.state.deleteThread({ id: threadId });
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
@@ -397,12 +395,6 @@ export default function Sidebar() {
}
}
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: crypto.randomUUID(),
projectId,
createdAt: new Date().toISOString(),
});
},
[api, dispatch, state.projects, state.threads],
);
@@ -463,7 +455,7 @@ export default function Sidebar() {
return;
}
const firstProject = state.projects[0];
if (firstProject) handleNewThread(firstProject.id);
if (firstProject) void handleNewThread(firstProject.id);
}}
>
<span className="text-foreground">+</span>
@@ -578,7 +570,9 @@ export default function Sidebar() {
<button
type="button"
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => handleNewThread(project.id)}
onClick={() => {
void handleNewThread(project.id);
}}
>
<span>+</span> New thread
</button>
+1 -1
View File
@@ -1,5 +1,5 @@
import { useMemo } from "react";
import { readNativeApi } from "../nativeApi";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
+18 -2
View File
@@ -1,13 +1,29 @@
import type { ProviderEvent } from "@t3tools/contracts";
import { useMemo } from "react";
import { inferCheckpointTurnCountByTurnId } from "../session-logic";
import { deriveTurnDiffSummaries, inferCheckpointTurnCountByTurnId } from "../session-logic";
import type { Thread, TurnDiffSummary } from "../types";
const derivedTurnDiffSummaryCache = new WeakMap<readonly ProviderEvent[], TurnDiffSummary[]>();
function deriveTurnDiffSummariesCached(events: ProviderEvent[]): TurnDiffSummary[] {
const cached = derivedTurnDiffSummaryCache.get(events);
if (cached) {
return cached;
}
const derived = deriveTurnDiffSummaries(events);
derivedTurnDiffSummaryCache.set(events, derived);
return derived;
}
export function useTurnDiffSummaries(activeThread: Thread | undefined) {
const turnDiffSummaries = useMemo(() => {
if (!activeThread) {
return [];
}
return activeThread.turnDiffSummaries;
if (activeThread.turnDiffSummaries.length > 0) {
return activeThread.turnDiffSummaries;
}
return deriveTurnDiffSummariesCached(activeThread.events);
}, [activeThread]);
const inferredCheckpointTurnCountByTurnId = useMemo(
-18
View File
@@ -1,18 +0,0 @@
import type { NativeApi } from "@t3tools/contracts";
import { createWsNativeApi } from "./wsNativeApi";
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
cachedApi = createWsNativeApi();
return cachedApi;
}
+38 -61
View File
@@ -2,8 +2,9 @@ import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
useParams,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { useEffect } from "react";
import { QueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
@@ -11,9 +12,8 @@ import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { DEFAULT_MODEL } from "../model-logic";
import { useStore } from "../store";
import { onServerWelcome } from "../wsNativeApi";
import { type AppState, useStore } from "../store";
import { onServerStateUpdate, onServerWelcome } from "../wsNativeApi";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -123,83 +123,60 @@ function errorDetails(error: unknown): string {
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const activeThreadId = useParams({
strict: false,
select: (params) => params.threadId,
});
useEffect(() => {
if (!api) return;
void api.orchestration
.getSnapshot()
.then((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
})
.catch(() => undefined);
const unsubReadModel = api.orchestration.onReadModel((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
let mounted = true;
void api.state.getSnapshot().then((snapshot) => {
if (!mounted) return;
dispatch({ type: "SET_SERVER_STATE", state: snapshot as AppState });
});
return () => {
unsubReadModel();
mounted = false;
};
}, [api, dispatch]);
useEffect(() => {
return onServerStateUpdate((snapshot) => {
dispatch({ type: "SET_SERVER_STATE", state: snapshot as AppState });
});
}, [dispatch]);
useEffect(() => {
if (!activeThreadId) return;
const visitedAt = new Date().toISOString();
if (!api) return;
void api.state.markThreadVisited({ threadId: activeThreadId, visitedAt });
}, [activeThreadId, api]);
return null;
}
function AutoProjectBootstrap() {
const api = useNativeApi();
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
const { dispatch } = useStore();
useEffect(() => {
if (!api) return;
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
return onServerWelcome((payload) => {
if (bootstrappedRef.current) return;
// Don't create duplicate projects for the same cwd
const existing = state.projects.find((project) => project.cwd === payload.cwd);
if (existing) {
bootstrappedRef.current = true;
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
return;
}
bootstrappedRef.current = true;
const projectId = crypto.randomUUID();
const threadId = crypto.randomUUID();
const now = new Date().toISOString();
void api.orchestration
.dispatchCommand({
type: "project.create",
commandId: crypto.randomUUID(),
projectId,
name: payload.projectName,
cwd: payload.cwd,
model: DEFAULT_MODEL,
createdAt: now,
})
.then(() =>
api.orchestration.dispatchCommand({
type: "thread.create",
commandId: crypto.randomUUID(),
threadId,
projectId,
title: "New thread",
model: DEFAULT_MODEL,
branch: null,
worktreePath: null,
createdAt: now,
}),
)
.catch(() => undefined);
return onServerWelcome(() => {
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
});
}, [api, state.projects, dispatch]);
}, [dispatch]);
return null;
}
function DesktopProjectBootstrap() {
// Desktop now hydrates from orchestration read-model snapshots.
const api = useNativeApi();
const { dispatch } = useStore();
useEffect(() => {
if (!isElectron || !api) return;
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
}, [api, dispatch]);
return null;
}
+935
View File
@@ -0,0 +1,935 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTurnDiffFilesFromUnifiedDiff,
deriveTurnDiffSummaries,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
} from "./session-logic";
import type { ChatMessage } from "./types";
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-08T10:00:00.000Z",
method: "noop",
...overrides,
};
}
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-08T09:59:00.000Z",
updatedAt: "2026-02-08T09:59:00.000Z",
...overrides,
};
}
describe("deriveTimelineEntries", () => {
it("interleaves messages and work entries by timestamp", () => {
const messages: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:05:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:02:00.000Z",
tone: "tool",
},
{
id: "w-2",
label: "Preamble",
createdAt: "2026-02-08T10:03:00.000Z",
tone: "thinking",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual([
"message:m-user",
"work:w-1",
"work:w-2",
"message:m-assistant",
]);
});
it("prefers work entries when timestamps are equal", () => {
const messages: ChatMessage[] = [
{
id: "m-1",
role: "assistant",
text: "Done",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:00:00.000Z",
tone: "tool",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
});
});
describe("deriveWorkLogEntries", () => {
it("drops preamble/work events from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-1",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { item: { type: "preamble", text: "thinking" } },
}),
makeEvent({
id: "evt-2",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "work", text: "planning" } },
}),
makeEvent({
id: "evt-3",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
});
it("does not surface successful turn completion as a work-log row", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("shows failed turn completion in the work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: {
turn: {
id: "turn-1",
status: "failed",
error: { message: "sandbox denied" },
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Turn failed");
expect(entries[0]?.detail).toBe("sandbox denied");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-summary-part",
method: "item/reasoning/summaryPartAdded",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-summary-delta",
method: "item/reasoning/summaryTextDelta",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
}),
makeEvent({
id: "evt-agent-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
},
}),
makeEvent({
id: "evt-agent-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
item: {
id: "item-msg",
type: "agentMessage",
text: "Done response",
},
},
}),
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-tool-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:06.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:08.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
});
it("coalesces command start/completed lifecycle into one entry", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-command-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
makeEvent({
id: "evt-command-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Command run");
expect(entries[0]?.detail).toBe("git status --short");
});
it("preserves full tool-call detail text without data truncation", () => {
const longCommand =
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: longCommand },
},
}),
],
"turn-1",
);
expect(entries[0]?.detail).toBe(longCommand);
});
it("hides generic tool-call rows that have no identifying detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call" },
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("includes collab tool-call rows with tool name detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-collab-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-collab",
type: "collabAgentToolCall",
tool: "spawnAgent",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
expect(entries[0]?.detail).toBe("spawnAgent");
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-1-tool",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
makeEvent({
id: "evt-turn-2-tool",
method: "item/started",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "pwd" } },
}),
],
undefined,
);
expect(entries).toHaveLength(2);
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
});
});
describe("deriveTurnDiffSummaries", () => {
it("tracks completed turns and links them to assistant message completion", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-file-change",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-file-change",
type: "fileChange",
status: "completed",
changes: [
{
path: "src/a.ts",
kind: "modified",
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
},
],
},
},
}),
makeEvent({
id: "evt-turn-diff-updated",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
threadId: "thr-1",
turnId: "turn-1",
diff: [
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old",
"+new",
"diff --git a/src/b.ts b/src/b.ts",
"@@ -0,0 +1 @@",
"+created",
].join("\n"),
},
}),
makeEvent({
id: "evt-agent-msg",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: {
id: "msg-1",
type: "agentMessage",
text: "Done",
},
},
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
makeEvent({
id: "evt-turn-2-file-change",
method: "item/completed",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-file-change-2",
type: "fileChange",
status: "completed",
changes: [
{
path: "src/unfinished.ts",
kind: "modified",
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
},
],
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.turnId).toBe("turn-1");
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
expect(summaries[0]?.files[0]?.kind).toBe("modified");
expect(summaries[0]?.files[0]?.additions).toBe(1);
expect(summaries[0]?.files[0]?.deletions).toBe(1);
expect(summaries[0]).not.toHaveProperty("unifiedDiff");
});
it("includes completed turns even when no fileChange tool events were emitted", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.turnId).toBe("turn-1");
expect(summaries[0]?.files).toEqual([]);
});
it("keeps newest diff data when older events provide stale values", () => {
const summaries = deriveTurnDiffSummaries([
makeEvent({
id: "evt-turn-diff-old",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
diff: [
"diff --git a/src/example.ts b/src/example.ts",
"@@ -1 +1,2 @@",
"-old",
"+older",
"+extra",
].join("\n"),
},
}),
makeEvent({
id: "evt-turn-diff-new",
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
diff: [
"diff --git a/src/example.ts b/src/example.ts",
"@@ -1 +1 @@",
"-old",
"+newest",
].join("\n"),
},
}),
makeEvent({
id: "evt-turn-completed",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
turn: {
id: "turn-1",
status: "completed",
},
},
}),
]);
expect(summaries).toHaveLength(1);
expect(summaries[0]?.files[0]?.path).toBe("src/example.ts");
expect(summaries[0]?.files[0]?.additions).toBe(1);
expect(summaries[0]?.files[0]?.deletions).toBe(1);
});
});
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
it("splits a multi-file patch into sorted per-file entries", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/src/b.ts b/src/b.ts",
"@@ -1 +1 @@",
"-old-b",
"+new-b",
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old-a",
"+new-a",
].join("\n"),
);
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
expect(files[0]?.additions).toBe(1);
expect(files[0]?.deletions).toBe(1);
});
it("parses git headers when file paths include ` b/`", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
"--- a/subdir b/example.ts",
"+++ b/subdir b/example.ts",
"@@ -1 +1 @@",
"-old",
"+new",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]?.path).toBe("subdir b/example.ts");
});
it("parses git header fallback for binary diffs with ` b/` in path", () => {
const files = deriveTurnDiffFilesFromUnifiedDiff(
[
"diff --git a/subdir b/image.png b/subdir b/image.png",
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]?.path).toBe("subdir b/image.png");
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "thread/started",
createdAt: "2026-02-08T10:01:00.000Z",
payload: { thread: { id: "thread-1" } },
}),
);
expect(next.threadId).toBe("thread-1");
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("moves to running and records active turn on turn start", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:02:00.000Z",
}),
);
expect(next.status).toBe("running");
expect(next.activeTurnId).toBe("turn-1");
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
});
it("returns to ready and clears active turn on successful completion", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
lastError: "older error",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
);
expect(next.status).toBe("ready");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("older error");
});
it("marks session as error when turn fails", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: {
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
},
}),
);
expect(next.status).toBe("error");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("boom");
});
it("moves to error on runtime error events", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
kind: "error",
method: "runtime/error",
createdAt: "2026-02-08T10:04:00.000Z",
message: "runtime failure",
}),
);
expect(next.status).toBe("error");
expect(next.lastError).toBe("runtime failure");
});
it("closes session on close lifecycle events", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "session/closed",
createdAt: "2026-02-08T10:05:00.000Z",
message: "closed",
}),
);
expect(next.status).toBe("closed");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("closed");
});
});
describe("applyEventToMessages", () => {
it("handles start/delta/completed flow for assistant messages", () => {
const activeAssistantItemRef = { current: null as string | null };
const started = applyEventToMessages(
[],
makeEvent({
method: "item/started",
createdAt: "2026-02-08T10:00:00.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello",
},
},
}),
activeAssistantItemRef,
);
expect(started).toEqual([
{
id: "item-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
]);
expect(activeAssistantItemRef.current).toBe("item-1");
const withDelta = applyEventToMessages(
started,
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-1",
textDelta: " world",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.text).toBe("Hello world");
expect(withDelta[0]?.streaming).toBe(true);
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello world!",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Hello world!");
expect(completed[0]?.streaming).toBe(false);
expect(activeAssistantItemRef.current).toBeNull();
});
it("supports out-of-order delta before started/completed", () => {
const activeAssistantItemRef = { current: null as string | null };
const withDelta = applyEventToMessages(
[],
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-2",
textDelta: "Partial",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.id).toBe("item-2");
expect(withDelta[0]?.text).toBe("Partial");
expect(withDelta[0]?.streaming).toBe(true);
expect(activeAssistantItemRef.current).toBe("item-2");
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-2",
type: "agentMessage",
text: "Partial + final",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Partial + final");
expect(completed[0]?.streaming).toBe(false);
});
it("clears all streaming flags when turn completes", () => {
const previous: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Typing",
createdAt: "2026-02-08T10:00:01.000Z",
streaming: true,
},
];
const next = applyEventToMessages(
previous,
makeEvent({
method: "turn/completed",
}),
{ current: null },
);
expect(next.every((entry) => entry.streaming === false)).toBe(true);
});
});
+857 -63
View File
@@ -1,6 +1,6 @@
import type { ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -11,6 +11,73 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
// Prefer Electron preload bridge if available
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
// Fall back to WebSocket transport
cachedApi = createWsNativeApi();
return cachedApi;
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
function asArray(value: unknown): unknown[] | undefined {
return Array.isArray(value) ? value : undefined;
}
export function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
return null;
}
return formatDuration(endedAt - startedAt);
}
export interface WorkLogEntry {
id: string;
createdAt: string;
@@ -40,77 +107,465 @@ export type TimelineEntry =
entry: WorkLogEntry;
};
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
export type { TurnDiffFileChange, TurnDiffSummary } from "./types";
function normalizeDetail(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._/-]/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
function shouldDropItemType(type: string): boolean {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
return true;
}
return type === "work" || type.startsWith("work ");
}
function shouldShowItemLifecycle(type: string): boolean {
return type.includes("tool") || type.includes("command") || type.includes("file change");
}
function shouldDropMethod(method: string): boolean {
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
}
function itemTypeMeta(type: string): {
label: string;
tone: WorkLogEntry["tone"];
} {
if (type.includes("command")) {
return { label: "Command run", tone: "tool" };
}
if (type.includes("file change")) {
return { label: "File change", tone: "tool" };
}
if (type.includes("tool")) {
return { label: "Tool call", tone: "tool" };
}
return { label: "Work item", tone: "info" };
}
interface ItemLifecycleCandidate {
id: string;
itemId?: string;
createdAt: string;
label: string;
detail?: string;
tone: WorkLogEntry["tone"];
phase: "started" | "completed";
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.command),
asString(item?.tool),
asString(item?.name),
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.prompt),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
];
for (const candidate of candidates) {
const detail = normalizeDetail(candidate);
if (detail) return detail;
}
return undefined;
}
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
return null;
}
return formatDuration(endedAt - startedAt);
if (!shouldShowItemLifecycle(normalizedType)) {
return null;
}
const meta = itemTypeMeta(normalizedType);
const isStarted = event.method === "item/started";
const isCompleted = event.method === "item/completed";
if (!isStarted && !isCompleted) {
return null;
}
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label: meta.label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
export function derivePendingApprovals(_events: unknown[]): PendingApproval[] {
return [];
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "request") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method.includes("commandExecution")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Command approval requested",
tone: "tool",
};
}
if (event.method.includes("fileChange")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "File-change approval requested",
tone: "tool",
};
}
if (event.method.includes("requestUserInput")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Tool requested user input",
tone: "tool",
};
}
return {
id: event.id,
createdAt: event.createdAt,
label: `Request: ${event.method}`,
tone: "info",
};
}
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "notification") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method === "item/agentMessage/delta") return null;
if (event.method === "turn/started") {
return null;
}
if (event.method === "thread/started") return null;
if (event.method === "turn/completed") {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
if (status !== "failed") {
return null;
}
const turnError = asObject(turn?.error);
const turnErrorMessage = asString(turnError?.message);
const turnErrorDetail = normalizeDetail(turnErrorMessage);
return {
id: event.id,
createdAt: event.createdAt,
label: "Turn failed",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: "error",
};
}
if (event.method.startsWith("item/")) return null;
return null;
}
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "error") return null;
if (shouldDropMethod(event.method)) return null;
const detail = normalizeDetail(event.message);
return {
id: event.id,
createdAt: event.createdAt,
label: "Runtime error",
...(detail ? { detail } : {}),
tone: "error",
};
}
function eventTurnId(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return event.turnId ?? asString(turn?.id);
}
export function deriveWorkLogEntries(
_events: unknown[],
_latestTurnId: string | undefined,
events: ProviderEvent[],
turnId: string | undefined,
): WorkLogEntry[] {
return [];
const ordered = [...events].toReversed();
const entries: WorkLogEntry[] = [];
const turnStartedAtIso = turnId
? ordered.find((event) => {
if (event.method !== "turn/started") return false;
return eventTurnId(event) === turnId;
})?.createdAt
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
const shouldIncludeEvent = (event: ProviderEvent): boolean => {
if (!turnId) return true;
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
return false;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
return false;
}
}
return true;
};
const completedLifecycleItemIds = new Set<string>();
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const candidate = lifecycleCandidateFromItemEvent(event);
if (candidate?.phase === "completed" && candidate.itemId) {
completedLifecycleItemIds.add(candidate.itemId);
}
}
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const lifecycleCandidate = lifecycleCandidateFromItemEvent(event);
if (lifecycleCandidate) {
if (
lifecycleCandidate.phase === "started" &&
lifecycleCandidate.itemId &&
completedLifecycleItemIds.has(lifecycleCandidate.itemId)
) {
continue;
}
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
continue;
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
}
const fromRequest = entryFromRequest(event);
if (fromRequest) {
entries.push(fromRequest);
continue;
}
const fromNotification = entryFromNotification(event);
if (fromNotification) {
entries.push(fromNotification);
continue;
}
const fromError = entryFromError(event);
if (fromError) {
entries.push(fromError);
}
}
return entries;
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
): TimelineEntry[] {
const messageRows: TimelineEntry[] = messages.map((message) => ({
id: message.id,
kind: "message",
createdAt: message.createdAt,
message,
}));
const workRows: TimelineEntry[] = workEntries.map((entry) => ({
id: entry.id,
kind: "work",
createdAt: entry.createdAt,
entry,
}));
return [...messageRows, ...workRows].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
interface MutableTurnDiffSummary {
turnId: string;
completedAt: string | undefined;
status: string | undefined;
assistantMessageId: string | undefined;
hasTurnDiffUpdate: boolean;
filesByPath: Map<string, TurnDiffFileChange>;
}
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
if (event.method !== "item/completed") {
return [];
}
const item = asObject(asObject(event.payload)?.item);
const itemType = normalizeItemType(asString(item?.type));
if (itemType !== "file change") {
return [];
}
const changes = asArray(item?.changes) ?? [];
const parsed: TurnDiffFileChange[] = [];
for (const rawChange of changes) {
const change = asObject(rawChange);
if (!change) continue;
const diff = normalizeDetail(asString(change.diff));
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
if (!path) continue;
const additions = asNumber(change.additions);
const deletions = asNumber(change.deletions);
const stat = additions !== undefined && deletions !== undefined ? null : diff ? countDiffStat(diff) : null;
const kind = normalizeDetail(asString(change.kind));
parsed.push({
path,
...(kind ? { kind } : {}),
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
});
}
return parsed;
}
function mergeTurnDiffFileChange(
byPath: Map<string, TurnDiffFileChange>,
incoming: TurnDiffFileChange,
): void {
const existing = byPath.get(incoming.path);
if (!existing) {
byPath.set(incoming.path, incoming);
return;
}
if (existing.kind === undefined && incoming.kind !== undefined) {
existing.kind = incoming.kind;
}
if (existing.additions === undefined && incoming.additions !== undefined) {
existing.additions = incoming.additions;
}
if (existing.deletions === undefined && incoming.deletions !== undefined) {
existing.deletions = incoming.deletions;
}
}
function parsePathFromDiff(diff: string): string | undefined {
const normalized = diff.replace(/\r\n/g, "\n");
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
if (bPath && bPath[1]) return bPath[1];
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
if (gitHeader && gitHeader[1]) return gitHeader[1];
const direct = normalized.match(/^\+\+\+ (.+)$/m);
if (!direct || !direct[1] || direct[1] === "/dev/null") {
return undefined;
}
return direct[1];
}
export function splitUnifiedDiffByFile(diff: string): Map<string, string> {
const normalized = diff.replace(/\r\n/g, "\n");
const byPath = new Map<string, string>();
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
if (headerMatches.length === 0) {
const path = parsePathFromDiff(normalized);
if (path) {
byPath.set(path, 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 nextStart = headerMatches[index + 1]?.index ?? normalized.length;
const segment = normalized.slice(start, nextStart).trim();
const path = parsePathFromDiff(segment);
if (!path || segment.length === 0) continue;
byPath.set(path, segment);
}
return byPath;
}
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
const files: TurnDiffFileChange[] = [];
const lines = diff.split("\n");
for (const line of lines) {
if (!line.startsWith("diff --git ")) continue;
const match = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
const filePath = match?.[2] ?? match?.[1];
if (!filePath) continue;
files.push({ path: filePath });
}
return files;
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
return Array.from(fileDiffsByPath.entries())
.map(([path, fileDiff]) => {
const stat = countDiffStat(fileDiff);
return {
path,
additions: stat.additions,
deletions: stat.deletions,
};
})
.toSorted((a, b) => a.path.localeCompare(b.path));
}
export function inferCheckpointTurnCountByTurnId(
@@ -120,7 +575,7 @@ export function inferCheckpointTurnCountByTurnId(
return {};
}
const sorted = [...summaries].sort((a, b) => {
const sorted = [...summaries].toSorted((a, b) => {
const aTime = Date.parse(a.completedAt);
const bTime = Date.parse(b.completedAt);
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
@@ -129,23 +584,203 @@ export function inferCheckpointTurnCountByTurnId(
return aTime - bTime;
});
const result: Record<string, number> = {};
const next: Record<string, number> = {};
let fallbackTurnCount = 1;
for (const summary of sorted) {
if (typeof summary.checkpointTurnCount === "number") {
result[summary.turnId] = summary.checkpointTurnCount;
next[summary.turnId] = summary.checkpointTurnCount;
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
continue;
}
result[summary.turnId] = fallbackTurnCount;
next[summary.turnId] = fallbackTurnCount;
fallbackTurnCount += 1;
}
return result;
return next;
}
export function deriveTurnDiffSummaries(_events: unknown[]): TurnDiffSummary[] {
return [];
export function countDiffStat(patch: string | undefined): { additions: number; deletions: number } {
if (!patch) {
return { additions: 0, deletions: 0 };
}
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 deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
const firstEventAt = Date.parse(events[0]?.createdAt ?? "");
const lastEventAt = Date.parse(events.at(-1)?.createdAt ?? "");
const ordered =
events.length < 2 ||
Number.isNaN(firstEventAt) ||
Number.isNaN(lastEventAt) ||
firstEventAt >= lastEventAt
? events
: [...events].toReversed();
const byTurnId = new Map<string, MutableTurnDiffSummary>();
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
const existing = byTurnId.get(turnId);
if (existing) return existing;
const next: MutableTurnDiffSummary = {
turnId,
completedAt: undefined,
status: undefined,
assistantMessageId: undefined,
hasTurnDiffUpdate: false,
filesByPath: new Map<string, TurnDiffFileChange>(),
};
byTurnId.set(turnId, next);
return next;
};
for (const event of ordered) {
const turnId = eventTurnId(event);
if (!turnId) continue;
const summary = ensureSummary(turnId);
if (event.method === "turn/completed") {
if (summary.completedAt === undefined) {
summary.completedAt = event.createdAt;
}
const turn = asObject(asObject(event.payload)?.turn);
if (summary.status === undefined) {
summary.status = normalizeDetail(asString(turn?.status));
}
}
if (event.method === "item/completed") {
const item = asObject(asObject(event.payload)?.item);
if (asString(item?.type) === "agentMessage") {
const itemId = normalizeDetail(asString(item?.id));
if (itemId && summary.assistantMessageId === undefined) {
summary.assistantMessageId = itemId;
}
}
}
if (event.method === "turn/diff/updated" && !summary.hasTurnDiffUpdate) {
summary.hasTurnDiffUpdate = true;
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
if (diff) {
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
mergeTurnDiffFileChange(summary.filesByPath, file);
}
}
}
for (const file of parseFileChangeEntriesFromEvent(event)) {
mergeTurnDiffFileChange(summary.filesByPath, file);
}
}
const summaries: TurnDiffSummary[] = [];
for (const summary of byTurnId.values()) {
if (!summary.completedAt) continue;
summaries.push({
turnId: summary.turnId,
completedAt: summary.completedAt,
...(summary.status ? { status: summary.status } : {}),
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
a.path.localeCompare(b.path),
),
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
});
}
summaries.sort((a, b) => {
const aTime = Date.parse(a.completedAt);
const bTime = Date.parse(b.completedAt);
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
return b.completedAt.localeCompare(a.completedAt);
}
return bTime - aTime;
});
return summaries;
}
function toTimestamp(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
): TimelineEntry[] {
const timeline: TimelineEntry[] = [];
let messageIndex = 0;
let workIndex = 0;
while (messageIndex < messages.length || workIndex < workEntries.length) {
const message = messages[messageIndex];
const workEntry = workEntries[workIndex];
if (!message && workEntry) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
if (!workEntry && message) {
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
continue;
}
if (!message || !workEntry) {
break;
}
const messageAt = toTimestamp(message.createdAt);
const workAt = toTimestamp(workEntry.createdAt);
if (workAt <= messageAt) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
}
return timeline;
}
export function derivePhase(session: ProviderSession | null): SessionPhase {
@@ -154,3 +789,162 @@ export function derivePhase(session: ProviderSession | null): SessionPhase {
if (session.status === "running") return "running";
return "ready";
}
export function evolveSession(previous: ProviderSession, event: ProviderEvent): ProviderSession {
const payload = asObject(event.payload);
if (event.method === "thread/started") {
const thread = asObject(payload?.thread);
return {
...previous,
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/started") {
const turn = asObject(payload?.turn);
return {
...previous,
status: "running",
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/completed") {
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
const turnError = asObject(turn?.error);
return {
...previous,
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: asString(turnError?.message) ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.kind === "error") {
return {
...previous,
status: "error",
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.method === "session/closed" || event.method === "session/exited") {
return {
...previous,
status: "closed",
activeTurnId: undefined,
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
return { ...previous, updatedAt: event.createdAt };
}
export function applyEventToMessages(
previous: ChatMessage[],
event: ProviderEvent,
activeAssistantItemRef: { current: string | null },
): ChatMessage[] {
const payload = asObject(event.payload);
if (event.method === "item/started") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
activeAssistantItemRef.current = itemId;
const seedText = asString(item?.text) ?? "";
const filtered = previous.filter((entry) => entry.id !== itemId);
return [
...filtered,
{
id: itemId,
role: "assistant",
text: seedText,
createdAt: event.createdAt,
streaming: true,
},
];
}
if (event.method === "item/agentMessage/delta") {
const itemId = event.itemId ?? asString(payload?.itemId);
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
if (!itemId || !delta) return previous;
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
activeAssistantItemRef.current = itemId;
return [
...previous,
{
id: itemId,
role: "assistant",
text: delta,
createdAt: event.createdAt,
streaming: true,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: `${existing.text}${delta}`,
streaming: true,
};
return updated;
}
if (event.method === "item/completed") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
const fullText = asString(item?.text);
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
return [
...previous,
{
id: itemId,
role: "assistant",
text: fullText ?? "",
createdAt: event.createdAt,
streaming: false,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: fullText ?? existing.text,
streaming: false,
};
if (activeAssistantItemRef.current === itemId) {
activeAssistantItemRef.current = null;
}
return updated;
}
if (event.method === "turn/completed") {
return previous.map((entry) => ({ ...entry, streaming: false }));
}
return previous;
}
+259 -136
View File
@@ -4,17 +4,13 @@ import {
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import {
type OrchestrationReadModel,
normalizeProjectScripts,
} from "@t3tools/contracts";
import { type ProviderSession, normalizeProjectScripts } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
@@ -28,10 +24,14 @@ import {
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { type: "SET_SERVER_STATE"; state: AppState }
| { type: "ADD_PROJECT"; project: Project }
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "SET_THREADS_HYDRATED"; hydrated: boolean }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "DELETE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
@@ -39,14 +39,39 @@ type Action =
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| {
type: "PUSH_USER_MESSAGE";
threadId: string;
id: string;
text: string;
attachments?: ChatAttachment[];
}
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
| {
type: "REVERT_TO_CHECKPOINT";
threadId: string;
sessionId: string;
threadRuntimeId: string;
turnCount: number;
messageCount: number;
}
| {
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS";
threadId: string;
checkpointTurnCountByTurnId: Record<string, number>;
}
| {
type: "SET_THREAD_BRANCH";
threadId: string;
branch: string | null;
worktreePath: string | null;
}
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
| { type: "MARK_THREAD_VISITED"; threadId: string; visitedAt?: string }
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
| { type: "DELETE_THREAD"; threadId: string };
// ── State ────────────────────────────────────────────────────────────
@@ -57,75 +82,21 @@ export interface AppState {
runtimeMode: RuntimeMode;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
const initialState: AppState = {
projects: [],
threads: [],
threadsHydrated: false,
runtimeMode: DEFAULT_RUNTIME_MODE,
};
const persistedExpandedProjectCwds = new Set<string>();
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) return initialState;
const parsed = JSON.parse(raw) as {
runtimeMode?: RuntimeMode;
expandedProjectCwds?: string[];
};
persistedExpandedProjectCwds.clear();
for (const cwd of parsed.expandedProjectCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0) {
persistedExpandedProjectCwds.add(cwd);
}
}
return {
...initialState,
runtimeMode:
parsed.runtimeMode === "approval-required" || parsed.runtimeMode === "full-access"
? parsed.runtimeMode
: DEFAULT_RUNTIME_MODE,
};
} catch {
return initialState;
}
return initialState;
}
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
runtimeMode: state.runtimeMode,
expandedProjectCwds: state.projects
.filter((project) => project.expanded)
.map((project) => project.cwd),
}),
);
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
void state;
}
function updateThread(
@@ -136,7 +107,6 @@ function updateThread(
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
@@ -323,80 +293,31 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
});
}
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "SYNC_SERVER_READ_MODEL": {
const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
const projects = action.readModel.projects.map((project) => {
const existing = state.projects.find((entry) => entry.id === project.id);
return {
id: project.id,
name: project.name,
cwd: project.cwd,
model: resolveModelSlug(project.model),
expanded:
existing?.expanded ??
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.cwd)
: true),
scripts: existing?.scripts ?? [],
};
});
const threads = action.readModel.threads.map((thread) => {
const existing = existingThreadById.get(thread.id);
return normalizeThreadTerminals({
id: thread.id,
codexThreadId: thread.session?.threadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
terminalOpen: existing?.terminalOpen ?? false,
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: existing?.runningTerminalIds ?? [],
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: existing?.terminalGroups ?? [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
],
activeTerminalGroupId: existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: thread.session
? {
sessionId: thread.session.sessionId,
provider: thread.session.provider,
status: thread.session.status,
threadId: thread.session.threadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.createdAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => ({ ...message })),
error: thread.error,
createdAt: thread.createdAt,
latestTurnId: thread.latestTurnId ?? undefined,
latestTurnStartedAt: thread.latestTurnStartedAt ?? undefined,
latestTurnCompletedAt: thread.latestTurnCompletedAt ?? undefined,
latestTurnDurationMs: thread.latestTurnDurationMs ?? undefined,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
...summary,
files: summary.files.map((file) => ({ ...file })),
})),
});
});
case "SET_SERVER_STATE":
return {
...action.state,
threads: action.state.threads.map((thread) => normalizeThreadTerminals(thread)),
};
case "ADD_PROJECT":
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
return state;
}
return {
...state,
projects,
threads,
threadsHydrated: true,
projects: [
...state.projects,
{
...action.project,
model: resolveModelSlug(action.project.model),
scripts: normalizeProjectScripts(action.project.scripts),
},
],
};
}
case "SET_PROJECT_SCRIPTS":
return {
@@ -417,6 +338,46 @@ export function reducer(state: AppState, action: Action): AppState {
threadsHydrated: action.hydrated,
};
case "SYNC_PROJECTS": {
const previousByCwd = new Map(
state.projects.map((project) => [project.cwd, project] as const),
);
const nextProjects = action.projects.map((project) => {
const previous = previousByCwd.get(project.cwd);
const scripts = normalizeProjectScripts(project.scripts);
return {
...project,
model: resolveModelSlug(previous?.model ?? project.model),
expanded: previous?.expanded ?? project.expanded,
scripts,
};
});
const previousProjectById = new Map(
state.projects.map((project) => [project.id, project] as const),
);
const nextProjectIdByCwd = new Map(
nextProjects.map((project) => [project.cwd, project.id] as const),
);
const nextThreads = state.threads
.map((thread) => {
const previousProject = previousProjectById.get(thread.projectId);
if (!previousProject) return null;
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
if (!mappedProjectId) return null;
return normalizeThreadTerminals({
...thread,
projectId: mappedProjectId,
});
})
.filter((thread): thread is Thread => thread !== null);
return {
...state,
projects: nextProjects,
threads: nextThreads,
};
}
case "TOGGLE_PROJECT":
return {
...state,
@@ -425,6 +386,34 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "DELETE_PROJECT": {
const projects = state.projects.filter((project) => project.id !== action.projectId);
if (projects.length === state.projects.length) {
return state;
}
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
return {
...state,
projects,
threads,
};
}
case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
turnDiffSummaries: action.thread.turnDiffSummaries ?? [],
});
return {
...state,
threads: [...state.threads, nextThread],
};
}
case "TOGGLE_THREAD_TERMINAL":
return {
...state,
@@ -592,6 +581,43 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "UPDATE_SESSION":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
session: action.session,
codexThreadId: action.session.threadId ?? t.codexThreadId,
events: [],
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
})),
};
case "PUSH_USER_MESSAGE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
messages: [
...t.messages,
{
id: action.id,
role: "user" as const,
text: action.text,
...(action.attachments && action.attachments.length > 0
? { attachments: action.attachments }
: {}),
createdAt: new Date().toISOString(),
streaming: false,
},
],
})),
};
case "SET_ERROR":
return {
...state,
@@ -601,6 +627,90 @@ export function reducer(state: AppState, action: Action): AppState {
})),
};
case "SET_THREAD_TITLE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
title: action.title,
})),
};
case "SET_THREAD_MODEL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
model: resolveModelSlug(action.model),
})),
};
case "REVERT_TO_CHECKPOINT":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => {
const nextMessageCount = Math.max(0, Math.floor(action.messageCount));
const nextTurnCount = Math.max(0, Math.floor(action.turnCount));
const now = new Date().toISOString();
return {
...t,
codexThreadId: action.threadRuntimeId,
session:
t.session?.sessionId === action.sessionId
? {
...t.session,
status: "ready",
threadId: action.threadRuntimeId,
activeTurnId: undefined,
updatedAt: now,
lastError: undefined,
}
: t.session,
messages: t.messages.slice(0, nextMessageCount),
events: [],
turnDiffSummaries: t.turnDiffSummaries.filter(
(summary) =>
typeof summary.checkpointTurnCount === "number" &&
summary.checkpointTurnCount <= nextTurnCount,
),
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
lastVisitedAt: now,
};
}),
};
case "SET_THREAD_TURN_CHECKPOINT_COUNTS":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => {
const hasUpdates = t.turnDiffSummaries.some(
(summary) =>
action.checkpointTurnCountByTurnId[summary.turnId] !== undefined &&
action.checkpointTurnCountByTurnId[summary.turnId] !== summary.checkpointTurnCount,
);
if (!hasUpdates) {
return t;
}
return {
...t,
turnDiffSummaries: t.turnDiffSummaries.map((summary) => {
const turnCount = action.checkpointTurnCountByTurnId[summary.turnId];
if (turnCount === undefined) {
return summary;
}
return {
...summary,
checkpointTurnCount: turnCount,
};
}),
};
}),
};
case "SET_THREAD_BRANCH": {
return {
...state,
@@ -619,12 +729,29 @@ export function reducer(state: AppState, action: Action): AppState {
};
}
case "MARK_THREAD_VISITED": {
const visitedAt = action.visitedAt ?? new Date().toISOString();
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
lastVisitedAt: visitedAt,
})),
};
}
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
case "DELETE_THREAD":
return {
...state,
threads: state.threads.filter((t) => t.id !== action.threadId),
};
default:
return state;
}
@@ -640,10 +767,6 @@ const StoreContext = createContext<{
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
+1
View File
@@ -32,6 +32,7 @@ export function createThread(projectId: string, options: CreateThreadOptions = {
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
turnDiffSummaries: [],
error: null,
createdAt,
+2
View File
@@ -1,5 +1,6 @@
import type {
ProjectScript as ContractProjectScript,
ProviderEvent,
ProviderSession,
} from "@t3tools/contracts";
@@ -76,6 +77,7 @@ export interface Thread {
activeTerminalGroupId: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
+1
View File
@@ -24,6 +24,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
turnDiffSummaries: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
+35 -29
View File
@@ -1,20 +1,13 @@
import {
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type NativeApi,
WS_CHANNELS,
WS_METHODS,
type OrchestrationEvent,
type OrchestrationReadModel,
type WsWelcomePayload,
} from "@t3tools/contracts";
import { type NativeApi, WS_CHANNELS, WS_METHODS, type WsWelcomePayload } from "@t3tools/contracts";
import { showContextMenuFallback } from "./contextMenuFallback";
import { WsTransport } from "./wsTransport";
let instance: { api: NativeApi; transport: WsTransport } | null = null;
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
const stateListeners = new Set<(state: unknown) => void>();
let lastWelcome: WsWelcomePayload | null = null;
let lastStateSnapshot: unknown = null;
/**
* Subscribe to the server welcome message. If a welcome was already received
@@ -38,6 +31,20 @@ export function onServerWelcome(listener: (payload: WsWelcomePayload) => void):
};
}
export function onServerStateUpdate(listener: (state: unknown) => void): () => void {
stateListeners.add(listener);
if (lastStateSnapshot) {
try {
listener(lastStateSnapshot);
} catch {
// Swallow listener errors
}
}
return () => {
stateListeners.delete(listener);
};
}
export function createWsNativeApi(): NativeApi {
if (instance) return instance.api;
@@ -56,6 +63,16 @@ export function createWsNativeApi(): NativeApi {
}
}
});
transport.subscribe(WS_CHANNELS.stateUpdated, (data) => {
lastStateSnapshot = data;
for (const listener of stateListeners) {
try {
listener(data);
} catch {
// Swallow listener errors
}
}
});
const api: NativeApi = {
todos: {
@@ -99,10 +116,12 @@ export function createWsNativeApi(): NativeApi {
interruptTurn: (input) => transport.request(WS_METHODS.providersInterruptTurn, input),
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
listSessions: () => transport.request(WS_METHODS.providersListSessions),
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
revertToCheckpoint: (input) =>
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
onEvent: () => () => {},
},
projects: {
list: () => transport.request(WS_METHODS.projectsList),
@@ -155,25 +174,12 @@ export function createWsNativeApi(): NativeApi {
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
},
orchestration: {
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
dispatchCommand: (command) =>
transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, command),
replayEvents: (fromSequenceExclusive) =>
transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
onReadModel: (callback) =>
transport.subscribe(
ORCHESTRATION_WS_CHANNELS.readModel,
(data: unknown) => {
const payload = data as { snapshot: OrchestrationReadModel };
callback(payload.snapshot);
},
),
onDomainEvent: (callback) =>
transport.subscribe(
ORCHESTRATION_WS_CHANNELS.domainEvent,
callback as (data: unknown) => void,
),
state: {
getSnapshot: () => transport.request(WS_METHODS.stateGetSnapshot),
createThread: (input) => transport.request(WS_METHODS.stateCreateThread, input),
deleteThread: (input) => transport.request(WS_METHODS.stateDeleteThread, input),
markThreadVisited: (input) => transport.request(WS_METHODS.stateMarkThreadVisited, input),
setRuntimeMode: (input) => transport.request(WS_METHODS.stateSetRuntimeMode, input),
},
};
+154 -4
View File
@@ -34,7 +34,9 @@
"t3": "./dist/index.mjs",
},
"dependencies": {
"effect": "^3.19.19",
"@t3tools/core": "workspace:*",
"@t3tools/infra-sqlite": "workspace:*",
"effect": "^3.18.4",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
@@ -88,7 +90,6 @@
"name": "@t3tools/contracts",
"version": "0.0.0",
"dependencies": {
"effect": "^3.19.19",
"zod": "^3.24.1",
},
"devDependencies": {
@@ -96,6 +97,33 @@
"typescript": "^5.7.3",
},
},
"packages/core": {
"name": "@t3tools/core",
"version": "0.0.0",
"dependencies": {
"effect": "^3.18.4",
},
"devDependencies": {
"@types/node": "^25.3.0",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
},
},
"packages/infra-sqlite": {
"name": "@t3tools/infra-sqlite",
"version": "0.0.0",
"dependencies": {
"@effect/sql": "^0.49.0",
"@effect/sql-sqlite-node": "^0.50.1",
"@t3tools/core": "workspace:*",
"effect": "^3.18.4",
},
"devDependencies": {
"@types/node": "^25.3.0",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
},
},
},
"packages": {
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
@@ -146,6 +174,14 @@
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
"@effect/experimental": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/platform": "^0.94.0", "effect": "^3.19.13", "ioredis": "^5", "lmdb": "^3" }, "optionalPeers": ["ioredis", "lmdb"] }, "sha512-IEP9sapjF6rFy5TkoqDPc86st/fnqUfjT7Xa3pWJrFGr1hzaMXHo+mWsYOZS9LAOVKnpHuVziDK97EP5qsCHVA=="],
"@effect/platform": ["@effect/[email protected]", "", { "dependencies": { "find-my-way-ts": "^0.1.6", "msgpackr": "^1.11.4", "multipasta": "^0.2.7" }, "peerDependencies": { "effect": "^3.19.17" } }, "sha512-z05APUiDDPbodhTkH/RJqOLoCU11bU2IZLfcwLFrld03+ob1VeqRnELQlmueLIYm6NZifHAtjl32V+GRt34y4A=="],
"@effect/sql": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.0", "effect": "^3.19.13" } }, "sha512-9UEKR+z+MrI/qMAmSvb/RiD9KlgIazjZUCDSpwNgm0lEK9/Q6ExEyfziiYFVCPiptp52cBw8uBHRic8hHnwqXA=="],
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.4", "@effect/sql": "^0.49.0", "effect": "^3.19.16" } }, "sha512-L7DlHcOVl9/9V5stttFyv9wjvA9PBbaXwsp9pU+KN8KqokWgAVBNBEDf/dVfboUrynbDpDWwMU9SJmRJ1LXASQ=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
@@ -246,6 +282,18 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
@@ -420,8 +468,12 @@
"@t3tools/contracts": ["@t3tools/contracts@workspace:packages/contracts"],
"@t3tools/core": ["@t3tools/core@workspace:packages/core"],
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
"@t3tools/infra-sqlite": ["@t3tools/infra-sqlite@workspace:packages/infra-sqlite"],
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
@@ -520,7 +572,7 @@
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/node": ["@types/node@25.3.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
@@ -584,18 +636,28 @@
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
"birpc": ["[email protected]", "", {}, "sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw=="],
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
@@ -626,6 +688,8 @@
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
@@ -658,6 +722,8 @@
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
@@ -730,6 +796,8 @@
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
@@ -742,12 +810,18 @@
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
"follow-redirects": ["[email protected]", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
@@ -766,6 +840,8 @@
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
@@ -814,10 +890,16 @@
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
@@ -1012,16 +1094,30 @@
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
"multipasta": ["[email protected]", "", {}, "sha512-KPA58d68KgGil15oDqXjkUBEBYc00XvbPj5/X+dyzeo/lWm9Nc25pQRlf1D+gv4OpK7NM0J1odrbu9JNNGvynA=="],
"mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
"node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
@@ -1066,6 +1162,8 @@
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
@@ -1082,6 +1180,8 @@
"quick-lru": ["[email protected]", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
@@ -1090,6 +1190,8 @@
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
@@ -1140,6 +1242,8 @@
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
@@ -1158,6 +1262,10 @@
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
@@ -1176,10 +1284,14 @@
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
@@ -1200,6 +1312,10 @@
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
@@ -1234,6 +1350,8 @@
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.7", "turbo-darwin-arm64": "2.8.7", "turbo-linux-64": "2.8.7", "turbo-linux-arm64": "2.8.7", "turbo-windows-64": "2.8.7", "turbo-windows-arm64": "2.8.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RBLh5caMAu1kFdTK1jgH2gH/z+jFsvX5rGbhgJ9nlIAWXSvxlzwId05uDlBA1+pBd3wO/UaKYzaQZQBXDd7kcA=="],
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xr4TO/oDDwoozbDtBvunb66g//WK8uHRygl72vUthuwzmiw48pil4IuoG/QbMHd9RE8aBnVmzC0WZEWk/WWt3A=="],
@@ -1254,7 +1372,7 @@
"unconfig-core": ["[email protected]", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-VgPCvLWugINbXvMQDf8Jh0mlbvNjNC6eSUziHsBCMpxR05OPrNrvDnyatdMjRgcHaaNsCqz+wjNXxNw1kRLHUg=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
@@ -1284,6 +1402,10 @@
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
@@ -1350,6 +1472,8 @@
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@t3tools/desktop/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
@@ -1374,6 +1498,16 @@
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
@@ -1400,6 +1534,8 @@
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"t3/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
@@ -1408,6 +1544,8 @@
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"@t3tools/desktop/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
@@ -1430,8 +1568,20 @@
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"electron/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
"t3/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
}
}
-1
View File
@@ -23,7 +23,6 @@
"test": "vitest run"
},
"dependencies": {
"effect": "^3.19.19",
"zod": "^3.24.1"
},
"devDependencies": {
-1
View File
@@ -9,4 +9,3 @@ export * from "./keybindings";
export * from "./server";
export * from "./project";
export * from "./git";
export * from "./orchestration";
+18 -11
View File
@@ -16,6 +16,7 @@ import type {
GitStatusResult,
} from "./git";
import type {
ProviderEvent,
ProviderGetCheckpointDiffInput,
ProviderGetCheckpointDiffResult,
ProviderInterruptTurnInput,
@@ -41,6 +42,7 @@ import type {
ProjectUpdateScriptsResult,
} from "./project";
import type { ServerConfig } from "./server";
type RuntimeMode = "approval-required" | "full-access";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -52,11 +54,6 @@ import type {
} from "./terminal";
import type { NewTodoInput, Todo } from "./todo";
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "./orchestration";
export const EDITORS = [
{ id: "cursor", label: "Cursor", command: "cursor" },
@@ -98,6 +95,7 @@ export interface NativeApi {
interruptTurn: (input: ProviderInterruptTurnInput) => Promise<void>;
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
listSessions: () => Promise<ProviderSession[]>;
listCheckpoints: (
input: ProviderListCheckpointsInput,
) => Promise<ProviderListCheckpointsResult>;
@@ -107,6 +105,7 @@ export interface NativeApi {
revertToCheckpoint: (
input: ProviderRevertToCheckpointInput,
) => Promise<ProviderRevertToCheckpointResult>;
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
};
projects: {
list: () => Promise<ProjectListResult>;
@@ -142,11 +141,19 @@ export interface NativeApi {
getConfig: () => Promise<ServerConfig>;
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
};
orchestration: {
getSnapshot: () => Promise<OrchestrationReadModel>;
dispatchCommand: (command: OrchestrationCommand) => Promise<{ sequence: number }>;
replayEvents: (fromSequenceExclusive: number) => Promise<OrchestrationEvent[]>;
onReadModel: (callback: (snapshot: OrchestrationReadModel) => void) => () => void;
onDomainEvent: (callback: (event: OrchestrationEvent) => void) => () => void;
state: {
getSnapshot: () => Promise<unknown>;
createThread: (input: {
id: string;
projectId: string;
title: string;
model: string;
createdAt: string;
branch: string | null;
worktreePath: string | null;
}) => Promise<unknown>;
deleteThread: (input: { id: string }) => Promise<unknown>;
markThreadVisited: (input: { threadId: string; visitedAt?: string }) => Promise<unknown>;
setRuntimeMode: (input: { mode: RuntimeMode }) => Promise<unknown>;
};
}
-247
View File
@@ -1,247 +0,0 @@
import { Schema } from "effect";
export const ORCHESTRATION_WS_METHODS = {
getSnapshot: "orchestration.getSnapshot",
dispatchCommand: "orchestration.dispatchCommand",
replayEvents: "orchestration.replayEvents",
} as const;
export const ORCHESTRATION_WS_CHANNELS = {
readModel: "orchestration.readModel",
domainEvent: "orchestration.domainEvent",
} as const;
const IsoDateTimeSchema = Schema.String;
const IdSchema = Schema.String;
export const OrchestrationMessageSchema = Schema.Struct({
id: IdSchema,
role: Schema.Literal("user", "assistant"),
text: Schema.String,
createdAt: IsoDateTimeSchema,
streaming: Schema.Boolean,
});
export type OrchestrationMessage = Schema.Schema.Type<typeof OrchestrationMessageSchema>;
export const OrchestrationSessionSchema = Schema.Struct({
sessionId: IdSchema,
status: Schema.Literal("connecting", "ready", "running", "error", "closed"),
provider: Schema.Literal("codex", "claudeCode"),
threadId: IdSchema,
activeTurnId: Schema.NullOr(Schema.String),
createdAt: IsoDateTimeSchema,
updatedAt: IsoDateTimeSchema,
lastError: Schema.NullOr(Schema.String),
});
export type OrchestrationSession = Schema.Schema.Type<typeof OrchestrationSessionSchema>;
export const OrchestrationTurnDiffFileSchema = Schema.Struct({
path: Schema.String,
kind: Schema.optional(Schema.String),
additions: Schema.optional(Schema.Number),
deletions: Schema.optional(Schema.Number),
});
export type OrchestrationTurnDiffFile = Schema.Schema.Type<typeof OrchestrationTurnDiffFileSchema>;
export const OrchestrationTurnDiffSummarySchema = Schema.Struct({
turnId: IdSchema,
completedAt: IsoDateTimeSchema,
status: Schema.optional(Schema.String),
files: Schema.Array(OrchestrationTurnDiffFileSchema),
assistantMessageId: Schema.optional(Schema.String),
checkpointTurnCount: Schema.optional(Schema.Number),
});
export type OrchestrationTurnDiffSummary = Schema.Schema.Type<
typeof OrchestrationTurnDiffSummarySchema
>;
export const OrchestrationThreadSchema = Schema.Struct({
id: IdSchema,
projectId: IdSchema,
title: Schema.String,
model: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
createdAt: IsoDateTimeSchema,
updatedAt: IsoDateTimeSchema,
latestTurnId: Schema.NullOr(Schema.String),
latestTurnStartedAt: Schema.NullOr(Schema.String),
latestTurnCompletedAt: Schema.NullOr(Schema.String),
latestTurnDurationMs: Schema.NullOr(Schema.Number),
messages: Schema.Array(OrchestrationMessageSchema),
session: Schema.NullOr(OrchestrationSessionSchema),
turnDiffSummaries: Schema.Array(OrchestrationTurnDiffSummarySchema),
error: Schema.NullOr(Schema.String),
});
export type OrchestrationThread = Schema.Schema.Type<typeof OrchestrationThreadSchema>;
export const OrchestrationProjectSchema = Schema.Struct({
id: IdSchema,
name: Schema.String,
cwd: Schema.String,
model: Schema.String,
createdAt: IsoDateTimeSchema,
updatedAt: IsoDateTimeSchema,
});
export type OrchestrationProject = Schema.Schema.Type<typeof OrchestrationProjectSchema>;
export const OrchestrationGitReadModelSchema = Schema.Struct({
projectId: IdSchema,
branch: Schema.NullOr(Schema.String),
hasWorkingTreeChanges: Schema.Boolean,
aheadCount: Schema.Number,
behindCount: Schema.Number,
updatedAt: IsoDateTimeSchema,
});
export type OrchestrationGitReadModel = Schema.Schema.Type<typeof OrchestrationGitReadModelSchema>;
export const OrchestrationReadModelSchema = Schema.Struct({
sequence: Schema.Number,
projects: Schema.Array(OrchestrationProjectSchema),
threads: Schema.Array(OrchestrationThreadSchema),
gitByProjectId: Schema.Record({ key: Schema.String, value: OrchestrationGitReadModelSchema }),
updatedAt: IsoDateTimeSchema,
});
export type OrchestrationReadModel = Schema.Schema.Type<typeof OrchestrationReadModelSchema>;
export const CreateProjectCommandSchema = Schema.Struct({
type: Schema.Literal("project.create"),
commandId: IdSchema,
projectId: IdSchema,
name: Schema.String,
cwd: Schema.String,
model: Schema.String,
createdAt: IsoDateTimeSchema,
});
export const DeleteProjectCommandSchema = Schema.Struct({
type: Schema.Literal("project.delete"),
commandId: IdSchema,
projectId: IdSchema,
createdAt: IsoDateTimeSchema,
});
export const CreateThreadCommandSchema = Schema.Struct({
type: Schema.Literal("thread.create"),
commandId: IdSchema,
threadId: IdSchema,
projectId: IdSchema,
title: Schema.String,
model: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
createdAt: IsoDateTimeSchema,
});
export const DeleteThreadCommandSchema = Schema.Struct({
type: Schema.Literal("thread.delete"),
commandId: IdSchema,
threadId: IdSchema,
createdAt: IsoDateTimeSchema,
});
export const UpdateThreadMetaCommandSchema = Schema.Struct({
type: Schema.Literal("thread.meta.update"),
commandId: IdSchema,
threadId: IdSchema,
title: Schema.optional(Schema.String),
model: Schema.optional(Schema.String),
branch: Schema.optional(Schema.NullOr(Schema.String)),
worktreePath: Schema.optional(Schema.NullOr(Schema.String)),
createdAt: IsoDateTimeSchema,
});
export const SendMessageCommandSchema = Schema.Struct({
type: Schema.Literal("message.send"),
commandId: IdSchema,
threadId: IdSchema,
messageId: IdSchema,
role: Schema.Literal("user", "assistant"),
text: Schema.String,
streaming: Schema.optional(Schema.Boolean),
createdAt: IsoDateTimeSchema,
});
export const SetThreadSessionSchema = Schema.Struct({
type: Schema.Literal("thread.session"),
commandId: IdSchema,
threadId: IdSchema,
session: OrchestrationSessionSchema,
createdAt: IsoDateTimeSchema,
});
export const UpsertGitReadModelCommandSchema = Schema.Struct({
type: Schema.Literal("git.readModel.upsert"),
commandId: IdSchema,
projectId: IdSchema,
branch: Schema.NullOr(Schema.String),
hasWorkingTreeChanges: Schema.Boolean,
aheadCount: Schema.Number,
behindCount: Schema.Number,
createdAt: IsoDateTimeSchema,
});
export const CompleteThreadTurnDiffCommandSchema = Schema.Struct({
type: Schema.Literal("thread.turnDiff.complete"),
commandId: IdSchema,
threadId: IdSchema,
turnId: IdSchema,
completedAt: IsoDateTimeSchema,
status: Schema.optional(Schema.String),
files: Schema.Array(OrchestrationTurnDiffFileSchema),
assistantMessageId: Schema.optional(Schema.String),
checkpointTurnCount: Schema.optional(Schema.Number),
createdAt: IsoDateTimeSchema,
});
export const RevertThreadCommandSchema = Schema.Struct({
type: Schema.Literal("thread.revert"),
commandId: IdSchema,
threadId: IdSchema,
turnCount: Schema.Number,
messageCount: Schema.Number,
createdAt: IsoDateTimeSchema,
});
export const OrchestrationCommandSchema = Schema.Union(
CreateProjectCommandSchema,
DeleteProjectCommandSchema,
CreateThreadCommandSchema,
DeleteThreadCommandSchema,
UpdateThreadMetaCommandSchema,
SendMessageCommandSchema,
SetThreadSessionSchema,
UpsertGitReadModelCommandSchema,
CompleteThreadTurnDiffCommandSchema,
RevertThreadCommandSchema,
);
export type OrchestrationCommand = Schema.Schema.Type<typeof OrchestrationCommandSchema>;
export const OrchestrationEventSchema = Schema.Struct({
sequence: Schema.Number,
eventId: IdSchema,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: IsoDateTimeSchema,
commandId: Schema.NullOr(Schema.String),
payload: Schema.Unknown,
});
export type OrchestrationEvent = Schema.Schema.Type<typeof OrchestrationEventSchema>;
export const OrchestrationReadModelPushSchema = Schema.Struct({
sequence: Schema.Number,
snapshot: OrchestrationReadModelSchema,
});
export type OrchestrationReadModelPush = Schema.Schema.Type<typeof OrchestrationReadModelPushSchema>;
+2
View File
@@ -46,6 +46,7 @@ export const providerSessionSchema = z.object({
});
export const providerSessionStartInputSchema = z.object({
uiThreadId: z.string().trim().min(1).optional(),
provider: providerKindSchema.default("codex"),
cwd: z.string().min(1).optional(),
model: z.string().trim().min(1).optional(),
@@ -80,6 +81,7 @@ export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type"
export const providerSendTurnInputSchema = z
.object({
uiThreadId: z.string().trim().min(1).optional(),
sessionId: z.string().min(1),
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
attachments: z
+10
View File
@@ -9,6 +9,7 @@ export const WS_METHODS = {
providersInterruptTurn: "providers.interruptTurn",
providersRespondToRequest: "providers.respondToRequest",
providersStopSession: "providers.stopSession",
providersListSessions: "providers.listSessions",
providersListCheckpoints: "providers.listCheckpoints",
providersGetCheckpointDiff: "providers.getCheckpointDiff",
providersRevertToCheckpoint: "providers.revertToCheckpoint",
@@ -45,13 +46,22 @@ export const WS_METHODS = {
// Server meta
serverGetConfig: "server.getConfig",
serverUpsertKeybinding: "server.upsertKeybinding",
// Server-authoritative state
stateGetSnapshot: "state.getSnapshot",
stateCreateThread: "state.createThread",
stateDeleteThread: "state.deleteThread",
stateMarkThreadVisited: "state.markThreadVisited",
stateSetRuntimeMode: "state.setRuntimeMode",
} as const;
// ── Push Event Channels ──────────────────────────────────────────────
export const WS_CHANNELS = {
providerEvent: "providers.event",
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
stateUpdated: "state.updated",
} as const;
// ── Client → Server (request) ────────────────────────────────────────
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@t3tools/core",
"version": "0.0.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"effect": "^3.18.4"
},
"devDependencies": {
"@types/node": "^25.3.0",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
}
}
+78
View File
@@ -0,0 +1,78 @@
import type { AnyDomainCommand } from "../domain/commands";
import type { NewDomainEvent } from "../domain/events";
import type { AppViewState } from "../domain/models";
function eventFromCommand(
command: AnyDomainCommand,
eventType: NewDomainEvent["type"],
payload: NewDomainEvent["payload"],
streamId: string,
): NewDomainEvent {
return {
streamId,
type: eventType,
payload,
occurredAt: command.issuedAt,
...(command.id ? { causationId: command.id } : {}),
...(command.correlationId ? { correlationId: command.correlationId } : {}),
};
}
function streamIdFromCommand(command: AnyDomainCommand): string {
switch (command.type) {
case "app.bootstrap":
case "runtime.setMode":
return "app";
case "project.add":
case "project.remove":
case "project.updateScripts":
return `project:${command.payload.id}`;
case "thread.create":
case "thread.delete":
return `thread:${command.payload.id}`;
case "thread.addUserMessage":
case "thread.updateProviderSession":
case "thread.recordProviderEvent":
case "thread.setBranch":
case "thread.setTerminalActivity":
case "thread.markVisited":
return `thread:${command.payload.threadId}`;
default:
return "app";
}
}
export function decide(command: AnyDomainCommand, currentState: AppViewState): ReadonlyArray<NewDomainEvent> {
switch (command.type) {
case "app.bootstrap": {
if (currentState.projects.length > 0) return [];
return [eventFromCommand(command, "app.bootstrapped", command.payload, streamIdFromCommand(command))];
}
case "project.add":
return [eventFromCommand(command, "project.added", command.payload, streamIdFromCommand(command))];
case "project.remove":
return [eventFromCommand(command, "project.removed", command.payload, streamIdFromCommand(command))];
case "project.updateScripts":
return [eventFromCommand(command, "project.scriptsUpdated", command.payload, streamIdFromCommand(command))];
case "thread.create":
return [eventFromCommand(command, "thread.created", command.payload, streamIdFromCommand(command))];
case "thread.delete":
return [eventFromCommand(command, "thread.deleted", command.payload, streamIdFromCommand(command))];
case "thread.addUserMessage":
return [eventFromCommand(command, "thread.userMessageAdded", command.payload, streamIdFromCommand(command))];
case "thread.updateProviderSession":
return [eventFromCommand(command, "thread.providerSessionUpdated", command.payload, streamIdFromCommand(command))];
case "thread.recordProviderEvent":
return [eventFromCommand(command, "thread.providerEventRecorded", command.payload, streamIdFromCommand(command))];
case "thread.setBranch":
return [eventFromCommand(command, "thread.branchSet", command.payload, streamIdFromCommand(command))];
case "thread.setTerminalActivity":
return [eventFromCommand(command, "thread.terminalActivitySet", command.payload, streamIdFromCommand(command))];
case "thread.markVisited":
return [eventFromCommand(command, "thread.markVisited", command.payload, streamIdFromCommand(command))];
case "runtime.setMode":
return [eventFromCommand(command, "runtime.modeSet", command.payload, streamIdFromCommand(command))];
default:
return [];
}
}
+49
View File
@@ -0,0 +1,49 @@
import { emptyAppViewState, type AppViewState } from "../domain/models";
import type { AnyDomainCommand } from "../domain/commands";
import { decide } from "./decide";
import type { EventStorePort, ProjectionStorePort } from "../ports";
import { QueueProjector } from "./projector";
import { reduceEvents } from "../projections/reducer";
export class OrchestrationEngine {
constructor(
private readonly eventStore: EventStorePort,
projectionStore: ProjectionStorePort,
private readonly projector: QueueProjector,
) {
this.projectionStore = projectionStore;
}
private readonly projectionStore: ProjectionStorePort;
async start(): Promise<void> {
const state = await this.projectionStore.readState();
if (!state) {
const allEvents = await this.eventStore.loadAll();
const next = allEvents.length === 0 ? emptyAppViewState() : reduceEvents(allEvents, emptyAppViewState());
await this.projectionStore.writeState(next);
}
await this.projector.start();
const pending = await this.eventStore.loadAfterPosition((await this.currentState()).lastPosition);
if (pending.length > 0) {
await this.projector.enqueue(pending);
}
}
async stop(): Promise<void> {
await this.projector.stop();
}
async execute(command: AnyDomainCommand): Promise<AppViewState> {
const current = await this.currentState();
const pending = decide(command, current);
if (pending.length === 0) return current;
const appended = await this.eventStore.append(pending);
await this.projector.enqueue(appended);
return this.currentState();
}
async currentState(): Promise<AppViewState> {
return this.projector.readState();
}
}
+64
View File
@@ -0,0 +1,64 @@
import type { StateUpdatedNotification } from "../domain/events";
import type { FanoutPort } from "../ports";
interface Sink<T> {
push(value: T): void;
close(): void;
iterable: AsyncIterable<T>;
}
function createSink<T>(): Sink<T> {
const queue: T[] = [];
const waiters: Array<(value: IteratorResult<T>) => void> = [];
let closed = false;
const push = (value: T) => {
if (closed) return;
const waiter = waiters.shift();
if (waiter) {
waiter({ value, done: false });
return;
}
queue.push(value);
};
const close = () => {
closed = true;
while (waiters.length > 0) {
const waiter = waiters.shift();
waiter?.({ value: undefined as never, done: true });
}
};
const iterable: AsyncIterable<T> = {
[Symbol.asyncIterator]() {
return {
async next() {
if (queue.length > 0) {
return { value: queue.shift() as T, done: false };
}
if (closed) {
return { value: undefined as never, done: true };
}
return new Promise<IteratorResult<T>>((resolve) => {
waiters.push(resolve);
});
},
};
},
};
return { push, close, iterable };
}
export class EffectFanout implements FanoutPort {
private readonly sinks = new Set<Sink<StateUpdatedNotification>>();
async publish(notification: StateUpdatedNotification): Promise<void> {
for (const sink of this.sinks) {
sink.push(notification);
}
}
async subscribe(): Promise<AsyncIterable<StateUpdatedNotification>> {
const sink = createSink<StateUpdatedNotification>();
this.sinks.add(sink);
return sink.iterable;
}
}
@@ -0,0 +1,51 @@
import type { DomainEventEnvelope } from "../domain/events";
import { emptyAppViewState, type AppViewState } from "../domain/models";
import type { FanoutPort, ProjectionStorePort } from "../ports";
import { reduceEvents } from "../projections/reducer";
export class QueueProjector {
private readonly queue: ReadonlyArray<DomainEventEnvelope>[] = [];
private processing = false;
private stopSignal = false;
constructor(
private readonly projectionStore: ProjectionStorePort,
private readonly fanout: FanoutPort,
) {}
async start(): Promise<void> {
if (this.processing) return;
this.stopSignal = false;
this.processing = true;
void this.drain();
}
async stop(): Promise<void> {
this.stopSignal = true;
this.processing = false;
}
async enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void> {
if (events.length === 0) return;
this.queue.push(events);
if (this.processing) {
void this.drain();
}
}
async readState(): Promise<AppViewState> {
return (await this.projectionStore.readState()) ?? emptyAppViewState();
}
private async drain(): Promise<void> {
if (!this.processing) return;
while (!this.stopSignal && this.queue.length > 0) {
const chunk = this.queue.shift();
if (!chunk || chunk.length === 0) continue;
const current = (await this.projectionStore.readState()) ?? emptyAppViewState();
const next = reduceEvents(chunk, current);
await this.projectionStore.writeState(next);
await this.fanout.publish({ state: next, events: chunk });
}
}
}
+158
View File
@@ -0,0 +1,158 @@
import { Schema } from "effect";
import { ProjectScriptSchema, ProviderEventSchema, ProviderSessionViewSchema, RuntimeModeSchema } from "./models";
export const CommandTypeSchema = Schema.Literal(
"app.bootstrap",
"project.add",
"project.remove",
"project.updateScripts",
"thread.create",
"thread.delete",
"thread.addUserMessage",
"thread.updateProviderSession",
"thread.recordProviderEvent",
"thread.setBranch",
"thread.setTerminalActivity",
"thread.markVisited",
"runtime.setMode",
);
export type CommandType = Schema.Schema.Type<typeof CommandTypeSchema>;
export interface DomainCommand<TPayload> {
readonly id: string;
readonly type: CommandType;
readonly payload: TPayload;
readonly issuedAt: string;
readonly correlationId?: string;
}
export interface AppBootstrapCommand
extends DomainCommand<{
cwd: string;
projectName: string;
}> {
readonly type: "app.bootstrap";
}
export interface ProjectAddCommand
extends DomainCommand<{
id: string;
name: string;
cwd: string;
model: string;
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
}> {
readonly type: "project.add";
}
export interface ProjectRemoveCommand extends DomainCommand<{ id: string }> {
readonly type: "project.remove";
}
export interface ProjectUpdateScriptsCommand
extends DomainCommand<{
id: string;
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
}> {
readonly type: "project.updateScripts";
}
export interface ThreadCreateCommand
extends DomainCommand<{
id: string;
projectId: string;
title: string;
model: string;
createdAt: string;
branch: string | null;
worktreePath: string | null;
}> {
readonly type: "thread.create";
}
export interface ThreadDeleteCommand extends DomainCommand<{ id: string }> {
readonly type: "thread.delete";
}
export interface ThreadAddUserMessageCommand
extends DomainCommand<{
threadId: string;
messageId: string;
text: string;
createdAt: string;
attachments?: Array<{
type: "image";
id: string;
name: string;
mimeType: string;
sizeBytes: number;
previewUrl?: string;
}>;
}> {
readonly type: "thread.addUserMessage";
}
export interface ThreadUpdateProviderSessionCommand
extends DomainCommand<{
threadId: string;
session: Schema.Schema.Type<typeof ProviderSessionViewSchema> | null;
}> {
readonly type: "thread.updateProviderSession";
}
export interface ThreadRecordProviderEventCommand
extends DomainCommand<{
threadId: string;
event: Schema.Schema.Type<typeof ProviderEventSchema>;
}> {
readonly type: "thread.recordProviderEvent";
}
export interface ThreadSetBranchCommand
extends DomainCommand<{
threadId: string;
branch: string | null;
worktreePath: string | null;
}> {
readonly type: "thread.setBranch";
}
export interface ThreadSetTerminalActivityCommand
extends DomainCommand<{
threadId: string;
terminalId: string;
running: boolean;
}> {
readonly type: "thread.setTerminalActivity";
}
export interface ThreadMarkVisitedCommand
extends DomainCommand<{
threadId: string;
visitedAt: string;
}> {
readonly type: "thread.markVisited";
}
export interface RuntimeSetModeCommand
extends DomainCommand<{
mode: Schema.Schema.Type<typeof RuntimeModeSchema>;
}> {
readonly type: "runtime.setMode";
}
export type AnyDomainCommand =
| AppBootstrapCommand
| ProjectAddCommand
| ProjectRemoveCommand
| ProjectUpdateScriptsCommand
| ThreadCreateCommand
| ThreadDeleteCommand
| ThreadAddUserMessageCommand
| ThreadUpdateProviderSessionCommand
| ThreadRecordProviderEventCommand
| ThreadSetBranchCommand
| ThreadSetTerminalActivityCommand
| ThreadMarkVisitedCommand
| RuntimeSetModeCommand;
+149
View File
@@ -0,0 +1,149 @@
import { Schema } from "effect";
import {
type AppViewState,
ProjectScriptSchema,
ProviderEventSchema,
ProviderSessionViewSchema,
RuntimeModeSchema,
} from "./models";
export const DomainEventTypeSchema = Schema.Literal(
"app.bootstrapped",
"project.added",
"project.removed",
"project.scriptsUpdated",
"thread.created",
"thread.deleted",
"thread.userMessageAdded",
"thread.providerSessionUpdated",
"thread.providerEventRecorded",
"thread.branchSet",
"thread.terminalActivitySet",
"thread.markVisited",
"runtime.modeSet",
);
export type DomainEventType = Schema.Schema.Type<typeof DomainEventTypeSchema>;
const AppBootstrappedPayloadSchema = Schema.Struct({
cwd: Schema.String,
projectName: Schema.String,
});
const ProjectAddedPayloadSchema = Schema.Struct({
id: Schema.String,
name: Schema.String,
cwd: Schema.String,
model: Schema.String,
scripts: Schema.Array(ProjectScriptSchema),
});
const ProjectRemovedPayloadSchema = Schema.Struct({ id: Schema.String });
const ProjectScriptsUpdatedPayloadSchema = Schema.Struct({
id: Schema.String,
scripts: Schema.Array(ProjectScriptSchema),
});
const ThreadCreatedPayloadSchema = Schema.Struct({
id: Schema.String,
projectId: Schema.String,
title: Schema.String,
model: Schema.String,
createdAt: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
});
const ThreadDeletedPayloadSchema = Schema.Struct({ id: Schema.String });
const ThreadUserMessageAddedPayloadSchema = Schema.Struct({
threadId: Schema.String,
messageId: Schema.String,
text: Schema.String,
createdAt: Schema.String,
attachments: Schema.optional(
Schema.Array(
Schema.Struct({
type: Schema.Literal("image"),
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
previewUrl: Schema.optional(Schema.String),
}),
),
),
});
const ThreadProviderSessionUpdatedPayloadSchema = Schema.Struct({
threadId: Schema.String,
session: Schema.NullOr(ProviderSessionViewSchema),
});
const ThreadProviderEventRecordedPayloadSchema = Schema.Struct({
threadId: Schema.String,
event: ProviderEventSchema,
});
const ThreadBranchSetPayloadSchema = Schema.Struct({
threadId: Schema.String,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
});
const ThreadTerminalActivitySetPayloadSchema = Schema.Struct({
threadId: Schema.String,
terminalId: Schema.String,
running: Schema.Boolean,
});
const ThreadMarkVisitedPayloadSchema = Schema.Struct({
threadId: Schema.String,
visitedAt: Schema.String,
});
const RuntimeModeSetPayloadSchema = Schema.Struct({
mode: RuntimeModeSchema,
});
export type DomainEventPayload =
| Schema.Schema.Type<typeof AppBootstrappedPayloadSchema>
| Schema.Schema.Type<typeof ProjectAddedPayloadSchema>
| Schema.Schema.Type<typeof ProjectRemovedPayloadSchema>
| Schema.Schema.Type<typeof ProjectScriptsUpdatedPayloadSchema>
| Schema.Schema.Type<typeof ThreadCreatedPayloadSchema>
| Schema.Schema.Type<typeof ThreadDeletedPayloadSchema>
| Schema.Schema.Type<typeof ThreadUserMessageAddedPayloadSchema>
| Schema.Schema.Type<typeof ThreadProviderSessionUpdatedPayloadSchema>
| Schema.Schema.Type<typeof ThreadProviderEventRecordedPayloadSchema>
| Schema.Schema.Type<typeof ThreadBranchSetPayloadSchema>
| Schema.Schema.Type<typeof ThreadTerminalActivitySetPayloadSchema>
| Schema.Schema.Type<typeof ThreadMarkVisitedPayloadSchema>
| Schema.Schema.Type<typeof RuntimeModeSetPayloadSchema>;
export interface DomainEventEnvelope {
readonly eventId: string;
readonly streamId: string;
readonly sequence: number;
readonly position: number;
readonly type: DomainEventType;
readonly occurredAt: string;
readonly payload: DomainEventPayload;
readonly causationId?: string;
readonly correlationId?: string;
}
export interface NewDomainEvent {
readonly streamId: string;
readonly type: DomainEventType;
readonly payload: DomainEventPayload;
readonly occurredAt: string;
readonly causationId?: string;
readonly correlationId?: string;
}
export interface StateUpdatedNotification {
readonly state: AppViewState;
readonly events: readonly DomainEventEnvelope[];
}
+152
View File
@@ -0,0 +1,152 @@
import { Schema } from "effect";
export const RuntimeModeSchema = Schema.Literal("approval-required", "full-access");
export type RuntimeMode = Schema.Schema.Type<typeof RuntimeModeSchema>;
export const ProjectScriptSchema = Schema.Struct({
id: Schema.String,
name: Schema.String,
command: Schema.String,
keybinding: Schema.optional(Schema.String),
});
export type ProjectScript = Schema.Schema.Type<typeof ProjectScriptSchema>;
export const ProjectViewSchema = Schema.Struct({
id: Schema.String,
name: Schema.String,
cwd: Schema.String,
model: Schema.String,
expanded: Schema.Boolean,
scripts: Schema.Array(ProjectScriptSchema),
});
export type ProjectView = Schema.Schema.Type<typeof ProjectViewSchema>;
export const ChatAttachmentSchema = Schema.Struct({
type: Schema.Literal("image"),
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
previewUrl: Schema.optional(Schema.String),
});
export type ChatAttachment = Schema.Schema.Type<typeof ChatAttachmentSchema>;
export const ChatMessageSchema = Schema.Struct({
id: Schema.String,
role: Schema.Literal("user", "assistant"),
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachmentSchema)),
createdAt: Schema.String,
streaming: Schema.Boolean,
});
export type ChatMessage = Schema.Schema.Type<typeof ChatMessageSchema>;
export const SessionStatusSchema = Schema.Literal(
"connecting",
"ready",
"running",
"error",
"closed",
);
export type SessionStatus = Schema.Schema.Type<typeof SessionStatusSchema>;
export const ProviderSessionViewSchema = Schema.Struct({
sessionId: Schema.String,
provider: Schema.Literal("codex", "claudeCode"),
status: SessionStatusSchema,
cwd: Schema.optional(Schema.String),
model: Schema.optional(Schema.String),
threadId: Schema.optional(Schema.String),
activeTurnId: Schema.optional(Schema.String),
createdAt: Schema.String,
updatedAt: Schema.String,
lastError: Schema.optional(Schema.String),
});
export type ProviderSessionView = Schema.Schema.Type<typeof ProviderSessionViewSchema>;
export const ProviderEventSchema = Schema.Struct({
id: Schema.String,
kind: Schema.Literal("session", "notification", "request", "error"),
method: Schema.String,
payload: Schema.optional(Schema.Unknown),
createdAt: Schema.String,
sessionId: Schema.String,
threadId: Schema.optional(Schema.String),
turnId: Schema.optional(Schema.String),
itemId: Schema.optional(Schema.String),
textDelta: Schema.optional(Schema.String),
requestId: Schema.optional(Schema.String),
requestKind: Schema.optional(Schema.String),
message: Schema.optional(Schema.String),
});
export type ProviderEvent = Schema.Schema.Type<typeof ProviderEventSchema>;
export const TurnDiffFileChangeSchema = Schema.Struct({
path: Schema.String,
kind: Schema.optional(Schema.String),
additions: Schema.optional(Schema.Number),
deletions: Schema.optional(Schema.Number),
});
export type TurnDiffFileChange = Schema.Schema.Type<typeof TurnDiffFileChangeSchema>;
export const TurnDiffSummarySchema = Schema.Struct({
turnId: Schema.String,
completedAt: Schema.String,
status: Schema.optional(Schema.String),
files: Schema.Array(TurnDiffFileChangeSchema),
assistantMessageId: Schema.optional(Schema.String),
checkpointTurnCount: Schema.optional(Schema.Number),
});
export type TurnDiffSummary = Schema.Schema.Type<typeof TurnDiffSummarySchema>;
export const ThreadTerminalGroupSchema = Schema.Struct({
id: Schema.String,
terminalIds: Schema.Array(Schema.String),
});
export type ThreadTerminalGroup = Schema.Schema.Type<typeof ThreadTerminalGroupSchema>;
export const ThreadViewSchema = Schema.Struct({
id: Schema.String,
codexThreadId: Schema.NullOr(Schema.String),
projectId: Schema.String,
title: Schema.String,
model: Schema.String,
terminalOpen: Schema.Boolean,
terminalHeight: Schema.Number,
terminalIds: Schema.Array(Schema.String),
runningTerminalIds: Schema.Array(Schema.String),
activeTerminalId: Schema.String,
terminalGroups: Schema.Array(ThreadTerminalGroupSchema),
activeTerminalGroupId: Schema.String,
session: Schema.NullOr(ProviderSessionViewSchema),
messages: Schema.Array(ChatMessageSchema),
events: Schema.Array(ProviderEventSchema),
error: Schema.NullOr(Schema.String),
createdAt: Schema.String,
latestTurnId: Schema.optional(Schema.String),
latestTurnStartedAt: Schema.optional(Schema.String),
latestTurnCompletedAt: Schema.optional(Schema.String),
latestTurnDurationMs: Schema.optional(Schema.Number),
lastVisitedAt: Schema.optional(Schema.String),
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
turnDiffSummaries: Schema.Array(TurnDiffSummarySchema),
});
export type ThreadView = Schema.Schema.Type<typeof ThreadViewSchema>;
export const AppViewStateSchema = Schema.Struct({
projects: Schema.Array(ProjectViewSchema),
threads: Schema.Array(ThreadViewSchema),
threadsHydrated: Schema.Boolean,
runtimeMode: RuntimeModeSchema,
lastPosition: Schema.Number,
});
export type AppViewState = Schema.Schema.Type<typeof AppViewStateSchema>;
export const emptyAppViewState = (): AppViewState => ({
projects: [],
threads: [],
threadsHydrated: false,
runtimeMode: "full-access",
lastPosition: 0,
});
+7
View File
@@ -0,0 +1,7 @@
import type { AppViewState } from "./models";
export type DomainQuery = { readonly type: "app.getState" };
export interface QueryResultMap {
"app.getState": AppViewState;
}
+10
View File
@@ -0,0 +1,10 @@
export * from "./domain/models";
export * from "./domain/commands";
export * from "./domain/events";
export * from "./domain/queries";
export * from "./ports";
export * from "./projections/reducer";
export * from "./application/decide";
export * from "./application/fanout";
export * from "./application/projector";
export * from "./application/engine";
+30
View File
@@ -0,0 +1,30 @@
import type { AnyDomainCommand } from "../domain/commands";
import type { DomainEventEnvelope, NewDomainEvent, StateUpdatedNotification } from "../domain/events";
import type { AppViewState } from "../domain/models";
export interface EventStorePort {
append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>>;
loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>>;
loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>>;
}
export interface ProjectionStorePort {
readState(): Promise<AppViewState | null>;
writeState(state: AppViewState): Promise<void>;
}
export interface FanoutPort {
publish(notification: StateUpdatedNotification): Promise<void>;
subscribe(): Promise<AsyncIterable<StateUpdatedNotification>>;
}
export interface DeterministicProjectorPort {
start(): Promise<void>;
stop(): Promise<void>;
enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void>;
}
export interface CoreApplicationPort {
execute(command: AnyDomainCommand): Promise<AppViewState>;
currentState(): Promise<AppViewState>;
}
+370
View File
@@ -0,0 +1,370 @@
import type { DomainEventEnvelope } from "../domain/events";
import type { AppViewState, ChatMessage, ProviderEvent, ProviderSessionView, ThreadView } from "../domain/models";
import { emptyAppViewState } from "../domain/models";
function asObject(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function eventTurnId(event: ProviderEvent): string | undefined {
if (event.turnId) return event.turnId;
const turn = asObject(asObject(event.payload)?.turn);
return asString(turn?.id);
}
function durationMs(startIso: string, endIso: string): number | undefined {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) return undefined;
return end - start;
}
function evolveSession(previous: ProviderSessionView, event: ProviderEvent): ProviderSessionView {
const payload = asObject(event.payload);
if (event.method === "thread/started") {
const thread = asObject(payload?.thread);
return { ...previous, threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId, updatedAt: event.createdAt };
}
if (event.method === "turn/started") {
const turn = asObject(payload?.turn);
return {
...previous,
status: "running",
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/completed") {
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
const turnError = asObject(turn?.error);
return {
...previous,
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: asString(turnError?.message) ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.kind === "error") {
return {
...previous,
status: "error",
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.method === "session/closed" || event.method === "session/exited") {
return {
...previous,
status: "closed",
activeTurnId: undefined,
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
return { ...previous, updatedAt: event.createdAt };
}
function applyEventToMessages(previous: ReadonlyArray<ChatMessage>, event: ProviderEvent): ChatMessage[] {
const payload = asObject(event.payload);
if (event.method === "item/started") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return [...previous];
const itemId = asString(item?.id);
if (!itemId) return [...previous];
const seedText = asString(item?.text) ?? "";
return [
...previous.filter((entry) => entry.id !== itemId),
{ id: itemId, role: "assistant", text: seedText, createdAt: event.createdAt, streaming: true },
];
}
if (event.method === "item/agentMessage/delta") {
const itemId = event.itemId ?? asString(payload?.itemId);
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
if (!itemId || !delta) return [...previous];
const idx = previous.findIndex((entry) => entry.id === itemId);
if (idx < 0) {
return [...previous, { id: itemId, role: "assistant", text: delta, createdAt: event.createdAt, streaming: true }];
}
const next = [...previous];
const current = next[idx];
if (!current) return [...previous];
next[idx] = { ...current, text: `${current.text}${delta}`, streaming: true };
return next;
}
if (event.method === "item/completed") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return [...previous];
const itemId = asString(item?.id);
if (!itemId) return [...previous];
const fullText = asString(item?.text);
const idx = previous.findIndex((entry) => entry.id === itemId);
if (idx < 0) {
return [...previous, { id: itemId, role: "assistant", text: fullText ?? "", createdAt: event.createdAt, streaming: false }];
}
const next = [...previous];
const current = next[idx];
if (!current) return [...previous];
next[idx] = { ...current, text: fullText ?? current.text, streaming: false };
return next;
}
if (event.method === "turn/completed") {
return previous.map((entry) => ({ ...entry, streaming: false }));
}
return [...previous];
}
function defaultThread(payload: {
id: string;
projectId: string;
title: string;
model: string;
createdAt: string;
branch: string | null;
worktreePath: string | null;
}): ThreadView {
return {
id: payload.id,
codexThreadId: null,
projectId: payload.projectId,
title: payload.title,
model: payload.model,
terminalOpen: false,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
session: null,
messages: [],
events: [],
error: null,
createdAt: payload.createdAt,
branch: payload.branch,
worktreePath: payload.worktreePath,
turnDiffSummaries: [],
};
}
export function applyDomainEvent(state: AppViewState, event: DomainEventEnvelope): AppViewState {
switch (event.type) {
case "app.bootstrapped": {
const payload = event.payload as { cwd: string; projectName: string };
if (state.projects.length > 0) return { ...state, threadsHydrated: true, lastPosition: event.position };
return {
...state,
projects: [
{
id: "bootstrap-project",
name: payload.projectName,
cwd: payload.cwd,
model: "gpt-5-codex",
expanded: true,
scripts: [],
},
],
threadsHydrated: true,
lastPosition: event.position,
};
}
case "project.added": {
const payload = event.payload as {
id: string;
name: string;
cwd: string;
model: string;
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
};
if (state.projects.some((project) => project.id === payload.id || project.cwd === payload.cwd)) {
return { ...state, lastPosition: event.position };
}
return {
...state,
projects: [...state.projects, { ...payload, expanded: true }],
lastPosition: event.position,
};
}
case "project.removed": {
const payload = event.payload as { id: string };
return {
...state,
projects: state.projects.filter((project) => project.id !== payload.id),
threads: state.threads.filter((thread) => thread.projectId !== payload.id),
lastPosition: event.position,
};
}
case "project.scriptsUpdated": {
const payload = event.payload as {
id: string;
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
};
return {
...state,
projects: state.projects.map((project) =>
project.id === payload.id ? { ...project, scripts: payload.scripts } : project,
),
lastPosition: event.position,
};
}
case "thread.created": {
const payload = event.payload as {
id: string;
projectId: string;
title: string;
model: string;
createdAt: string;
branch: string | null;
worktreePath: string | null;
};
if (state.threads.some((thread) => thread.id === payload.id)) {
return { ...state, lastPosition: event.position };
}
return { ...state, threads: [...state.threads, defaultThread(payload)], lastPosition: event.position };
}
case "thread.deleted": {
const payload = event.payload as { id: string };
return { ...state, threads: state.threads.filter((thread) => thread.id !== payload.id), lastPosition: event.position };
}
case "thread.userMessageAdded": {
const payload = event.payload as {
threadId: string;
messageId: string;
text: string;
createdAt: string;
attachments?: Array<{
type: "image";
id: string;
name: string;
mimeType: string;
sizeBytes: number;
previewUrl?: string;
}>;
};
return {
...state,
threads: state.threads.map((thread) =>
thread.id === payload.threadId
? {
...thread,
messages: [
...thread.messages,
{
id: payload.messageId,
role: "user",
text: payload.text,
attachments: payload.attachments ? [...payload.attachments] : undefined,
createdAt: payload.createdAt,
streaming: false,
},
],
}
: thread,
),
lastPosition: event.position,
};
}
case "thread.providerSessionUpdated": {
const payload = event.payload as { threadId: string; session: ProviderSessionView | null };
return {
...state,
threads: state.threads.map((thread) =>
thread.id === payload.threadId
? {
...thread,
session: payload.session,
codexThreadId: payload.session?.threadId ?? thread.codexThreadId,
...(payload.session ? {} : { events: [], messages: [], turnDiffSummaries: [] }),
}
: thread,
),
lastPosition: event.position,
};
}
case "thread.providerEventRecorded": {
const payload = event.payload as { threadId: string; event: ProviderEvent };
return {
...state,
threads: state.threads.map((thread) => {
if (thread.id !== payload.threadId) return thread;
const nextEvents = [payload.event, ...thread.events];
const nextSession = thread.session ? evolveSession(thread.session, payload.event) : thread.session;
const nextMessages = applyEventToMessages(thread.messages, payload.event);
const nextTurnId = payload.event.method === "turn/started" ? eventTurnId(payload.event) ?? thread.latestTurnId : thread.latestTurnId;
const nextTurnStartedAt = payload.event.method === "turn/started" ? payload.event.createdAt : thread.latestTurnStartedAt;
const nextTurnCompletedAt = payload.event.method === "turn/completed" ? payload.event.createdAt : thread.latestTurnCompletedAt;
const nextTurnDuration =
payload.event.method === "turn/completed" && thread.latestTurnStartedAt
? durationMs(thread.latestTurnStartedAt, payload.event.createdAt)
: thread.latestTurnDurationMs;
return {
...thread,
events: nextEvents,
messages: nextMessages,
session: nextSession,
error: payload.event.kind === "error" && payload.event.message ? payload.event.message : thread.error,
latestTurnId: nextTurnId,
latestTurnStartedAt: nextTurnStartedAt,
latestTurnCompletedAt: nextTurnCompletedAt,
latestTurnDurationMs: nextTurnDuration,
};
}),
lastPosition: event.position,
};
}
case "thread.branchSet": {
const payload = event.payload as { threadId: string; branch: string | null; worktreePath: string | null };
return {
...state,
threads: state.threads.map((thread) =>
thread.id === payload.threadId
? { ...thread, branch: payload.branch, worktreePath: payload.worktreePath }
: thread,
),
lastPosition: event.position,
};
}
case "thread.terminalActivitySet": {
const payload = event.payload as { threadId: string; terminalId: string; running: boolean };
return {
...state,
threads: state.threads.map((thread) => {
if (thread.id !== payload.threadId) return thread;
const running = new Set(thread.runningTerminalIds);
if (payload.running) running.add(payload.terminalId);
else running.delete(payload.terminalId);
const terminalIds = thread.terminalIds.includes(payload.terminalId)
? thread.terminalIds
: [...thread.terminalIds, payload.terminalId];
return { ...thread, terminalIds, runningTerminalIds: [...running] };
}),
lastPosition: event.position,
};
}
case "thread.markVisited": {
const payload = event.payload as { threadId: string; visitedAt: string };
return {
...state,
threads: state.threads.map((thread) =>
thread.id === payload.threadId ? { ...thread, lastVisitedAt: payload.visitedAt } : thread,
),
lastPosition: event.position,
};
}
case "runtime.modeSet": {
const payload = event.payload as { mode: "approval-required" | "full-access" };
return { ...state, runtimeMode: payload.mode, lastPosition: event.position };
}
default:
return { ...state, lastPosition: event.position };
}
}
export function reduceEvents(events: ReadonlyArray<DomainEventEnvelope>, seed?: AppViewState): AppViewState {
return events.reduce((state, event) => applyDomainEvent(state, event), seed ?? emptyAppViewState());
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2023"],
"types": ["node"]
},
"include": ["src/**/*.ts"]
}
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@t3tools/infra-sqlite",
"version": "0.0.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
}
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@effect/sql": "^0.49.0",
"@effect/sql-sqlite-node": "^0.50.1",
"@t3tools/core": "workspace:*",
"effect": "^3.18.4"
},
"devDependencies": {
"@types/node": "^25.3.0",
"typescript": "^5.7.3",
"vitest": "^4.0.0"
}
}
+1
View File
@@ -0,0 +1 @@
export * from "./sqliteStore";
+175
View File
@@ -0,0 +1,175 @@
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import crypto from "node:crypto";
import type { AppViewState, DomainEventEnvelope, EventStorePort, NewDomainEvent, ProjectionStorePort } from "@t3tools/core";
interface EventRow {
event_id: string;
stream_id: string;
sequence: number;
position: number;
type: string;
occurred_at: string;
payload_json: string;
causation_id: string | null;
correlation_id: string | null;
}
function ensureDir(filePath: string): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
function parseState(raw: string | null): AppViewState | null {
if (!raw) return null;
return JSON.parse(raw) as AppViewState;
}
export class SqliteEventStore implements EventStorePort {
constructor(private readonly db: DatabaseSync) {}
async append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>> {
if (events.length === 0) return [];
const out: DomainEventEnvelope[] = [];
this.db.exec("BEGIN IMMEDIATE TRANSACTION");
try {
for (const event of events) {
const sequenceStmt = this.db.prepare(
"SELECT COALESCE(MAX(sequence), 0) + 1 AS nextSequence FROM events WHERE stream_id = ?",
);
const sequenceRow = sequenceStmt.get(event.streamId) as { nextSequence: number };
const insert = this.db.prepare(
[
"INSERT INTO events(",
"event_id, stream_id, sequence, type, occurred_at, payload_json, causation_id, correlation_id",
") VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
].join(" "),
);
const eventId = crypto.randomUUID();
insert.run(
eventId,
event.streamId,
sequenceRow.nextSequence,
event.type,
event.occurredAt,
JSON.stringify(event.payload),
event.causationId ?? null,
event.correlationId ?? null,
);
const positionRow = this.db
.prepare("SELECT position FROM events WHERE event_id = ?")
.get(eventId) as { position: number };
out.push({
eventId,
streamId: event.streamId,
sequence: sequenceRow.nextSequence,
position: positionRow.position,
type: event.type,
occurredAt: event.occurredAt,
payload: event.payload,
...(event.causationId ? { causationId: event.causationId } : {}),
...(event.correlationId ? { correlationId: event.correlationId } : {}),
});
}
this.db.exec("COMMIT");
return out;
} catch (error) {
this.db.exec("ROLLBACK");
throw error;
}
}
async loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>> {
const stmt = this.db.prepare(
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events ORDER BY position ASC",
);
const rows = stmt.all() as unknown as EventRow[];
return rows.map(mapEventRow);
}
async loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>> {
const stmt = this.db.prepare(
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events WHERE position > ? ORDER BY position ASC",
);
const rows = stmt.all(position) as unknown as EventRow[];
return rows.map(mapEventRow);
}
}
function mapEventRow(row: EventRow): DomainEventEnvelope {
return {
eventId: row.event_id,
streamId: row.stream_id,
sequence: row.sequence,
position: row.position,
type: row.type as DomainEventEnvelope["type"],
occurredAt: row.occurred_at,
payload: JSON.parse(row.payload_json) as DomainEventEnvelope["payload"],
...(row.causation_id ? { causationId: row.causation_id } : {}),
...(row.correlation_id ? { correlationId: row.correlation_id } : {}),
};
}
export class SqliteProjectionStore implements ProjectionStorePort {
constructor(private readonly db: DatabaseSync) {}
async readState(): Promise<AppViewState | null> {
const row = this.db
.prepare("SELECT state_json FROM projection_state WHERE projection_name = 'app_state'")
.get() as { state_json: string } | undefined;
return parseState(row?.state_json ?? null);
}
async writeState(state: AppViewState): Promise<void> {
this.db
.prepare(
[
"INSERT INTO projection_state(projection_name, state_json, updated_at)",
"VALUES('app_state', ?, ?)",
"ON CONFLICT(projection_name) DO UPDATE SET",
"state_json = excluded.state_json,",
"updated_at = excluded.updated_at",
].join(" "),
)
.run(JSON.stringify(state), new Date().toISOString());
}
}
export function createSqliteStores(dbPath: string): {
db: DatabaseSync;
eventStore: SqliteEventStore;
projectionStore: SqliteProjectionStore;
} {
ensureDir(dbPath);
const db = new DatabaseSync(dbPath);
db.exec("PRAGMA journal_mode = WAL;");
db.exec("PRAGMA foreign_keys = ON;");
db.exec(
[
"CREATE TABLE IF NOT EXISTS events(",
"position INTEGER PRIMARY KEY AUTOINCREMENT,",
"event_id TEXT NOT NULL UNIQUE,",
"stream_id TEXT NOT NULL,",
"sequence INTEGER NOT NULL,",
"type TEXT NOT NULL,",
"occurred_at TEXT NOT NULL,",
"payload_json TEXT NOT NULL,",
"causation_id TEXT,",
"correlation_id TEXT,",
"UNIQUE(stream_id, sequence)",
");",
"CREATE INDEX IF NOT EXISTS idx_events_stream_position ON events(stream_id, position);",
"CREATE TABLE IF NOT EXISTS projection_state(",
"projection_name TEXT PRIMARY KEY,",
"state_json TEXT NOT NULL,",
"updated_at TEXT NOT NULL",
");",
].join(" "),
);
return {
db,
eventStore: new SqliteEventStore(db),
projectionStore: new SqliteProjectionStore(db),
};
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2023"],
"types": ["node"]
},
"include": ["src/**/*.ts"]
}