Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac44561caf |
No files matched your search
@@ -17,10 +17,9 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/schema": "^0.75.5",
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"effect": "^3.19.19",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { EffectFanout, OrchestrationEngine, QueueProjector, type AppViewState } from "@t3tools/core";
|
||||
import { createSqliteStores } from "@t3tools/infra-sqlite";
|
||||
|
||||
import type { ProviderManager } from "./providerManager";
|
||||
import type { TerminalManager } from "./terminalManager";
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
export class CoreRuntime {
|
||||
private readonly fanout = new EffectFanout();
|
||||
private readonly stores;
|
||||
private readonly projector: QueueProjector;
|
||||
private readonly engine: OrchestrationEngine;
|
||||
|
||||
constructor(dbDir: string) {
|
||||
const dbPath = path.join(dbDir, "event-store.sqlite");
|
||||
this.stores = createSqliteStores(dbPath);
|
||||
this.projector = new QueueProjector(this.stores.projectionStore, this.fanout);
|
||||
this.engine = new OrchestrationEngine(this.stores.eventStore, this.stores.projectionStore, this.projector);
|
||||
}
|
||||
|
||||
async start(cwd: string, projectName: string): Promise<void> {
|
||||
await this.engine.start();
|
||||
await this.engine.execute({
|
||||
id: crypto.randomUUID(),
|
||||
type: "app.bootstrap",
|
||||
issuedAt: nowIso(),
|
||||
payload: { cwd, projectName },
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.engine.stop();
|
||||
this.stores.db.close();
|
||||
}
|
||||
|
||||
async state(): Promise<AppViewState> {
|
||||
return this.engine.currentState();
|
||||
}
|
||||
|
||||
async dispatch(command: Parameters<OrchestrationEngine["execute"]>[0]): Promise<AppViewState> {
|
||||
return this.engine.execute(command);
|
||||
}
|
||||
|
||||
subscribe() {
|
||||
return this.fanout.subscribe();
|
||||
}
|
||||
|
||||
bindProviderEvents(providerManager: ProviderManager): void {
|
||||
providerManager.on("event", (event: ProviderEvent) => {
|
||||
void this.ingestProviderEvent(event);
|
||||
});
|
||||
}
|
||||
|
||||
bindTerminalEvents(terminalManager: TerminalManager): void {
|
||||
terminalManager.on("event", (event: TerminalEvent) => {
|
||||
if (event.type !== "activity" && event.type !== "error" && event.type !== "exited") return;
|
||||
void this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.setTerminalActivity",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
running: event.type === "activity" ? event.hasRunningSubprocess : false,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async bindProviderSession(threadId: string, session: ProviderSession): Promise<void> {
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.updateProviderSession",
|
||||
issuedAt: nowIso(),
|
||||
payload: { threadId, session },
|
||||
});
|
||||
}
|
||||
|
||||
async clearProviderSession(threadId: string): Promise<void> {
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.updateProviderSession",
|
||||
issuedAt: nowIso(),
|
||||
payload: { threadId, session: null },
|
||||
});
|
||||
}
|
||||
|
||||
async ingestProviderEvent(event: ProviderEvent): Promise<void> {
|
||||
const state = await this.state();
|
||||
const target = state.threads.find((thread) => thread.session?.sessionId === event.sessionId);
|
||||
if (!target) return;
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.recordProviderEvent",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: target.id,
|
||||
event,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
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;
|
||||
@@ -1,211 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -118,10 +118,10 @@ async function main() {
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
stateDir,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
|
||||
+197
-232
@@ -3,23 +3,18 @@ import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import {
|
||||
EDITORS,
|
||||
coreDispatchInputSchema,
|
||||
coreGetSnapshotInputSchema,
|
||||
gitStatusResultSchema,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type CoreDispatchInput,
|
||||
type CoreViewDelta,
|
||||
type TerminalEvent,
|
||||
type WsPush,
|
||||
type WsRequest,
|
||||
type WsResponse,
|
||||
wsRequestSchema,
|
||||
DEFAULT_MODEL,
|
||||
} from "@t3tools/contracts";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
@@ -39,8 +34,7 @@ import {
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { CoreEngine } from "./effect/coreEngine";
|
||||
import { SqliteEventStore } from "./effect/eventStore";
|
||||
import { CoreRuntime } from "./coreRuntime";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -61,11 +55,11 @@ export interface ServerOptions {
|
||||
port: number;
|
||||
host?: string | undefined;
|
||||
cwd: string;
|
||||
stateDir?: string | undefined;
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
stateDir?: string | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
authToken?: string | undefined;
|
||||
@@ -84,11 +78,11 @@ export function createServer(options: ServerOptions) {
|
||||
port,
|
||||
host,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
stateDir,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
@@ -98,26 +92,12 @@ export function createServer(options: ServerOptions) {
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
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 runtimeStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
|
||||
const coreRuntime = new CoreRuntime(runtimeStateDir);
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
@@ -143,47 +123,29 @@ export function createServer(options: ServerOptions) {
|
||||
logOutgoingPush(push, recipients);
|
||||
}
|
||||
|
||||
// Forward provider events to all connected WebSocket clients
|
||||
providerManager.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(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
threadId: event.threadId,
|
||||
messageId: event.itemId ?? crypto.randomUUID(),
|
||||
text: event.message,
|
||||
createdAt: event.createdAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const onTerminalEvent = (event: TerminalEvent) => {
|
||||
const push: WsPush = {
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.terminalEvent,
|
||||
data: event,
|
||||
};
|
||||
broadcastPush(push);
|
||||
});
|
||||
if (event.type === "activity" || event.type === "exited" || event.type === "error") {
|
||||
void coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.setTerminalActivity",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
running: event.type === "activity" ? event.hasRunningSubprocess : false,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
terminalManager.on("event", onTerminalEvent);
|
||||
|
||||
let unsubscribeCoreDelta: (() => void) | null = null;
|
||||
coreRuntime.bindProviderEvents(providerManager);
|
||||
let stateStreamStopped = false;
|
||||
let stateStreamTask: Promise<void> | null = null;
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
@@ -281,10 +243,6 @@ export function createServer(options: ServerOptions) {
|
||||
wss.on("connection", (ws) => {
|
||||
clients.add(ws);
|
||||
|
||||
// Send welcome message with project info
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
const welcome: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
@@ -335,12 +293,44 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
|
||||
async function routeRequest(request: WsRequest): Promise<unknown> {
|
||||
switch (request.method) {
|
||||
case WS_METHODS.providersStartSession:
|
||||
return providerManager.startSession(request.params as never);
|
||||
const requestNow = new Date().toISOString();
|
||||
const paramsObj = (request.params ?? {}) as Record<string, unknown>;
|
||||
const state = await coreRuntime.state();
|
||||
const findThreadBySessionId = (sessionId: string | undefined) =>
|
||||
sessionId
|
||||
? state.threads.find((thread) => thread.session?.sessionId === sessionId)
|
||||
: undefined;
|
||||
|
||||
case WS_METHODS.providersSendTurn:
|
||||
switch (request.method) {
|
||||
case WS_METHODS.providersStartSession: {
|
||||
const session = await providerManager.startSession(request.params as never);
|
||||
const uiThreadId = typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
|
||||
if (uiThreadId) {
|
||||
await coreRuntime.bindProviderSession(uiThreadId, session);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
case WS_METHODS.providersSendTurn: {
|
||||
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
|
||||
const uiThreadId = typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
|
||||
const targetThread = uiThreadId ? state.threads.find((thread) => thread.id === uiThreadId) : findThreadBySessionId(sessionId);
|
||||
const inputText = typeof paramsObj.input === "string" ? paramsObj.input : undefined;
|
||||
if (targetThread && inputText && inputText.trim().length > 0) {
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.addUserMessage",
|
||||
issuedAt: requestNow,
|
||||
payload: {
|
||||
threadId: targetThread.id,
|
||||
messageId: crypto.randomUUID(),
|
||||
text: inputText,
|
||||
createdAt: requestNow,
|
||||
},
|
||||
});
|
||||
}
|
||||
return providerManager.sendTurn(request.params as never);
|
||||
}
|
||||
|
||||
case WS_METHODS.providersInterruptTurn:
|
||||
return providerManager.interruptTurn(request.params as never);
|
||||
@@ -349,7 +339,12 @@ export function createServer(options: ServerOptions) {
|
||||
return providerManager.respondToRequest(request.params as never);
|
||||
|
||||
case WS_METHODS.providersStopSession: {
|
||||
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
|
||||
const boundThread = findThreadBySessionId(sessionId);
|
||||
providerManager.stopSession(request.params as never);
|
||||
if (boundThread) {
|
||||
await coreRuntime.clearProviderSession(boundThread.id);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -369,33 +364,51 @@ export function createServer(options: ServerOptions) {
|
||||
return projectRegistry.list();
|
||||
|
||||
case WS_METHODS.projectsAdd:
|
||||
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: DEFAULT_MODEL,
|
||||
},
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.add",
|
||||
issuedAt: requestNow,
|
||||
payload: {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: "gpt-5-codex",
|
||||
scripts: result.project.scripts,
|
||||
},
|
||||
};
|
||||
await coreEngine.dispatch(command);
|
||||
});
|
||||
return result;
|
||||
})();
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsRemove:
|
||||
{
|
||||
const projectId = typeof paramsObj.id === "string" ? paramsObj.id : undefined;
|
||||
if (projectId) {
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.remove",
|
||||
issuedAt: requestNow,
|
||||
payload: { id: projectId },
|
||||
});
|
||||
}
|
||||
projectRegistry.remove(request.params as never);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
case WS_METHODS.projectsUpdateScripts:
|
||||
return projectRegistry.updateScripts(request.params as never);
|
||||
{
|
||||
const result = projectRegistry.updateScripts(request.params as never);
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.updateScripts",
|
||||
issuedAt: requestNow,
|
||||
payload: { id: result.project.id, scripts: result.project.scripts },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
@@ -445,128 +458,27 @@ export function createServer(options: ServerOptions) {
|
||||
return gitManager.status(request.params as never);
|
||||
|
||||
case WS_METHODS.gitPull:
|
||||
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;
|
||||
});
|
||||
return pullGitBranch(request.params as never);
|
||||
|
||||
case WS_METHODS.gitRunStackedAction:
|
||||
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;
|
||||
});
|
||||
return gitManager.runStackedAction(request.params as never);
|
||||
case WS_METHODS.gitListBranches:
|
||||
return listGitBranches(request.params as never);
|
||||
|
||||
case WS_METHODS.gitCreateWorktree:
|
||||
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;
|
||||
});
|
||||
return createGitWorktree(request.params as never);
|
||||
|
||||
case WS_METHODS.gitRemoveWorktree:
|
||||
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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
return removeGitWorktree(request.params as never);
|
||||
|
||||
case WS_METHODS.gitCreateBranch:
|
||||
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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
return createGitBranch(request.params as never);
|
||||
|
||||
case WS_METHODS.gitCheckout:
|
||||
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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
return checkoutGitBranch(request.params as never);
|
||||
|
||||
case WS_METHODS.gitInit:
|
||||
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 },
|
||||
},
|
||||
});
|
||||
});
|
||||
return initGitRepo(request.params as never);
|
||||
|
||||
case WS_METHODS.terminalOpen:
|
||||
return terminalManager.open(request.params as never);
|
||||
@@ -602,13 +514,59 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.coreGetSnapshot:
|
||||
coreGetSnapshotInputSchema.parse(request.params ?? {});
|
||||
return coreEngine.getSnapshot();
|
||||
case WS_METHODS.stateGetSnapshot:
|
||||
return coreRuntime.state();
|
||||
|
||||
case WS_METHODS.coreDispatch: {
|
||||
const input = coreDispatchInputSchema.parse(request.params);
|
||||
return coreEngine.dispatch(input);
|
||||
case WS_METHODS.stateCreateThread: {
|
||||
const params = request.params as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.create",
|
||||
issuedAt: requestNow,
|
||||
payload: params,
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
case WS_METHODS.stateDeleteThread: {
|
||||
const params = request.params as { id: string };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.delete",
|
||||
issuedAt: requestNow,
|
||||
payload: params,
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
case WS_METHODS.stateMarkThreadVisited: {
|
||||
const params = request.params as { threadId: string; visitedAt?: string };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.markVisited",
|
||||
issuedAt: requestNow,
|
||||
payload: { threadId: params.threadId, visitedAt: params.visitedAt ?? requestNow },
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.stateSetRuntimeMode: {
|
||||
const params = request.params as { mode: "approval-required" | "full-access" };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "runtime.setMode",
|
||||
issuedAt: requestNow,
|
||||
payload: { mode: params.mode },
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
default:
|
||||
@@ -617,46 +575,49 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
|
||||
function start() {
|
||||
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);
|
||||
});
|
||||
return 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);
|
||||
void (async () => {
|
||||
try {
|
||||
await coreRuntime.start(cwd, projectName);
|
||||
stateStreamStopped = false;
|
||||
stateStreamTask = (async () => {
|
||||
const iterable = await coreRuntime.subscribe();
|
||||
for await (const update of iterable) {
|
||||
if (stateStreamStopped) break;
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.stateUpdated,
|
||||
data: update.state,
|
||||
});
|
||||
}
|
||||
})();
|
||||
resolve();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
return;
|
||||
} catch (error) {
|
||||
reject(error as Error);
|
||||
}
|
||||
httpServer.listen(port, onListening);
|
||||
}),
|
||||
);
|
||||
})();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
return;
|
||||
}
|
||||
httpServer.listen(port, onListening);
|
||||
});
|
||||
}
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
if (unsubscribeCoreDelta) {
|
||||
unsubscribeCoreDelta();
|
||||
unsubscribeCoreDelta = null;
|
||||
}
|
||||
stateStreamStopped = true;
|
||||
terminalManager.off("event", onTerminalEvent);
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
terminalManager.dispose();
|
||||
await coreEngine.stop();
|
||||
eventStore.close();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
@@ -692,6 +653,10 @@ export function createServer(options: ServerOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
if (stateStreamTask) {
|
||||
await Promise.race([stateStreamTask, Promise.resolve()]);
|
||||
}
|
||||
await coreRuntime.stop();
|
||||
await Promise.all([closeWebSocketServer, closeHttpServer]);
|
||||
}
|
||||
|
||||
|
||||
@@ -120,18 +120,6 @@ export default function BranchToolbar({
|
||||
if (sessionId && worktreePath !== activeWorktreePath) {
|
||||
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
|
||||
}
|
||||
void api?.core.dispatch({
|
||||
command: {
|
||||
kind: "SetThreadBranch",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
threadId: activeThreadId,
|
||||
branch,
|
||||
worktreePath,
|
||||
},
|
||||
},
|
||||
});
|
||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
||||
};
|
||||
|
||||
|
||||
@@ -1074,6 +1074,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
dispatch({ type: "SET_RUNTIME_MODE", mode });
|
||||
scheduleComposerFocus();
|
||||
if (!api) return;
|
||||
await api.state.setRuntimeMode({ mode });
|
||||
|
||||
const sessionIds = state.threads
|
||||
.map((t) => t.session)
|
||||
@@ -1524,6 +1525,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
uiThreadId: activeThread.id,
|
||||
provider: "codex",
|
||||
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
|
||||
model: selectedModel || undefined,
|
||||
@@ -1709,18 +1711,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
newBranch,
|
||||
});
|
||||
sessionCwd = result.worktree.path;
|
||||
void api.core.dispatch({
|
||||
command: {
|
||||
kind: "SetThreadBranch",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
threadId: activeThread.id,
|
||||
branch: result.worktree.branch,
|
||||
worktreePath: result.worktree.path,
|
||||
},
|
||||
},
|
||||
});
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThread.id,
|
||||
@@ -1769,27 +1759,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
const messageId = crypto.randomUUID();
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: messageId,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
void api.core.dispatch({
|
||||
command: {
|
||||
kind: "AppendUserMessage",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
threadId: activeThread.id,
|
||||
messageId,
|
||||
text: trimmed,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
promptRef.current = "";
|
||||
setPrompt("");
|
||||
@@ -1825,6 +1801,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
).text
|
||||
: trimmed || undefined;
|
||||
await api.providers.sendTurn({
|
||||
uiThreadId: activeThread.id,
|
||||
sessionId: sessionInfo.sessionId,
|
||||
...(input ? { input } : {}),
|
||||
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
|
||||
|
||||
@@ -10,7 +10,7 @@ import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Project, type Thread } from "../types";
|
||||
import { type Thread } from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -140,7 +140,7 @@ export default function Sidebar() {
|
||||
}, [state.threads]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
async (
|
||||
projectId: string,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
@@ -152,30 +152,21 @@ export default function Sidebar() {
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
});
|
||||
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,
|
||||
await api?.state.createThread({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
createdAt: thread.createdAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
},
|
||||
[dispatch, navigate, state.projects],
|
||||
[api, navigate, state.projects],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -206,23 +197,11 @@ export default function Sidebar() {
|
||||
try {
|
||||
if (isElectron && api) {
|
||||
const result = await api.projects.add({ cwd });
|
||||
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;
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === result.project.cwd);
|
||||
const resolvedProjectId = existingByCwd?.id ?? result.project.id;
|
||||
|
||||
if (result.created) {
|
||||
handleNewThread(resolvedProjectId);
|
||||
await handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
@@ -232,31 +211,9 @@ export default function Sidebar() {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const name = inferProjectName(cwd);
|
||||
const project: Project = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
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);
|
||||
if (!api) return;
|
||||
const result = await api.projects.add({ cwd });
|
||||
await handleNewThread(result.project.id);
|
||||
}
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
@@ -348,7 +305,7 @@ export default function Sidebar() {
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
dispatch({ type: "DELETE_THREAD", threadId });
|
||||
await api.state.deleteThread({ id: threadId });
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -438,7 +395,6 @@ export default function Sidebar() {
|
||||
}
|
||||
}
|
||||
|
||||
dispatch({ type: "DELETE_PROJECT", projectId });
|
||||
},
|
||||
[api, dispatch, state.projects, state.threads],
|
||||
);
|
||||
@@ -499,7 +455,7 @@ export default function Sidebar() {
|
||||
return;
|
||||
}
|
||||
const firstProject = state.projects[0];
|
||||
if (firstProject) handleNewThread(firstProject.id);
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
}}
|
||||
>
|
||||
<span className="text-foreground">+</span>
|
||||
@@ -614,7 +570,9 @@ export default function Sidebar() {
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
|
||||
onClick={() => handleNewThread(project.id)}
|
||||
onClick={() => {
|
||||
void handleNewThread(project.id);
|
||||
}}
|
||||
>
|
||||
<span>+</span> New thread
|
||||
</button>
|
||||
|
||||
+25
-105
@@ -4,18 +4,16 @@ import {
|
||||
type ErrorComponentProps,
|
||||
useParams,
|
||||
} from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
import { QueryClient } 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";
|
||||
import { type AppState, useStore } from "../store";
|
||||
import { onServerStateUpdate, onServerWelcome } from "../wsNativeApi";
|
||||
|
||||
export const Route = createRootRouteWithContext<{
|
||||
queryClient: QueryClient;
|
||||
@@ -125,7 +123,6 @@ 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,
|
||||
@@ -133,78 +130,41 @@ function EventRouter() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
let cancelled = false;
|
||||
void api.core
|
||||
.getSnapshot()
|
||||
.then((snapshot) => {
|
||||
if (cancelled) return;
|
||||
dispatch({ type: "APPLY_CORE_SNAPSHOT", 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);
|
||||
}
|
||||
let mounted = true;
|
||||
void api.state.getSnapshot().then((snapshot) => {
|
||||
if (!mounted) return;
|
||||
dispatch({ type: "SET_SERVER_STATE", state: snapshot as AppState });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribeCore();
|
||||
mounted = false;
|
||||
};
|
||||
}, [api, dispatch, queryClient]);
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
return onServerStateUpdate((snapshot) => {
|
||||
dispatch({ type: "SET_SERVER_STATE", state: snapshot as AppState });
|
||||
});
|
||||
}, [dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "MARK_THREAD_VISITED",
|
||||
threadId: activeThreadId,
|
||||
visitedAt: new Date().toISOString(),
|
||||
});
|
||||
}, [activeThreadId, dispatch]);
|
||||
const visitedAt = new Date().toISOString();
|
||||
if (!api) return;
|
||||
void api.state.markThreadVisited({ threadId: activeThreadId, visitedAt });
|
||||
}, [activeThreadId, api]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function AutoProjectBootstrap() {
|
||||
const { state, dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
const { dispatch } = useStore();
|
||||
|
||||
useEffect(() => {
|
||||
// Browser mode bootstraps from server welcome.
|
||||
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
|
||||
if (isElectron) return;
|
||||
|
||||
return onServerWelcome((payload) => {
|
||||
if (bootstrappedRef.current) return;
|
||||
|
||||
// Don't create duplicate projects for the same cwd
|
||||
const existing = state.projects.find((project) => project.cwd === payload.cwd);
|
||||
if (existing) {
|
||||
bootstrappedRef.current = true;
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
return;
|
||||
}
|
||||
|
||||
bootstrappedRef.current = true;
|
||||
|
||||
// Create project + thread from server cwd
|
||||
const projectId = crypto.randomUUID();
|
||||
dispatch({
|
||||
type: "ADD_PROJECT",
|
||||
project: {
|
||||
id: projectId,
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
});
|
||||
return onServerWelcome(() => {
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
});
|
||||
}, [state.projects, dispatch]);
|
||||
}, [dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -212,50 +172,10 @@ function AutoProjectBootstrap() {
|
||||
function DesktopProjectBootstrap() {
|
||||
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);
|
||||
}
|
||||
};
|
||||
if (!isElectron || !api) return;
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,935 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
derivePendingApprovals,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTurnDiffSummaries,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { ChatMessage } from "./types";
|
||||
|
||||
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
|
||||
return {
|
||||
id: "evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
method: "noop",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-08T09:59:00.000Z",
|
||||
updatedAt: "2026-02-08T09:59:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
it("interleaves messages and work entries by timestamp", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: "m-user",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-assistant",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:05:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const workEntries: WorkLogEntry[] = [
|
||||
{
|
||||
id: "w-1",
|
||||
label: "Tool call",
|
||||
createdAt: "2026-02-08T10:02:00.000Z",
|
||||
tone: "tool",
|
||||
},
|
||||
{
|
||||
id: "w-2",
|
||||
label: "Preamble",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
tone: "thinking",
|
||||
},
|
||||
];
|
||||
|
||||
const timeline = deriveTimelineEntries(messages, workEntries);
|
||||
|
||||
expect(timeline.map((entry) => entry.id)).toEqual([
|
||||
"message:m-user",
|
||||
"work:w-1",
|
||||
"work:w-2",
|
||||
"message:m-assistant",
|
||||
]);
|
||||
});
|
||||
|
||||
it("prefers work entries when timestamps are equal", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const workEntries: WorkLogEntry[] = [
|
||||
{
|
||||
id: "w-1",
|
||||
label: "Tool call",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
tone: "tool",
|
||||
},
|
||||
];
|
||||
|
||||
const timeline = deriveTimelineEntries(messages, workEntries);
|
||||
|
||||
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries", () => {
|
||||
it("drops preamble/work events from the visible work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-1",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: { item: { type: "preamble", text: "thinking" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-2",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { item: { type: "work", text: "planning" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-3",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: { item: { type: "tool_call", command: "ls -la" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Tool call");
|
||||
});
|
||||
|
||||
it("does not surface successful turn completion as a work-log row", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:10.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("shows failed turn completion in the work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:10.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "failed",
|
||||
error: { message: "sandbox denied" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Turn failed");
|
||||
expect(entries[0]?.detail).toBe("sandbox denied");
|
||||
});
|
||||
|
||||
it("hides reasoning and agent-message noise from the visible work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-summary-part",
|
||||
method: "item/reasoning/summaryPartAdded",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-summary-delta",
|
||||
method: "item/reasoning/summaryTextDelta",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-msg",
|
||||
type: "agentMessage",
|
||||
text: "Done response",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-tool-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:06.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:08.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
|
||||
});
|
||||
|
||||
it("coalesces command start/completed lifecycle into one entry", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-command-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-command",
|
||||
type: "command_execution",
|
||||
command: "git status --short",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-command-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-command",
|
||||
type: "command_execution",
|
||||
command: "git status --short",
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Command run");
|
||||
expect(entries[0]?.detail).toBe("git status --short");
|
||||
});
|
||||
|
||||
it("preserves full tool-call detail text without data truncation", () => {
|
||||
const longCommand =
|
||||
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: longCommand },
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries[0]?.detail).toBe(longCommand);
|
||||
});
|
||||
|
||||
it("hides generic tool-call rows that have no identifying detail", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call" },
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("includes collab tool-call rows with tool name detail", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-collab-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-collab",
|
||||
type: "collabAgentToolCall",
|
||||
tool: "spawnAgent",
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Tool call");
|
||||
expect(entries[0]?.detail).toBe("spawnAgent");
|
||||
});
|
||||
|
||||
it("can derive work-log entries across all turns when not scoped", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-turn-1-tool",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { item: { type: "tool_call", command: "ls -la" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-tool",
|
||||
method: "item/started",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: { item: { type: "tool_call", command: "pwd" } },
|
||||
}),
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffSummaries", () => {
|
||||
it("tracks completed turns and links them to assistant message completion", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/a.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-updated",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
threadId: "thr-1",
|
||||
turnId: "turn-1",
|
||||
diff: [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -0,0 +1 @@",
|
||||
"+created",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-msg",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "msg-1",
|
||||
type: "agentMessage",
|
||||
text: "Done",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change-2",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/unfinished.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(summaries[0]?.files[0]?.kind).toBe("modified");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
expect(summaries[0]).not.toHaveProperty("unifiedDiff");
|
||||
});
|
||||
|
||||
it("includes completed turns even when no fileChange tool events were emitted", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.files).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps newest diff data when older events provide stale values", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-old",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1,2 @@",
|
||||
"-old",
|
||||
"+older",
|
||||
"+extra",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-new",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+newest",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.files[0]?.path).toBe("src/example.ts");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("splits a multi-file patch into sorted per-file entries", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-b",
|
||||
"+new-b",
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-a",
|
||||
"+new-a",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(files[0]?.additions).toBe(1);
|
||||
expect(files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
it("parses git headers when file paths include ` b/`", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
|
||||
"--- a/subdir b/example.ts",
|
||||
"+++ b/subdir b/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]?.path).toBe("subdir b/example.ts");
|
||||
});
|
||||
|
||||
it("parses git header fallback for binary diffs with ` b/` in path", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/subdir b/image.png b/subdir b/image.png",
|
||||
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]?.path).toBe("subdir b/image.png");
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePendingApprovals", () => {
|
||||
it("returns pending command/file-change approvals", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
makeEvent({
|
||||
id: "evt-request",
|
||||
kind: "request",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "req-1",
|
||||
requestKind: "command",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: { command: "git commit -m 'msg'" },
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(approvals).toEqual([
|
||||
{
|
||||
requestId: "req-1",
|
||||
requestKind: "command",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
detail: "git commit -m 'msg'",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("removes approvals after a decision event", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
makeEvent({
|
||||
id: "evt-decision",
|
||||
method: "item/requestApproval/decision",
|
||||
requestId: "req-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-request",
|
||||
kind: "request",
|
||||
method: "item/fileChange/requestApproval",
|
||||
requestId: "req-1",
|
||||
requestKind: "file-change",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(approvals).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("clears pending approvals after turn completion", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
makeEvent({
|
||||
id: "evt-turn-complete",
|
||||
method: "turn/completed",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-request",
|
||||
kind: "request",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "req-1",
|
||||
requestKind: "command",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(approvals).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evolveSession", () => {
|
||||
it("updates thread id when thread starts", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "thread/started",
|
||||
createdAt: "2026-02-08T10:01:00.000Z",
|
||||
payload: { thread: { id: "thread-1" } },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threadId).toBe("thread-1");
|
||||
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
|
||||
});
|
||||
|
||||
it("moves to running and records active turn on turn start", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:02:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("running");
|
||||
expect(next.activeTurnId).toBe("turn-1");
|
||||
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
|
||||
});
|
||||
|
||||
it("returns to ready and clears active turn on successful completion", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: "older error",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/completed",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("ready");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
expect(next.lastError).toBe("older error");
|
||||
});
|
||||
|
||||
it("marks session as error when turn fails", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/completed",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
payload: {
|
||||
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("error");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
expect(next.lastError).toBe("boom");
|
||||
});
|
||||
|
||||
it("moves to error on runtime error events", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
kind: "error",
|
||||
method: "runtime/error",
|
||||
createdAt: "2026-02-08T10:04:00.000Z",
|
||||
message: "runtime failure",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("error");
|
||||
expect(next.lastError).toBe("runtime failure");
|
||||
});
|
||||
|
||||
it("closes session on close lifecycle events", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "session/closed",
|
||||
createdAt: "2026-02-08T10:05:00.000Z",
|
||||
message: "closed",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("closed");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
expect(next.lastError).toBe("closed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyEventToMessages", () => {
|
||||
it("handles start/delta/completed flow for assistant messages", () => {
|
||||
const activeAssistantItemRef = { current: null as string | null };
|
||||
const started = applyEventToMessages(
|
||||
[],
|
||||
makeEvent({
|
||||
method: "item/started",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-1",
|
||||
type: "agentMessage",
|
||||
text: "Hello",
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
|
||||
expect(started).toEqual([
|
||||
{
|
||||
id: "item-1",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
]);
|
||||
expect(activeAssistantItemRef.current).toBe("item-1");
|
||||
|
||||
const withDelta = applyEventToMessages(
|
||||
started,
|
||||
makeEvent({
|
||||
method: "item/agentMessage/delta",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
itemId: "item-1",
|
||||
textDelta: " world",
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
expect(withDelta[0]?.text).toBe("Hello world");
|
||||
expect(withDelta[0]?.streaming).toBe(true);
|
||||
|
||||
const completed = applyEventToMessages(
|
||||
withDelta,
|
||||
makeEvent({
|
||||
method: "item/completed",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-1",
|
||||
type: "agentMessage",
|
||||
text: "Hello world!",
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
expect(completed[0]?.text).toBe("Hello world!");
|
||||
expect(completed[0]?.streaming).toBe(false);
|
||||
expect(activeAssistantItemRef.current).toBeNull();
|
||||
});
|
||||
|
||||
it("supports out-of-order delta before started/completed", () => {
|
||||
const activeAssistantItemRef = { current: null as string | null };
|
||||
const withDelta = applyEventToMessages(
|
||||
[],
|
||||
makeEvent({
|
||||
method: "item/agentMessage/delta",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
itemId: "item-2",
|
||||
textDelta: "Partial",
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
expect(withDelta[0]?.id).toBe("item-2");
|
||||
expect(withDelta[0]?.text).toBe("Partial");
|
||||
expect(withDelta[0]?.streaming).toBe(true);
|
||||
expect(activeAssistantItemRef.current).toBe("item-2");
|
||||
|
||||
const completed = applyEventToMessages(
|
||||
withDelta,
|
||||
makeEvent({
|
||||
method: "item/completed",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-2",
|
||||
type: "agentMessage",
|
||||
text: "Partial + final",
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
|
||||
expect(completed[0]?.text).toBe("Partial + final");
|
||||
expect(completed[0]?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("clears all streaming flags when turn completes", () => {
|
||||
const previous: ChatMessage[] = [
|
||||
{
|
||||
id: "m-user",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-assistant",
|
||||
role: "assistant",
|
||||
text: "Typing",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
|
||||
const next = applyEventToMessages(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/completed",
|
||||
}),
|
||||
{ current: null },
|
||||
);
|
||||
|
||||
expect(next.every((entry) => entry.streaming === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
+10
-190
@@ -7,17 +7,10 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
type CoreReadModelSnapshot,
|
||||
type CoreThreadMessageView,
|
||||
type CoreViewDelta,
|
||||
type ProviderSession,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
import { 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,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
@@ -28,29 +21,14 @@ 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: "SET_SERVER_STATE"; state: AppState }
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
| { type: "SET_THREADS_HYDRATED"; hydrated: boolean }
|
||||
| { type: "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 }
|
||||
@@ -117,84 +95,8 @@ function readPersistedState(): AppState {
|
||||
return initialState;
|
||||
}
|
||||
|
||||
function mapCoreMessageToChatMessage(message: CoreThreadMessageView): Thread["messages"][number] {
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
};
|
||||
}
|
||||
|
||||
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 persistState(state: AppState): void {
|
||||
void state;
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
@@ -395,6 +297,12 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "SET_SERVER_STATE":
|
||||
return {
|
||||
...action.state,
|
||||
threads: action.state.threads.map((thread) => normalizeThreadTerminals(thread)),
|
||||
};
|
||||
|
||||
case "ADD_PROJECT":
|
||||
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
|
||||
return state;
|
||||
@@ -430,94 +338,6 @@ 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;
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
case "SYNC_PROJECTS": {
|
||||
const previousByCwd = new Map(
|
||||
state.projects.map((project) => [project.cwd, project] as const),
|
||||
|
||||
@@ -5,7 +5,9 @@ import { WsTransport } from "./wsTransport";
|
||||
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
const stateListeners = new Set<(state: unknown) => void>();
|
||||
let lastWelcome: WsWelcomePayload | null = null;
|
||||
let lastStateSnapshot: unknown = null;
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
@@ -29,6 +31,20 @@ export function onServerWelcome(listener: (payload: WsWelcomePayload) => void):
|
||||
};
|
||||
}
|
||||
|
||||
export function onServerStateUpdate(listener: (state: unknown) => void): () => void {
|
||||
stateListeners.add(listener);
|
||||
if (lastStateSnapshot) {
|
||||
try {
|
||||
listener(lastStateSnapshot);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
stateListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
if (instance) return instance.api;
|
||||
|
||||
@@ -47,6 +63,16 @@ export function createWsNativeApi(): NativeApi {
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.stateUpdated, (data) => {
|
||||
lastStateSnapshot = data;
|
||||
for (const listener of stateListeners) {
|
||||
try {
|
||||
listener(data);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const api: NativeApi = {
|
||||
todos: {
|
||||
@@ -95,8 +121,7 @@ export function createWsNativeApi(): NativeApi {
|
||||
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),
|
||||
onEvent: () => () => {},
|
||||
},
|
||||
projects: {
|
||||
list: () => transport.request(WS_METHODS.projectsList),
|
||||
@@ -149,11 +174,12 @@ export function createWsNativeApi(): NativeApi {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
},
|
||||
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),
|
||||
state: {
|
||||
getSnapshot: () => transport.request(WS_METHODS.stateGetSnapshot),
|
||||
createThread: (input) => transport.request(WS_METHODS.stateCreateThread, input),
|
||||
deleteThread: (input) => transport.request(WS_METHODS.stateDeleteThread, input),
|
||||
markThreadVisited: (input) => transport.request(WS_METHODS.stateMarkThreadVisited, input),
|
||||
setRuntimeMode: (input) => transport.request(WS_METHODS.stateSetRuntimeMode, input),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -34,10 +34,9 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/schema": "^0.75.5",
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"effect": "^3.19.19",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
@@ -98,6 +97,33 @@
|
||||
"typescript": "^5.7.3",
|
||||
},
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@t3tools/core",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"effect": "^3.18.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
"packages/infra-sqlite": {
|
||||
"name": "@t3tools/infra-sqlite",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
@@ -152,8 +178,6 @@
|
||||
|
||||
"@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=="],
|
||||
@@ -444,8 +468,12 @@
|
||||
|
||||
"@t3tools/contracts": ["@t3tools/contracts@workspace:packages/contracts"],
|
||||
|
||||
"@t3tools/core": ["@t3tools/core@workspace:packages/core"],
|
||||
|
||||
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@t3tools/infra-sqlite": ["@t3tools/infra-sqlite@workspace:packages/infra-sqlite"],
|
||||
|
||||
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
|
||||
|
||||
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
|
||||
@@ -544,7 +572,7 @@
|
||||
|
||||
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
|
||||
|
||||
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
"@types/node": ["@types/node@25.3.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A=="],
|
||||
|
||||
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
|
||||
|
||||
@@ -1344,7 +1372,7 @@
|
||||
|
||||
"unconfig-core": ["[email protected]", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-VgPCvLWugINbXvMQDf8Jh0mlbvNjNC6eSUziHsBCMpxR05OPrNrvDnyatdMjRgcHaaNsCqz+wjNXxNw1kRLHUg=="],
|
||||
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
@@ -1444,6 +1472,8 @@
|
||||
|
||||
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@t3tools/desktop/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -1468,6 +1498,16 @@
|
||||
|
||||
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
|
||||
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
@@ -1494,6 +1534,8 @@
|
||||
|
||||
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
|
||||
|
||||
"t3/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
|
||||
|
||||
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
@@ -1502,6 +1544,8 @@
|
||||
|
||||
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"@t3tools/desktop/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
|
||||
@@ -1524,8 +1568,20 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"electron/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"t3/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
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>;
|
||||
@@ -9,4 +9,3 @@ export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
export * from "./core";
|
||||
@@ -1,11 +1,4 @@
|
||||
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
|
||||
import type {
|
||||
CoreDispatchInput,
|
||||
CoreDispatchResult,
|
||||
CoreGetSnapshotInput,
|
||||
CoreReadModelSnapshot,
|
||||
CoreViewDelta,
|
||||
} from "./core";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
@@ -49,6 +42,7 @@ import type {
|
||||
ProjectUpdateScriptsResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
type RuntimeMode = "approval-required" | "full-access";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -147,9 +141,19 @@ export interface NativeApi {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
};
|
||||
core: {
|
||||
getSnapshot: (input?: CoreGetSnapshotInput) => Promise<CoreReadModelSnapshot>;
|
||||
dispatch: (input: CoreDispatchInput) => Promise<CoreDispatchResult>;
|
||||
onViewDelta: (callback: (delta: CoreViewDelta) => void) => () => void;
|
||||
state: {
|
||||
getSnapshot: () => Promise<unknown>;
|
||||
createThread: (input: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}) => Promise<unknown>;
|
||||
deleteThread: (input: { id: string }) => Promise<unknown>;
|
||||
markThreadVisited: (input: { threadId: string; visitedAt?: string }) => Promise<unknown>;
|
||||
setRuntimeMode: (input: { mode: RuntimeMode }) => Promise<unknown>;
|
||||
};
|
||||
}
|
||||
@@ -46,6 +46,7 @@ export const providerSessionSchema = z.object({
|
||||
});
|
||||
|
||||
export const providerSessionStartInputSchema = z.object({
|
||||
uiThreadId: z.string().trim().min(1).optional(),
|
||||
provider: providerKindSchema.default("codex"),
|
||||
cwd: z.string().min(1).optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
@@ -80,6 +81,7 @@ export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type"
|
||||
|
||||
export const providerSendTurnInputSchema = z
|
||||
.object({
|
||||
uiThreadId: z.string().trim().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
|
||||
attachments: z
|
||||
|
||||
@@ -47,9 +47,12 @@ export const WS_METHODS = {
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
|
||||
// Core event-sourced views
|
||||
coreGetSnapshot: "core.getSnapshot",
|
||||
coreDispatch: "core.dispatch",
|
||||
// Server-authoritative state
|
||||
stateGetSnapshot: "state.getSnapshot",
|
||||
stateCreateThread: "state.createThread",
|
||||
stateDeleteThread: "state.deleteThread",
|
||||
stateMarkThreadVisited: "state.markThreadVisited",
|
||||
stateSetRuntimeMode: "state.setRuntimeMode",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
@@ -58,7 +61,7 @@ export const WS_CHANNELS = {
|
||||
providerEvent: "providers.event",
|
||||
terminalEvent: "terminal.event",
|
||||
serverWelcome: "server.welcome",
|
||||
coreViewDelta: "core.viewDelta",
|
||||
stateUpdated: "state.updated",
|
||||
} as const;
|
||||
|
||||
// ── Client → Server (request) ────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@t3tools/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "^3.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import type { NewDomainEvent } from "../domain/events";
|
||||
import type { AppViewState } from "../domain/models";
|
||||
|
||||
function eventFromCommand(
|
||||
command: AnyDomainCommand,
|
||||
eventType: NewDomainEvent["type"],
|
||||
payload: NewDomainEvent["payload"],
|
||||
streamId: string,
|
||||
): NewDomainEvent {
|
||||
return {
|
||||
streamId,
|
||||
type: eventType,
|
||||
payload,
|
||||
occurredAt: command.issuedAt,
|
||||
...(command.id ? { causationId: command.id } : {}),
|
||||
...(command.correlationId ? { correlationId: command.correlationId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function streamIdFromCommand(command: AnyDomainCommand): string {
|
||||
switch (command.type) {
|
||||
case "app.bootstrap":
|
||||
case "runtime.setMode":
|
||||
return "app";
|
||||
case "project.add":
|
||||
case "project.remove":
|
||||
case "project.updateScripts":
|
||||
return `project:${command.payload.id}`;
|
||||
case "thread.create":
|
||||
case "thread.delete":
|
||||
return `thread:${command.payload.id}`;
|
||||
case "thread.addUserMessage":
|
||||
case "thread.updateProviderSession":
|
||||
case "thread.recordProviderEvent":
|
||||
case "thread.setBranch":
|
||||
case "thread.setTerminalActivity":
|
||||
case "thread.markVisited":
|
||||
return `thread:${command.payload.threadId}`;
|
||||
default:
|
||||
return "app";
|
||||
}
|
||||
}
|
||||
|
||||
export function decide(command: AnyDomainCommand, currentState: AppViewState): ReadonlyArray<NewDomainEvent> {
|
||||
switch (command.type) {
|
||||
case "app.bootstrap": {
|
||||
if (currentState.projects.length > 0) return [];
|
||||
return [eventFromCommand(command, "app.bootstrapped", command.payload, streamIdFromCommand(command))];
|
||||
}
|
||||
case "project.add":
|
||||
return [eventFromCommand(command, "project.added", command.payload, streamIdFromCommand(command))];
|
||||
case "project.remove":
|
||||
return [eventFromCommand(command, "project.removed", command.payload, streamIdFromCommand(command))];
|
||||
case "project.updateScripts":
|
||||
return [eventFromCommand(command, "project.scriptsUpdated", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.create":
|
||||
return [eventFromCommand(command, "thread.created", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.delete":
|
||||
return [eventFromCommand(command, "thread.deleted", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.addUserMessage":
|
||||
return [eventFromCommand(command, "thread.userMessageAdded", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.updateProviderSession":
|
||||
return [eventFromCommand(command, "thread.providerSessionUpdated", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.recordProviderEvent":
|
||||
return [eventFromCommand(command, "thread.providerEventRecorded", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.setBranch":
|
||||
return [eventFromCommand(command, "thread.branchSet", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.setTerminalActivity":
|
||||
return [eventFromCommand(command, "thread.terminalActivitySet", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.markVisited":
|
||||
return [eventFromCommand(command, "thread.markVisited", command.payload, streamIdFromCommand(command))];
|
||||
case "runtime.setMode":
|
||||
return [eventFromCommand(command, "runtime.modeSet", command.payload, streamIdFromCommand(command))];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { emptyAppViewState, type AppViewState } from "../domain/models";
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import { decide } from "./decide";
|
||||
import type { EventStorePort, ProjectionStorePort } from "../ports";
|
||||
import { QueueProjector } from "./projector";
|
||||
import { reduceEvents } from "../projections/reducer";
|
||||
|
||||
export class OrchestrationEngine {
|
||||
constructor(
|
||||
private readonly eventStore: EventStorePort,
|
||||
projectionStore: ProjectionStorePort,
|
||||
private readonly projector: QueueProjector,
|
||||
) {
|
||||
this.projectionStore = projectionStore;
|
||||
}
|
||||
|
||||
private readonly projectionStore: ProjectionStorePort;
|
||||
|
||||
async start(): Promise<void> {
|
||||
const state = await this.projectionStore.readState();
|
||||
if (!state) {
|
||||
const allEvents = await this.eventStore.loadAll();
|
||||
const next = allEvents.length === 0 ? emptyAppViewState() : reduceEvents(allEvents, emptyAppViewState());
|
||||
await this.projectionStore.writeState(next);
|
||||
}
|
||||
await this.projector.start();
|
||||
const pending = await this.eventStore.loadAfterPosition((await this.currentState()).lastPosition);
|
||||
if (pending.length > 0) {
|
||||
await this.projector.enqueue(pending);
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.projector.stop();
|
||||
}
|
||||
|
||||
async execute(command: AnyDomainCommand): Promise<AppViewState> {
|
||||
const current = await this.currentState();
|
||||
const pending = decide(command, current);
|
||||
if (pending.length === 0) return current;
|
||||
const appended = await this.eventStore.append(pending);
|
||||
await this.projector.enqueue(appended);
|
||||
return this.currentState();
|
||||
}
|
||||
|
||||
async currentState(): Promise<AppViewState> {
|
||||
return this.projector.readState();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { StateUpdatedNotification } from "../domain/events";
|
||||
import type { FanoutPort } from "../ports";
|
||||
|
||||
interface Sink<T> {
|
||||
push(value: T): void;
|
||||
close(): void;
|
||||
iterable: AsyncIterable<T>;
|
||||
}
|
||||
|
||||
function createSink<T>(): Sink<T> {
|
||||
const queue: T[] = [];
|
||||
const waiters: Array<(value: IteratorResult<T>) => void> = [];
|
||||
let closed = false;
|
||||
const push = (value: T) => {
|
||||
if (closed) return;
|
||||
const waiter = waiters.shift();
|
||||
if (waiter) {
|
||||
waiter({ value, done: false });
|
||||
return;
|
||||
}
|
||||
queue.push(value);
|
||||
};
|
||||
const close = () => {
|
||||
closed = true;
|
||||
while (waiters.length > 0) {
|
||||
const waiter = waiters.shift();
|
||||
waiter?.({ value: undefined as never, done: true });
|
||||
}
|
||||
};
|
||||
const iterable: AsyncIterable<T> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
async next() {
|
||||
if (queue.length > 0) {
|
||||
return { value: queue.shift() as T, done: false };
|
||||
}
|
||||
if (closed) {
|
||||
return { value: undefined as never, done: true };
|
||||
}
|
||||
return new Promise<IteratorResult<T>>((resolve) => {
|
||||
waiters.push(resolve);
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
return { push, close, iterable };
|
||||
}
|
||||
|
||||
export class EffectFanout implements FanoutPort {
|
||||
private readonly sinks = new Set<Sink<StateUpdatedNotification>>();
|
||||
|
||||
async publish(notification: StateUpdatedNotification): Promise<void> {
|
||||
for (const sink of this.sinks) {
|
||||
sink.push(notification);
|
||||
}
|
||||
}
|
||||
|
||||
async subscribe(): Promise<AsyncIterable<StateUpdatedNotification>> {
|
||||
const sink = createSink<StateUpdatedNotification>();
|
||||
this.sinks.add(sink);
|
||||
return sink.iterable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { DomainEventEnvelope } from "../domain/events";
|
||||
import { emptyAppViewState, type AppViewState } from "../domain/models";
|
||||
import type { FanoutPort, ProjectionStorePort } from "../ports";
|
||||
import { reduceEvents } from "../projections/reducer";
|
||||
|
||||
export class QueueProjector {
|
||||
private readonly queue: ReadonlyArray<DomainEventEnvelope>[] = [];
|
||||
private processing = false;
|
||||
private stopSignal = false;
|
||||
|
||||
constructor(
|
||||
private readonly projectionStore: ProjectionStorePort,
|
||||
private readonly fanout: FanoutPort,
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.processing) return;
|
||||
this.stopSignal = false;
|
||||
this.processing = true;
|
||||
void this.drain();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopSignal = true;
|
||||
this.processing = false;
|
||||
}
|
||||
|
||||
async enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void> {
|
||||
if (events.length === 0) return;
|
||||
this.queue.push(events);
|
||||
if (this.processing) {
|
||||
void this.drain();
|
||||
}
|
||||
}
|
||||
|
||||
async readState(): Promise<AppViewState> {
|
||||
return (await this.projectionStore.readState()) ?? emptyAppViewState();
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
if (!this.processing) return;
|
||||
while (!this.stopSignal && this.queue.length > 0) {
|
||||
const chunk = this.queue.shift();
|
||||
if (!chunk || chunk.length === 0) continue;
|
||||
const current = (await this.projectionStore.readState()) ?? emptyAppViewState();
|
||||
const next = reduceEvents(chunk, current);
|
||||
await this.projectionStore.writeState(next);
|
||||
await this.fanout.publish({ state: next, events: chunk });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { ProjectScriptSchema, ProviderEventSchema, ProviderSessionViewSchema, RuntimeModeSchema } from "./models";
|
||||
|
||||
export const CommandTypeSchema = Schema.Literal(
|
||||
"app.bootstrap",
|
||||
"project.add",
|
||||
"project.remove",
|
||||
"project.updateScripts",
|
||||
"thread.create",
|
||||
"thread.delete",
|
||||
"thread.addUserMessage",
|
||||
"thread.updateProviderSession",
|
||||
"thread.recordProviderEvent",
|
||||
"thread.setBranch",
|
||||
"thread.setTerminalActivity",
|
||||
"thread.markVisited",
|
||||
"runtime.setMode",
|
||||
);
|
||||
export type CommandType = Schema.Schema.Type<typeof CommandTypeSchema>;
|
||||
|
||||
export interface DomainCommand<TPayload> {
|
||||
readonly id: string;
|
||||
readonly type: CommandType;
|
||||
readonly payload: TPayload;
|
||||
readonly issuedAt: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface AppBootstrapCommand
|
||||
extends DomainCommand<{
|
||||
cwd: string;
|
||||
projectName: string;
|
||||
}> {
|
||||
readonly type: "app.bootstrap";
|
||||
}
|
||||
|
||||
export interface ProjectAddCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
|
||||
}> {
|
||||
readonly type: "project.add";
|
||||
}
|
||||
|
||||
export interface ProjectRemoveCommand extends DomainCommand<{ id: string }> {
|
||||
readonly type: "project.remove";
|
||||
}
|
||||
|
||||
export interface ProjectUpdateScriptsCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
|
||||
}> {
|
||||
readonly type: "project.updateScripts";
|
||||
}
|
||||
|
||||
export interface ThreadCreateCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}> {
|
||||
readonly type: "thread.create";
|
||||
}
|
||||
|
||||
export interface ThreadDeleteCommand extends DomainCommand<{ id: string }> {
|
||||
readonly type: "thread.delete";
|
||||
}
|
||||
|
||||
export interface ThreadAddUserMessageCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}>;
|
||||
}> {
|
||||
readonly type: "thread.addUserMessage";
|
||||
}
|
||||
|
||||
export interface ThreadUpdateProviderSessionCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
session: Schema.Schema.Type<typeof ProviderSessionViewSchema> | null;
|
||||
}> {
|
||||
readonly type: "thread.updateProviderSession";
|
||||
}
|
||||
|
||||
export interface ThreadRecordProviderEventCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
event: Schema.Schema.Type<typeof ProviderEventSchema>;
|
||||
}> {
|
||||
readonly type: "thread.recordProviderEvent";
|
||||
}
|
||||
|
||||
export interface ThreadSetBranchCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}> {
|
||||
readonly type: "thread.setBranch";
|
||||
}
|
||||
|
||||
export interface ThreadSetTerminalActivityCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
running: boolean;
|
||||
}> {
|
||||
readonly type: "thread.setTerminalActivity";
|
||||
}
|
||||
|
||||
export interface ThreadMarkVisitedCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
visitedAt: string;
|
||||
}> {
|
||||
readonly type: "thread.markVisited";
|
||||
}
|
||||
|
||||
export interface RuntimeSetModeCommand
|
||||
extends DomainCommand<{
|
||||
mode: Schema.Schema.Type<typeof RuntimeModeSchema>;
|
||||
}> {
|
||||
readonly type: "runtime.setMode";
|
||||
}
|
||||
|
||||
export type AnyDomainCommand =
|
||||
| AppBootstrapCommand
|
||||
| ProjectAddCommand
|
||||
| ProjectRemoveCommand
|
||||
| ProjectUpdateScriptsCommand
|
||||
| ThreadCreateCommand
|
||||
| ThreadDeleteCommand
|
||||
| ThreadAddUserMessageCommand
|
||||
| ThreadUpdateProviderSessionCommand
|
||||
| ThreadRecordProviderEventCommand
|
||||
| ThreadSetBranchCommand
|
||||
| ThreadSetTerminalActivityCommand
|
||||
| ThreadMarkVisitedCommand
|
||||
| RuntimeSetModeCommand;
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import {
|
||||
type AppViewState,
|
||||
ProjectScriptSchema,
|
||||
ProviderEventSchema,
|
||||
ProviderSessionViewSchema,
|
||||
RuntimeModeSchema,
|
||||
} from "./models";
|
||||
|
||||
export const DomainEventTypeSchema = Schema.Literal(
|
||||
"app.bootstrapped",
|
||||
"project.added",
|
||||
"project.removed",
|
||||
"project.scriptsUpdated",
|
||||
"thread.created",
|
||||
"thread.deleted",
|
||||
"thread.userMessageAdded",
|
||||
"thread.providerSessionUpdated",
|
||||
"thread.providerEventRecorded",
|
||||
"thread.branchSet",
|
||||
"thread.terminalActivitySet",
|
||||
"thread.markVisited",
|
||||
"runtime.modeSet",
|
||||
);
|
||||
export type DomainEventType = Schema.Schema.Type<typeof DomainEventTypeSchema>;
|
||||
|
||||
const AppBootstrappedPayloadSchema = Schema.Struct({
|
||||
cwd: Schema.String,
|
||||
projectName: Schema.String,
|
||||
});
|
||||
|
||||
const ProjectAddedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
cwd: Schema.String,
|
||||
model: Schema.String,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
|
||||
const ProjectRemovedPayloadSchema = Schema.Struct({ id: Schema.String });
|
||||
|
||||
const ProjectScriptsUpdatedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
|
||||
const ThreadCreatedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
projectId: Schema.String,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ThreadDeletedPayloadSchema = Schema.Struct({ id: Schema.String });
|
||||
|
||||
const ThreadUserMessageAddedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
messageId: Schema.String,
|
||||
text: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
attachments: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
previewUrl: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const ThreadProviderSessionUpdatedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
session: Schema.NullOr(ProviderSessionViewSchema),
|
||||
});
|
||||
|
||||
const ThreadProviderEventRecordedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
event: ProviderEventSchema,
|
||||
});
|
||||
|
||||
const ThreadBranchSetPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ThreadTerminalActivitySetPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
running: Schema.Boolean,
|
||||
});
|
||||
|
||||
const ThreadMarkVisitedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
visitedAt: Schema.String,
|
||||
});
|
||||
|
||||
const RuntimeModeSetPayloadSchema = Schema.Struct({
|
||||
mode: RuntimeModeSchema,
|
||||
});
|
||||
|
||||
export type DomainEventPayload =
|
||||
| Schema.Schema.Type<typeof AppBootstrappedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectAddedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectRemovedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectScriptsUpdatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadCreatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadDeletedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadUserMessageAddedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadProviderSessionUpdatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadProviderEventRecordedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadBranchSetPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadTerminalActivitySetPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadMarkVisitedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof RuntimeModeSetPayloadSchema>;
|
||||
|
||||
export interface DomainEventEnvelope {
|
||||
readonly eventId: string;
|
||||
readonly streamId: string;
|
||||
readonly sequence: number;
|
||||
readonly position: number;
|
||||
readonly type: DomainEventType;
|
||||
readonly occurredAt: string;
|
||||
readonly payload: DomainEventPayload;
|
||||
readonly causationId?: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface NewDomainEvent {
|
||||
readonly streamId: string;
|
||||
readonly type: DomainEventType;
|
||||
readonly payload: DomainEventPayload;
|
||||
readonly occurredAt: string;
|
||||
readonly causationId?: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface StateUpdatedNotification {
|
||||
readonly state: AppViewState;
|
||||
readonly events: readonly DomainEventEnvelope[];
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const RuntimeModeSchema = Schema.Literal("approval-required", "full-access");
|
||||
export type RuntimeMode = Schema.Schema.Type<typeof RuntimeModeSchema>;
|
||||
|
||||
export const ProjectScriptSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
command: Schema.String,
|
||||
keybinding: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProjectScript = Schema.Schema.Type<typeof ProjectScriptSchema>;
|
||||
|
||||
export const ProjectViewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
cwd: Schema.String,
|
||||
model: Schema.String,
|
||||
expanded: Schema.Boolean,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
export type ProjectView = Schema.Schema.Type<typeof ProjectViewSchema>;
|
||||
|
||||
export const ChatAttachmentSchema = Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
previewUrl: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ChatAttachment = Schema.Schema.Type<typeof ChatAttachmentSchema>;
|
||||
|
||||
export const ChatMessageSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
role: Schema.Literal("user", "assistant"),
|
||||
text: Schema.String,
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachmentSchema)),
|
||||
createdAt: Schema.String,
|
||||
streaming: Schema.Boolean,
|
||||
});
|
||||
export type ChatMessage = Schema.Schema.Type<typeof ChatMessageSchema>;
|
||||
|
||||
export const SessionStatusSchema = Schema.Literal(
|
||||
"connecting",
|
||||
"ready",
|
||||
"running",
|
||||
"error",
|
||||
"closed",
|
||||
);
|
||||
export type SessionStatus = Schema.Schema.Type<typeof SessionStatusSchema>;
|
||||
|
||||
export const ProviderSessionViewSchema = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
provider: Schema.Literal("codex", "claudeCode"),
|
||||
status: SessionStatusSchema,
|
||||
cwd: Schema.optional(Schema.String),
|
||||
model: Schema.optional(Schema.String),
|
||||
threadId: Schema.optional(Schema.String),
|
||||
activeTurnId: Schema.optional(Schema.String),
|
||||
createdAt: Schema.String,
|
||||
updatedAt: Schema.String,
|
||||
lastError: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProviderSessionView = Schema.Schema.Type<typeof ProviderSessionViewSchema>;
|
||||
|
||||
export const ProviderEventSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
kind: Schema.Literal("session", "notification", "request", "error"),
|
||||
method: Schema.String,
|
||||
payload: Schema.optional(Schema.Unknown),
|
||||
createdAt: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
threadId: Schema.optional(Schema.String),
|
||||
turnId: Schema.optional(Schema.String),
|
||||
itemId: Schema.optional(Schema.String),
|
||||
textDelta: Schema.optional(Schema.String),
|
||||
requestId: Schema.optional(Schema.String),
|
||||
requestKind: Schema.optional(Schema.String),
|
||||
message: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProviderEvent = Schema.Schema.Type<typeof ProviderEventSchema>;
|
||||
|
||||
export const TurnDiffFileChangeSchema = Schema.Struct({
|
||||
path: Schema.String,
|
||||
kind: Schema.optional(Schema.String),
|
||||
additions: Schema.optional(Schema.Number),
|
||||
deletions: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type TurnDiffFileChange = Schema.Schema.Type<typeof TurnDiffFileChangeSchema>;
|
||||
|
||||
export const TurnDiffSummarySchema = Schema.Struct({
|
||||
turnId: Schema.String,
|
||||
completedAt: Schema.String,
|
||||
status: Schema.optional(Schema.String),
|
||||
files: Schema.Array(TurnDiffFileChangeSchema),
|
||||
assistantMessageId: Schema.optional(Schema.String),
|
||||
checkpointTurnCount: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type TurnDiffSummary = Schema.Schema.Type<typeof TurnDiffSummarySchema>;
|
||||
|
||||
export const ThreadTerminalGroupSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
terminalIds: Schema.Array(Schema.String),
|
||||
});
|
||||
export type ThreadTerminalGroup = Schema.Schema.Type<typeof ThreadTerminalGroupSchema>;
|
||||
|
||||
export const ThreadViewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
codexThreadId: Schema.NullOr(Schema.String),
|
||||
projectId: Schema.String,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
terminalOpen: Schema.Boolean,
|
||||
terminalHeight: Schema.Number,
|
||||
terminalIds: Schema.Array(Schema.String),
|
||||
runningTerminalIds: Schema.Array(Schema.String),
|
||||
activeTerminalId: Schema.String,
|
||||
terminalGroups: Schema.Array(ThreadTerminalGroupSchema),
|
||||
activeTerminalGroupId: Schema.String,
|
||||
session: Schema.NullOr(ProviderSessionViewSchema),
|
||||
messages: Schema.Array(ChatMessageSchema),
|
||||
events: Schema.Array(ProviderEventSchema),
|
||||
error: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.String,
|
||||
latestTurnId: Schema.optional(Schema.String),
|
||||
latestTurnStartedAt: Schema.optional(Schema.String),
|
||||
latestTurnCompletedAt: Schema.optional(Schema.String),
|
||||
latestTurnDurationMs: Schema.optional(Schema.Number),
|
||||
lastVisitedAt: Schema.optional(Schema.String),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
turnDiffSummaries: Schema.Array(TurnDiffSummarySchema),
|
||||
});
|
||||
export type ThreadView = Schema.Schema.Type<typeof ThreadViewSchema>;
|
||||
|
||||
export const AppViewStateSchema = Schema.Struct({
|
||||
projects: Schema.Array(ProjectViewSchema),
|
||||
threads: Schema.Array(ThreadViewSchema),
|
||||
threadsHydrated: Schema.Boolean,
|
||||
runtimeMode: RuntimeModeSchema,
|
||||
lastPosition: Schema.Number,
|
||||
});
|
||||
export type AppViewState = Schema.Schema.Type<typeof AppViewStateSchema>;
|
||||
|
||||
export const emptyAppViewState = (): AppViewState => ({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: "full-access",
|
||||
lastPosition: 0,
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { AppViewState } from "./models";
|
||||
|
||||
export type DomainQuery = { readonly type: "app.getState" };
|
||||
|
||||
export interface QueryResultMap {
|
||||
"app.getState": AppViewState;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export * from "./domain/models";
|
||||
export * from "./domain/commands";
|
||||
export * from "./domain/events";
|
||||
export * from "./domain/queries";
|
||||
export * from "./ports";
|
||||
export * from "./projections/reducer";
|
||||
export * from "./application/decide";
|
||||
export * from "./application/fanout";
|
||||
export * from "./application/projector";
|
||||
export * from "./application/engine";
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import type { DomainEventEnvelope, NewDomainEvent, StateUpdatedNotification } from "../domain/events";
|
||||
import type { AppViewState } from "../domain/models";
|
||||
|
||||
export interface EventStorePort {
|
||||
append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
}
|
||||
|
||||
export interface ProjectionStorePort {
|
||||
readState(): Promise<AppViewState | null>;
|
||||
writeState(state: AppViewState): Promise<void>;
|
||||
}
|
||||
|
||||
export interface FanoutPort {
|
||||
publish(notification: StateUpdatedNotification): Promise<void>;
|
||||
subscribe(): Promise<AsyncIterable<StateUpdatedNotification>>;
|
||||
}
|
||||
|
||||
export interface DeterministicProjectorPort {
|
||||
start(): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void>;
|
||||
}
|
||||
|
||||
export interface CoreApplicationPort {
|
||||
execute(command: AnyDomainCommand): Promise<AppViewState>;
|
||||
currentState(): Promise<AppViewState>;
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
import type { DomainEventEnvelope } from "../domain/events";
|
||||
import type { AppViewState, ChatMessage, ProviderEvent, ProviderSessionView, ThreadView } from "../domain/models";
|
||||
import { emptyAppViewState } from "../domain/models";
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function eventTurnId(event: ProviderEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const turn = asObject(asObject(event.payload)?.turn);
|
||||
return asString(turn?.id);
|
||||
}
|
||||
|
||||
function durationMs(startIso: string, endIso: string): number | undefined {
|
||||
const start = Date.parse(startIso);
|
||||
const end = Date.parse(endIso);
|
||||
if (Number.isNaN(start) || Number.isNaN(end) || end < start) return undefined;
|
||||
return end - start;
|
||||
}
|
||||
|
||||
function evolveSession(previous: ProviderSessionView, event: ProviderEvent): ProviderSessionView {
|
||||
const payload = asObject(event.payload);
|
||||
if (event.method === "thread/started") {
|
||||
const thread = asObject(payload?.thread);
|
||||
return { ...previous, threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId, updatedAt: event.createdAt };
|
||||
}
|
||||
if (event.method === "turn/started") {
|
||||
const turn = asObject(payload?.turn);
|
||||
return {
|
||||
...previous,
|
||||
status: "running",
|
||||
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.method === "turn/completed") {
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asObject(turn?.error);
|
||||
return {
|
||||
...previous,
|
||||
status: status === "failed" ? "error" : "ready",
|
||||
activeTurnId: undefined,
|
||||
lastError: asString(turnError?.message) ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.kind === "error") {
|
||||
return {
|
||||
...previous,
|
||||
status: "error",
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
return {
|
||||
...previous,
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
return { ...previous, updatedAt: event.createdAt };
|
||||
}
|
||||
|
||||
function applyEventToMessages(previous: ReadonlyArray<ChatMessage>, event: ProviderEvent): ChatMessage[] {
|
||||
const payload = asObject(event.payload);
|
||||
if (event.method === "item/started") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") return [...previous];
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) return [...previous];
|
||||
const seedText = asString(item?.text) ?? "";
|
||||
return [
|
||||
...previous.filter((entry) => entry.id !== itemId),
|
||||
{ id: itemId, role: "assistant", text: seedText, createdAt: event.createdAt, streaming: true },
|
||||
];
|
||||
}
|
||||
if (event.method === "item/agentMessage/delta") {
|
||||
const itemId = event.itemId ?? asString(payload?.itemId);
|
||||
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
|
||||
if (!itemId || !delta) return [...previous];
|
||||
const idx = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (idx < 0) {
|
||||
return [...previous, { id: itemId, role: "assistant", text: delta, createdAt: event.createdAt, streaming: true }];
|
||||
}
|
||||
const next = [...previous];
|
||||
const current = next[idx];
|
||||
if (!current) return [...previous];
|
||||
next[idx] = { ...current, text: `${current.text}${delta}`, streaming: true };
|
||||
return next;
|
||||
}
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") return [...previous];
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) return [...previous];
|
||||
const fullText = asString(item?.text);
|
||||
const idx = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (idx < 0) {
|
||||
return [...previous, { id: itemId, role: "assistant", text: fullText ?? "", createdAt: event.createdAt, streaming: false }];
|
||||
}
|
||||
const next = [...previous];
|
||||
const current = next[idx];
|
||||
if (!current) return [...previous];
|
||||
next[idx] = { ...current, text: fullText ?? current.text, streaming: false };
|
||||
return next;
|
||||
}
|
||||
if (event.method === "turn/completed") {
|
||||
return previous.map((entry) => ({ ...entry, streaming: false }));
|
||||
}
|
||||
return [...previous];
|
||||
}
|
||||
|
||||
function defaultThread(payload: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}): ThreadView {
|
||||
return {
|
||||
id: payload.id,
|
||||
codexThreadId: null,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: payload.createdAt,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
turnDiffSummaries: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function applyDomainEvent(state: AppViewState, event: DomainEventEnvelope): AppViewState {
|
||||
switch (event.type) {
|
||||
case "app.bootstrapped": {
|
||||
const payload = event.payload as { cwd: string; projectName: string };
|
||||
if (state.projects.length > 0) return { ...state, threadsHydrated: true, lastPosition: event.position };
|
||||
return {
|
||||
...state,
|
||||
projects: [
|
||||
{
|
||||
id: "bootstrap-project",
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: "gpt-5-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threadsHydrated: true,
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.added": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
|
||||
};
|
||||
if (state.projects.some((project) => project.id === payload.id || project.cwd === payload.cwd)) {
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
projects: [...state.projects, { ...payload, expanded: true }],
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.removed": {
|
||||
const payload = event.payload as { id: string };
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.filter((project) => project.id !== payload.id),
|
||||
threads: state.threads.filter((thread) => thread.projectId !== payload.id),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.scriptsUpdated": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((project) =>
|
||||
project.id === payload.id ? { ...project, scripts: payload.scripts } : project,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.created": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
if (state.threads.some((thread) => thread.id === payload.id)) {
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
return { ...state, threads: [...state.threads, defaultThread(payload)], lastPosition: event.position };
|
||||
}
|
||||
case "thread.deleted": {
|
||||
const payload = event.payload as { id: string };
|
||||
return { ...state, threads: state.threads.filter((thread) => thread.id !== payload.id), lastPosition: event.position };
|
||||
}
|
||||
case "thread.userMessageAdded": {
|
||||
const payload = event.payload as {
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}>;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? {
|
||||
...thread,
|
||||
messages: [
|
||||
...thread.messages,
|
||||
{
|
||||
id: payload.messageId,
|
||||
role: "user",
|
||||
text: payload.text,
|
||||
attachments: payload.attachments ? [...payload.attachments] : undefined,
|
||||
createdAt: payload.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.providerSessionUpdated": {
|
||||
const payload = event.payload as { threadId: string; session: ProviderSessionView | null };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? {
|
||||
...thread,
|
||||
session: payload.session,
|
||||
codexThreadId: payload.session?.threadId ?? thread.codexThreadId,
|
||||
...(payload.session ? {} : { events: [], messages: [], turnDiffSummaries: [] }),
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.providerEventRecorded": {
|
||||
const payload = event.payload as { threadId: string; event: ProviderEvent };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) => {
|
||||
if (thread.id !== payload.threadId) return thread;
|
||||
const nextEvents = [payload.event, ...thread.events];
|
||||
const nextSession = thread.session ? evolveSession(thread.session, payload.event) : thread.session;
|
||||
const nextMessages = applyEventToMessages(thread.messages, payload.event);
|
||||
const nextTurnId = payload.event.method === "turn/started" ? eventTurnId(payload.event) ?? thread.latestTurnId : thread.latestTurnId;
|
||||
const nextTurnStartedAt = payload.event.method === "turn/started" ? payload.event.createdAt : thread.latestTurnStartedAt;
|
||||
const nextTurnCompletedAt = payload.event.method === "turn/completed" ? payload.event.createdAt : thread.latestTurnCompletedAt;
|
||||
const nextTurnDuration =
|
||||
payload.event.method === "turn/completed" && thread.latestTurnStartedAt
|
||||
? durationMs(thread.latestTurnStartedAt, payload.event.createdAt)
|
||||
: thread.latestTurnDurationMs;
|
||||
return {
|
||||
...thread,
|
||||
events: nextEvents,
|
||||
messages: nextMessages,
|
||||
session: nextSession,
|
||||
error: payload.event.kind === "error" && payload.event.message ? payload.event.message : thread.error,
|
||||
latestTurnId: nextTurnId,
|
||||
latestTurnStartedAt: nextTurnStartedAt,
|
||||
latestTurnCompletedAt: nextTurnCompletedAt,
|
||||
latestTurnDurationMs: nextTurnDuration,
|
||||
};
|
||||
}),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.branchSet": {
|
||||
const payload = event.payload as { threadId: string; branch: string | null; worktreePath: string | null };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? { ...thread, branch: payload.branch, worktreePath: payload.worktreePath }
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.terminalActivitySet": {
|
||||
const payload = event.payload as { threadId: string; terminalId: string; running: boolean };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) => {
|
||||
if (thread.id !== payload.threadId) return thread;
|
||||
const running = new Set(thread.runningTerminalIds);
|
||||
if (payload.running) running.add(payload.terminalId);
|
||||
else running.delete(payload.terminalId);
|
||||
const terminalIds = thread.terminalIds.includes(payload.terminalId)
|
||||
? thread.terminalIds
|
||||
: [...thread.terminalIds, payload.terminalId];
|
||||
return { ...thread, terminalIds, runningTerminalIds: [...running] };
|
||||
}),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.markVisited": {
|
||||
const payload = event.payload as { threadId: string; visitedAt: string };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId ? { ...thread, lastVisitedAt: payload.visitedAt } : thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "runtime.modeSet": {
|
||||
const payload = event.payload as { mode: "approval-required" | "full-access" };
|
||||
return { ...state, runtimeMode: payload.mode, lastPosition: event.position };
|
||||
}
|
||||
default:
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
}
|
||||
|
||||
export function reduceEvents(events: ReadonlyArray<DomainEventEnvelope>, seed?: AppViewState): AppViewState {
|
||||
return events.reduce((state, event) => applyDomainEvent(state, event), seed ?? emptyAppViewState());
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@t3tools/infra-sqlite",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"effect": "^3.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./sqliteStore";
|
||||
@@ -0,0 +1,175 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import type { AppViewState, DomainEventEnvelope, EventStorePort, NewDomainEvent, ProjectionStorePort } from "@t3tools/core";
|
||||
|
||||
interface EventRow {
|
||||
event_id: string;
|
||||
stream_id: string;
|
||||
sequence: number;
|
||||
position: number;
|
||||
type: string;
|
||||
occurred_at: string;
|
||||
payload_json: string;
|
||||
causation_id: string | null;
|
||||
correlation_id: string | null;
|
||||
}
|
||||
|
||||
function ensureDir(filePath: string): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
|
||||
function parseState(raw: string | null): AppViewState | null {
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as AppViewState;
|
||||
}
|
||||
|
||||
export class SqliteEventStore implements EventStorePort {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
async append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
if (events.length === 0) return [];
|
||||
const out: DomainEventEnvelope[] = [];
|
||||
this.db.exec("BEGIN IMMEDIATE TRANSACTION");
|
||||
try {
|
||||
for (const event of events) {
|
||||
const sequenceStmt = this.db.prepare(
|
||||
"SELECT COALESCE(MAX(sequence), 0) + 1 AS nextSequence FROM events WHERE stream_id = ?",
|
||||
);
|
||||
const sequenceRow = sequenceStmt.get(event.streamId) as { nextSequence: number };
|
||||
const insert = this.db.prepare(
|
||||
[
|
||||
"INSERT INTO events(",
|
||||
"event_id, stream_id, sequence, type, occurred_at, payload_json, causation_id, correlation_id",
|
||||
") VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
].join(" "),
|
||||
);
|
||||
const eventId = crypto.randomUUID();
|
||||
insert.run(
|
||||
eventId,
|
||||
event.streamId,
|
||||
sequenceRow.nextSequence,
|
||||
event.type,
|
||||
event.occurredAt,
|
||||
JSON.stringify(event.payload),
|
||||
event.causationId ?? null,
|
||||
event.correlationId ?? null,
|
||||
);
|
||||
const positionRow = this.db
|
||||
.prepare("SELECT position FROM events WHERE event_id = ?")
|
||||
.get(eventId) as { position: number };
|
||||
out.push({
|
||||
eventId,
|
||||
streamId: event.streamId,
|
||||
sequence: sequenceRow.nextSequence,
|
||||
position: positionRow.position,
|
||||
type: event.type,
|
||||
occurredAt: event.occurredAt,
|
||||
payload: event.payload,
|
||||
...(event.causationId ? { causationId: event.causationId } : {}),
|
||||
...(event.correlationId ? { correlationId: event.correlationId } : {}),
|
||||
});
|
||||
}
|
||||
this.db.exec("COMMIT");
|
||||
return out;
|
||||
} catch (error) {
|
||||
this.db.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
const stmt = this.db.prepare(
|
||||
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events ORDER BY position ASC",
|
||||
);
|
||||
const rows = stmt.all() as unknown as EventRow[];
|
||||
return rows.map(mapEventRow);
|
||||
}
|
||||
|
||||
async loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
const stmt = this.db.prepare(
|
||||
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events WHERE position > ? ORDER BY position ASC",
|
||||
);
|
||||
const rows = stmt.all(position) as unknown as EventRow[];
|
||||
return rows.map(mapEventRow);
|
||||
}
|
||||
}
|
||||
|
||||
function mapEventRow(row: EventRow): DomainEventEnvelope {
|
||||
return {
|
||||
eventId: row.event_id,
|
||||
streamId: row.stream_id,
|
||||
sequence: row.sequence,
|
||||
position: row.position,
|
||||
type: row.type as DomainEventEnvelope["type"],
|
||||
occurredAt: row.occurred_at,
|
||||
payload: JSON.parse(row.payload_json) as DomainEventEnvelope["payload"],
|
||||
...(row.causation_id ? { causationId: row.causation_id } : {}),
|
||||
...(row.correlation_id ? { correlationId: row.correlation_id } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export class SqliteProjectionStore implements ProjectionStorePort {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
async readState(): Promise<AppViewState | null> {
|
||||
const row = this.db
|
||||
.prepare("SELECT state_json FROM projection_state WHERE projection_name = 'app_state'")
|
||||
.get() as { state_json: string } | undefined;
|
||||
return parseState(row?.state_json ?? null);
|
||||
}
|
||||
|
||||
async writeState(state: AppViewState): Promise<void> {
|
||||
this.db
|
||||
.prepare(
|
||||
[
|
||||
"INSERT INTO projection_state(projection_name, state_json, updated_at)",
|
||||
"VALUES('app_state', ?, ?)",
|
||||
"ON CONFLICT(projection_name) DO UPDATE SET",
|
||||
"state_json = excluded.state_json,",
|
||||
"updated_at = excluded.updated_at",
|
||||
].join(" "),
|
||||
)
|
||||
.run(JSON.stringify(state), new Date().toISOString());
|
||||
}
|
||||
}
|
||||
|
||||
export function createSqliteStores(dbPath: string): {
|
||||
db: DatabaseSync;
|
||||
eventStore: SqliteEventStore;
|
||||
projectionStore: SqliteProjectionStore;
|
||||
} {
|
||||
ensureDir(dbPath);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec("PRAGMA journal_mode = WAL;");
|
||||
db.exec("PRAGMA foreign_keys = ON;");
|
||||
db.exec(
|
||||
[
|
||||
"CREATE TABLE IF NOT EXISTS events(",
|
||||
"position INTEGER PRIMARY KEY AUTOINCREMENT,",
|
||||
"event_id TEXT NOT NULL UNIQUE,",
|
||||
"stream_id TEXT NOT NULL,",
|
||||
"sequence INTEGER NOT NULL,",
|
||||
"type TEXT NOT NULL,",
|
||||
"occurred_at TEXT NOT NULL,",
|
||||
"payload_json TEXT NOT NULL,",
|
||||
"causation_id TEXT,",
|
||||
"correlation_id TEXT,",
|
||||
"UNIQUE(stream_id, sequence)",
|
||||
");",
|
||||
"CREATE INDEX IF NOT EXISTS idx_events_stream_position ON events(stream_id, position);",
|
||||
"CREATE TABLE IF NOT EXISTS projection_state(",
|
||||
"projection_name TEXT PRIMARY KEY,",
|
||||
"state_json TEXT NOT NULL,",
|
||||
"updated_at TEXT NOT NULL",
|
||||
");",
|
||||
].join(" "),
|
||||
);
|
||||
return {
|
||||
db,
|
||||
eventStore: new SqliteEventStore(db),
|
||||
projectionStore: new SqliteProjectionStore(db),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user