Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dbbc225fe6 | ||
|
|
4ce3c3bf8a |
No files matched your search
@@ -17,6 +17,10 @@
|
||||
"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",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import type { CoreCommand, CoreGitStatusSnapshot, CoreProjectView } from "@t3tools/contracts";
|
||||
|
||||
import type { AppendEventInput } from "./eventStore";
|
||||
|
||||
export interface CommandHandlerContext {
|
||||
readonly actor: string;
|
||||
readonly nowIso: string;
|
||||
readonly probeGitStatus: (cwd: string) => Promise<CoreGitStatusSnapshot>;
|
||||
}
|
||||
|
||||
function json(value: unknown): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function baseEvent(input: {
|
||||
eventId: string;
|
||||
streamId: string;
|
||||
aggregateType: "project" | "thread" | "git";
|
||||
occurredAt: string;
|
||||
causationId: string;
|
||||
correlationId: string;
|
||||
actor: string;
|
||||
eventType: string;
|
||||
payload: unknown;
|
||||
idempotencyKey?: string | undefined;
|
||||
}): AppendEventInput {
|
||||
return {
|
||||
eventId: input.eventId,
|
||||
streamId: input.streamId,
|
||||
aggregateType: input.aggregateType,
|
||||
occurredAt: input.occurredAt,
|
||||
causationId: input.causationId,
|
||||
correlationId: input.correlationId,
|
||||
actor: input.actor,
|
||||
eventType: input.eventType,
|
||||
payloadJson: json(input.payload),
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
};
|
||||
}
|
||||
|
||||
function newEventId(prefix: string): string {
|
||||
return `${prefix}_${crypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
export async function handleCoreCommand(
|
||||
command: CoreCommand,
|
||||
context: CommandHandlerContext,
|
||||
): Promise<AppendEventInput[]> {
|
||||
const events: AppendEventInput[] = [];
|
||||
const occurredAt = context.nowIso;
|
||||
const causationId = command.commandId;
|
||||
const correlationId = command.commandId;
|
||||
|
||||
switch (command.kind) {
|
||||
case "CreateProject": {
|
||||
const project: CoreProjectView = {
|
||||
id: command.payload.id,
|
||||
name: command.payload.name,
|
||||
cwd: command.payload.cwd,
|
||||
model: command.payload.model,
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
};
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("project_created"),
|
||||
streamId: command.payload.id,
|
||||
aggregateType: "project",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "ProjectCreated",
|
||||
payload: project,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
case "CreateThread": {
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("thread_created"),
|
||||
streamId: command.payload.id,
|
||||
aggregateType: "thread",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "ThreadCreated",
|
||||
payload: command.payload,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
case "AppendUserMessage": {
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("message_user"),
|
||||
streamId: command.payload.threadId,
|
||||
aggregateType: "thread",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "UserMessageAppended",
|
||||
payload: command.payload,
|
||||
idempotencyKey: command.commandId,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
case "AppendAssistantMessage": {
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("message_assistant"),
|
||||
streamId: command.payload.threadId,
|
||||
aggregateType: "thread",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "AssistantMessageAppended",
|
||||
payload: command.payload,
|
||||
idempotencyKey: command.commandId,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
case "SetThreadBranch": {
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("thread_branch"),
|
||||
streamId: command.payload.threadId,
|
||||
aggregateType: "thread",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "ThreadBranchSet",
|
||||
payload: command.payload,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
case "GitWorkflow": {
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("git_workflow"),
|
||||
streamId: command.payload.cwd,
|
||||
aggregateType: "git",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "GitWorkflowRecorded",
|
||||
payload: command.payload,
|
||||
}),
|
||||
);
|
||||
const status = await context.probeGitStatus(command.payload.cwd);
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("git_observed"),
|
||||
streamId: command.payload.cwd,
|
||||
aggregateType: "git",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "GitStateObserved",
|
||||
payload: status,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
case "GitProbe": {
|
||||
const status = await context.probeGitStatus(command.payload.cwd);
|
||||
events.push(
|
||||
baseEvent({
|
||||
eventId: newEventId("git_observed"),
|
||||
streamId: command.payload.cwd,
|
||||
aggregateType: "git",
|
||||
occurredAt,
|
||||
causationId,
|
||||
correlationId,
|
||||
actor: context.actor,
|
||||
eventType: "GitStateObserved",
|
||||
payload: status,
|
||||
}),
|
||||
);
|
||||
return events;
|
||||
}
|
||||
default:
|
||||
return events;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import type {
|
||||
CoreCommand,
|
||||
CoreDispatchInput,
|
||||
CoreDispatchResult,
|
||||
CoreGitStatusSnapshot,
|
||||
CoreReadModelSnapshot,
|
||||
CoreViewDelta,
|
||||
} from "@t3tools/contracts";
|
||||
import { coreCommandSchema } from "@t3tools/contracts";
|
||||
import { Effect, Fiber, PubSub, Queue, Ref, Stream } from "effect";
|
||||
|
||||
import { handleCoreCommand } from "./commandHandlers";
|
||||
import { type PersistedEvent, SqliteEventStore } from "./eventStore";
|
||||
import {
|
||||
applyEventToReadModels,
|
||||
deltaFromEvent,
|
||||
emptyReadModelMaps,
|
||||
rebuildReadModels,
|
||||
toReadModelSnapshot,
|
||||
type ReadModelMaps,
|
||||
} from "./readModels";
|
||||
|
||||
interface CommandEnvelope {
|
||||
readonly input: CoreDispatchInput;
|
||||
readonly resolve: (value: CoreDispatchResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface CoreEngineOptions {
|
||||
readonly eventStore: SqliteEventStore;
|
||||
readonly probeGitStatus: (cwd: string) => Promise<CoreGitStatusSnapshot>;
|
||||
}
|
||||
|
||||
export class CoreEngine {
|
||||
private readonly eventStore: SqliteEventStore;
|
||||
private readonly probeGitStatus: (cwd: string) => Promise<CoreGitStatusSnapshot>;
|
||||
private queue: Queue.Queue<CommandEnvelope> | null = null;
|
||||
private pubSub: PubSub.PubSub<CoreViewDelta> | null = null;
|
||||
private stateRef: Ref.Ref<ReadModelMaps> | null = null;
|
||||
private worker: Fiber.RuntimeFiber<void, unknown> | null = null;
|
||||
|
||||
constructor(options: CoreEngineOptions) {
|
||||
this.eventStore = options.eventStore;
|
||||
this.probeGitStatus = options.probeGitStatus;
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.queue = await Effect.runPromise(Queue.unbounded<CommandEnvelope>());
|
||||
this.pubSub = await Effect.runPromise(PubSub.unbounded<CoreViewDelta>());
|
||||
const events = await Effect.runPromise(this.eventStore.listSince(0));
|
||||
const initialState = events.length > 0 ? rebuildReadModels(events) : emptyReadModelMaps();
|
||||
this.stateRef = await Effect.runPromise(Ref.make(initialState));
|
||||
this.worker = Effect.runFork(this.commandLoop());
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.worker) {
|
||||
await Effect.runPromise(Fiber.interrupt(this.worker));
|
||||
this.worker = null;
|
||||
}
|
||||
this.queue = null;
|
||||
this.pubSub = null;
|
||||
this.stateRef = null;
|
||||
}
|
||||
|
||||
async getSnapshot(): Promise<CoreReadModelSnapshot> {
|
||||
const state = await this.getState();
|
||||
return toReadModelSnapshot(state);
|
||||
}
|
||||
|
||||
async dispatch(input: CoreDispatchInput): Promise<CoreDispatchResult> {
|
||||
const queue = this.requireQueue();
|
||||
return new Promise((resolve, reject) => {
|
||||
void Effect.runPromise(
|
||||
Queue.offer(queue, {
|
||||
input,
|
||||
resolve,
|
||||
reject,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
subscribe(listener: (delta: CoreViewDelta) => void): () => void {
|
||||
const pubSub = this.requirePubSub();
|
||||
const stream = Stream.fromPubSub(pubSub);
|
||||
const fiber = Effect.runFork(
|
||||
Stream.runForEach(stream, (delta) =>
|
||||
Effect.sync(() => {
|
||||
listener(delta);
|
||||
}),
|
||||
),
|
||||
);
|
||||
return () => {
|
||||
void Effect.runPromise(Fiber.interrupt(fiber));
|
||||
};
|
||||
}
|
||||
|
||||
private commandLoop(): Effect.Effect<void> {
|
||||
const queue = this.requireQueue();
|
||||
return Effect.forever(
|
||||
Effect.flatMap(Queue.take(queue), (envelope) =>
|
||||
Effect.tryPromise({
|
||||
try: () => this.processCommand(envelope),
|
||||
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
|
||||
}).pipe(Effect.catchAll(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async processCommand(envelope: CommandEnvelope): Promise<void> {
|
||||
try {
|
||||
const parsed = coreCommandSchema.parse(envelope.input.command);
|
||||
const events = await handleCoreCommand(parsed, {
|
||||
actor: "ws-client",
|
||||
nowIso: new Date().toISOString(),
|
||||
probeGitStatus: this.probeGitStatus,
|
||||
});
|
||||
|
||||
let lastSequence = 0;
|
||||
for (const eventInput of events) {
|
||||
const persisted = await Effect.runPromise(this.eventStore.append(eventInput));
|
||||
lastSequence = persisted.sequence;
|
||||
await this.applyPersistedEvent(persisted);
|
||||
}
|
||||
|
||||
envelope.resolve({
|
||||
accepted: true,
|
||||
sequence: lastSequence,
|
||||
});
|
||||
} catch (error) {
|
||||
envelope.reject(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
|
||||
private async applyPersistedEvent(event: PersistedEvent): Promise<void> {
|
||||
const stateRef = this.requireStateRef();
|
||||
const pubSub = this.requirePubSub();
|
||||
const nextState = await Effect.runPromise(
|
||||
Ref.updateAndGet(stateRef, (state) => applyEventToReadModels(state, event)),
|
||||
);
|
||||
const delta = deltaFromEvent(event, nextState);
|
||||
await Effect.runPromise(PubSub.publish(pubSub, delta));
|
||||
}
|
||||
|
||||
private async getState(): Promise<ReadModelMaps> {
|
||||
return Effect.runPromise(Ref.get(this.requireStateRef()));
|
||||
}
|
||||
|
||||
private requireQueue(): Queue.Queue<CommandEnvelope> {
|
||||
if (!this.queue) throw new Error("CoreEngine not started");
|
||||
return this.queue;
|
||||
}
|
||||
|
||||
private requirePubSub(): PubSub.PubSub<CoreViewDelta> {
|
||||
if (!this.pubSub) throw new Error("CoreEngine not started");
|
||||
return this.pubSub;
|
||||
}
|
||||
|
||||
private requireStateRef(): Ref.Ref<ReadModelMaps> {
|
||||
if (!this.stateRef) throw new Error("CoreEngine not started");
|
||||
return this.stateRef;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const aggregateTypeSchema = Schema.Literal("project", "thread", "git");
|
||||
export type AggregateType = typeof aggregateTypeSchema.Type;
|
||||
|
||||
export class DomainEventEnvelope extends Schema.Class<DomainEventEnvelope>("DomainEventEnvelope")({
|
||||
eventId: Schema.String,
|
||||
streamId: Schema.String,
|
||||
aggregateType: aggregateTypeSchema,
|
||||
version: Schema.Number.pipe(Schema.int(), Schema.nonNegative()),
|
||||
occurredAt: Schema.String,
|
||||
causationId: Schema.String,
|
||||
correlationId: Schema.String,
|
||||
actor: Schema.String,
|
||||
eventType: Schema.String,
|
||||
payloadJson: Schema.String,
|
||||
}) {}
|
||||
|
||||
export const domainEventPayloadSchema = Schema.Struct({
|
||||
kind: Schema.String,
|
||||
payload: Schema.Unknown,
|
||||
});
|
||||
export type DomainEventPayload = typeof domainEventPayloadSchema.Type;
|
||||
@@ -0,0 +1,211 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import type { AggregateType } from "./domain";
|
||||
|
||||
export interface PersistedEvent {
|
||||
sequence: number;
|
||||
eventId: string;
|
||||
streamId: string;
|
||||
aggregateType: AggregateType;
|
||||
version: number;
|
||||
occurredAt: string;
|
||||
causationId: string;
|
||||
correlationId: string;
|
||||
actor: string;
|
||||
eventType: string;
|
||||
payloadJson: string;
|
||||
idempotencyKey: string | null;
|
||||
}
|
||||
|
||||
export interface AppendEventInput {
|
||||
eventId: string;
|
||||
streamId: string;
|
||||
aggregateType: AggregateType;
|
||||
expectedVersion?: number | undefined;
|
||||
occurredAt: string;
|
||||
causationId: string;
|
||||
correlationId: string;
|
||||
actor: string;
|
||||
eventType: string;
|
||||
payloadJson: string;
|
||||
idempotencyKey?: string | undefined;
|
||||
}
|
||||
|
||||
interface EventRow {
|
||||
sequence: number;
|
||||
event_id: string;
|
||||
stream_id: string;
|
||||
aggregate_type: AggregateType;
|
||||
version: number;
|
||||
occurred_at: string;
|
||||
causation_id: string;
|
||||
correlation_id: string;
|
||||
actor: string;
|
||||
event_type: string;
|
||||
payload_json: string;
|
||||
idempotency_key: string | null;
|
||||
}
|
||||
|
||||
function mapEventRow(row: EventRow): PersistedEvent {
|
||||
return {
|
||||
sequence: row.sequence,
|
||||
eventId: row.event_id,
|
||||
streamId: row.stream_id,
|
||||
aggregateType: row.aggregate_type,
|
||||
version: row.version,
|
||||
occurredAt: row.occurred_at,
|
||||
causationId: row.causation_id,
|
||||
correlationId: row.correlation_id,
|
||||
actor: row.actor,
|
||||
eventType: row.event_type,
|
||||
payloadJson: row.payload_json,
|
||||
idempotencyKey: row.idempotency_key,
|
||||
};
|
||||
}
|
||||
|
||||
export class SqliteEventStore {
|
||||
private readonly db: DatabaseSync;
|
||||
|
||||
constructor(databasePath: string) {
|
||||
fs.mkdirSync(path.dirname(databasePath), { recursive: true });
|
||||
this.db = new DatabaseSync(databasePath);
|
||||
this.db.exec("PRAGMA journal_mode = WAL;");
|
||||
this.db.exec("PRAGMA synchronous = NORMAL;");
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_id TEXT NOT NULL UNIQUE,
|
||||
stream_id TEXT NOT NULL,
|
||||
aggregate_type TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
occurred_at TEXT NOT NULL,
|
||||
causation_id TEXT NOT NULL,
|
||||
correlation_id TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
idempotency_key TEXT UNIQUE
|
||||
);
|
||||
`);
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_events_stream_version
|
||||
ON events(stream_id, version);
|
||||
`);
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_events_aggregate
|
||||
ON events(aggregate_type, stream_id, version);
|
||||
`);
|
||||
}
|
||||
|
||||
append(input: AppendEventInput): Effect.Effect<PersistedEvent, Error> {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
this.db.exec("BEGIN IMMEDIATE TRANSACTION");
|
||||
try {
|
||||
if (input.idempotencyKey) {
|
||||
const existingByKeyRow = this.db
|
||||
.prepare(
|
||||
`SELECT sequence, event_id, stream_id, aggregate_type, version, occurred_at,
|
||||
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
|
||||
FROM events
|
||||
WHERE idempotency_key = ?`,
|
||||
)
|
||||
.get(input.idempotencyKey) as EventRow | undefined;
|
||||
if (existingByKeyRow) {
|
||||
this.db.exec("COMMIT");
|
||||
return mapEventRow(existingByKeyRow);
|
||||
}
|
||||
}
|
||||
|
||||
const latest = this.db
|
||||
.prepare("SELECT version FROM events WHERE stream_id = ? ORDER BY version DESC LIMIT 1")
|
||||
.get(input.streamId) as { version: number } | undefined;
|
||||
const currentVersion = latest?.version ?? 0;
|
||||
|
||||
if (typeof input.expectedVersion === "number" && input.expectedVersion !== currentVersion) {
|
||||
throw new Error(
|
||||
`Optimistic concurrency conflict for stream ${input.streamId}: expected ${input.expectedVersion}, got ${currentVersion}`,
|
||||
);
|
||||
}
|
||||
|
||||
const nextVersion = currentVersion + 1;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO events (
|
||||
event_id, stream_id, aggregate_type, version, occurred_at,
|
||||
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
input.eventId,
|
||||
input.streamId,
|
||||
input.aggregateType,
|
||||
nextVersion,
|
||||
input.occurredAt,
|
||||
input.causationId,
|
||||
input.correlationId,
|
||||
input.actor,
|
||||
input.eventType,
|
||||
input.payloadJson,
|
||||
input.idempotencyKey ?? null,
|
||||
);
|
||||
|
||||
const persistedRow = this.db
|
||||
.prepare(
|
||||
`SELECT sequence, event_id, stream_id, aggregate_type, version, occurred_at,
|
||||
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
|
||||
FROM events
|
||||
WHERE event_id = ?`,
|
||||
)
|
||||
.get(input.eventId) as EventRow | undefined;
|
||||
if (!persistedRow) {
|
||||
throw new Error(`Inserted event missing from store: ${input.eventId}`);
|
||||
}
|
||||
this.db.exec("COMMIT");
|
||||
return mapEventRow(persistedRow);
|
||||
} catch (error) {
|
||||
this.db.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
|
||||
});
|
||||
}
|
||||
|
||||
listSince(minSequence: number): Effect.Effect<PersistedEvent[], Error> {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT sequence, event_id, stream_id, aggregate_type, version, occurred_at,
|
||||
causation_id, correlation_id, actor, event_type, payload_json, idempotency_key
|
||||
FROM events
|
||||
WHERE sequence > ?
|
||||
ORDER BY sequence ASC`,
|
||||
)
|
||||
.all(minSequence) as unknown as EventRow[];
|
||||
return rows.map((row) => mapEventRow(row));
|
||||
},
|
||||
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
|
||||
});
|
||||
}
|
||||
|
||||
lastSequence(): Effect.Effect<number, Error> {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const row = this.db.prepare("SELECT MAX(sequence) as sequence FROM events").get() as
|
||||
| { sequence: number | null }
|
||||
| undefined;
|
||||
return row?.sequence ?? 0;
|
||||
},
|
||||
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import {
|
||||
providerInterruptTurnInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { CodexAppServerManager } from "../../codexAppServerManager";
|
||||
import type { ProviderAdapter, ProviderThreadSnapshot } from "./providerAdapter";
|
||||
|
||||
export class CodexProviderAdapter implements ProviderAdapter {
|
||||
readonly kind = "codex" as const;
|
||||
private readonly manager = new CodexAppServerManager();
|
||||
|
||||
onEvent(listener: (event: ProviderEvent) => void): () => void {
|
||||
this.manager.on("event", listener);
|
||||
return () => {
|
||||
this.manager.off("event", listener);
|
||||
};
|
||||
}
|
||||
|
||||
hasSession(sessionId: string): boolean {
|
||||
return this.manager.hasSession(sessionId);
|
||||
}
|
||||
|
||||
startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const parsed = providerSessionStartInputSchema.parse(input);
|
||||
if (parsed.provider !== this.kind) {
|
||||
throw new Error(`Provider '${parsed.provider}' is not implemented by CodexProviderAdapter.`);
|
||||
}
|
||||
return this.manager.startSession(parsed);
|
||||
}
|
||||
|
||||
sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
return this.manager.sendTurn(providerSendTurnInputSchema.parse(input));
|
||||
}
|
||||
|
||||
interruptTurn(input: ProviderInterruptTurnInput): Promise<void> {
|
||||
const parsed = providerInterruptTurnInputSchema.parse(input);
|
||||
return this.manager.interruptTurn(parsed.sessionId, parsed.turnId);
|
||||
}
|
||||
|
||||
respondToRequest(input: ProviderRespondToRequestInput): Promise<void> {
|
||||
const parsed = providerRespondToRequestInputSchema.parse(input);
|
||||
return this.manager.respondToRequest(parsed.sessionId, parsed.requestId, parsed.decision);
|
||||
}
|
||||
|
||||
stopSession(input: ProviderStopSessionInput): void {
|
||||
const parsed = providerStopSessionInputSchema.parse(input);
|
||||
this.manager.stopSession(parsed.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return this.manager.listSessions();
|
||||
}
|
||||
|
||||
async readThread(sessionId: string): Promise<ProviderThreadSnapshot> {
|
||||
const snapshot = await this.manager.readThread(sessionId);
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
turns: snapshot.turns.map((turn) => ({
|
||||
id: turn.id,
|
||||
items: turn.items,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async rollbackThread(sessionId: string, numTurns: number): Promise<ProviderThreadSnapshot> {
|
||||
const snapshot = await this.manager.rollbackThread(sessionId, numTurns);
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
turns: snapshot.turns.map((turn) => ({
|
||||
id: turn.id,
|
||||
items: turn.items,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.manager.stopAll();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.manager.stopAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderKind,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface ProviderThreadTurnSnapshot {
|
||||
id: string;
|
||||
items: unknown[];
|
||||
}
|
||||
|
||||
export interface ProviderThreadSnapshot {
|
||||
threadId: string;
|
||||
turns: ProviderThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
export interface ProviderAdapter {
|
||||
readonly kind: ProviderKind;
|
||||
onEvent(listener: (event: ProviderEvent) => void): () => void;
|
||||
hasSession(sessionId: string): boolean;
|
||||
startSession(input: ProviderSessionStartInput): Promise<ProviderSession>;
|
||||
sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult>;
|
||||
interruptTurn(input: ProviderInterruptTurnInput): Promise<void>;
|
||||
respondToRequest(input: ProviderRespondToRequestInput): Promise<void>;
|
||||
stopSession(input: ProviderStopSessionInput): void;
|
||||
listSessions(): ProviderSession[];
|
||||
readThread(sessionId: string): Promise<ProviderThreadSnapshot>;
|
||||
rollbackThread(sessionId: string, numTurns: number): Promise<ProviderThreadSnapshot>;
|
||||
stopAll(): void;
|
||||
dispose(): void;
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type {
|
||||
ProviderCheckpoint,
|
||||
ProviderEvent,
|
||||
ProviderGetCheckpointDiffInput,
|
||||
ProviderGetCheckpointDiffResult,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderKind,
|
||||
ProviderListCheckpointsInput,
|
||||
ProviderListCheckpointsResult,
|
||||
ProviderRevertToCheckpointInput,
|
||||
ProviderRevertToCheckpointResult,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
providerGetCheckpointDiffInputSchema,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { FilesystemCheckpointStore } from "../../filesystemCheckpointStore";
|
||||
import type { ProviderAdapter, ProviderThreadTurnSnapshot } from "./providerAdapter";
|
||||
|
||||
export interface ProviderOrchestratorEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class ProviderOrchestrator extends EventEmitter<ProviderOrchestratorEvents> {
|
||||
private readonly adapters: Map<ProviderKind, ProviderAdapter>;
|
||||
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
|
||||
private readonly sessionToProvider = new Map<string, ProviderKind>();
|
||||
private readonly sessionCheckpointCwds = new Map<string, string>();
|
||||
private readonly filesystemLocks = new Map<string, Promise<void>>();
|
||||
private readonly unsubscribers: Array<() => void>;
|
||||
|
||||
constructor(adapters: ProviderAdapter[]) {
|
||||
super();
|
||||
this.adapters = new Map(adapters.map((adapter) => [adapter.kind, adapter] as const));
|
||||
this.unsubscribers = adapters.map((adapter) =>
|
||||
adapter.onEvent((event) => {
|
||||
this.sessionToProvider.set(event.sessionId, event.provider);
|
||||
this.emit("event", event);
|
||||
this.maybeCaptureFilesystemCheckpoint(event);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async startSession(raw: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const input = providerSessionStartInputSchema.parse(raw);
|
||||
const provider = input.provider ?? "codex";
|
||||
const adapter = this.requireAdapter(provider);
|
||||
const session = await adapter.startSession(input);
|
||||
this.sessionToProvider.set(session.sessionId, session.provider);
|
||||
await this.initializeFilesystemCheckpointing(adapter, session, input.cwd).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const input = providerSendTurnInputSchema.parse(raw);
|
||||
return this.resolveAdapterForSession(input.sessionId).sendTurn(input);
|
||||
}
|
||||
|
||||
async interruptTurn(raw: ProviderInterruptTurnInput): Promise<void> {
|
||||
const input = providerInterruptTurnInputSchema.parse(raw);
|
||||
return this.resolveAdapterForSession(input.sessionId).interruptTurn(input);
|
||||
}
|
||||
|
||||
async respondToRequest(raw: ProviderRespondToRequestInput): Promise<void> {
|
||||
const input = providerRespondToRequestInputSchema.parse(raw);
|
||||
return this.resolveAdapterForSession(input.sessionId).respondToRequest(input);
|
||||
}
|
||||
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.resolveAdapterForSession(input.sessionId).stopSession(input);
|
||||
this.sessionToProvider.delete(input.sessionId);
|
||||
this.sessionCheckpointCwds.delete(input.sessionId);
|
||||
this.filesystemLocks.delete(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
const sessions = [...this.adapters.values()].flatMap((adapter) => adapter.listSessions());
|
||||
for (const session of sessions) {
|
||||
this.sessionToProvider.set(session.sessionId, session.provider);
|
||||
}
|
||||
return sessions;
|
||||
}
|
||||
|
||||
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
|
||||
const input = providerListCheckpointsInputSchema.parse(raw);
|
||||
const adapter = this.resolveAdapterForSession(input.sessionId);
|
||||
const snapshot = await adapter.readThread(input.sessionId);
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
checkpoints: buildCheckpoints(snapshot.turns),
|
||||
};
|
||||
}
|
||||
|
||||
async getCheckpointDiff(
|
||||
raw: ProviderGetCheckpointDiffInput,
|
||||
): Promise<ProviderGetCheckpointDiffResult> {
|
||||
const input = providerGetCheckpointDiffInputSchema.parse(raw);
|
||||
const adapter = this.resolveAdapterForSession(input.sessionId);
|
||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId, adapter);
|
||||
if (!checkpointCwd) {
|
||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
||||
}
|
||||
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const snapshot = await adapter.readThread(input.sessionId);
|
||||
if (input.toTurnCount > snapshot.turns.length) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
});
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async revertToCheckpoint(
|
||||
raw: ProviderRevertToCheckpointInput,
|
||||
): Promise<ProviderRevertToCheckpointResult> {
|
||||
const input = providerRevertToCheckpointInputSchema.parse(raw);
|
||||
const adapter = this.resolveAdapterForSession(input.sessionId);
|
||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId, adapter);
|
||||
if (!checkpointCwd) {
|
||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
||||
}
|
||||
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const beforeSnapshot = await adapter.readThread(input.sessionId);
|
||||
const currentTurnCount = beforeSnapshot.turns.length;
|
||||
if (input.turnCount > currentTurnCount) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (input.turnCount > 0) {
|
||||
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!hasCheckpoint) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!restored) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const rollbackTurns = currentTurnCount - input.turnCount;
|
||||
const afterSnapshot =
|
||||
rollbackTurns > 0
|
||||
? await adapter.rollbackThread(input.sessionId, rollbackTurns)
|
||||
: beforeSnapshot;
|
||||
|
||||
await this.filesystemCheckpointStore.pruneAfterTurn({
|
||||
cwd: checkpointCwd,
|
||||
threadId: afterSnapshot.threadId,
|
||||
maxTurnCount: afterSnapshot.turns.length,
|
||||
});
|
||||
|
||||
const checkpoints = buildCheckpoints(afterSnapshot.turns);
|
||||
const currentCheckpoint =
|
||||
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
|
||||
checkpoints[checkpoints.length - 1] ??
|
||||
checkpoints[0];
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
|
||||
|
||||
return {
|
||||
threadId: afterSnapshot.threadId,
|
||||
turnCount: currentCheckpoint?.turnCount ?? 0,
|
||||
messageCount: currentCheckpoint?.messageCount ?? 0,
|
||||
rolledBackTurns,
|
||||
checkpoints,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
for (const adapter of this.adapters.values()) {
|
||||
adapter.stopAll();
|
||||
}
|
||||
this.sessionToProvider.clear();
|
||||
this.sessionCheckpointCwds.clear();
|
||||
this.filesystemLocks.clear();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const unsubscribe of this.unsubscribers) {
|
||||
unsubscribe();
|
||||
}
|
||||
for (const adapter of this.adapters.values()) {
|
||||
adapter.dispose();
|
||||
}
|
||||
this.unsubscribers.length = 0;
|
||||
this.sessionToProvider.clear();
|
||||
this.sessionCheckpointCwds.clear();
|
||||
this.filesystemLocks.clear();
|
||||
}
|
||||
|
||||
private async initializeFilesystemCheckpointing(
|
||||
adapter: ProviderAdapter,
|
||||
session: ProviderSession,
|
||||
preferredCwd?: string,
|
||||
): Promise<void> {
|
||||
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
|
||||
await this.withFilesystemLock(session.sessionId, async () => {
|
||||
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
|
||||
if (!supportsGit) {
|
||||
this.sessionCheckpointCwds.delete(session.sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await adapter.readThread(session.sessionId);
|
||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
});
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
this.sessionCheckpointCwds.set(session.sessionId, cwd);
|
||||
});
|
||||
}
|
||||
|
||||
private async getOrInitializeFilesystemCheckpointCwd(
|
||||
sessionId: string,
|
||||
adapter: ProviderAdapter,
|
||||
): Promise<string | null> {
|
||||
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
|
||||
if (existingCwd) return existingCwd;
|
||||
|
||||
const session = adapter.listSessions().find((entry) => entry.sessionId === sessionId);
|
||||
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
|
||||
|
||||
await this.withFilesystemLock(sessionId, async () => {
|
||||
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
|
||||
if (currentCwd) return;
|
||||
|
||||
const cwdSupport = await Promise.all(
|
||||
candidateCwds.map(async (cwd) => ({
|
||||
cwd,
|
||||
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
|
||||
})),
|
||||
);
|
||||
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
|
||||
if (!supportedCwd) {
|
||||
this.sessionCheckpointCwds.delete(sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await adapter.readThread(sessionId);
|
||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
||||
cwd: supportedCwd,
|
||||
threadId: snapshot.threadId,
|
||||
});
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: supportedCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
|
||||
});
|
||||
|
||||
return this.sessionCheckpointCwds.get(sessionId) ?? null;
|
||||
}
|
||||
|
||||
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
|
||||
if (event.kind !== "notification" || event.method !== "turn/completed") {
|
||||
return;
|
||||
}
|
||||
const adapter = this.resolveAdapterForSession(event.sessionId);
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId, adapter)
|
||||
.then(async (initializedCwd) => {
|
||||
if (!initializedCwd) return;
|
||||
const snapshot = await adapter.readThread(event.sessionId);
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
})
|
||||
.catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void this.withFilesystemLock(event.sessionId, async () => {
|
||||
const snapshot = await adapter.readThread(event.sessionId);
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
}
|
||||
|
||||
private emitCheckpointCaptured(sessionId: string, threadId: string, turnCount: number): void {
|
||||
this.emit("event", {
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: this.sessionToProvider.get(sessionId) ?? "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/captured",
|
||||
threadId,
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private emitFilesystemCheckpointError(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
threadId?: string,
|
||||
): void {
|
||||
this.emit("event", {
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: this.sessionToProvider.get(sessionId) ?? "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/filesystemError",
|
||||
message,
|
||||
...(threadId ? { threadId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
|
||||
const next = previous.catch(() => undefined).then(fn);
|
||||
const completion = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
this.filesystemLocks.set(sessionId, completion);
|
||||
return next.finally(() => {
|
||||
const tracked = this.filesystemLocks.get(sessionId);
|
||||
if (tracked === completion) {
|
||||
this.filesystemLocks.delete(sessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private resolveAdapterForSession(sessionId: string): ProviderAdapter {
|
||||
const mappedProvider = this.sessionToProvider.get(sessionId);
|
||||
if (mappedProvider) {
|
||||
return this.requireAdapter(mappedProvider);
|
||||
}
|
||||
for (const adapter of this.adapters.values()) {
|
||||
if (adapter.hasSession(sessionId)) {
|
||||
this.sessionToProvider.set(sessionId, adapter.kind);
|
||||
return adapter;
|
||||
}
|
||||
}
|
||||
throw new Error(`Unknown provider session: ${sessionId}`);
|
||||
}
|
||||
|
||||
private requireAdapter(provider: ProviderKind): ProviderAdapter {
|
||||
const adapter = this.adapters.get(provider);
|
||||
if (!adapter) {
|
||||
throw new Error(`Provider '${provider}' is not implemented yet.`);
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function trimToPreview(value: string): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
if (normalized.length <= 120) return normalized;
|
||||
return `${normalized.slice(0, 117)}...`;
|
||||
}
|
||||
|
||||
function summarizeUserMessageContent(content: unknown[]): string | undefined {
|
||||
const segments: string[] = [];
|
||||
for (const part of content) {
|
||||
const record = asObject(part);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
if (type === "text") {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
segments.push(text.trim());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (type === "image") {
|
||||
segments.push("[Image attachment]");
|
||||
continue;
|
||||
}
|
||||
if (type === "localImage") {
|
||||
segments.push("[Local image attachment]");
|
||||
}
|
||||
}
|
||||
if (segments.length === 0) return undefined;
|
||||
return trimToPreview(segments.join(" "));
|
||||
}
|
||||
|
||||
function summarizeTurn(turn: ProviderThreadTurnSnapshot): { messageCountDelta: number; preview?: string } {
|
||||
let messageCountDelta = 0;
|
||||
let preview: string | undefined;
|
||||
for (const item of turn.items) {
|
||||
const record = asObject(item);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
if (type === "userMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
preview = summarizeUserMessageContent(asArray(record?.content));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (type === "agentMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
preview = trimToPreview(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
messageCountDelta,
|
||||
...(preview ? { preview } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildCheckpoints(turns: ProviderThreadTurnSnapshot[]): ProviderCheckpoint[] {
|
||||
const checkpoints: ProviderCheckpoint[] = [];
|
||||
let messageCount = 0;
|
||||
const isEmpty = turns.length === 0;
|
||||
checkpoints.push({
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: isEmpty,
|
||||
});
|
||||
for (let index = 0; index < turns.length; index += 1) {
|
||||
const turn = turns[index];
|
||||
if (!turn) continue;
|
||||
const turnSummary = summarizeTurn(turn);
|
||||
messageCount += turnSummary.messageCountDelta;
|
||||
checkpoints.push({
|
||||
id: turn.id,
|
||||
turnCount: index + 1,
|
||||
messageCount,
|
||||
label: `Turn ${index + 1}`,
|
||||
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
|
||||
isCurrent: index === turns.length - 1,
|
||||
});
|
||||
}
|
||||
return checkpoints;
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import type {
|
||||
CoreGitStatusSnapshot,
|
||||
CoreProjectView,
|
||||
CoreReadModelSnapshot,
|
||||
CoreThreadMessageView,
|
||||
CoreThreadView,
|
||||
CoreViewDelta,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { PersistedEvent } from "./eventStore";
|
||||
|
||||
export interface ReadModelMaps {
|
||||
projects: Map<string, CoreProjectView>;
|
||||
threads: Map<string, CoreThreadView>;
|
||||
git: Map<string, CoreGitStatusSnapshot>;
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
export function emptyReadModelMaps(): ReadModelMaps {
|
||||
return {
|
||||
projects: new Map(),
|
||||
threads: new Map(),
|
||||
git: new Map(),
|
||||
sequence: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function parsePayload(event: PersistedEvent): unknown {
|
||||
return JSON.parse(event.payloadJson) as unknown;
|
||||
}
|
||||
|
||||
function cloneMaps(state: ReadModelMaps): ReadModelMaps {
|
||||
return {
|
||||
projects: new Map(state.projects),
|
||||
threads: new Map(state.threads),
|
||||
git: new Map(state.git),
|
||||
sequence: state.sequence,
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadBase(payload: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt?: string;
|
||||
}): CoreThreadView {
|
||||
const createdAt = payload.createdAt ?? new Date().toISOString();
|
||||
return {
|
||||
id: payload.id,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
sessionId: null,
|
||||
messages: [],
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
function appendMessage(
|
||||
thread: CoreThreadView,
|
||||
message: { id: string; role: "user" | "assistant"; text: string; createdAt: string },
|
||||
updatedAt: string,
|
||||
): CoreThreadView {
|
||||
const nextMessage: CoreThreadMessageView = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: false,
|
||||
};
|
||||
return {
|
||||
...thread,
|
||||
updatedAt,
|
||||
messages: [...thread.messages, nextMessage],
|
||||
};
|
||||
}
|
||||
|
||||
export function applyEventToReadModels(state: ReadModelMaps, event: PersistedEvent): ReadModelMaps {
|
||||
const next = cloneMaps(state);
|
||||
next.sequence = event.sequence;
|
||||
|
||||
switch (event.eventType) {
|
||||
case "ProjectCreated": {
|
||||
const payload = parsePayload(event) as CoreProjectView;
|
||||
next.projects.set(payload.id, payload);
|
||||
return next;
|
||||
}
|
||||
case "ProjectDeleted": {
|
||||
const payload = parsePayload(event) as { id: string };
|
||||
next.projects.delete(payload.id);
|
||||
return next;
|
||||
}
|
||||
case "ThreadCreated": {
|
||||
const payload = parsePayload(event) as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt?: string;
|
||||
};
|
||||
next.threads.set(payload.id, buildThreadBase(payload));
|
||||
return next;
|
||||
}
|
||||
case "UserMessageAppended": {
|
||||
const payload = parsePayload(event) as {
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
};
|
||||
const existing = next.threads.get(payload.threadId);
|
||||
if (!existing) return next;
|
||||
next.threads.set(
|
||||
payload.threadId,
|
||||
appendMessage(
|
||||
existing,
|
||||
{
|
||||
id: payload.messageId,
|
||||
role: "user",
|
||||
text: payload.text,
|
||||
createdAt: payload.createdAt,
|
||||
},
|
||||
event.occurredAt,
|
||||
),
|
||||
);
|
||||
return next;
|
||||
}
|
||||
case "AssistantMessageAppended": {
|
||||
const payload = parsePayload(event) as {
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
};
|
||||
const existing = next.threads.get(payload.threadId);
|
||||
if (!existing) return next;
|
||||
next.threads.set(
|
||||
payload.threadId,
|
||||
appendMessage(
|
||||
existing,
|
||||
{
|
||||
id: payload.messageId,
|
||||
role: "assistant",
|
||||
text: payload.text,
|
||||
createdAt: payload.createdAt,
|
||||
},
|
||||
event.occurredAt,
|
||||
),
|
||||
);
|
||||
return next;
|
||||
}
|
||||
case "ThreadBranchSet": {
|
||||
const payload = parsePayload(event) as {
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
const existing = next.threads.get(payload.threadId);
|
||||
if (!existing) return next;
|
||||
next.threads.set(payload.threadId, {
|
||||
...existing,
|
||||
updatedAt: event.occurredAt,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
});
|
||||
return next;
|
||||
}
|
||||
case "GitStateObserved": {
|
||||
const payload = parsePayload(event) as CoreGitStatusSnapshot;
|
||||
next.git.set(payload.cwd, payload);
|
||||
return next;
|
||||
}
|
||||
default:
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
export function rebuildReadModels(events: readonly PersistedEvent[]): ReadModelMaps {
|
||||
let state = emptyReadModelMaps();
|
||||
for (const event of events) {
|
||||
state = applyEventToReadModels(state, event);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function toReadModelSnapshot(state: ReadModelMaps): CoreReadModelSnapshot {
|
||||
return {
|
||||
sequence: state.sequence,
|
||||
generatedAt: new Date().toISOString(),
|
||||
projects: [...state.projects.values()],
|
||||
threads: [...state.threads.values()].toSorted(
|
||||
(a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt),
|
||||
),
|
||||
git: [...state.git.values()],
|
||||
};
|
||||
}
|
||||
|
||||
export function deltaFromEvent(event: PersistedEvent, state: ReadModelMaps): CoreViewDelta {
|
||||
switch (event.eventType) {
|
||||
case "ProjectCreated":
|
||||
return {
|
||||
kind: "projectUpsert",
|
||||
sequence: event.sequence,
|
||||
project: state.projects.get(event.streamId) ?? (JSON.parse(event.payloadJson) as CoreProjectView),
|
||||
};
|
||||
case "ProjectDeleted":
|
||||
return {
|
||||
kind: "projectDelete",
|
||||
sequence: event.sequence,
|
||||
projectId: (JSON.parse(event.payloadJson) as { id: string }).id,
|
||||
};
|
||||
case "ThreadCreated":
|
||||
case "UserMessageAppended":
|
||||
case "AssistantMessageAppended":
|
||||
case "ThreadBranchSet": {
|
||||
const payload = JSON.parse(event.payloadJson) as { id?: string; threadId?: string };
|
||||
const threadId = payload.threadId ?? payload.id ?? event.streamId;
|
||||
return {
|
||||
kind: "threadUpsert",
|
||||
sequence: event.sequence,
|
||||
thread:
|
||||
state.threads.get(threadId) ??
|
||||
({
|
||||
id: threadId,
|
||||
projectId: "",
|
||||
title: "Unknown thread",
|
||||
model: "gpt-5",
|
||||
createdAt: event.occurredAt,
|
||||
updatedAt: event.occurredAt,
|
||||
sessionId: null,
|
||||
messages: [],
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
} satisfies CoreThreadView),
|
||||
};
|
||||
}
|
||||
case "GitStateObserved":
|
||||
return {
|
||||
kind: "gitStatusUpsert",
|
||||
sequence: event.sequence,
|
||||
git:
|
||||
state.git.get((JSON.parse(event.payloadJson) as { cwd: string }).cwd) ??
|
||||
(JSON.parse(event.payloadJson) as CoreGitStatusSnapshot),
|
||||
};
|
||||
default:
|
||||
return {
|
||||
kind: "snapshot",
|
||||
sequence: event.sequence,
|
||||
snapshot: toReadModelSnapshot(state),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,7 @@ async function main() {
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
|
||||
+243
-53
@@ -7,8 +7,13 @@ 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,
|
||||
@@ -19,7 +24,6 @@ import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { GitManager } from "./gitManager";
|
||||
import {
|
||||
checkoutGitBranch,
|
||||
@@ -33,6 +37,10 @@ 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 { CodexProviderAdapter } from "./effect/providers/codexProviderAdapter";
|
||||
import { ProviderOrchestrator } from "./effect/providers/providerOrchestrator";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -53,6 +61,7 @@ export interface ServerOptions {
|
||||
port: number;
|
||||
host?: string | undefined;
|
||||
cwd: string;
|
||||
stateDir?: string | undefined;
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
@@ -75,6 +84,7 @@ export function createServer(options: ServerOptions) {
|
||||
port,
|
||||
host,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
@@ -83,11 +93,29 @@ export function createServer(options: ServerOptions) {
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
} = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const providerOrchestrator = new ProviderOrchestrator([new CodexProviderAdapter()]);
|
||||
const terminalManager = providedTerminalManager ?? new TerminalManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const eventStore = new SqliteEventStore(
|
||||
path.join(stateDir ?? path.join(os.homedir(), ".t3", "userdata"), "event-core.sqlite"),
|
||||
);
|
||||
const coreEngine = new CoreEngine({
|
||||
eventStore,
|
||||
probeGitStatus: async (probeCwd) => {
|
||||
const status = await gitManager.status({ cwd: probeCwd });
|
||||
const parsed = gitStatusResultSchema.parse(status);
|
||||
return {
|
||||
cwd: probeCwd,
|
||||
branch: parsed.branch,
|
||||
hasWorkingTreeChanges: parsed.hasWorkingTreeChanges,
|
||||
aheadCount: parsed.aheadCount,
|
||||
behindCount: parsed.behindCount,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
},
|
||||
});
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const logWebSocketEvents =
|
||||
@@ -103,13 +131,7 @@ export function createServer(options: ServerOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
// Forward provider events to all connected WebSocket clients
|
||||
providerManager.on("event", (event) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.providerEvent,
|
||||
data: event,
|
||||
};
|
||||
function broadcastPush(push: WsPush): void {
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
@@ -119,6 +141,36 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
}
|
||||
|
||||
// Forward provider events to all connected WebSocket clients
|
||||
providerOrchestrator.on("event", (event) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.providerEvent,
|
||||
data: event,
|
||||
};
|
||||
broadcastPush(push);
|
||||
if (
|
||||
event.threadId &&
|
||||
typeof event.message === "string" &&
|
||||
event.message.trim().length > 0 &&
|
||||
(event.kind === "notification" || event.method === "turn/completed")
|
||||
) {
|
||||
void coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "AppendAssistantMessage",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
threadId: event.threadId,
|
||||
messageId: event.itemId ?? crypto.randomUUID(),
|
||||
text: event.message,
|
||||
createdAt: event.createdAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const onTerminalEvent = (event: TerminalEvent) => {
|
||||
@@ -127,18 +179,12 @@ export function createServer(options: ServerOptions) {
|
||||
channel: WS_CHANNELS.terminalEvent,
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
if (client.readyState === client.OPEN) {
|
||||
client.send(message);
|
||||
recipients += 1;
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
broadcastPush(push);
|
||||
};
|
||||
terminalManager.on("event", onTerminalEvent);
|
||||
|
||||
let unsubscribeCoreDelta: (() => void) | null = null;
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
// In dev mode, redirect to Vite dev server
|
||||
@@ -291,39 +337,56 @@ export function createServer(options: ServerOptions) {
|
||||
async function routeRequest(request: WsRequest): Promise<unknown> {
|
||||
switch (request.method) {
|
||||
case WS_METHODS.providersStartSession:
|
||||
return providerManager.startSession(request.params as never);
|
||||
return providerOrchestrator.startSession(request.params as never);
|
||||
|
||||
case WS_METHODS.providersSendTurn:
|
||||
return providerManager.sendTurn(request.params as never);
|
||||
return providerOrchestrator.sendTurn(request.params as never);
|
||||
|
||||
case WS_METHODS.providersInterruptTurn:
|
||||
return providerManager.interruptTurn(request.params as never);
|
||||
return providerOrchestrator.interruptTurn(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRespondToRequest:
|
||||
return providerManager.respondToRequest(request.params as never);
|
||||
return providerOrchestrator.respondToRequest(request.params as never);
|
||||
|
||||
case WS_METHODS.providersStopSession: {
|
||||
providerManager.stopSession(request.params as never);
|
||||
providerOrchestrator.stopSession(request.params as never);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.providersListSessions:
|
||||
return providerManager.listSessions();
|
||||
return providerOrchestrator.listSessions();
|
||||
|
||||
case WS_METHODS.providersListCheckpoints:
|
||||
return providerManager.listCheckpoints(request.params as never);
|
||||
return providerOrchestrator.listCheckpoints(request.params as never);
|
||||
|
||||
case WS_METHODS.providersGetCheckpointDiff:
|
||||
return providerManager.getCheckpointDiff(request.params as never);
|
||||
return providerOrchestrator.getCheckpointDiff(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRevertToCheckpoint:
|
||||
return providerManager.revertToCheckpoint(request.params as never);
|
||||
return providerOrchestrator.revertToCheckpoint(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
|
||||
case WS_METHODS.projectsAdd:
|
||||
return projectRegistry.add(request.params as never);
|
||||
return (async () => {
|
||||
const result = projectRegistry.add(request.params as never);
|
||||
const command: CoreDispatchInput = {
|
||||
command: {
|
||||
kind: "CreateProject",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: "gpt-5",
|
||||
},
|
||||
},
|
||||
};
|
||||
await coreEngine.dispatch(command);
|
||||
return result;
|
||||
})();
|
||||
|
||||
case WS_METHODS.projectsRemove:
|
||||
projectRegistry.remove(request.params as never);
|
||||
@@ -382,27 +445,128 @@ export function createServer(options: ServerOptions) {
|
||||
return gitManager.status(request.params as never);
|
||||
|
||||
case WS_METHODS.gitPull:
|
||||
return pullGitBranch(request.params as never);
|
||||
return pullGitBranch(request.params as never).then(async (result) => {
|
||||
const input = request.params as { cwd: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitWorkflow",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
workflow: "stacked_action",
|
||||
cwd: input.cwd,
|
||||
metadata: { source: "git.pull", result },
|
||||
},
|
||||
},
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
case WS_METHODS.gitRunStackedAction:
|
||||
return gitManager.runStackedAction(request.params as never);
|
||||
return gitManager.runStackedAction(request.params as never).then(async (result) => {
|
||||
const input = request.params as { cwd: string; action: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitWorkflow",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
workflow: "stacked_action",
|
||||
cwd: input.cwd,
|
||||
metadata: { source: "git.runStackedAction", action: input.action, result },
|
||||
},
|
||||
},
|
||||
});
|
||||
return result;
|
||||
});
|
||||
case WS_METHODS.gitListBranches:
|
||||
return listGitBranches(request.params as never);
|
||||
|
||||
case WS_METHODS.gitCreateWorktree:
|
||||
return createGitWorktree(request.params as never);
|
||||
return createGitWorktree(request.params as never).then(async (result) => {
|
||||
const input = request.params as { cwd: string; branch: string; newBranch: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitWorkflow",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
workflow: "create_worktree",
|
||||
cwd: input.cwd,
|
||||
metadata: {
|
||||
branch: input.branch,
|
||||
newBranch: input.newBranch,
|
||||
result,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
case WS_METHODS.gitRemoveWorktree:
|
||||
return removeGitWorktree(request.params as never);
|
||||
return removeGitWorktree(request.params as never).then(async () => {
|
||||
const input = request.params as { cwd: string; path: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitWorkflow",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
workflow: "remove_worktree",
|
||||
cwd: input.cwd,
|
||||
metadata: { path: input.path },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
case WS_METHODS.gitCreateBranch:
|
||||
return createGitBranch(request.params as never);
|
||||
return createGitBranch(request.params as never).then(async () => {
|
||||
const input = request.params as { cwd: string; branch: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitWorkflow",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
workflow: "create_branch",
|
||||
cwd: input.cwd,
|
||||
metadata: { branch: input.branch },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
case WS_METHODS.gitCheckout:
|
||||
return checkoutGitBranch(request.params as never);
|
||||
return checkoutGitBranch(request.params as never).then(async () => {
|
||||
const input = request.params as { cwd: string; branch: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitWorkflow",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: {
|
||||
workflow: "checkout",
|
||||
cwd: input.cwd,
|
||||
metadata: { branch: input.branch },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
case WS_METHODS.gitInit:
|
||||
return initGitRepo(request.params as never);
|
||||
return initGitRepo(request.params as never).then(async () => {
|
||||
const input = request.params as { cwd: string };
|
||||
await coreEngine.dispatch({
|
||||
command: {
|
||||
kind: "GitProbe",
|
||||
commandId: crypto.randomUUID(),
|
||||
issuedAt: new Date().toISOString(),
|
||||
payload: { cwd: input.cwd },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
case WS_METHODS.terminalOpen:
|
||||
return terminalManager.open(request.params as never);
|
||||
@@ -438,35 +602,61 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.coreGetSnapshot:
|
||||
coreGetSnapshotInputSchema.parse(request.params ?? {});
|
||||
return coreEngine.getSnapshot();
|
||||
|
||||
case WS_METHODS.coreDispatch: {
|
||||
const input = coreDispatchInputSchema.parse(request.params);
|
||||
return coreEngine.dispatch(input);
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
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);
|
||||
resolve();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
return;
|
||||
}
|
||||
httpServer.listen(port, onListening);
|
||||
});
|
||||
return coreEngine.start().then(
|
||||
() =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => {
|
||||
httpServer.off("error", onError);
|
||||
reject(error);
|
||||
};
|
||||
httpServer.once("error", onError);
|
||||
const onListening = () => {
|
||||
httpServer.off("error", onError);
|
||||
unsubscribeCoreDelta = coreEngine.subscribe((delta: CoreViewDelta) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.coreViewDelta,
|
||||
data: delta,
|
||||
};
|
||||
broadcastPush(push);
|
||||
});
|
||||
resolve();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
return;
|
||||
}
|
||||
httpServer.listen(port, onListening);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
if (unsubscribeCoreDelta) {
|
||||
unsubscribeCoreDelta();
|
||||
unsubscribeCoreDelta = null;
|
||||
}
|
||||
terminalManager.off("event", onTerminalEvent);
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
providerOrchestrator.stopAll();
|
||||
providerOrchestrator.dispose();
|
||||
terminalManager.dispose();
|
||||
await coreEngine.stop();
|
||||
eventStore.close();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
|
||||
@@ -120,6 +120,18 @@ 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 });
|
||||
};
|
||||
|
||||
|
||||
@@ -1709,6 +1709,18 @@ 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,
|
||||
@@ -1764,6 +1776,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
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: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
promptRef.current = "";
|
||||
setPrompt("");
|
||||
|
||||
@@ -152,6 +152,20 @@ 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,
|
||||
@@ -228,6 +242,19 @@ export default function Sidebar() {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,507 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
describe("hydratePersistedState", () => {
|
||||
it("returns null for invalid payloads", () => {
|
||||
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
|
||||
expect(hydratePersistedState("not-json", false)).toBeNull();
|
||||
});
|
||||
|
||||
it("migrates the legacy default model to the current default", () => {
|
||||
const payload = JSON.stringify({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.2-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.2-codex",
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, true);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
|
||||
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
|
||||
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("filters unknown project references and repairs active thread", () => {
|
||||
const payload = JSON.stringify({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
projectId: "p-1",
|
||||
title: "Valid thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "t-2",
|
||||
projectId: "p-missing",
|
||||
title: "Dangling thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-2",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
|
||||
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("hydrates runtime mode from v3 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 3,
|
||||
runtimeMode: "approval-required",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
activeThreadId: null,
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("hydrates terminal fields from legacy v6 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 6,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalLayout: "tabs",
|
||||
splitTerminalIds: [],
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
|
||||
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
|
||||
});
|
||||
|
||||
it("hydrates legacy split layout into a grouped split", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 6,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalLayout: "split",
|
||||
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("defaults terminalHeight when hydrating v5 payloads", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 5,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("hydrates persisted turn diff summaries as metadata-only entries", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops malformed persisted turn diff summaries instead of rejecting the whole snapshot", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
files: [{ path: 123 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads[0]?.id).toBe("t-1");
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v7 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
session: null,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
previewUrl: "blob:preview-1",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [],
|
||||
error: "boom",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:02:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const persisted = toPersistedState({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(7);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
createdAt: thread.createdAt,
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const persistedThread = persisted.threads[0];
|
||||
expect(persistedThread).toBeDefined();
|
||||
if (!persistedThread) return;
|
||||
|
||||
expect("error" in persistedThread).toBe(false);
|
||||
expect("session" in persistedThread).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,399 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { projectScriptSchema } from "@t3tools/contracts";
|
||||
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
|
||||
const persistedProjectSchema = 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(),
|
||||
scripts: z.array(projectScriptSchema).default([]),
|
||||
});
|
||||
|
||||
const persistedMessageSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
role: z.enum(["user", "assistant"]),
|
||||
text: z.string(),
|
||||
attachments: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.literal("image"),
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().min(1),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
createdAt: z.string().min(1),
|
||||
streaming: z.boolean(),
|
||||
});
|
||||
|
||||
const persistedTerminalGroupSchema = z.object({
|
||||
id: z.string().trim().min(1),
|
||||
terminalIds: z.array(z.string().trim().min(1)),
|
||||
});
|
||||
|
||||
const persistedTurnDiffFileChangeSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: z.string().min(1).optional(),
|
||||
additions: z.number().int().min(0).optional(),
|
||||
deletions: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
const persistedTurnDiffSummarySchema = z.object({
|
||||
turnId: z.string().min(1),
|
||||
completedAt: z.string().min(1),
|
||||
status: z.string().min(1).optional(),
|
||||
files: z.array(persistedTurnDiffFileChangeSchema),
|
||||
assistantMessageId: z.string().min(1).optional(),
|
||||
checkpointTurnCount: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
const persistedThreadSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
codexThreadId: z.string().min(1).nullable().default(null),
|
||||
projectId: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
terminalOpen: z.boolean().default(false),
|
||||
terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
|
||||
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
|
||||
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
|
||||
activeTerminalGroupId: z.string().trim().min(1).optional(),
|
||||
// Legacy v6 and older fields retained for migration.
|
||||
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
|
||||
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
|
||||
messages: z.array(persistedMessageSchema),
|
||||
createdAt: z.string().min(1),
|
||||
lastVisitedAt: z.string().min(1).optional(),
|
||||
branch: z.string().min(1).nullable().optional(),
|
||||
worktreePath: z.string().min(1).nullable().optional(),
|
||||
turnDiffSummaries: z.array(persistedTurnDiffSummarySchema).catch([]).default([]),
|
||||
});
|
||||
|
||||
const persistedStateBodySchema = z.object({
|
||||
projects: z.array(persistedProjectSchema),
|
||||
threads: z.array(persistedThreadSchema),
|
||||
activeThreadId: z.string().min(1).nullable().optional(),
|
||||
});
|
||||
|
||||
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
|
||||
|
||||
export const persistedStateV1Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(1).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV2Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(2).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV3Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(3).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV4Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(4).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV6Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(6).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV7Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(7).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV5Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(5).optional(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV7Schema,
|
||||
persistedStateV6Schema,
|
||||
persistedStateV5Schema,
|
||||
persistedStateV4Schema,
|
||||
persistedStateV3Schema,
|
||||
persistedStateV2Schema,
|
||||
persistedStateV1Schema,
|
||||
]);
|
||||
|
||||
export interface PersistedStoreSnapshot {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
|
||||
if (!isLegacyPayload) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
|
||||
}
|
||||
|
||||
function hydrateProject(
|
||||
project: z.infer<typeof persistedProjectSchema>,
|
||||
isLegacyPayload: boolean,
|
||||
): Project {
|
||||
return {
|
||||
...project,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
|
||||
scripts: project.scripts,
|
||||
};
|
||||
}
|
||||
|
||||
function hydrateThread(
|
||||
thread: z.infer<typeof persistedThreadSchema>,
|
||||
isLegacyPayload: boolean,
|
||||
): Thread {
|
||||
const terminalIds = [
|
||||
...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
];
|
||||
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const safeTerminalIdSet = new Set(safeTerminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const normalizedGroups: ThreadTerminalGroup[] = [];
|
||||
const assignUniqueGroupId = (groupId: string): string => {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
};
|
||||
|
||||
for (const terminalGroup of thread.terminalGroups) {
|
||||
const nextTerminalIds = [
|
||||
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
].filter((terminalId) => {
|
||||
if (!safeTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (nextTerminalIds.length === 0) continue;
|
||||
for (const terminalId of nextTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
terminalGroup.id.trim().length > 0
|
||||
? terminalGroup.id.trim()
|
||||
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId),
|
||||
terminalIds: nextTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
|
||||
const splitTerminalIds = [
|
||||
...new Set(
|
||||
(thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
|
||||
),
|
||||
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
|
||||
if (splitTerminalIds.length >= 2) {
|
||||
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
|
||||
for (const terminalId of splitGroupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
|
||||
terminalIds: splitGroupTerminalIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const terminalId of safeTerminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(`group-${terminalId}`),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
const activeGroupIndexFromId = normalizedGroups.findIndex(
|
||||
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
|
||||
terminalGroup.terminalIds.includes(activeTerminalId),
|
||||
);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: activeGroupIndexFromTerminal >= 0
|
||||
? activeGroupIndexFromTerminal
|
||||
: 0;
|
||||
const activeTerminalGroupId =
|
||||
normalizedGroups[activeGroupIndex]?.id ??
|
||||
normalizedGroups[0]?.id ??
|
||||
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
|
||||
terminalOpen: thread.terminalOpen ?? false,
|
||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: safeTerminalIds,
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId,
|
||||
terminalGroups: normalizedGroups,
|
||||
activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(hydratedAttachments && hydratedAttachments.length > 0
|
||||
? { attachments: hydratedAttachments }
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: false,
|
||||
};
|
||||
}),
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: thread.createdAt,
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: thread.branch ?? null,
|
||||
worktreePath: thread.worktreePath ?? null,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function hydratePersistedState(
|
||||
raw: string,
|
||||
isLegacyPayload: boolean,
|
||||
): PersistedStoreSnapshot | null {
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
parsedJson = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedState = persistedStateSchema.safeParse(parsedJson);
|
||||
if (!parsedState.success) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const projects = parsedState.data.projects.map((project) =>
|
||||
hydrateProject(project, isLegacyPayload),
|
||||
);
|
||||
const projectIds = new Set(projects.map((project) => project.id));
|
||||
const threads = parsedState.data.threads
|
||||
.map((thread) => hydrateThread(thread, isLegacyPayload))
|
||||
.filter((thread) => projectIds.has(thread.projectId));
|
||||
return {
|
||||
projects,
|
||||
threads,
|
||||
runtimeMode:
|
||||
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV7Schema> {
|
||||
return {
|
||||
version: 7,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
terminalOpen: thread.terminalOpen,
|
||||
terminalHeight: thread.terminalHeight,
|
||||
terminalIds: thread.terminalIds,
|
||||
activeTerminalId: thread.activeTerminalId,
|
||||
terminalGroups: thread.terminalGroups,
|
||||
activeTerminalGroupId: thread.activeTerminalGroupId,
|
||||
messages: thread.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments && message.attachments.length > 0
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})),
|
||||
createdAt: thread.createdAt,
|
||||
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
})),
|
||||
runtimeMode: state.runtimeMode,
|
||||
};
|
||||
}
|
||||
@@ -126,7 +126,6 @@ function EventRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
const activeThreadId = useParams({
|
||||
strict: false,
|
||||
select: (params) => params.threadId,
|
||||
@@ -134,30 +133,27 @@ function EventRouter() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.providers.onEvent((event) => {
|
||||
if (event.method === "turn/completed") {
|
||||
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);
|
||||
}
|
||||
if (event.method === "checkpoint/captured") {
|
||||
const payload = event.payload as { turnCount?: number } | undefined;
|
||||
const turnCount = payload?.turnCount;
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["providers", "checkpointDiff"] as const,
|
||||
predicate: (query) => {
|
||||
if (typeof turnCount !== "number") return true;
|
||||
return query.queryKey[5] === turnCount;
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "APPLY_EVENT",
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
activeThreadId,
|
||||
});
|
||||
});
|
||||
}, [activeThreadId, api, dispatch, queryClient]);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribeCore();
|
||||
};
|
||||
}, [api, dispatch, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -168,16 +164,6 @@ function EventRouter() {
|
||||
});
|
||||
}, [activeThreadId, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,935 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,983 +0,0 @@
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
} from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
type TerminalActivityEvent = Extract<TerminalEvent, { type: "activity" }>;
|
||||
|
||||
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
updatedAt: "2026-02-09T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeEvent(overrides: Partial<ProviderEvent> = {}): ProviderEvent {
|
||||
return {
|
||||
id: "evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
method: "thread/started",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: null,
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: makeSession(),
|
||||
messages: [],
|
||||
events: [],
|
||||
turnDiffSummaries: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeState(thread: Thread): AppState {
|
||||
return {
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalStartedEvent(
|
||||
overrides: Partial<TerminalStartedEvent> = {},
|
||||
): TerminalStartedEvent {
|
||||
return {
|
||||
type: "started",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
snapshot: {
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalActivityEvent(
|
||||
overrides: Partial<TerminalActivityEvent> = {},
|
||||
): TerminalActivityEvent {
|
||||
return {
|
||||
type: "activity",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer thread continuity", () => {
|
||||
it("stores codexThreadId from UPDATE_SESSION", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
session: null,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "UPDATE_SESSION",
|
||||
threadId: "thread-local-1",
|
||||
session: makeSession({ threadId: "thr_123" }),
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_123");
|
||||
});
|
||||
|
||||
it("toggles terminal open state per thread", () => {
|
||||
const state = makeState(makeThread({ terminalOpen: false }));
|
||||
const next = reducer(state, {
|
||||
type: "TOGGLE_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
});
|
||||
expect(next.threads[0]?.terminalOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("sets terminal open state per thread", () => {
|
||||
const state = makeState(makeThread({ terminalOpen: true }));
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: "thread-local-1",
|
||||
open: false,
|
||||
});
|
||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("sets terminal height per thread", () => {
|
||||
const state = makeState(makeThread({ terminalHeight: 280 }));
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TERMINAL_HEIGHT",
|
||||
threadId: "thread-local-1",
|
||||
height: 360,
|
||||
});
|
||||
expect(next.threads[0]?.terminalHeight).toBe(360);
|
||||
});
|
||||
|
||||
it("splits the active terminal into side-by-side mode", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("creates a new full-width terminal and switches to tab mode", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
|
||||
});
|
||||
|
||||
it("switches the active terminal and restores its owning group", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-3",
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_ACTIVE_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("supports splitting beyond two terminals in the same group", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-3",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
},
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-3");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("caps split terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
});
|
||||
|
||||
it("caps new terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
{ id: "group-term-4", terminalIds: ["term-4"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-4",
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
|
||||
});
|
||||
|
||||
it("closes a terminal and keeps grouped layout coherent", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the final terminal and hides the drawer", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalOpen: true,
|
||||
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("tracks running terminals from subprocess activity events", () => {
|
||||
const state = makeState(makeThread());
|
||||
const started = reducer(state, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalStartedEvent(),
|
||||
});
|
||||
expect(started.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
|
||||
const active = reducer(started, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent(),
|
||||
});
|
||||
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
|
||||
const idle = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
|
||||
});
|
||||
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
|
||||
const exited = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:05.000Z",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
},
|
||||
});
|
||||
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps running status when another terminal in the thread is still running", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:07.000Z",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
|
||||
});
|
||||
|
||||
it("backfills codexThreadId from routed provider events", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: null }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "thread/started",
|
||||
payload: { thread: { id: "thr_backfilled" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
|
||||
});
|
||||
|
||||
it("ignores events from a foreign thread within the same session", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/started",
|
||||
threadId: "thr_unexpected",
|
||||
payload: { turn: { id: "turn-1" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next).toBe(state);
|
||||
});
|
||||
|
||||
it("rebases thread identity on thread/started during connect", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
codexThreadId: "thr_old",
|
||||
session: makeSession({
|
||||
status: "connecting",
|
||||
threadId: "thr_old",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "thread/started",
|
||||
threadId: "thr_new",
|
||||
payload: { thread: { id: "thr_new" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_new");
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
|
||||
});
|
||||
|
||||
it("preserves persisted turn diffs when events were reset and appends new completed turn diffs", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
events: [],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:01.000Z",
|
||||
files: [{ path: "src/existing.ts", kind: "modified" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const withFileChange = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
type: "fileChange",
|
||||
changes: [{ path: "src/new.ts", kind: "added" }],
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(withFileChange.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
"turn-1",
|
||||
]);
|
||||
|
||||
const completed = reducer(withFileChange, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-2", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(completed.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
"turn-2",
|
||||
"turn-1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
|
||||
const state = makeState(makeThread({ turnDiffSummaries: [] }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
it("reconciles project ids by cwd when syncing backend projects", () => {
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
{
|
||||
id: "project-old-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
id: "project-old-b",
|
||||
name: "B",
|
||||
cwd: "/tmp/b",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
makeThread({
|
||||
id: "thread-a",
|
||||
projectId: "project-old-a",
|
||||
}),
|
||||
makeThread({
|
||||
id: "thread-b",
|
||||
projectId: "project-old-b",
|
||||
}),
|
||||
],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: [
|
||||
{
|
||||
id: "project-new-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.id).toBe("project-new-a");
|
||||
// Preserve existing project UI preferences by cwd
|
||||
expect(next.projects[0]?.expanded).toBe(false);
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-a");
|
||||
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
||||
});
|
||||
|
||||
it("treats empty scripts from sync as authoritative", () => {
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
{
|
||||
id: "project-old-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: [
|
||||
{
|
||||
id: "project-new-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(next.projects[0]?.scripts).toEqual([]);
|
||||
});
|
||||
|
||||
it("updates project scripts", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_PROJECT_SCRIPTS",
|
||||
projectId: "project-1",
|
||||
scripts: [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(next.projects[0]?.scripts).toEqual([
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks threads hydration state", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREADS_HYDRATED",
|
||||
hydrated: false,
|
||||
});
|
||||
|
||||
expect(next.threadsHydrated).toBe(false);
|
||||
});
|
||||
|
||||
it("deletes a project and all of its threads", () => {
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
name: "One",
|
||||
cwd: "/tmp/one",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
id: "project-2",
|
||||
name: "Two",
|
||||
cwd: "/tmp/two",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
makeThread({
|
||||
id: "thread-a",
|
||||
projectId: "project-1",
|
||||
}),
|
||||
makeThread({
|
||||
id: "thread-b",
|
||||
projectId: "project-2",
|
||||
}),
|
||||
],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "DELETE_PROJECT",
|
||||
projectId: "project-1",
|
||||
});
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.id).toBe("project-2");
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-b");
|
||||
});
|
||||
|
||||
it("marks completion as seen immediately for the active thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
session: makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
}),
|
||||
lastVisitedAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const completedAt = "2026-02-08T10:00:10.000Z";
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: completedAt,
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
activeThreadId: "thread-local-1",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
|
||||
});
|
||||
|
||||
it("marks a thread as visited when selected", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
latestTurnCompletedAt: "2026-02-08T10:00:10.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const nextVisitedAt = "2026-02-08T10:00:20.000Z";
|
||||
const next = reducer(state, {
|
||||
type: "MARK_THREAD_VISITED",
|
||||
threadId: "thread-local-1",
|
||||
visitedAt: nextVisitedAt,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(nextVisitedAt);
|
||||
});
|
||||
|
||||
it("reverts thread state to a checkpoint snapshot", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
codexThreadId: "thr_before",
|
||||
session: makeSession({
|
||||
status: "running",
|
||||
threadId: "thr_before",
|
||||
activeTurnId: "turn-live",
|
||||
}),
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "First",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-2",
|
||||
role: "assistant",
|
||||
text: "First reply",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-3",
|
||||
role: "user",
|
||||
text: "Second",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [
|
||||
makeEvent({
|
||||
method: "turn/started",
|
||||
turnId: "turn-live",
|
||||
}),
|
||||
],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn_1",
|
||||
completedAt: "2026-02-08T10:00:01.000Z",
|
||||
files: [{ path: "src/first.ts", kind: "modified" }],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
{
|
||||
turnId: "turn_2",
|
||||
completedAt: "2026-02-08T10:00:03.000Z",
|
||||
files: [{ path: "src/second.ts", kind: "modified" }],
|
||||
checkpointTurnCount: 2,
|
||||
},
|
||||
],
|
||||
error: "temporary failure",
|
||||
latestTurnId: "turn-live",
|
||||
latestTurnStartedAt: "2026-02-08T10:00:03.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: "thread-local-1",
|
||||
sessionId: "sess-1",
|
||||
threadRuntimeId: "thr_after",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual(["m-1", "m-2"]);
|
||||
expect(next.threads[0]?.events).toEqual([]);
|
||||
expect(next.threads[0]?.error).toBeNull();
|
||||
expect(next.threads[0]?.session?.status).toBe("ready");
|
||||
expect(next.threads[0]?.session?.activeTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.latestTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn_1"]);
|
||||
});
|
||||
|
||||
it("keeps existing turn file metadata when later events for the same turn arrive", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:03.000Z",
|
||||
files: [
|
||||
{
|
||||
path: "src/from-checkpoint.ts",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:04.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/from-checkpoint.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
it("updates checkpoint turn counts from authoritative checkpoint mappings", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:03.000Z",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
{
|
||||
turnId: "turn-2",
|
||||
completedAt: "2026-02-09T00:00:04.000Z",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
|
||||
threadId: "thread-local-1",
|
||||
checkpointTurnCountByTurnId: {
|
||||
"turn-1": 2,
|
||||
"turn-2": 3,
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(2);
|
||||
expect(next.threads[0]?.turnDiffSummaries[1]?.checkpointTurnCount).toBe(3);
|
||||
});
|
||||
|
||||
it("does not rederive completed turn summaries from late turn diff events", () => {
|
||||
const completed = reducer(makeState(makeThread()), {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(completed.threads[0]?.turnDiffSummaries[0]?.files).toEqual([]);
|
||||
|
||||
const withLateDiff = reducer(completed, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:04.000Z",
|
||||
payload: {
|
||||
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",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(withLateDiff.threads[0]?.turnDiffSummaries[0]?.files).toEqual([]);
|
||||
});
|
||||
});
|
||||
+188
-282
@@ -4,23 +4,20 @@ import {
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import {
|
||||
applyEventToMessages,
|
||||
asObject,
|
||||
asString,
|
||||
deriveTurnDiffSummaries,
|
||||
inferCheckpointTurnCountByTurnId,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
type CoreReadModelSnapshot,
|
||||
type CoreThreadMessageView,
|
||||
type CoreViewDelta,
|
||||
type ProviderSession,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
@@ -31,6 +28,20 @@ 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 =
|
||||
@@ -38,6 +49,8 @@ type Action =
|
||||
| { 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 }
|
||||
@@ -48,13 +61,6 @@ type Action =
|
||||
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
activeThreadId?: string | null;
|
||||
}
|
||||
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| {
|
||||
type: "PUSH_USER_MESSAGE";
|
||||
@@ -98,18 +104,6 @@ export interface AppState {
|
||||
runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
"t3code:renderer-state:v6",
|
||||
"t3code:renderer-state:v5",
|
||||
"t3code:renderer-state:v4",
|
||||
"t3code:renderer-state:v3",
|
||||
"codething:renderer-state:v4",
|
||||
"codething:renderer-state:v3",
|
||||
"codething:renderer-state:v2",
|
||||
"codething:renderer-state:v1",
|
||||
] as const;
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
threads: [],
|
||||
@@ -120,41 +114,87 @@ const initialState: AppState = {
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
|
||||
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
if (!raw) return initialState;
|
||||
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
|
||||
|
||||
return {
|
||||
...hydrated,
|
||||
threads,
|
||||
threadsHydrated: threads.length > 0,
|
||||
};
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
return initialState;
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
function mapCoreMessageToChatMessage(message: CoreThreadMessageView): Thread["messages"][number] {
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
function mapCoreScriptsToProjectScripts(
|
||||
scripts: CoreReadModelSnapshot["projects"][number]["scripts"],
|
||||
): ProjectScript[] {
|
||||
return scripts.map((script) => {
|
||||
const icon = normalizeScriptIcon(script.icon ?? undefined);
|
||||
return {
|
||||
id: script.id,
|
||||
name: script.name,
|
||||
command: script.command,
|
||||
icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate ?? false,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function mapSnapshotToState(snapshot: CoreReadModelSnapshot, previous: AppState): AppState {
|
||||
const projects: Project[] = snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: project.model,
|
||||
expanded: project.expanded,
|
||||
scripts: mapCoreScriptsToProjectScripts(project.scripts),
|
||||
}));
|
||||
|
||||
const threads: Thread[] = snapshot.threads.map((thread) => {
|
||||
const existing = previous.threads.find((entry) => entry.id === thread.id);
|
||||
const next: Thread = {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
terminalOpen: existing?.terminalOpen ?? false,
|
||||
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: existing?.runningTerminalIds ?? [],
|
||||
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: existing?.terminalGroups ?? [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: existing?.session ?? null,
|
||||
messages: thread.messages.map(mapCoreMessageToChatMessage),
|
||||
events: existing?.events ?? [],
|
||||
error: existing?.error ?? null,
|
||||
createdAt: thread.createdAt,
|
||||
latestTurnId: existing?.latestTurnId,
|
||||
latestTurnStartedAt: existing?.latestTurnStartedAt,
|
||||
latestTurnCompletedAt: existing?.latestTurnCompletedAt,
|
||||
latestTurnDurationMs: existing?.latestTurnDurationMs,
|
||||
lastVisitedAt: existing?.lastVisitedAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: existing?.turnDiffSummaries ?? [],
|
||||
};
|
||||
return normalizeThreadTerminals(next);
|
||||
});
|
||||
|
||||
return {
|
||||
...previous,
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
@@ -165,64 +205,6 @@ function updateThread(
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function mergeTurnDiffSummaries(
|
||||
existing: Thread["turnDiffSummaries"],
|
||||
next: Thread["turnDiffSummaries"],
|
||||
): Thread["turnDiffSummaries"] {
|
||||
if (next.length === 0) return existing;
|
||||
|
||||
const existingByTurnId = new Map(existing.map((summary) => [summary.turnId, summary] as const));
|
||||
const merged = next.map((summary) => {
|
||||
const previous = existingByTurnId.get(summary.turnId);
|
||||
if (!previous) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const files =
|
||||
summary.files.length === 0 && previous.files.length > 0 ? previous.files : summary.files;
|
||||
|
||||
return {
|
||||
...summary,
|
||||
files,
|
||||
...(summary.assistantMessageId
|
||||
? {}
|
||||
: previous.assistantMessageId
|
||||
? { assistantMessageId: previous.assistantMessageId }
|
||||
: {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? {}
|
||||
: typeof previous.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: previous.checkpointTurnCount }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const mergedTurnIds = new Set(merged.map((summary) => summary.turnId));
|
||||
for (const summary of existing) {
|
||||
if (!mergedTurnIds.has(summary.turnId)) {
|
||||
merged.push(summary);
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = merged.toSorted((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
const inferredTurnCountByTurnId = inferCheckpointTurnCountByTurnId(sorted);
|
||||
return sorted.map((summary) =>
|
||||
typeof summary.checkpointTurnCount === "number"
|
||||
? summary
|
||||
: Object.assign({}, summary, {
|
||||
checkpointTurnCount: inferredTurnCountByTurnId[summary.turnId],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
@@ -409,89 +391,6 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
});
|
||||
}
|
||||
|
||||
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
|
||||
return threads.find((t) => t.session?.sessionId === sessionId);
|
||||
}
|
||||
|
||||
function getEventTurnId(event: ProviderEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
return asString(turn?.id);
|
||||
}
|
||||
|
||||
function getEventThreadId(event: ProviderEvent): string | undefined {
|
||||
if (event.threadId) return event.threadId;
|
||||
const payload = asObject(event.payload);
|
||||
const payloadThread = asObject(payload?.thread);
|
||||
const payloadMessage = asObject(payload?.msg);
|
||||
return (
|
||||
asString(payload?.threadId) ??
|
||||
asString(payloadThread?.id) ??
|
||||
asString(payload?.conversationId) ??
|
||||
asString(payload?.thread_id) ??
|
||||
asString(payloadMessage?.thread_id)
|
||||
);
|
||||
}
|
||||
|
||||
function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderEvent): boolean {
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
if (!eventThreadId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedThreadId = thread.session?.threadId ?? thread.codexThreadId;
|
||||
if (!expectedThreadId || eventThreadId === expectedThreadId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// During connect, accept a thread/started notification as an identity rebind.
|
||||
if (event.method === "thread/started" && thread.session?.status === "connecting") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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 updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
|
||||
if (event.method === "turn/started") {
|
||||
return {
|
||||
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
|
||||
latestTurnStartedAt: event.createdAt,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
|
||||
const startedAt =
|
||||
completedTurnId && completedTurnId === thread.latestTurnId
|
||||
? thread.latestTurnStartedAt
|
||||
: undefined;
|
||||
const elapsed =
|
||||
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
|
||||
|
||||
return {
|
||||
latestTurnId: completedTurnId ?? thread.latestTurnId,
|
||||
latestTurnCompletedAt: event.createdAt,
|
||||
latestTurnDurationMs: elapsed,
|
||||
};
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
@@ -531,6 +430,92 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threadsHydrated: action.hydrated,
|
||||
};
|
||||
|
||||
case "APPLY_CORE_SNAPSHOT":
|
||||
return mapSnapshotToState(action.snapshot, state);
|
||||
|
||||
case "APPLY_CORE_DELTA": {
|
||||
const delta = action.delta;
|
||||
switch (delta.kind) {
|
||||
case "snapshot":
|
||||
return mapSnapshotToState(delta.snapshot, state);
|
||||
case "projectUpsert": {
|
||||
const project: Project = {
|
||||
id: delta.project.id,
|
||||
name: delta.project.name,
|
||||
cwd: delta.project.cwd,
|
||||
model: delta.project.model,
|
||||
expanded: delta.project.expanded,
|
||||
scripts: mapCoreScriptsToProjectScripts(delta.project.scripts),
|
||||
};
|
||||
const existing = state.projects.find((item) => item.id === project.id);
|
||||
return {
|
||||
...state,
|
||||
projects: existing
|
||||
? state.projects.map((item) => (item.id === project.id ? project : item))
|
||||
: [...state.projects, project],
|
||||
};
|
||||
}
|
||||
case "projectDelete":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.filter((project) => project.id !== delta.projectId),
|
||||
threads: state.threads.filter((thread) => thread.projectId !== delta.projectId),
|
||||
};
|
||||
case "threadDelete":
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.filter((thread) => thread.id !== delta.threadId),
|
||||
};
|
||||
case "threadUpsert": {
|
||||
const snapshot: CoreReadModelSnapshot = {
|
||||
sequence: delta.sequence,
|
||||
generatedAt: new Date().toISOString(),
|
||||
projects: state.projects.map((project) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: project.model,
|
||||
expanded: project.expanded,
|
||||
scripts: project.scripts.map((script) => ({
|
||||
id: script.id,
|
||||
name: script.name,
|
||||
command: script.command,
|
||||
icon: script.icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
||||
})),
|
||||
})),
|
||||
threads: [
|
||||
...state.threads
|
||||
.filter((thread) => thread.id !== delta.thread.id)
|
||||
.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.latestTurnCompletedAt ?? thread.createdAt,
|
||||
sessionId: thread.session?.sessionId ?? null,
|
||||
messages: thread.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})),
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
})),
|
||||
delta.thread,
|
||||
],
|
||||
git: [],
|
||||
};
|
||||
return mapSnapshotToState(snapshot, state);
|
||||
}
|
||||
case "gitStatusUpsert":
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
case "SYNC_PROJECTS": {
|
||||
const previousByCwd = new Map(
|
||||
state.projects.map((project) => [project.cwd, project] as const),
|
||||
@@ -774,81 +759,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
),
|
||||
};
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.event.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
|
||||
if (action.event.type === "started" || action.event.type === "restarted") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
} else if (action.event.type === "activity") {
|
||||
if (action.event.hasRunningSubprocess) {
|
||||
runningTerminalIdSet.add(action.event.terminalId);
|
||||
} else {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
} else if (action.event.type === "exited" || action.event.type === "error") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIdSet],
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "APPLY_EVENT": {
|
||||
const { event, activeAssistantItemRef, activeThreadId } = action;
|
||||
const target = findThreadBySessionId(state.threads, event.sessionId);
|
||||
if (!target) return state;
|
||||
if (shouldIgnoreForeignThreadEvent(target, event)) return state;
|
||||
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, target.id, (t) => {
|
||||
const nextEvents = [event, ...t.events];
|
||||
const eventTurnId = getEventTurnId(event);
|
||||
const hasCompletedSummaryForTurn = Boolean(
|
||||
eventTurnId && t.turnDiffSummaries.some((summary) => summary.turnId === eventTurnId),
|
||||
);
|
||||
const itemType = asString(asObject(asObject(event.payload)?.item)?.type);
|
||||
const normalizedItemType = itemType?.replace(/[_-]/g, "").toLowerCase();
|
||||
const isMetadataItemCompleted =
|
||||
event.method === "item/completed" &&
|
||||
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange");
|
||||
const shouldRederiveDiffs =
|
||||
event.method === "turn/completed" ||
|
||||
(hasCompletedSummaryForTurn && isMetadataItemCompleted);
|
||||
const turnDiffSummaries = shouldRederiveDiffs
|
||||
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
|
||||
: t.turnDiffSummaries;
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
const shouldRebindIdentity =
|
||||
event.method === "thread/started" && t.session?.status === "connecting";
|
||||
return {
|
||||
...t,
|
||||
codexThreadId: shouldRebindIdentity
|
||||
? (eventThreadId ?? t.codexThreadId)
|
||||
: (t.codexThreadId ?? eventThreadId ?? null),
|
||||
error: event.kind === "error" && event.message ? event.message : t.error,
|
||||
session: t.session ? evolveSession(t.session, event) : t.session,
|
||||
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
||||
events: nextEvents,
|
||||
turnDiffSummaries,
|
||||
...updateTurnFields(t, event),
|
||||
...(event.method === "turn/completed" && t.id === activeThreadId
|
||||
? { lastVisitedAt: event.createdAt }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "UPDATE_SESSION":
|
||||
return {
|
||||
...state,
|
||||
@@ -1035,10 +945,6 @@ const StoreContext = createContext<{
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
|
||||
@@ -149,6 +149,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),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
|
||||
@@ -34,6 +34,10 @@
|
||||
"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",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
@@ -144,6 +148,16 @@
|
||||
|
||||
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
|
||||
|
||||
"@effect/experimental": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/platform": "^0.94.0", "effect": "^3.19.13", "ioredis": "^5", "lmdb": "^3" }, "optionalPeers": ["ioredis", "lmdb"] }, "sha512-IEP9sapjF6rFy5TkoqDPc86st/fnqUfjT7Xa3pWJrFGr1hzaMXHo+mWsYOZS9LAOVKnpHuVziDK97EP5qsCHVA=="],
|
||||
|
||||
"@effect/platform": ["@effect/[email protected]", "", { "dependencies": { "find-my-way-ts": "^0.1.6", "msgpackr": "^1.11.4", "multipasta": "^0.2.7" }, "peerDependencies": { "effect": "^3.19.17" } }, "sha512-z05APUiDDPbodhTkH/RJqOLoCU11bU2IZLfcwLFrld03+ob1VeqRnELQlmueLIYm6NZifHAtjl32V+GRt34y4A=="],
|
||||
|
||||
"@effect/schema": ["@effect/[email protected]", "", { "dependencies": { "fast-check": "^3.21.0" }, "peerDependencies": { "effect": "^3.9.2" } }, "sha512-TQInulTVCuF+9EIbJpyLP6dvxbQJMphrnRqgexm/Ze39rSjfhJuufF7XvU3SxTgg3HnL7B/kpORTJbHhlE6thw=="],
|
||||
|
||||
"@effect/sql": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.0", "effect": "^3.19.13" } }, "sha512-9UEKR+z+MrI/qMAmSvb/RiD9KlgIazjZUCDSpwNgm0lEK9/Q6ExEyfziiYFVCPiptp52cBw8uBHRic8hHnwqXA=="],
|
||||
|
||||
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.4", "@effect/sql": "^0.49.0", "effect": "^3.19.16" } }, "sha512-L7DlHcOVl9/9V5stttFyv9wjvA9PBbaXwsp9pU+KN8KqokWgAVBNBEDf/dVfboUrynbDpDWwMU9SJmRJ1LXASQ=="],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -244,6 +258,18 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
|
||||
|
||||
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
|
||||
|
||||
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
|
||||
@@ -582,18 +608,28 @@
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
|
||||
|
||||
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
|
||||
|
||||
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
|
||||
|
||||
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
|
||||
|
||||
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
|
||||
|
||||
"birpc": ["[email protected]", "", {}, "sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw=="],
|
||||
|
||||
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
|
||||
|
||||
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
|
||||
|
||||
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
|
||||
|
||||
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
|
||||
|
||||
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
@@ -624,6 +660,8 @@
|
||||
|
||||
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
|
||||
|
||||
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
|
||||
|
||||
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
|
||||
|
||||
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
|
||||
@@ -656,6 +694,8 @@
|
||||
|
||||
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
|
||||
|
||||
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
|
||||
|
||||
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
|
||||
@@ -686,6 +726,8 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-Yc8U/SVXo2dHnaP7zNBlAo83h/nzSJpi7vph6Hzyl4ulgMBIgPmz3UzOjb9sBgpFE00gC0iETR244sfXDNLHRg=="],
|
||||
|
||||
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
|
||||
|
||||
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
|
||||
@@ -726,22 +768,32 @@
|
||||
|
||||
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
|
||||
|
||||
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
|
||||
|
||||
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
|
||||
|
||||
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
|
||||
|
||||
"fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
||||
|
||||
"fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
|
||||
|
||||
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
|
||||
|
||||
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
|
||||
|
||||
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
|
||||
|
||||
"follow-redirects": ["[email protected]", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
|
||||
|
||||
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
|
||||
|
||||
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
|
||||
|
||||
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
@@ -760,6 +812,8 @@
|
||||
|
||||
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
|
||||
|
||||
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
|
||||
|
||||
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
|
||||
@@ -808,10 +862,16 @@
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
|
||||
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
|
||||
|
||||
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
|
||||
|
||||
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
|
||||
|
||||
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
|
||||
|
||||
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
|
||||
@@ -1006,16 +1066,30 @@
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
|
||||
|
||||
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
|
||||
|
||||
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
|
||||
|
||||
"multipasta": ["[email protected]", "", {}, "sha512-KPA58d68KgGil15oDqXjkUBEBYc00XvbPj5/X+dyzeo/lWm9Nc25pQRlf1D+gv4OpK7NM0J1odrbu9JNNGvynA=="],
|
||||
|
||||
"mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
|
||||
|
||||
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
|
||||
|
||||
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
|
||||
|
||||
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
|
||||
|
||||
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
|
||||
|
||||
"node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
|
||||
|
||||
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
|
||||
@@ -1060,6 +1134,8 @@
|
||||
|
||||
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
|
||||
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
|
||||
@@ -1070,10 +1146,14 @@
|
||||
|
||||
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
|
||||
|
||||
"pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
||||
|
||||
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
|
||||
|
||||
"quick-lru": ["[email protected]", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
|
||||
|
||||
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
|
||||
|
||||
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
|
||||
|
||||
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
|
||||
@@ -1082,6 +1162,8 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
|
||||
|
||||
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
|
||||
|
||||
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
|
||||
@@ -1132,6 +1214,8 @@
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
@@ -1150,6 +1234,10 @@
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
|
||||
|
||||
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1168,10 +1256,14 @@
|
||||
|
||||
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
|
||||
|
||||
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
|
||||
|
||||
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
|
||||
|
||||
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
|
||||
|
||||
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
|
||||
@@ -1192,6 +1284,10 @@
|
||||
|
||||
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
|
||||
|
||||
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
|
||||
|
||||
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
|
||||
|
||||
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
|
||||
|
||||
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
|
||||
@@ -1226,6 +1322,8 @@
|
||||
|
||||
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
|
||||
|
||||
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
|
||||
|
||||
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.7", "turbo-darwin-arm64": "2.8.7", "turbo-linux-64": "2.8.7", "turbo-linux-arm64": "2.8.7", "turbo-windows-64": "2.8.7", "turbo-windows-arm64": "2.8.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RBLh5caMAu1kFdTK1jgH2gH/z+jFsvX5rGbhgJ9nlIAWXSvxlzwId05uDlBA1+pBd3wO/UaKYzaQZQBXDd7kcA=="],
|
||||
|
||||
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xr4TO/oDDwoozbDtBvunb66g//WK8uHRygl72vUthuwzmiw48pil4IuoG/QbMHd9RE8aBnVmzC0WZEWk/WWt3A=="],
|
||||
@@ -1276,6 +1374,10 @@
|
||||
|
||||
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
|
||||
|
||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
|
||||
|
||||
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
|
||||
|
||||
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const coreGitStatusSnapshotSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
branch: z.string().min(1).nullable(),
|
||||
hasWorkingTreeChanges: z.boolean(),
|
||||
aheadCount: z.number().int().nonnegative(),
|
||||
behindCount: z.number().int().nonnegative(),
|
||||
observedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const coreProjectViewSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
expanded: z.boolean().default(true),
|
||||
scripts: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
command: z.string().min(1),
|
||||
icon: z.string().min(1).nullable().optional(),
|
||||
runOnWorktreeCreate: z.boolean().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const coreThreadMessageViewSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
role: z.enum(["user", "assistant"]),
|
||||
text: z.string(),
|
||||
createdAt: z.string().datetime(),
|
||||
streaming: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const coreThreadViewSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
projectId: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
sessionId: z.string().min(1).nullable(),
|
||||
messages: z.array(coreThreadMessageViewSchema),
|
||||
branch: z.string().min(1).nullable(),
|
||||
worktreePath: z.string().min(1).nullable(),
|
||||
});
|
||||
|
||||
export const coreReadModelSnapshotSchema = z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
generatedAt: z.string().datetime(),
|
||||
projects: z.array(coreProjectViewSchema),
|
||||
threads: z.array(coreThreadViewSchema),
|
||||
git: z.array(coreGitStatusSnapshotSchema),
|
||||
});
|
||||
|
||||
export const coreViewDeltaSchema = z.discriminatedUnion("kind", [
|
||||
z.object({
|
||||
kind: z.literal("snapshot"),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
snapshot: coreReadModelSnapshotSchema,
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("projectUpsert"),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
project: coreProjectViewSchema,
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("projectDelete"),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
projectId: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("threadUpsert"),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
thread: coreThreadViewSchema,
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("threadDelete"),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
threadId: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("gitStatusUpsert"),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
git: coreGitStatusSnapshotSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
const coreCommandBaseSchema = z.object({
|
||||
commandId: z.string().min(1),
|
||||
issuedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const coreCommandSchema = z.discriminatedUnion("kind", [
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("CreateProject"),
|
||||
payload: z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
}),
|
||||
}),
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("CreateThread"),
|
||||
payload: z.object({
|
||||
id: z.string().min(1),
|
||||
projectId: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
model: z.string().min(1),
|
||||
createdAt: z.string().datetime().optional(),
|
||||
}),
|
||||
}),
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("AppendUserMessage"),
|
||||
payload: z.object({
|
||||
threadId: z.string().min(1),
|
||||
messageId: z.string().min(1),
|
||||
text: z.string(),
|
||||
createdAt: z.string().datetime(),
|
||||
}),
|
||||
}),
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("AppendAssistantMessage"),
|
||||
payload: z.object({
|
||||
threadId: z.string().min(1),
|
||||
messageId: z.string().min(1),
|
||||
text: z.string(),
|
||||
createdAt: z.string().datetime(),
|
||||
}),
|
||||
}),
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("SetThreadBranch"),
|
||||
payload: z.object({
|
||||
threadId: z.string().min(1),
|
||||
branch: z.string().min(1).nullable(),
|
||||
worktreePath: z.string().min(1).nullable(),
|
||||
}),
|
||||
}),
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("GitProbe"),
|
||||
payload: z.object({
|
||||
cwd: z.string().min(1),
|
||||
}),
|
||||
}),
|
||||
coreCommandBaseSchema.extend({
|
||||
kind: z.literal("GitWorkflow"),
|
||||
payload: z.object({
|
||||
workflow: z.enum([
|
||||
"create_branch",
|
||||
"checkout",
|
||||
"create_worktree",
|
||||
"remove_worktree",
|
||||
"stacked_action",
|
||||
"checkpoint_capture",
|
||||
"checkpoint_restore",
|
||||
"open_pr",
|
||||
]),
|
||||
cwd: z.string().min(1),
|
||||
metadata: z.record(z.string(), z.unknown()).default({}),
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const coreDispatchInputSchema = z.object({
|
||||
command: coreCommandSchema,
|
||||
expectedVersion: z.number().int().nonnegative().optional(),
|
||||
idempotencyKey: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export const coreDispatchResultSchema = z.object({
|
||||
accepted: z.boolean(),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
export const coreGetSnapshotInputSchema = z.object({
|
||||
minSequence: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
|
||||
export type CoreGitStatusSnapshot = z.infer<typeof coreGitStatusSnapshotSchema>;
|
||||
export type CoreProjectView = z.infer<typeof coreProjectViewSchema>;
|
||||
export type CoreThreadMessageView = z.infer<typeof coreThreadMessageViewSchema>;
|
||||
export type CoreThreadView = z.infer<typeof coreThreadViewSchema>;
|
||||
export type CoreReadModelSnapshot = z.infer<typeof coreReadModelSnapshotSchema>;
|
||||
export type CoreViewDelta = z.infer<typeof coreViewDeltaSchema>;
|
||||
export type CoreCommand = z.infer<typeof coreCommandSchema>;
|
||||
export type CoreDispatchInput = z.input<typeof coreDispatchInputSchema>;
|
||||
export type CoreDispatchResult = z.infer<typeof coreDispatchResultSchema>;
|
||||
export type CoreGetSnapshotInput = z.input<typeof coreGetSnapshotInputSchema>;
|
||||
@@ -9,3 +9,4 @@ export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
export * from "./core";
|
||||
@@ -1,4 +1,11 @@
|
||||
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
|
||||
import type {
|
||||
CoreDispatchInput,
|
||||
CoreDispatchResult,
|
||||
CoreGetSnapshotInput,
|
||||
CoreReadModelSnapshot,
|
||||
CoreViewDelta,
|
||||
} from "./core";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
@@ -140,4 +147,9 @@ 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;
|
||||
};
|
||||
}
|
||||
@@ -46,6 +46,10 @@ export const WS_METHODS = {
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
|
||||
// Core event-sourced views
|
||||
coreGetSnapshot: "core.getSnapshot",
|
||||
coreDispatch: "core.dispatch",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
@@ -54,6 +58,7 @@ export const WS_CHANNELS = {
|
||||
providerEvent: "providers.event",
|
||||
terminalEvent: "terminal.event",
|
||||
serverWelcome: "server.welcome",
|
||||
coreViewDelta: "core.viewDelta",
|
||||
} as const;
|
||||
|
||||
// ── Client → Server (request) ────────────────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user