Compare commits

..
Author SHA1 Message Date
Julius MarmingeandClaude Opus 4.5 dbbc225fe6 Add provider orchestrator and Codex adapter
- ProviderOrchestrator manages provider sessions and message dispatch
- CodexProviderAdapter wraps Codex app-server integration
- Refactor wsServer to use new provider abstraction

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-21 17:19:18 -08:00
Julius MarmingeandClaude Opus 4.5 4ce3c3bf8a Add event-sourced CoreEngine for server-side state management
Introduces a new event-sourced architecture with SQLite persistence:
- CoreEngine handles command dispatch and read model generation
- SqliteEventStore provides durable event storage
- CommandHandlers process domain commands (CreateProject, CreateThread, etc.)
- ReadModels derive current state from event history

Simplifies client-side state management by moving persistence to the server.
Removes redundant client-side persistence schema and session logic tests.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-21 17:02:13 -08:00
37 changed files with 3687 additions and 1727 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 -2
View File
@@ -17,7 +17,9 @@
"test": "vitest run"
},
"dependencies": {
"better-sqlite3": "^12.6.2",
"@effect/schema": "^0.75.5",
"@effect/sql": "^0.49.0",
"@effect/sql-sqlite-node": "^0.50.1",
"effect": "^3.19.19",
"node-pty": "^1.1.0",
"open": "^10.1.0",
@@ -26,7 +28,6 @@
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
+195
View File
@@ -0,0 +1,195 @@
import type { CoreCommand, CoreGitStatusSnapshot, CoreProjectView } from "@t3tools/contracts";
import type { AppendEventInput } from "./eventStore";
export interface CommandHandlerContext {
readonly actor: string;
readonly nowIso: string;
readonly probeGitStatus: (cwd: string) => Promise<CoreGitStatusSnapshot>;
}
function json(value: unknown): string {
return JSON.stringify(value);
}
function baseEvent(input: {
eventId: string;
streamId: string;
aggregateType: "project" | "thread" | "git";
occurredAt: string;
causationId: string;
correlationId: string;
actor: string;
eventType: string;
payload: unknown;
idempotencyKey?: string | undefined;
}): AppendEventInput {
return {
eventId: input.eventId,
streamId: input.streamId,
aggregateType: input.aggregateType,
occurredAt: input.occurredAt,
causationId: input.causationId,
correlationId: input.correlationId,
actor: input.actor,
eventType: input.eventType,
payloadJson: json(input.payload),
idempotencyKey: input.idempotencyKey,
};
}
function newEventId(prefix: string): string {
return `${prefix}_${crypto.randomUUID()}`;
}
export async function handleCoreCommand(
command: CoreCommand,
context: CommandHandlerContext,
): Promise<AppendEventInput[]> {
const events: AppendEventInput[] = [];
const occurredAt = context.nowIso;
const causationId = command.commandId;
const correlationId = command.commandId;
switch (command.kind) {
case "CreateProject": {
const project: CoreProjectView = {
id: command.payload.id,
name: command.payload.name,
cwd: command.payload.cwd,
model: command.payload.model,
expanded: true,
scripts: [],
};
events.push(
baseEvent({
eventId: newEventId("project_created"),
streamId: command.payload.id,
aggregateType: "project",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "ProjectCreated",
payload: project,
}),
);
return events;
}
case "CreateThread": {
events.push(
baseEvent({
eventId: newEventId("thread_created"),
streamId: command.payload.id,
aggregateType: "thread",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "ThreadCreated",
payload: command.payload,
}),
);
return events;
}
case "AppendUserMessage": {
events.push(
baseEvent({
eventId: newEventId("message_user"),
streamId: command.payload.threadId,
aggregateType: "thread",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "UserMessageAppended",
payload: command.payload,
idempotencyKey: command.commandId,
}),
);
return events;
}
case "AppendAssistantMessage": {
events.push(
baseEvent({
eventId: newEventId("message_assistant"),
streamId: command.payload.threadId,
aggregateType: "thread",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "AssistantMessageAppended",
payload: command.payload,
idempotencyKey: command.commandId,
}),
);
return events;
}
case "SetThreadBranch": {
events.push(
baseEvent({
eventId: newEventId("thread_branch"),
streamId: command.payload.threadId,
aggregateType: "thread",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "ThreadBranchSet",
payload: command.payload,
}),
);
return events;
}
case "GitWorkflow": {
events.push(
baseEvent({
eventId: newEventId("git_workflow"),
streamId: command.payload.cwd,
aggregateType: "git",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "GitWorkflowRecorded",
payload: command.payload,
}),
);
const status = await context.probeGitStatus(command.payload.cwd);
events.push(
baseEvent({
eventId: newEventId("git_observed"),
streamId: command.payload.cwd,
aggregateType: "git",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "GitStateObserved",
payload: status,
}),
);
return events;
}
case "GitProbe": {
const status = await context.probeGitStatus(command.payload.cwd);
events.push(
baseEvent({
eventId: newEventId("git_observed"),
streamId: command.payload.cwd,
aggregateType: "git",
occurredAt,
causationId,
correlationId,
actor: context.actor,
eventType: "GitStateObserved",
payload: status,
}),
);
return events;
}
default:
return events;
}
}
+164
View File
@@ -0,0 +1,164 @@
import type {
CoreCommand,
CoreDispatchInput,
CoreDispatchResult,
CoreGitStatusSnapshot,
CoreReadModelSnapshot,
CoreViewDelta,
} from "@t3tools/contracts";
import { coreCommandSchema } from "@t3tools/contracts";
import { Effect, Fiber, PubSub, Queue, Ref, Stream } from "effect";
import { handleCoreCommand } from "./commandHandlers";
import { type PersistedEvent, SqliteEventStore } from "./eventStore";
import {
applyEventToReadModels,
deltaFromEvent,
emptyReadModelMaps,
rebuildReadModels,
toReadModelSnapshot,
type ReadModelMaps,
} from "./readModels";
interface CommandEnvelope {
readonly input: CoreDispatchInput;
readonly resolve: (value: CoreDispatchResult) => void;
readonly reject: (error: Error) => void;
}
interface CoreEngineOptions {
readonly eventStore: SqliteEventStore;
readonly probeGitStatus: (cwd: string) => Promise<CoreGitStatusSnapshot>;
}
export class CoreEngine {
private readonly eventStore: SqliteEventStore;
private readonly probeGitStatus: (cwd: string) => Promise<CoreGitStatusSnapshot>;
private queue: Queue.Queue<CommandEnvelope> | null = null;
private pubSub: PubSub.PubSub<CoreViewDelta> | null = null;
private stateRef: Ref.Ref<ReadModelMaps> | null = null;
private worker: Fiber.RuntimeFiber<void, unknown> | null = null;
constructor(options: CoreEngineOptions) {
this.eventStore = options.eventStore;
this.probeGitStatus = options.probeGitStatus;
}
async start(): Promise<void> {
this.queue = await Effect.runPromise(Queue.unbounded<CommandEnvelope>());
this.pubSub = await Effect.runPromise(PubSub.unbounded<CoreViewDelta>());
const events = await Effect.runPromise(this.eventStore.listSince(0));
const initialState = events.length > 0 ? rebuildReadModels(events) : emptyReadModelMaps();
this.stateRef = await Effect.runPromise(Ref.make(initialState));
this.worker = Effect.runFork(this.commandLoop());
}
async stop(): Promise<void> {
if (this.worker) {
await Effect.runPromise(Fiber.interrupt(this.worker));
this.worker = null;
}
this.queue = null;
this.pubSub = null;
this.stateRef = null;
}
async getSnapshot(): Promise<CoreReadModelSnapshot> {
const state = await this.getState();
return toReadModelSnapshot(state);
}
async dispatch(input: CoreDispatchInput): Promise<CoreDispatchResult> {
const queue = this.requireQueue();
return new Promise((resolve, reject) => {
void Effect.runPromise(
Queue.offer(queue, {
input,
resolve,
reject,
}),
);
});
}
subscribe(listener: (delta: CoreViewDelta) => void): () => void {
const pubSub = this.requirePubSub();
const stream = Stream.fromPubSub(pubSub);
const fiber = Effect.runFork(
Stream.runForEach(stream, (delta) =>
Effect.sync(() => {
listener(delta);
}),
),
);
return () => {
void Effect.runPromise(Fiber.interrupt(fiber));
};
}
private commandLoop(): Effect.Effect<void> {
const queue = this.requireQueue();
return Effect.forever(
Effect.flatMap(Queue.take(queue), (envelope) =>
Effect.tryPromise({
try: () => this.processCommand(envelope),
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
}).pipe(Effect.catchAll(() => Effect.void)),
),
);
}
private async processCommand(envelope: CommandEnvelope): Promise<void> {
try {
const parsed = coreCommandSchema.parse(envelope.input.command);
const events = await handleCoreCommand(parsed, {
actor: "ws-client",
nowIso: new Date().toISOString(),
probeGitStatus: this.probeGitStatus,
});
let lastSequence = 0;
for (const eventInput of events) {
const persisted = await Effect.runPromise(this.eventStore.append(eventInput));
lastSequence = persisted.sequence;
await this.applyPersistedEvent(persisted);
}
envelope.resolve({
accepted: true,
sequence: lastSequence,
});
} catch (error) {
envelope.reject(error instanceof Error ? error : new Error(String(error)));
}
}
private async applyPersistedEvent(event: PersistedEvent): Promise<void> {
const stateRef = this.requireStateRef();
const pubSub = this.requirePubSub();
const nextState = await Effect.runPromise(
Ref.updateAndGet(stateRef, (state) => applyEventToReadModels(state, event)),
);
const delta = deltaFromEvent(event, nextState);
await Effect.runPromise(PubSub.publish(pubSub, delta));
}
private async getState(): Promise<ReadModelMaps> {
return Effect.runPromise(Ref.get(this.requireStateRef()));
}
private requireQueue(): Queue.Queue<CommandEnvelope> {
if (!this.queue) throw new Error("CoreEngine not started");
return this.queue;
}
private requirePubSub(): PubSub.PubSub<CoreViewDelta> {
if (!this.pubSub) throw new Error("CoreEngine not started");
return this.pubSub;
}
private requireStateRef(): Ref.Ref<ReadModelMaps> {
if (!this.stateRef) throw new Error("CoreEngine not started");
return this.stateRef;
}
}
+23
View File
@@ -0,0 +1,23 @@
import * as Schema from "effect/Schema";
export const aggregateTypeSchema = Schema.Literal("project", "thread", "git");
export type AggregateType = typeof aggregateTypeSchema.Type;
export class DomainEventEnvelope extends Schema.Class<DomainEventEnvelope>("DomainEventEnvelope")({
eventId: Schema.String,
streamId: Schema.String,
aggregateType: aggregateTypeSchema,
version: Schema.Number.pipe(Schema.int(), Schema.nonNegative()),
occurredAt: Schema.String,
causationId: Schema.String,
correlationId: Schema.String,
actor: Schema.String,
eventType: Schema.String,
payloadJson: Schema.String,
}) {}
export const domainEventPayloadSchema = Schema.Struct({
kind: Schema.String,
payload: Schema.Unknown,
});
export type DomainEventPayload = typeof domainEventPayloadSchema.Type;
+211
View File
@@ -0,0 +1,211 @@
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { Effect } from "effect";
import type { AggregateType } from "./domain";
export interface PersistedEvent {
sequence: number;
eventId: string;
streamId: string;
aggregateType: AggregateType;
version: number;
occurredAt: string;
causationId: string;
correlationId: string;
actor: string;
eventType: string;
payloadJson: string;
idempotencyKey: string | null;
}
export interface AppendEventInput {
eventId: string;
streamId: string;
aggregateType: AggregateType;
expectedVersion?: number | undefined;
occurredAt: string;
causationId: string;
correlationId: string;
actor: string;
eventType: string;
payloadJson: string;
idempotencyKey?: string | undefined;
}
interface EventRow {
sequence: number;
event_id: string;
stream_id: string;
aggregate_type: AggregateType;
version: number;
occurred_at: string;
causation_id: string;
correlation_id: string;
actor: string;
event_type: string;
payload_json: string;
idempotency_key: string | null;
}
function mapEventRow(row: EventRow): PersistedEvent {
return {
sequence: row.sequence,
eventId: row.event_id,
streamId: row.stream_id,
aggregateType: row.aggregate_type,
version: row.version,
occurredAt: row.occurred_at,
causationId: row.causation_id,
correlationId: row.correlation_id,
actor: row.actor,
eventType: row.event_type,
payloadJson: row.payload_json,
idempotencyKey: row.idempotency_key,
};
}
export class SqliteEventStore {
private readonly db: DatabaseSync;
constructor(databasePath: string) {
fs.mkdirSync(path.dirname(databasePath), { recursive: true });
this.db = new DatabaseSync(databasePath);
this.db.exec("PRAGMA journal_mode = WAL;");
this.db.exec("PRAGMA synchronous = NORMAL;");
this.db.exec(`
CREATE TABLE IF NOT EXISTS events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
stream_id TEXT NOT NULL,
aggregate_type TEXT NOT NULL,
version INTEGER NOT NULL,
occurred_at TEXT NOT NULL,
causation_id TEXT NOT NULL,
correlation_id TEXT NOT NULL,
actor TEXT NOT NULL,
event_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
idempotency_key TEXT UNIQUE
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_events_stream_version
ON events(stream_id, version);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_events_aggregate
ON events(aggregate_type, stream_id, version);
`);
}
append(input: AppendEventInput): Effect.Effect<PersistedEvent, Error> {
return Effect.try({
try: () => {
this.db.exec("BEGIN IMMEDIATE TRANSACTION");
try {
if (input.idempotencyKey) {
const existingByKeyRow = this.db
.prepare(
`SELECT sequence, event_id, stream_id, aggregate_type, version, occurred_at,
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
FROM events
WHERE idempotency_key = ?`,
)
.get(input.idempotencyKey) as EventRow | undefined;
if (existingByKeyRow) {
this.db.exec("COMMIT");
return mapEventRow(existingByKeyRow);
}
}
const latest = this.db
.prepare("SELECT version FROM events WHERE stream_id = ? ORDER BY version DESC LIMIT 1")
.get(input.streamId) as { version: number } | undefined;
const currentVersion = latest?.version ?? 0;
if (typeof input.expectedVersion === "number" && input.expectedVersion !== currentVersion) {
throw new Error(
`Optimistic concurrency conflict for stream ${input.streamId}: expected ${input.expectedVersion}, got ${currentVersion}`,
);
}
const nextVersion = currentVersion + 1;
this.db
.prepare(
`INSERT INTO events (
event_id, stream_id, aggregate_type, version, occurred_at,
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
input.eventId,
input.streamId,
input.aggregateType,
nextVersion,
input.occurredAt,
input.causationId,
input.correlationId,
input.actor,
input.eventType,
input.payloadJson,
input.idempotencyKey ?? null,
);
const persistedRow = this.db
.prepare(
`SELECT sequence, event_id, stream_id, aggregate_type, version, occurred_at,
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
FROM events
WHERE event_id = ?`,
)
.get(input.eventId) as EventRow | undefined;
if (!persistedRow) {
throw new Error(`Inserted event missing from store: ${input.eventId}`);
}
this.db.exec("COMMIT");
return mapEventRow(persistedRow);
} catch (error) {
this.db.exec("ROLLBACK");
throw error;
}
},
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
});
}
listSince(minSequence: number): Effect.Effect<PersistedEvent[], Error> {
return Effect.try({
try: () => {
const rows = this.db
.prepare(
`SELECT sequence, event_id, stream_id, aggregate_type, version, occurred_at,
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
FROM events
WHERE sequence > ?
ORDER BY sequence ASC`,
)
.all(minSequence) as unknown as EventRow[];
return rows.map((row) => mapEventRow(row));
},
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
});
}
lastSequence(): Effect.Effect<number, Error> {
return Effect.try({
try: () => {
const row = this.db.prepare("SELECT MAX(sequence) as sequence FROM events").get() as
| { sequence: number | null }
| undefined;
return row?.sequence ?? 0;
},
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
});
}
close(): void {
this.db.close();
}
}
@@ -0,0 +1,97 @@
import {
providerInterruptTurnInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@t3tools/contracts";
import type {
ProviderEvent,
ProviderInterruptTurnInput,
ProviderRespondToRequestInput,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionStartInput,
ProviderStopSessionInput,
ProviderTurnStartResult,
} from "@t3tools/contracts";
import { CodexAppServerManager } from "../../codexAppServerManager";
import type { ProviderAdapter, ProviderThreadSnapshot } from "./providerAdapter";
export class CodexProviderAdapter implements ProviderAdapter {
readonly kind = "codex" as const;
private readonly manager = new CodexAppServerManager();
onEvent(listener: (event: ProviderEvent) => void): () => void {
this.manager.on("event", listener);
return () => {
this.manager.off("event", listener);
};
}
hasSession(sessionId: string): boolean {
return this.manager.hasSession(sessionId);
}
startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
const parsed = providerSessionStartInputSchema.parse(input);
if (parsed.provider !== this.kind) {
throw new Error(`Provider '${parsed.provider}' is not implemented by CodexProviderAdapter.`);
}
return this.manager.startSession(parsed);
}
sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
return this.manager.sendTurn(providerSendTurnInputSchema.parse(input));
}
interruptTurn(input: ProviderInterruptTurnInput): Promise<void> {
const parsed = providerInterruptTurnInputSchema.parse(input);
return this.manager.interruptTurn(parsed.sessionId, parsed.turnId);
}
respondToRequest(input: ProviderRespondToRequestInput): Promise<void> {
const parsed = providerRespondToRequestInputSchema.parse(input);
return this.manager.respondToRequest(parsed.sessionId, parsed.requestId, parsed.decision);
}
stopSession(input: ProviderStopSessionInput): void {
const parsed = providerStopSessionInputSchema.parse(input);
this.manager.stopSession(parsed.sessionId);
}
listSessions(): ProviderSession[] {
return this.manager.listSessions();
}
async readThread(sessionId: string): Promise<ProviderThreadSnapshot> {
const snapshot = await this.manager.readThread(sessionId);
return {
threadId: snapshot.threadId,
turns: snapshot.turns.map((turn) => ({
id: turn.id,
items: turn.items,
})),
};
}
async rollbackThread(sessionId: string, numTurns: number): Promise<ProviderThreadSnapshot> {
const snapshot = await this.manager.rollbackThread(sessionId, numTurns);
return {
threadId: snapshot.threadId,
turns: snapshot.turns.map((turn) => ({
id: turn.id,
items: turn.items,
})),
};
}
stopAll(): void {
this.manager.stopAll();
}
dispose(): void {
this.manager.stopAll();
}
}
@@ -0,0 +1,37 @@
import type {
ProviderEvent,
ProviderInterruptTurnInput,
ProviderKind,
ProviderRespondToRequestInput,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionStartInput,
ProviderStopSessionInput,
ProviderTurnStartResult,
} from "@t3tools/contracts";
export interface ProviderThreadTurnSnapshot {
id: string;
items: unknown[];
}
export interface ProviderThreadSnapshot {
threadId: string;
turns: ProviderThreadTurnSnapshot[];
}
export interface ProviderAdapter {
readonly kind: ProviderKind;
onEvent(listener: (event: ProviderEvent) => void): () => void;
hasSession(sessionId: string): boolean;
startSession(input: ProviderSessionStartInput): Promise<ProviderSession>;
sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult>;
interruptTurn(input: ProviderInterruptTurnInput): Promise<void>;
respondToRequest(input: ProviderRespondToRequestInput): Promise<void>;
stopSession(input: ProviderStopSessionInput): void;
listSessions(): ProviderSession[];
readThread(sessionId: string): Promise<ProviderThreadSnapshot>;
rollbackThread(sessionId: string, numTurns: number): Promise<ProviderThreadSnapshot>;
stopAll(): void;
dispose(): void;
}
@@ -0,0 +1,518 @@
import { EventEmitter } from "node:events";
import { randomUUID } from "node:crypto";
import type {
ProviderCheckpoint,
ProviderEvent,
ProviderGetCheckpointDiffInput,
ProviderGetCheckpointDiffResult,
ProviderInterruptTurnInput,
ProviderKind,
ProviderListCheckpointsInput,
ProviderListCheckpointsResult,
ProviderRevertToCheckpointInput,
ProviderRevertToCheckpointResult,
ProviderRespondToRequestInput,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionStartInput,
ProviderStopSessionInput,
ProviderTurnStartResult,
} from "@t3tools/contracts";
import {
providerGetCheckpointDiffInputSchema,
providerInterruptTurnInputSchema,
providerListCheckpointsInputSchema,
providerRevertToCheckpointInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@t3tools/contracts";
import { FilesystemCheckpointStore } from "../../filesystemCheckpointStore";
import type { ProviderAdapter, ProviderThreadTurnSnapshot } from "./providerAdapter";
export interface ProviderOrchestratorEvents {
event: [event: ProviderEvent];
}
export class ProviderOrchestrator extends EventEmitter<ProviderOrchestratorEvents> {
private readonly adapters: Map<ProviderKind, ProviderAdapter>;
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
private readonly sessionToProvider = new Map<string, ProviderKind>();
private readonly sessionCheckpointCwds = new Map<string, string>();
private readonly filesystemLocks = new Map<string, Promise<void>>();
private readonly unsubscribers: Array<() => void>;
constructor(adapters: ProviderAdapter[]) {
super();
this.adapters = new Map(adapters.map((adapter) => [adapter.kind, adapter] as const));
this.unsubscribers = adapters.map((adapter) =>
adapter.onEvent((event) => {
this.sessionToProvider.set(event.sessionId, event.provider);
this.emit("event", event);
this.maybeCaptureFilesystemCheckpoint(event);
}),
);
}
async startSession(raw: ProviderSessionStartInput): Promise<ProviderSession> {
const input = providerSessionStartInputSchema.parse(raw);
const provider = input.provider ?? "codex";
const adapter = this.requireAdapter(provider);
const session = await adapter.startSession(input);
this.sessionToProvider.set(session.sessionId, session.provider);
await this.initializeFilesystemCheckpointing(adapter, session, input.cwd).catch((error) => {
const message =
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
});
return session;
}
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
const input = providerSendTurnInputSchema.parse(raw);
return this.resolveAdapterForSession(input.sessionId).sendTurn(input);
}
async interruptTurn(raw: ProviderInterruptTurnInput): Promise<void> {
const input = providerInterruptTurnInputSchema.parse(raw);
return this.resolveAdapterForSession(input.sessionId).interruptTurn(input);
}
async respondToRequest(raw: ProviderRespondToRequestInput): Promise<void> {
const input = providerRespondToRequestInputSchema.parse(raw);
return this.resolveAdapterForSession(input.sessionId).respondToRequest(input);
}
stopSession(raw: ProviderStopSessionInput): void {
const input = providerStopSessionInputSchema.parse(raw);
this.resolveAdapterForSession(input.sessionId).stopSession(input);
this.sessionToProvider.delete(input.sessionId);
this.sessionCheckpointCwds.delete(input.sessionId);
this.filesystemLocks.delete(input.sessionId);
}
listSessions(): ProviderSession[] {
const sessions = [...this.adapters.values()].flatMap((adapter) => adapter.listSessions());
for (const session of sessions) {
this.sessionToProvider.set(session.sessionId, session.provider);
}
return sessions;
}
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
const input = providerListCheckpointsInputSchema.parse(raw);
const adapter = this.resolveAdapterForSession(input.sessionId);
const snapshot = await adapter.readThread(input.sessionId);
return {
threadId: snapshot.threadId,
checkpoints: buildCheckpoints(snapshot.turns),
};
}
async getCheckpointDiff(
raw: ProviderGetCheckpointDiffInput,
): Promise<ProviderGetCheckpointDiffResult> {
const input = providerGetCheckpointDiffInputSchema.parse(raw);
const adapter = this.resolveAdapterForSession(input.sessionId);
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId, adapter);
if (!checkpointCwd) {
throw new Error("Filesystem checkpoints are unavailable for this session.");
}
return this.withFilesystemLock(input.sessionId, async () => {
const snapshot = await adapter.readThread(input.sessionId);
if (input.toTurnCount > snapshot.turns.length) {
throw new Error(
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
);
}
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
cwd: checkpointCwd,
threadId: snapshot.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
});
return {
threadId: snapshot.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
});
}
async revertToCheckpoint(
raw: ProviderRevertToCheckpointInput,
): Promise<ProviderRevertToCheckpointResult> {
const input = providerRevertToCheckpointInputSchema.parse(raw);
const adapter = this.resolveAdapterForSession(input.sessionId);
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId, adapter);
if (!checkpointCwd) {
throw new Error("Filesystem checkpoints are unavailable for this session.");
}
return this.withFilesystemLock(input.sessionId, async () => {
const beforeSnapshot = await adapter.readThread(input.sessionId);
const currentTurnCount = beforeSnapshot.turns.length;
if (input.turnCount > currentTurnCount) {
throw new Error(
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
);
}
if (input.turnCount > 0) {
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
cwd: checkpointCwd,
threadId: beforeSnapshot.threadId,
turnCount: input.turnCount,
});
if (!hasCheckpoint) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
);
}
}
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
cwd: checkpointCwd,
threadId: beforeSnapshot.threadId,
turnCount: input.turnCount,
});
if (!restored) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
);
}
const rollbackTurns = currentTurnCount - input.turnCount;
const afterSnapshot =
rollbackTurns > 0
? await adapter.rollbackThread(input.sessionId, rollbackTurns)
: beforeSnapshot;
await this.filesystemCheckpointStore.pruneAfterTurn({
cwd: checkpointCwd,
threadId: afterSnapshot.threadId,
maxTurnCount: afterSnapshot.turns.length,
});
const checkpoints = buildCheckpoints(afterSnapshot.turns);
const currentCheckpoint =
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
checkpoints[checkpoints.length - 1] ??
checkpoints[0];
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
return {
threadId: afterSnapshot.threadId,
turnCount: currentCheckpoint?.turnCount ?? 0,
messageCount: currentCheckpoint?.messageCount ?? 0,
rolledBackTurns,
checkpoints,
};
});
}
stopAll(): void {
for (const adapter of this.adapters.values()) {
adapter.stopAll();
}
this.sessionToProvider.clear();
this.sessionCheckpointCwds.clear();
this.filesystemLocks.clear();
}
dispose(): void {
for (const unsubscribe of this.unsubscribers) {
unsubscribe();
}
for (const adapter of this.adapters.values()) {
adapter.dispose();
}
this.unsubscribers.length = 0;
this.sessionToProvider.clear();
this.sessionCheckpointCwds.clear();
this.filesystemLocks.clear();
}
private async initializeFilesystemCheckpointing(
adapter: ProviderAdapter,
session: ProviderSession,
preferredCwd?: string,
): Promise<void> {
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
await this.withFilesystemLock(session.sessionId, async () => {
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
if (!supportsGit) {
this.sessionCheckpointCwds.delete(session.sessionId);
return;
}
const snapshot = await adapter.readThread(session.sessionId);
await this.filesystemCheckpointStore.ensureRootCheckpoint({
cwd,
threadId: snapshot.threadId,
});
await this.filesystemCheckpointStore.captureCheckpoint({
cwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
this.sessionCheckpointCwds.set(session.sessionId, cwd);
});
}
private async getOrInitializeFilesystemCheckpointCwd(
sessionId: string,
adapter: ProviderAdapter,
): Promise<string | null> {
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
if (existingCwd) return existingCwd;
const session = adapter.listSessions().find((entry) => entry.sessionId === sessionId);
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
await this.withFilesystemLock(sessionId, async () => {
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
if (currentCwd) return;
const cwdSupport = await Promise.all(
candidateCwds.map(async (cwd) => ({
cwd,
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
})),
);
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
if (!supportedCwd) {
this.sessionCheckpointCwds.delete(sessionId);
return;
}
const snapshot = await adapter.readThread(sessionId);
await this.filesystemCheckpointStore.ensureRootCheckpoint({
cwd: supportedCwd,
threadId: snapshot.threadId,
});
await this.filesystemCheckpointStore.captureCheckpoint({
cwd: supportedCwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
});
return this.sessionCheckpointCwds.get(sessionId) ?? null;
}
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
if (event.kind !== "notification" || event.method !== "turn/completed") {
return;
}
const adapter = this.resolveAdapterForSession(event.sessionId);
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
if (!checkpointCwd) {
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId, adapter)
.then(async (initializedCwd) => {
if (!initializedCwd) return;
const snapshot = await adapter.readThread(event.sessionId);
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
})
.catch((error) => {
const message =
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
return;
}
void this.withFilesystemLock(event.sessionId, async () => {
const snapshot = await adapter.readThread(event.sessionId);
await this.filesystemCheckpointStore.captureCheckpoint({
cwd: checkpointCwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
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): void {
this.emit("event", {
id: randomUUID(),
kind: "notification",
provider: this.sessionToProvider.get(sessionId) ?? "codex",
sessionId,
createdAt: new Date().toISOString(),
method: "checkpoint/captured",
threadId,
payload: {
threadId,
turnCount,
},
});
}
private emitFilesystemCheckpointError(
sessionId: string,
message: string,
threadId?: string,
): void {
this.emit("event", {
id: randomUUID(),
kind: "error",
provider: this.sessionToProvider.get(sessionId) ?? "codex",
sessionId,
createdAt: new Date().toISOString(),
method: "checkpoint/filesystemError",
message,
...(threadId ? { threadId } : {}),
});
}
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
const next = previous.catch(() => undefined).then(fn);
const completion = next.then(
() => undefined,
() => undefined,
);
this.filesystemLocks.set(sessionId, completion);
return next.finally(() => {
const tracked = this.filesystemLocks.get(sessionId);
if (tracked === completion) {
this.filesystemLocks.delete(sessionId);
}
});
}
private resolveAdapterForSession(sessionId: string): ProviderAdapter {
const mappedProvider = this.sessionToProvider.get(sessionId);
if (mappedProvider) {
return this.requireAdapter(mappedProvider);
}
for (const adapter of this.adapters.values()) {
if (adapter.hasSession(sessionId)) {
this.sessionToProvider.set(sessionId, adapter.kind);
return adapter;
}
}
throw new Error(`Unknown provider session: ${sessionId}`);
}
private requireAdapter(provider: ProviderKind): ProviderAdapter {
const adapter = this.adapters.get(provider);
if (!adapter) {
throw new Error(`Provider '${provider}' is not implemented yet.`);
}
return adapter;
}
}
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function trimToPreview(value: string): string {
const normalized = value.replace(/\s+/g, " ").trim();
if (normalized.length <= 120) return normalized;
return `${normalized.slice(0, 117)}...`;
}
function summarizeUserMessageContent(content: unknown[]): string | undefined {
const segments: string[] = [];
for (const part of content) {
const record = asObject(part);
const type = asString(record?.type);
if (!type) continue;
if (type === "text") {
const text = asString(record?.text);
if (text && text.trim().length > 0) {
segments.push(text.trim());
}
continue;
}
if (type === "image") {
segments.push("[Image attachment]");
continue;
}
if (type === "localImage") {
segments.push("[Local image attachment]");
}
}
if (segments.length === 0) return undefined;
return trimToPreview(segments.join(" "));
}
function summarizeTurn(turn: ProviderThreadTurnSnapshot): { messageCountDelta: number; preview?: string } {
let messageCountDelta = 0;
let preview: string | undefined;
for (const item of turn.items) {
const record = asObject(item);
const type = asString(record?.type);
if (!type) continue;
if (type === "userMessage") {
messageCountDelta += 1;
if (!preview) {
preview = summarizeUserMessageContent(asArray(record?.content));
}
continue;
}
if (type === "agentMessage") {
messageCountDelta += 1;
if (!preview) {
const text = asString(record?.text);
if (text && text.trim().length > 0) {
preview = trimToPreview(text);
}
}
}
}
return {
messageCountDelta,
...(preview ? { preview } : {}),
};
}
function buildCheckpoints(turns: ProviderThreadTurnSnapshot[]): ProviderCheckpoint[] {
const checkpoints: ProviderCheckpoint[] = [];
let messageCount = 0;
const isEmpty = turns.length === 0;
checkpoints.push({
id: "root",
turnCount: 0,
messageCount: 0,
label: "Start of conversation",
isCurrent: isEmpty,
});
for (let index = 0; index < turns.length; index += 1) {
const turn = turns[index];
if (!turn) continue;
const turnSummary = summarizeTurn(turn);
messageCount += turnSummary.messageCountDelta;
checkpoints.push({
id: turn.id,
turnCount: index + 1,
messageCount,
label: `Turn ${index + 1}`,
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
isCurrent: index === turns.length - 1,
});
}
return checkpoints;
}
+256
View File
@@ -0,0 +1,256 @@
import type {
CoreGitStatusSnapshot,
CoreProjectView,
CoreReadModelSnapshot,
CoreThreadMessageView,
CoreThreadView,
CoreViewDelta,
} from "@t3tools/contracts";
import type { PersistedEvent } from "./eventStore";
export interface ReadModelMaps {
projects: Map<string, CoreProjectView>;
threads: Map<string, CoreThreadView>;
git: Map<string, CoreGitStatusSnapshot>;
sequence: number;
}
export function emptyReadModelMaps(): ReadModelMaps {
return {
projects: new Map(),
threads: new Map(),
git: new Map(),
sequence: 0,
};
}
function parsePayload(event: PersistedEvent): unknown {
return JSON.parse(event.payloadJson) as unknown;
}
function cloneMaps(state: ReadModelMaps): ReadModelMaps {
return {
projects: new Map(state.projects),
threads: new Map(state.threads),
git: new Map(state.git),
sequence: state.sequence,
};
}
function buildThreadBase(payload: {
id: string;
projectId: string;
title: string;
model: string;
createdAt?: string;
}): CoreThreadView {
const createdAt = payload.createdAt ?? new Date().toISOString();
return {
id: payload.id,
projectId: payload.projectId,
title: payload.title,
model: payload.model,
createdAt,
updatedAt: createdAt,
sessionId: null,
messages: [],
branch: null,
worktreePath: null,
};
}
function appendMessage(
thread: CoreThreadView,
message: { id: string; role: "user" | "assistant"; text: string; createdAt: string },
updatedAt: string,
): CoreThreadView {
const nextMessage: CoreThreadMessageView = {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: false,
};
return {
...thread,
updatedAt,
messages: [...thread.messages, nextMessage],
};
}
export function applyEventToReadModels(state: ReadModelMaps, event: PersistedEvent): ReadModelMaps {
const next = cloneMaps(state);
next.sequence = event.sequence;
switch (event.eventType) {
case "ProjectCreated": {
const payload = parsePayload(event) as CoreProjectView;
next.projects.set(payload.id, payload);
return next;
}
case "ProjectDeleted": {
const payload = parsePayload(event) as { id: string };
next.projects.delete(payload.id);
return next;
}
case "ThreadCreated": {
const payload = parsePayload(event) as {
id: string;
projectId: string;
title: string;
model: string;
createdAt?: string;
};
next.threads.set(payload.id, buildThreadBase(payload));
return next;
}
case "UserMessageAppended": {
const payload = parsePayload(event) as {
threadId: string;
messageId: string;
text: string;
createdAt: string;
};
const existing = next.threads.get(payload.threadId);
if (!existing) return next;
next.threads.set(
payload.threadId,
appendMessage(
existing,
{
id: payload.messageId,
role: "user",
text: payload.text,
createdAt: payload.createdAt,
},
event.occurredAt,
),
);
return next;
}
case "AssistantMessageAppended": {
const payload = parsePayload(event) as {
threadId: string;
messageId: string;
text: string;
createdAt: string;
};
const existing = next.threads.get(payload.threadId);
if (!existing) return next;
next.threads.set(
payload.threadId,
appendMessage(
existing,
{
id: payload.messageId,
role: "assistant",
text: payload.text,
createdAt: payload.createdAt,
},
event.occurredAt,
),
);
return next;
}
case "ThreadBranchSet": {
const payload = parsePayload(event) as {
threadId: string;
branch: string | null;
worktreePath: string | null;
};
const existing = next.threads.get(payload.threadId);
if (!existing) return next;
next.threads.set(payload.threadId, {
...existing,
updatedAt: event.occurredAt,
branch: payload.branch,
worktreePath: payload.worktreePath,
});
return next;
}
case "GitStateObserved": {
const payload = parsePayload(event) as CoreGitStatusSnapshot;
next.git.set(payload.cwd, payload);
return next;
}
default:
return next;
}
}
export function rebuildReadModels(events: readonly PersistedEvent[]): ReadModelMaps {
let state = emptyReadModelMaps();
for (const event of events) {
state = applyEventToReadModels(state, event);
}
return state;
}
export function toReadModelSnapshot(state: ReadModelMaps): CoreReadModelSnapshot {
return {
sequence: state.sequence,
generatedAt: new Date().toISOString(),
projects: [...state.projects.values()],
threads: [...state.threads.values()].toSorted(
(a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt),
),
git: [...state.git.values()],
};
}
export function deltaFromEvent(event: PersistedEvent, state: ReadModelMaps): CoreViewDelta {
switch (event.eventType) {
case "ProjectCreated":
return {
kind: "projectUpsert",
sequence: event.sequence,
project: state.projects.get(event.streamId) ?? (JSON.parse(event.payloadJson) as CoreProjectView),
};
case "ProjectDeleted":
return {
kind: "projectDelete",
sequence: event.sequence,
projectId: (JSON.parse(event.payloadJson) as { id: string }).id,
};
case "ThreadCreated":
case "UserMessageAppended":
case "AssistantMessageAppended":
case "ThreadBranchSet": {
const payload = JSON.parse(event.payloadJson) as { id?: string; threadId?: string };
const threadId = payload.threadId ?? payload.id ?? event.streamId;
return {
kind: "threadUpsert",
sequence: event.sequence,
thread:
state.threads.get(threadId) ??
({
id: threadId,
projectId: "",
title: "Unknown thread",
model: "gpt-5",
createdAt: event.occurredAt,
updatedAt: event.occurredAt,
sessionId: null,
messages: [],
branch: null,
worktreePath: null,
} satisfies CoreThreadView),
};
}
case "GitStateObserved":
return {
kind: "gitStatusUpsert",
sequence: event.sequence,
git:
state.git.get((JSON.parse(event.payloadJson) as { cwd: string }).cwd) ??
(JSON.parse(event.payloadJson) as CoreGitStatusSnapshot),
};
default:
return {
kind: "snapshot",
sequence: event.sequence,
snapshot: toReadModelSnapshot(state),
};
}
}
@@ -1,119 +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();
});
});
-275
View File
@@ -1,275 +0,0 @@
import path from "node:path";
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { OrchestrationCommandSchema } from "@t3tools/contracts";
import { PubSub, 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,
},
};
}
}
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 readModelPubSub: PubSub.PubSub<OrchestrationReadModel>;
private eventPubSub: PubSub.PubSub<OrchestrationEvent>;
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>());
this.readModelPubSub = Runtime.runSync(this.runtime)(PubSub.unbounded<OrchestrationReadModel>());
this.eventPubSub = Runtime.runSync(this.runtime)(PubSub.unbounded<OrchestrationEvent>());
}
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);
await Promise.all([
Runtime.runPromise(this.runtime)(PubSub.publish(this.eventPubSub, savedEvent)),
Runtime.runPromise(this.runtime)(PubSub.publish(this.readModelPubSub, this.readModel)),
]);
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);
};
}
}
-106
View File
@@ -1,106 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import type { OrchestrationEvent } from "@t3tools/contracts";
import Database from "better-sqlite3";
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;
}
export class SqliteEventStore {
private readonly db: Database.Database;
constructor(dbPath: string) {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
this.db = new Database(dbPath);
this.db.pragma("journal_mode = WAL");
this.db.pragma("foreign_keys = ON");
this.migrate();
}
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 stmt = this.db.prepare(`
INSERT INTO orchestration_events (
event_id, event_type, aggregate_type, aggregate_id, occurred_at, command_id, payload_json
)
VALUES (?, ?, ?, ?, ?, ?, ?)
`);
const result = stmt.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) as EventRow[];
return rows.map((row) => ({
sequence: row.sequence,
eventId: row.event_id,
type: row.event_type,
aggregateType: row.aggregate_type,
aggregateId: row.aggregate_id,
occurredAt: row.occurred_at,
commandId: row.command_id,
payload: JSON.parse(row.payload_json) as unknown,
}));
});
}
readAll(): Effect.Effect<OrchestrationEvent[]> {
return this.readFromSequence(0, Number.MAX_SAFE_INTEGER);
}
close(): void {
this.db.close();
}
}
-217
View File
@@ -1,217 +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;
}
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 "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"],
},
];
+21 -18
View File
@@ -249,7 +249,6 @@ describe("WebSocket Server", () => {
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
stateDir,
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
@@ -622,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");
@@ -631,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();
@@ -785,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 () => {
+238 -256
View File
@@ -7,11 +7,13 @@ import type { Duplex } from "node:stream";
import {
EDITORS,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
coreDispatchInputSchema,
coreGetSnapshotInputSchema,
gitStatusResultSchema,
WS_CHANNELS,
WS_METHODS,
type OrchestrationReadModelPush,
type CoreDispatchInput,
type CoreViewDelta,
type TerminalEvent,
type WsPush,
type WsRequest,
@@ -22,7 +24,6 @@ import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { ProviderManager } from "./providerManager";
import { GitManager } from "./gitManager";
import {
checkoutGitBranch,
@@ -36,7 +37,10 @@ import {
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { OrchestrationEngine } from "./orchestration/engine";
import { CoreEngine } from "./effect/coreEngine";
import { SqliteEventStore } from "./effect/eventStore";
import { CodexProviderAdapter } from "./effect/providers/codexProviderAdapter";
import { ProviderOrchestrator } from "./effect/providers/providerOrchestrator";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -89,14 +93,29 @@ export function createServer(options: ServerOptions) {
terminalManager: providedTerminalManager,
authToken,
} = options;
const providerManager = new ProviderManager();
const providerOrchestrator = new ProviderOrchestrator([new CodexProviderAdapter()]);
const terminalManager = providedTerminalManager ?? new TerminalManager();
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 eventStore = new SqliteEventStore(
path.join(stateDir ?? path.join(os.homedir(), ".t3", "userdata"), "event-core.sqlite"),
);
const coreEngine = new CoreEngine({
eventStore,
probeGitStatus: async (probeCwd) => {
const status = await gitManager.status({ cwd: probeCwd });
const parsed = gitStatusResultSchema.parse(status);
return {
cwd: probeCwd,
branch: parsed.branch,
hasWorkingTreeChanges: parsed.hasWorkingTreeChanges,
aheadCount: parsed.aheadCount,
behindCount: parsed.behindCount,
observedAt: new Date().toISOString(),
};
},
});
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
@@ -112,15 +131,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) {
@@ -130,129 +141,36 @@ 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") {
let turnStatus: "running" | "ready" | "error" = "ready";
let lastError: string | null = null;
if (event.method === "turn/started") {
turnStatus = "running";
} else {
const payload = event.payload as Record<string, unknown> | undefined;
const turn = payload?.turn as Record<string, unknown> | undefined;
if (typeof turn?.status === "string" && turn.status === "failed") {
turnStatus = "error";
const turnError = turn.error as Record<string, unknown> | undefined;
lastError = typeof turnError?.message === "string" ? turnError.message : null;
}
}
await orchestrationEngine.dispatch({
type: "thread.session",
providerOrchestrator.on("event", (event) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.providerEvent,
data: event,
};
broadcastPush(push);
if (
event.threadId &&
typeof event.message === "string" &&
event.message.trim().length > 0 &&
(event.kind === "notification" || event.method === "turn/completed")
) {
void coreEngine.dispatch({
command: {
kind: "AppendAssistantMessage",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: turnStatus,
threadId: thread.id,
activeTurnId: event.method === "turn/started" ? (event.turnId ?? null) : null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError,
issuedAt: new Date().toISOString(),
payload: {
threadId: event.threadId,
messageId: event.itemId ?? crypto.randomUUID(),
text: event.message,
createdAt: event.createdAt,
},
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.kind === "session" &&
(event.method === "session/closed" || event.method === "session/exited")
) {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: "closed",
threadId: thread.id,
activeTurnId: null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: event.message ?? null,
},
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) => {
@@ -261,18 +179,12 @@ export function createServer(options: ServerOptions) {
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;
}
}
logOutgoingPush(push, recipients);
broadcastPush(push);
};
terminalManager.on("event", onTerminalEvent);
let unsubscribeCoreDelta: (() => void) | null = null;
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer((req, res) => {
// In dev mode, redirect to Vite dev server
@@ -381,18 +293,6 @@ export function createServer(options: ServerOptions) {
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
const initialSnapshot = orchestrationEngine.getSnapshot();
const snapshotPush: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: initialSnapshot.sequence,
snapshot: initialSnapshot,
} satisfies OrchestrationReadModelPush,
};
logOutgoingPush(snapshotPush, 1);
ws.send(JSON.stringify(snapshotPush));
ws.on("message", (raw) => {
void handleMessage(ws, raw);
});
@@ -437,61 +337,60 @@ 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);
return providerOrchestrator.startSession(request.params as never);
case WS_METHODS.providersSendTurn:
return providerManager.sendTurn(request.params as never);
return providerOrchestrator.sendTurn(request.params as never);
case WS_METHODS.providersInterruptTurn:
return providerManager.interruptTurn(request.params as never);
return providerOrchestrator.interruptTurn(request.params as never);
case WS_METHODS.providersRespondToRequest:
return providerManager.respondToRequest(request.params as never);
return providerOrchestrator.respondToRequest(request.params as never);
case WS_METHODS.providersStopSession: {
providerManager.stopSession(request.params as never);
providerOrchestrator.stopSession(request.params as never);
return undefined;
}
case WS_METHODS.providersListSessions:
return providerOrchestrator.listSessions();
case WS_METHODS.providersListCheckpoints:
return providerManager.listCheckpoints(request.params as never);
return providerOrchestrator.listCheckpoints(request.params as never);
case WS_METHODS.providersGetCheckpointDiff:
return providerManager.getCheckpointDiff(request.params as never);
return providerOrchestrator.getCheckpointDiff(request.params as never);
case WS_METHODS.providersRevertToCheckpoint:
return providerManager.revertToCheckpoint(request.params as never);
return providerOrchestrator.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(),
});
return (async () => {
const result = projectRegistry.add(request.params as never);
const command: CoreDispatchInput = {
command: {
kind: "CreateProject",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: "gpt-5",
},
},
};
await coreEngine.dispatch(command);
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;
}
projectRegistry.remove(request.params as never);
return undefined;
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
@@ -543,47 +442,131 @@ 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);
return pullGitBranch(request.params as never).then(async (result) => {
const input = request.params as { cwd: string };
await coreEngine.dispatch({
command: {
kind: "GitWorkflow",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
workflow: "stacked_action",
cwd: input.cwd,
metadata: { source: "git.pull", result },
},
},
});
return result;
});
case WS_METHODS.gitRunStackedAction:
return gitManager.runStackedAction(request.params as never);
return gitManager.runStackedAction(request.params as never).then(async (result) => {
const input = request.params as { cwd: string; action: string };
await coreEngine.dispatch({
command: {
kind: "GitWorkflow",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
workflow: "stacked_action",
cwd: input.cwd,
metadata: { source: "git.runStackedAction", action: input.action, result },
},
},
});
return result;
});
case WS_METHODS.gitListBranches:
return listGitBranches(request.params as never);
case WS_METHODS.gitCreateWorktree:
return createGitWorktree(request.params as never);
return createGitWorktree(request.params as never).then(async (result) => {
const input = request.params as { cwd: string; branch: string; newBranch: string };
await coreEngine.dispatch({
command: {
kind: "GitWorkflow",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
workflow: "create_worktree",
cwd: input.cwd,
metadata: {
branch: input.branch,
newBranch: input.newBranch,
result,
},
},
},
});
return result;
});
case WS_METHODS.gitRemoveWorktree:
return removeGitWorktree(request.params as never);
return removeGitWorktree(request.params as never).then(async () => {
const input = request.params as { cwd: string; path: string };
await coreEngine.dispatch({
command: {
kind: "GitWorkflow",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
workflow: "remove_worktree",
cwd: input.cwd,
metadata: { path: input.path },
},
},
});
});
case WS_METHODS.gitCreateBranch:
return createGitBranch(request.params as never);
return createGitBranch(request.params as never).then(async () => {
const input = request.params as { cwd: string; branch: string };
await coreEngine.dispatch({
command: {
kind: "GitWorkflow",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
workflow: "create_branch",
cwd: input.cwd,
metadata: { branch: input.branch },
},
},
});
});
case WS_METHODS.gitCheckout:
return checkoutGitBranch(request.params as never);
return checkoutGitBranch(request.params as never).then(async () => {
const input = request.params as { cwd: string; branch: string };
await coreEngine.dispatch({
command: {
kind: "GitWorkflow",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
workflow: "checkout",
cwd: input.cwd,
metadata: { branch: input.branch },
},
},
});
});
case WS_METHODS.gitInit:
return initGitRepo(request.params as never);
return initGitRepo(request.params as never).then(async () => {
const input = request.params as { cwd: string };
await coreEngine.dispatch({
command: {
kind: "GitProbe",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: { cwd: input.cwd },
},
});
});
case WS_METHODS.terminalOpen:
return terminalManager.open(request.params as never);
@@ -619,24 +602,14 @@ export function createServer(options: ServerOptions) {
keybindings: keybindingsConfig,
};
case ORCHESTRATION_WS_METHODS.getSnapshot:
return orchestrationEngine.getSnapshot();
case WS_METHODS.coreGetSnapshot:
coreGetSnapshotInputSchema.parse(request.params ?? {});
return coreEngine.getSnapshot();
case ORCHESTRATION_WS_METHODS.dispatchCommand:
return orchestrationEngine.dispatchUnknown(request.params);
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.coreDispatch: {
const input = coreDispatchInputSchema.parse(request.params);
return coreEngine.dispatch(input);
}
default:
throw new Error(`Unknown method: ${request.method}`);
@@ -644,37 +617,46 @@ export function createServer(options: ServerOptions) {
}
function start() {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
reject(error);
};
httpServer.once("error", onError);
const onListening = async () => {
httpServer.off("error", onError);
try {
await orchestrationEngine.start();
resolve();
} catch (error) {
reject(error instanceof Error ? error : new Error("Failed to start orchestration engine"));
}
};
if (host) {
httpServer.listen(port, host, onListening);
return;
}
httpServer.listen(port, onListening);
});
return coreEngine.start().then(
() =>
new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
reject(error);
};
httpServer.once("error", onError);
const onListening = () => {
httpServer.off("error", onError);
unsubscribeCoreDelta = coreEngine.subscribe((delta: CoreViewDelta) => {
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.coreViewDelta,
data: delta,
};
broadcastPush(push);
});
resolve();
};
if (host) {
httpServer.listen(port, host, onListening);
return;
}
httpServer.listen(port, onListening);
}),
);
}
async function stop(): Promise<void> {
unsubscribeReadModel();
unsubscribeDomainEvents();
await orchestrationEngine.stop();
if (unsubscribeCoreDelta) {
unsubscribeCoreDelta();
unsubscribeCoreDelta = null;
}
terminalManager.off("event", onTerminalEvent);
providerManager.stopAll();
providerManager.dispose();
providerOrchestrator.stopAll();
providerOrchestrator.dispose();
terminalManager.dispose();
await coreEngine.stop();
eventStore.close();
for (const client of clients) {
client.close();
+12 -20
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,18 @@ 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",
void api?.core.dispatch({
command: {
kind: "SetThreadBranch",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch,
worktreePath,
createdAt: new Date().toISOString(),
});
}
issuedAt: new Date().toISOString(),
payload: {
threadId: activeThreadId,
branch,
worktreePath,
},
},
});
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
+137 -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";
@@ -433,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],
@@ -550,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;
@@ -1428,14 +1473,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
checkpointTurnCountSyncFingerprintRef.current.set(syncKey, turnFingerprint);
try {
await api.providers.listCheckpoints({
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, turnDiffSummaries],
[api, dispatch, turnDiffSummaries],
);
const ensureSession = useCallback(
@@ -1474,21 +1533,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 =
@@ -1524,6 +1572,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
api,
codexBinaryPath,
codexHomePath,
dispatch,
runtimeApprovalPolicy,
runtimeSandboxMode,
selectedModel,
@@ -1593,10 +1642,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,
@@ -1643,16 +1709,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
newBranch,
});
sessionCwd = result.worktree.path;
if (api) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
void api.core.dispatch({
command: {
kind: "SetThreadBranch",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
createdAt: new Date().toISOString(),
});
}
issuedAt: new Date().toISOString(),
payload: {
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
},
},
});
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, {
@@ -1679,15 +1753,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);
@@ -1699,19 +1769,26 @@ 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",
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
void api.core.dispatch({
command: {
kind: "AppendUserMessage",
commandId: crypto.randomUUID(),
threadId: activeThread.id,
messageId: userMessageId,
role: "user",
text: trimmed,
streaming: false,
createdAt: new Date().toISOString(),
});
}
issuedAt: new Date().toISOString(),
payload: {
threadId: activeThread.id,
messageId: crypto.randomUUID(),
text: trimmed,
createdAt: new Date().toISOString(),
},
},
});
const previousMessages = activeThread.messages;
promptRef.current = "";
setPrompt("");
@@ -1800,18 +1877,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) => {
+85 -51
View File
@@ -7,14 +7,16 @@ 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";
import { type Project, type Thread } from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
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,51 @@ 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;
await 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,
});
void api?.core.dispatch({
command: {
kind: "CreateThread",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
createdAt: thread.createdAt,
},
},
});
dispatch({
type: "ADD_THREAD",
thread,
});
void navigate({
to: "/$threadId",
params: { threadId },
params: { threadId: thread.id },
});
},
[api, dispatch, navigate, state.projects],
[dispatch, navigate, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
@@ -188,32 +204,60 @@ 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;
}
let projectId: string;
if (isElectron) {
if (isElectron && api) {
const result = await api.projects.add({ cwd });
projectId = result.project.id;
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: result.project.scripts,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
projectId = crypto.randomUUID();
const now = new Date().toISOString();
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const name = inferProjectName(cwd);
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: crypto.randomUUID(),
projectId,
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
createdAt: now,
expanded: true,
scripts: [],
};
await api?.core.dispatch({
command: {
kind: "CreateProject",
commandId: crypto.randomUUID(),
issuedAt: new Date().toISOString(),
payload: {
id: project.id,
name: project.name,
cwd: project.cwd,
model: project.model,
},
},
});
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
}
await handleNewThread(projectId);
} finally {
setIsAddingProject(false);
setNewCwd("");
@@ -304,12 +348,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(),
});
dispatch({ type: "DELETE_THREAD", threadId });
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
@@ -399,12 +438,7 @@ export default function Sidebar() {
}
}
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: crypto.randomUUID(),
projectId,
createdAt: new Date().toISOString(),
});
dispatch({ type: "DELETE_PROJECT", projectId });
},
[api, dispatch, state.projects, state.threads],
);
@@ -418,7 +452,7 @@ export default function Sidebar() {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId);
handleNewThread(projectId);
return;
}
@@ -426,7 +460,7 @@ export default function Sidebar() {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId, {
handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
@@ -465,7 +499,7 @@ export default function Sidebar() {
return;
}
const firstProject = state.projects[0];
if (firstProject) void handleNewThread(firstProject.id);
if (firstProject) handleNewThread(firstProject.id);
}}
>
<span className="text-foreground">+</span>
@@ -580,7 +614,7 @@ 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={() => void handleNewThread(project.id)}
onClick={() => 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;
}
+92 -35
View File
@@ -2,15 +2,17 @@ import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
useParams,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient } from "@tanstack/react-query";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { DEFAULT_MODEL } from "../model-logic";
import { useStore } from "../store";
import { onServerWelcome } from "../wsNativeApi";
@@ -123,33 +125,53 @@ function errorDetails(error: unknown): string {
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const queryClient = useQueryClient();
const activeThreadId = useParams({
strict: false,
select: (params) => params.threadId,
});
useEffect(() => {
if (!api) return;
void api.orchestration
let cancelled = false;
void api.core
.getSnapshot()
.then((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
if (cancelled) return;
dispatch({ type: "APPLY_CORE_SNAPSHOT", snapshot });
})
.catch(() => undefined);
const unsubReadModel = api.orchestration.onReadModel((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
.catch(() => {
// Keep existing UI state if snapshot bootstrap fails.
});
const unsubscribeCore = api.core.onViewDelta((delta) => {
dispatch({ type: "APPLY_CORE_DELTA", delta });
if (delta.kind === "gitStatusUpsert") {
void invalidateGitQueries(queryClient);
}
});
return () => {
unsubReadModel();
cancelled = true;
unsubscribeCore();
};
}, [api, dispatch]);
}, [api, dispatch, queryClient]);
useEffect(() => {
if (!activeThreadId) return;
dispatch({
type: "MARK_THREAD_VISITED",
threadId: activeThreadId,
visitedAt: new Date().toISOString(),
});
}, [activeThreadId, dispatch]);
return null;
}
function AutoProjectBootstrap() {
const api = useNativeApi();
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!api) return;
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
@@ -166,40 +188,75 @@ function AutoProjectBootstrap() {
}
bootstrappedRef.current = true;
// Create project + thread from server cwd
const projectId = crypto.randomUUID();
const threadId = crypto.randomUUID();
const now = new Date().toISOString();
void api.orchestration
.dispatchCommand({
type: "project.create",
commandId: crypto.randomUUID(),
projectId,
dispatch({
type: "ADD_PROJECT",
project: {
id: 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);
expanded: true,
scripts: [],
},
});
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
});
}, [api, state.projects, dispatch]);
}, [state.projects, dispatch]);
return null;
}
function DesktopProjectBootstrap() {
// Desktop now hydrates from orchestration read-model snapshots.
const api = useNativeApi();
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const attemptBootstrap = async () => {
try {
const projects = await api.projects.list();
if (disposed) return;
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: project.scripts,
})),
});
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
bootstrappedRef.current = true;
} catch {
if (disposed) return;
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
}
};
void attemptBootstrap();
return () => {
disposed = true;
if (retryTimer) {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
return null;
}
+881 -69
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,94 +107,680 @@ 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;
}
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 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(
summaries: TurnDiffSummary[],
): Record<string, number> {
if (summaries.length === 0) {
return {};
}
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)) {
return a.completedAt.localeCompare(b.completedAt);
}
return aTime - bTime;
});
const next: Record<string, number> = {};
let fallbackTurnCount = 1;
for (const summary of sorted) {
if (typeof summary.checkpointTurnCount === "number") {
next[summary.turnId] = summary.checkpointTurnCount;
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
continue;
}
next[summary.turnId] = fallbackTurnCount;
fallbackTurnCount += 1;
}
return next;
}
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 messageRows: TimelineEntry[] = messages.map((message) => ({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
}));
const workRows: TimelineEntry[] = workEntries.map((entry) => ({
id: `work:${entry.id}`,
kind: "work",
createdAt: entry.createdAt,
entry,
}));
return [...messageRows, ...workRows].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
const timeline: TimelineEntry[] = [];
let messageIndex = 0;
let workIndex = 0;
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 });
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 files;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<string, number> {
const sorted = [...summaries].sort((a, b) => a.completedAt.localeCompare(b.completedAt));
const result: Record<string, number> = {};
for (let index = 0; index < sorted.length; index += 1) {
const summary = sorted[index];
if (!summary) continue;
result[summary.turnId] = index + 1;
}
return result;
}
export function deriveTurnDiffSummaries(_events: unknown[]): TurnDiffSummary[] {
return [];
return timeline;
}
export function derivePhase(session: ProviderSession | null): SessionPhase {
@@ -136,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;
}
+433 -132
View File
@@ -4,16 +4,19 @@ import {
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import {
type OrchestrationReadModel,
type CoreReadModelSnapshot,
type CoreThreadMessageView,
type CoreViewDelta,
type ProviderSession,
normalizeProjectScripts,
} from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
@@ -25,13 +28,32 @@ import {
type ThreadTerminalGroup,
} from "./types";
function normalizeScriptIcon(icon: string | null | undefined): ProjectScript["icon"] {
switch (icon) {
case "play":
case "test":
case "lint":
case "configure":
case "build":
case "debug":
return icon;
default:
return "play";
}
}
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { 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: "APPLY_CORE_SNAPSHOT"; snapshot: CoreReadModelSnapshot }
| { type: "APPLY_CORE_DELTA"; delta: CoreViewDelta }
| { 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 +61,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 +104,97 @@ 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;
function mapCoreMessageToChatMessage(message: CoreThreadMessageView): Thread["messages"][number] {
return {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
};
}
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.
}
function mapCoreScriptsToProjectScripts(
scripts: CoreReadModelSnapshot["projects"][number]["scripts"],
): ProjectScript[] {
return scripts.map((script) => {
const icon = normalizeScriptIcon(script.icon ?? undefined);
return {
id: script.id,
name: script.name,
command: script.command,
icon,
runOnWorktreeCreate: script.runOnWorktreeCreate ?? false,
};
});
}
function mapSnapshotToState(snapshot: CoreReadModelSnapshot, previous: AppState): AppState {
const projects: Project[] = snapshot.projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: project.model,
expanded: project.expanded,
scripts: mapCoreScriptsToProjectScripts(project.scripts),
}));
const threads: Thread[] = snapshot.threads.map((thread) => {
const existing = previous.threads.find((entry) => entry.id === thread.id);
const next: Thread = {
id: thread.id,
codexThreadId: thread.id,
projectId: thread.projectId,
title: thread.title,
model: 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: existing?.session ?? null,
messages: thread.messages.map(mapCoreMessageToChatMessage),
events: existing?.events ?? [],
error: existing?.error ?? null,
createdAt: thread.createdAt,
latestTurnId: existing?.latestTurnId,
latestTurnStartedAt: existing?.latestTurnStartedAt,
latestTurnCompletedAt: existing?.latestTurnCompletedAt,
latestTurnDurationMs: existing?.latestTurnDurationMs,
lastVisitedAt: existing?.lastVisitedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: existing?.turnDiffSummaries ?? [],
};
return normalizeThreadTerminals(next);
});
return {
...previous,
projects,
threads,
threadsHydrated: true,
};
}
function updateThread(
@@ -136,7 +205,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 +391,25 @@ 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 "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 +430,132 @@ export function reducer(state: AppState, action: Action): AppState {
threadsHydrated: action.hydrated,
};
case "APPLY_CORE_SNAPSHOT":
return mapSnapshotToState(action.snapshot, state);
case "APPLY_CORE_DELTA": {
const delta = action.delta;
switch (delta.kind) {
case "snapshot":
return mapSnapshotToState(delta.snapshot, state);
case "projectUpsert": {
const project: Project = {
id: delta.project.id,
name: delta.project.name,
cwd: delta.project.cwd,
model: delta.project.model,
expanded: delta.project.expanded,
scripts: mapCoreScriptsToProjectScripts(delta.project.scripts),
};
const existing = state.projects.find((item) => item.id === project.id);
return {
...state,
projects: existing
? state.projects.map((item) => (item.id === project.id ? project : item))
: [...state.projects, project],
};
}
case "projectDelete":
return {
...state,
projects: state.projects.filter((project) => project.id !== delta.projectId),
threads: state.threads.filter((thread) => thread.projectId !== delta.projectId),
};
case "threadDelete":
return {
...state,
threads: state.threads.filter((thread) => thread.id !== delta.threadId),
};
case "threadUpsert": {
const snapshot: CoreReadModelSnapshot = {
sequence: delta.sequence,
generatedAt: new Date().toISOString(),
projects: state.projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: project.model,
expanded: project.expanded,
scripts: project.scripts.map((script) => ({
id: script.id,
name: script.name,
command: script.command,
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
})),
})),
threads: [
...state.threads
.filter((thread) => thread.id !== delta.thread.id)
.map((thread) => ({
id: thread.id,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
createdAt: thread.createdAt,
updatedAt: thread.latestTurnCompletedAt ?? thread.createdAt,
sessionId: thread.session?.sessionId ?? null,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
})),
branch: thread.branch,
worktreePath: thread.worktreePath,
})),
delta.thread,
],
git: [],
};
return mapSnapshotToState(snapshot, state);
}
case "gitStatusUpsert":
return state;
}
}
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 +564,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 +759,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 +805,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 +907,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 +945,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",
+9 -29
View File
@@ -1,13 +1,4 @@
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";
@@ -99,10 +90,13 @@ 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: (callback) =>
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
},
projects: {
list: () => transport.request(WS_METHODS.projectsList),
@@ -155,25 +149,11 @@ 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,
),
core: {
getSnapshot: (input) => transport.request(WS_METHODS.coreGetSnapshot, input),
dispatch: (input) => transport.request(WS_METHODS.coreDispatch, input),
onViewDelta: (callback) =>
transport.subscribe(WS_CHANNELS.coreViewDelta, callback as (data: unknown) => void),
},
};
+37 -9
View File
@@ -34,7 +34,9 @@
"t3": "./dist/index.mjs",
},
"dependencies": {
"better-sqlite3": "^12.6.2",
"@effect/schema": "^0.75.5",
"@effect/sql": "^0.49.0",
"@effect/sql-sqlite-node": "^0.50.1",
"effect": "^3.19.19",
"node-pty": "^1.1.0",
"open": "^10.1.0",
@@ -43,7 +45,6 @@
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
@@ -90,7 +91,6 @@
"name": "@t3tools/contracts",
"version": "0.0.0",
"dependencies": {
"effect": "^3.19.19",
"zod": "^3.24.1",
},
"devDependencies": {
@@ -148,6 +148,16 @@
"@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/schema": ["@effect/[email protected]", "", { "dependencies": { "fast-check": "^3.21.0" }, "peerDependencies": { "effect": "^3.9.2" } }, "sha512-TQInulTVCuF+9EIbJpyLP6dvxbQJMphrnRqgexm/Ze39rSjfhJuufF7XvU3SxTgg3HnL7B/kpORTJbHhlE6thw=="],
"@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=="],
@@ -248,6 +258,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=="],
@@ -498,8 +520,6 @@
"@types/babel__traverse": ["@types/[email protected]", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
"@types/better-sqlite3": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA=="],
"@types/cacheable-request": ["@types/[email protected]", "", { "dependencies": { "@types/http-cache-semantics": "*", "@types/keyv": "^3.1.4", "@types/node": "*", "@types/responselike": "^1.0.0" } }, "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw=="],
"@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
@@ -766,6 +786,8 @@
"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=="],
@@ -1048,8 +1070,14 @@
"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=="],
@@ -1060,6 +1088,8 @@
"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=="],
@@ -1346,6 +1376,8 @@
"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=="],
@@ -1436,8 +1468,6 @@
"@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/better-sqlite3/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
"@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=="],
@@ -1494,8 +1524,6 @@
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
"@types/better-sqlite3/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"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=="],
-1
View File
@@ -23,7 +23,6 @@
"test": "vitest run"
},
"dependencies": {
"effect": "^3.19.19",
"zod": "^3.24.1"
},
"devDependencies": {
+191
View File
@@ -0,0 +1,191 @@
import { z } from "zod";
export const coreGitStatusSnapshotSchema = z.object({
cwd: z.string().min(1),
branch: z.string().min(1).nullable(),
hasWorkingTreeChanges: z.boolean(),
aheadCount: z.number().int().nonnegative(),
behindCount: z.number().int().nonnegative(),
observedAt: z.string().datetime(),
});
export const coreProjectViewSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean().default(true),
scripts: z.array(
z.object({
id: z.string().min(1),
name: z.string().min(1),
command: z.string().min(1),
icon: z.string().min(1).nullable().optional(),
runOnWorktreeCreate: z.boolean().optional(),
}),
),
});
export const coreThreadMessageViewSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
createdAt: z.string().datetime(),
streaming: z.boolean().default(false),
});
export const coreThreadViewSchema = z.object({
id: z.string().min(1),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
sessionId: z.string().min(1).nullable(),
messages: z.array(coreThreadMessageViewSchema),
branch: z.string().min(1).nullable(),
worktreePath: z.string().min(1).nullable(),
});
export const coreReadModelSnapshotSchema = z.object({
sequence: z.number().int().nonnegative(),
generatedAt: z.string().datetime(),
projects: z.array(coreProjectViewSchema),
threads: z.array(coreThreadViewSchema),
git: z.array(coreGitStatusSnapshotSchema),
});
export const coreViewDeltaSchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("snapshot"),
sequence: z.number().int().nonnegative(),
snapshot: coreReadModelSnapshotSchema,
}),
z.object({
kind: z.literal("projectUpsert"),
sequence: z.number().int().nonnegative(),
project: coreProjectViewSchema,
}),
z.object({
kind: z.literal("projectDelete"),
sequence: z.number().int().nonnegative(),
projectId: z.string().min(1),
}),
z.object({
kind: z.literal("threadUpsert"),
sequence: z.number().int().nonnegative(),
thread: coreThreadViewSchema,
}),
z.object({
kind: z.literal("threadDelete"),
sequence: z.number().int().nonnegative(),
threadId: z.string().min(1),
}),
z.object({
kind: z.literal("gitStatusUpsert"),
sequence: z.number().int().nonnegative(),
git: coreGitStatusSnapshotSchema,
}),
]);
const coreCommandBaseSchema = z.object({
commandId: z.string().min(1),
issuedAt: z.string().datetime(),
});
export const coreCommandSchema = z.discriminatedUnion("kind", [
coreCommandBaseSchema.extend({
kind: z.literal("CreateProject"),
payload: z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
}),
}),
coreCommandBaseSchema.extend({
kind: z.literal("CreateThread"),
payload: z.object({
id: z.string().min(1),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
createdAt: z.string().datetime().optional(),
}),
}),
coreCommandBaseSchema.extend({
kind: z.literal("AppendUserMessage"),
payload: z.object({
threadId: z.string().min(1),
messageId: z.string().min(1),
text: z.string(),
createdAt: z.string().datetime(),
}),
}),
coreCommandBaseSchema.extend({
kind: z.literal("AppendAssistantMessage"),
payload: z.object({
threadId: z.string().min(1),
messageId: z.string().min(1),
text: z.string(),
createdAt: z.string().datetime(),
}),
}),
coreCommandBaseSchema.extend({
kind: z.literal("SetThreadBranch"),
payload: z.object({
threadId: z.string().min(1),
branch: z.string().min(1).nullable(),
worktreePath: z.string().min(1).nullable(),
}),
}),
coreCommandBaseSchema.extend({
kind: z.literal("GitProbe"),
payload: z.object({
cwd: z.string().min(1),
}),
}),
coreCommandBaseSchema.extend({
kind: z.literal("GitWorkflow"),
payload: z.object({
workflow: z.enum([
"create_branch",
"checkout",
"create_worktree",
"remove_worktree",
"stacked_action",
"checkpoint_capture",
"checkpoint_restore",
"open_pr",
]),
cwd: z.string().min(1),
metadata: z.record(z.string(), z.unknown()).default({}),
}),
}),
]);
export const coreDispatchInputSchema = z.object({
command: coreCommandSchema,
expectedVersion: z.number().int().nonnegative().optional(),
idempotencyKey: z.string().min(1).optional(),
});
export const coreDispatchResultSchema = z.object({
accepted: z.boolean(),
sequence: z.number().int().nonnegative(),
});
export const coreGetSnapshotInputSchema = z.object({
minSequence: z.number().int().nonnegative().optional(),
});
export type CoreGitStatusSnapshot = z.infer<typeof coreGitStatusSnapshotSchema>;
export type CoreProjectView = z.infer<typeof coreProjectViewSchema>;
export type CoreThreadMessageView = z.infer<typeof coreThreadMessageViewSchema>;
export type CoreThreadView = z.infer<typeof coreThreadViewSchema>;
export type CoreReadModelSnapshot = z.infer<typeof coreReadModelSnapshotSchema>;
export type CoreViewDelta = z.infer<typeof coreViewDeltaSchema>;
export type CoreCommand = z.infer<typeof coreCommandSchema>;
export type CoreDispatchInput = z.input<typeof coreDispatchInputSchema>;
export type CoreDispatchResult = z.infer<typeof coreDispatchResultSchema>;
export type CoreGetSnapshotInput = z.input<typeof coreGetSnapshotInputSchema>;
+1 -1
View File
@@ -9,4 +9,4 @@ export * from "./keybindings";
export * from "./server";
export * from "./project";
export * from "./git";
export * from "./orchestration";
export * from "./core";
+14 -11
View File
@@ -1,4 +1,11 @@
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
import type {
CoreDispatchInput,
CoreDispatchResult,
CoreGetSnapshotInput,
CoreReadModelSnapshot,
CoreViewDelta,
} from "./core";
import type {
GitCheckoutInput,
GitCreateBranchInput,
@@ -16,6 +23,7 @@ import type {
GitStatusResult,
} from "./git";
import type {
ProviderEvent,
ProviderGetCheckpointDiffInput,
ProviderGetCheckpointDiffResult,
ProviderInterruptTurnInput,
@@ -52,11 +60,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 +101,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 +111,7 @@ export interface NativeApi {
revertToCheckpoint: (
input: ProviderRevertToCheckpointInput,
) => Promise<ProviderRevertToCheckpointResult>;
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
};
projects: {
list: () => Promise<ProjectListResult>;
@@ -142,11 +147,9 @@ 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;
core: {
getSnapshot: (input?: CoreGetSnapshotInput) => Promise<CoreReadModelSnapshot>;
dispatch: (input: CoreDispatchInput) => Promise<CoreDispatchResult>;
onViewDelta: (callback: (delta: CoreViewDelta) => void) => () => void;
};
}
-223
View File
@@ -1,223 +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 OrchestrationCommandSchema = Schema.Union(
CreateProjectCommandSchema,
DeleteProjectCommandSchema,
CreateThreadCommandSchema,
DeleteThreadCommandSchema,
UpdateThreadMetaCommandSchema,
SendMessageCommandSchema,
SetThreadSessionSchema,
UpsertGitReadModelCommandSchema,
);
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>;
+7
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,19 @@ export const WS_METHODS = {
// Server meta
serverGetConfig: "server.getConfig",
serverUpsertKeybinding: "server.upsertKeybinding",
// Core event-sourced views
coreGetSnapshot: "core.getSnapshot",
coreDispatch: "core.dispatch",
} as const;
// ── Push Event Channels ──────────────────────────────────────────────
export const WS_CHANNELS = {
providerEvent: "providers.event",
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
coreViewDelta: "core.viewDelta",
} as const;
// ── Client → Server (request) ────────────────────────────────────────