Compare commits

...
Author SHA1 Message Date
Cursor Agent 95dd2b671c Fix snapshot sync bypassing recovery coordinator and dead loading state
- Remove refreshActiveSnapshot from unarchiveThread: the EventRouter's
  recovery coordinator already handles thread.unarchived events via
  fallbackToSnapshotRecovery, which properly updates latestSequence.
  Calling syncServerReadModel directly left the coordinator stale,
  causing already-applied events to be re-processed and potentially
  corrupting streaming message content via double concatenation.

- Fix archived threads loading state: placeholderData always returned
  EMPTY_ARCHIVED_THREADS on first load, making isPending permanently
  false and the loading UI unreachable. Now only uses previous query
  data as placeholder, allowing isPending to be true on first fetch.
2026-04-01 17:43:11 +00:00
Julius Marmingeandcodex bbe5e14696 Move archived threads off the main read path
Co-authored-by: codex <[email protected]>
2026-04-01 10:27:57 -07:00
Julius Marmingeandcodex 3938930b20 perf(server): bootstrap engine from persisted projections
Co-authored-by: codex <[email protected]>
2026-04-01 10:06:27 -07:00
Julius Marmingeandcodex f23d14185e perf(server): avoid thread-wide scans for message projection
Co-authored-by: codex <[email protected]>
2026-04-01 10:06:24 -07:00
Julius Marmingeandcodex 711a3e0163 test(server): fix startup heartbeat counts mock typing
Co-authored-by: codex <[email protected]>
2026-04-01 10:06:22 -07:00
Julius Marmingeandcodex 03d24d6110 perf(server): daemonize startup heartbeat analytics
Co-authored-by: codex <[email protected]>
2026-04-01 09:58:43 -07:00
Julius Marmingeandcodex c296cee137 perf(server): add targeted projection queries
Co-authored-by: codex <[email protected]>
2026-04-01 09:52:49 -07:00
35 changed files with 2334 additions and 480 deletions

No files matched your search

@@ -289,9 +289,10 @@ export const makeOrchestrationIntegrationHarness = (
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
@@ -333,7 +334,9 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = orchestrationReactorLayer.pipe(
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
@@ -1,83 +1,38 @@
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import {
ProjectionSnapshotQuery,
type ProjectionThreadCheckpointContext,
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
function makeSnapshot(input: {
function makeThreadCheckpointContext(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): OrchestrationReadModel {
}): ProjectionThreadCheckpointContext {
return {
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
threadId: input.threadId,
projectId: input.projectId,
workspaceRoot: input.workspaceRoot,
worktreePath: input.worktreePath,
checkpoints: [
{
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
};
@@ -95,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => {
readonly cwd: string;
}> = [];
const snapshot = makeSnapshot({
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
@@ -125,7 +80,15 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(snapshot),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getActiveSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the active orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
listArchivedThreads: () => Effect.succeed([]),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
}),
),
);
@@ -175,12 +138,14 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getActiveSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the active orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
listArchivedThreads: () => Effect.succeed([]),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
);
@@ -4,11 +4,11 @@ import {
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import { Effect, Layer, Option, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import {
CheckpointDiffQuery,
@@ -41,16 +41,17 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = thread.checkpoints.reduce(
const maxTurnCount = threadContext.value.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
@@ -62,10 +63,7 @@ const make = Effect.gen(function* () {
});
}
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
@@ -76,7 +74,7 @@ const make = Effect.gen(function* () {
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: thread.checkpoints.find(
: threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
@@ -87,7 +85,7 @@ const make = Effect.gen(function* () {
});
}
const toCheckpointRef = thread.checkpoints.find(
const toCheckpointRef = threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
@@ -23,6 +23,7 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -249,6 +250,7 @@ describe("CheckpointReactor", () => {
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -8,7 +8,7 @@ import {
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
import { Effect, Layer, ManagedRuntime, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -21,11 +21,13 @@ import {
} from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
type OrchestrationProjectionPipelineShape,
} from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -39,6 +41,7 @@ async function createOrchestrationSystem() {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -60,6 +63,107 @@ function now() {
}
describe("OrchestrationEngine", () => {
it("bootstraps the in-memory read model from persisted projections", async () => {
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
append: () =>
Effect.fail(
new PersistenceSqlError({
operation: "test.append",
detail: "append should not be called during bootstrap",
}),
),
readFromSequence: () => Stream.empty,
readAll: () =>
Stream.fail(
new PersistenceSqlError({
operation: "test.readAll",
detail: "historical replay should not be used during bootstrap",
}),
),
};
const projectionSnapshot = {
snapshotSequence: 7,
updatedAt: "2026-03-03T00:00:04.000Z",
projects: [
{
id: asProjectId("project-bootstrap"),
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
scripts: [],
createdAt: "2026-03-03T00:00:00.000Z",
updatedAt: "2026-03-03T00:00:01.000Z",
deletedAt: null,
},
],
threads: [
{
id: ThreadId.makeUnsafe("thread-bootstrap"),
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-03-03T00:00:02.000Z",
updatedAt: "2026-03-03T00:00:03.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
};
const layer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(projectionSnapshot),
getActiveSnapshot: () => Effect.succeed(projectionSnapshot),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
listArchivedThreads: () => Effect.succeed([]),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
Layer.provide(
Layer.succeed(OrchestrationProjectionPipeline, {
bootstrap: Effect.void,
projectEvent: () => Effect.void,
} satisfies OrchestrationProjectionPipelineShape),
),
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
);
const runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const readModel = await runtime.runPromise(engine.getReadModel());
expect(readModel.snapshotSequence).toBe(7);
expect(readModel.projects).toHaveLength(1);
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
expect(readModel.threads).toHaveLength(1);
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
await runtime.dispose();
});
it("returns deterministic read models for repeated reads", async () => {
const createdAt = now();
const system = await createOrchestrationSystem();
@@ -417,6 +521,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -512,6 +617,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -653,6 +759,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -19,6 +19,7 @@ import {
import { decideOrchestrationCommand } from "../decider.ts";
import { createEmptyReadModel, projectEvent } from "../projector.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
@@ -54,6 +55,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore;
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
let readModel = createEmptyReadModel(new Date().toISOString());
@@ -195,13 +197,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
};
yield* projectionPipeline.bootstrap;
// bootstrap in-memory read model from event store
yield* Stream.runForEach(eventStore.readAll(), (event) =>
Effect.gen(function* () {
readModel = yield* projectEvent(readModel, event);
}),
);
readModel = yield* projectionSnapshotQuery.getSnapshot();
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
@@ -25,6 +25,7 @@ import {
ORCHESTRATION_PROJECTOR_NAMES,
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1841,6 +1842,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -623,24 +623,23 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
messageId: event.payload.messageId,
});
const existingMessage = existingRows.find(
(row) => row.messageId === event.payload.messageId,
);
const nextText =
existingMessage && event.payload.streaming
? `${existingMessage.text}${event.payload.text}`
: existingMessage && event.payload.text.length === 0
? existingMessage.text
Option.isSome(existingMessage) && event.payload.streaming
? `${existingMessage.value.text}${event.payload.text}`
: Option.isSome(existingMessage) && event.payload.text.length === 0
? existingMessage.value.text
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
: Option.isSome(existingMessage)
? existingMessage.value.attachments
: undefined;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
@@ -649,7 +648,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
createdAt: Option.isSome(existingMessage)
? existingMessage.value.createdAt
: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
@@ -338,4 +338,547 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
]);
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-active',
'Active Project',
'/tmp/workspace',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-03-01T00:00:00.000Z',
'2026-03-01T00:00:01.000Z',
NULL
),
(
'project-deleted',
'Deleted Project',
'/tmp/deleted',
NULL,
'[]',
'2026-03-01T00:00:02.000Z',
'2026-03-01T00:00:03.000Z',
'2026-03-01T00:00:04.000Z'
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-first',
'project-active',
'First Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:05.000Z',
'2026-03-01T00:00:06.000Z',
NULL,
NULL
),
(
'thread-second',
'project-active',
'Second Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:07.000Z',
'2026-03-01T00:00:08.000Z',
NULL,
NULL
),
(
'thread-archived',
'project-active',
'Archived Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
'/tmp/worktree-archived',
NULL,
'2026-03-01T00:00:04.000Z',
'2026-03-01T00:00:04.500Z',
'2026-03-01T00:00:04.750Z',
NULL
),
(
'thread-deleted',
'project-active',
'Deleted Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:09.000Z',
'2026-03-01T00:00:10.000Z',
NULL,
'2026-03-01T00:00:11.000Z'
)
`;
const counts = yield* snapshotQuery.getCounts();
assert.deepEqual(counts, {
projectCount: 2,
threadCount: 4,
});
const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace");
assert.equal(project._tag, "Some");
if (project._tag === "Some") {
assert.equal(project.value.id, asProjectId("project-active"));
}
const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing");
assert.equal(missingProject._tag, "None");
const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId(
asProjectId("project-active"),
);
assert.equal(firstThreadId._tag, "Some");
if (firstThreadId._tag === "Some") {
assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
}
const archivedThreads = yield* snapshotQuery.listArchivedThreads();
assert.deepEqual(archivedThreads, [
{
threadId: ThreadId.makeUnsafe("thread-archived"),
projectId: asProjectId("project-active"),
projectTitle: "Active Project",
workspaceRoot: "/tmp/workspace",
title: "Archived Thread",
worktreePath: "/tmp/worktree-archived",
createdAt: "2026-03-01T00:00:04.000Z",
updatedAt: "2026-03-01T00:00:04.500Z",
archivedAt: "2026-03-01T00:00:04.750Z",
},
]);
}),
);
it.effect("hydrates an active snapshot without archived or deleted thread data", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_proposed_plans`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_thread_sessions`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-active-only',
'Active-only Project',
'/tmp/active-only',
NULL,
'[]',
'2026-03-03T00:00:00.000Z',
'2026-03-03T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-active-only',
'project-active-only',
'Active Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
'turn-active-only',
'2026-03-03T00:00:02.000Z',
'2026-03-03T00:00:03.000Z',
NULL,
NULL
),
(
'thread-archived-only',
'project-active-only',
'Archived Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
'turn-archived-only',
'2026-03-03T00:00:04.000Z',
'2026-03-03T00:00:05.000Z',
'2026-03-03T00:00:06.000Z',
NULL
),
(
'thread-deleted-only',
'project-active-only',
'Deleted Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-03T00:00:07.000Z',
'2026-03-03T00:00:08.000Z',
NULL,
'2026-03-03T00:00:09.000Z'
)
`;
yield* sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
is_streaming,
created_at,
updated_at
)
VALUES
(
'message-active-only',
'thread-active-only',
'turn-active-only',
'assistant',
'active message',
0,
'2026-03-03T00:00:10.000Z',
'2026-03-03T00:00:11.000Z'
),
(
'message-archived-only',
'thread-archived-only',
'turn-archived-only',
'assistant',
'archived message',
0,
'2026-03-03T00:00:12.000Z',
'2026-03-03T00:00:13.000Z'
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES
(
'thread-active-only',
'turn-active-only',
NULL,
NULL,
NULL,
'message-active-only',
'completed',
'2026-03-03T00:00:14.000Z',
'2026-03-03T00:00:14.000Z',
'2026-03-03T00:00:14.000Z',
1,
'checkpoint-active-only',
'ready',
'[]'
),
(
'thread-archived-only',
'turn-archived-only',
NULL,
NULL,
NULL,
'message-archived-only',
'completed',
'2026-03-03T00:00:15.000Z',
'2026-03-03T00:00:15.000Z',
'2026-03-03T00:00:15.000Z',
1,
'checkpoint-archived-only',
'ready',
'[]'
)
`;
let sequence = 9;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (
projector,
last_applied_sequence,
updated_at
)
VALUES (
${projector},
${sequence},
'2026-03-03T00:00:16.000Z'
)
`;
sequence += 1;
}
const snapshot = yield* snapshotQuery.getActiveSnapshot();
assert.equal(snapshot.snapshotSequence, 9);
assert.equal(snapshot.projects.length, 1);
assert.deepEqual(
snapshot.threads.map((thread) => ({
id: thread.id,
title: thread.title,
messageCount: thread.messages.length,
checkpointCount: thread.checkpoints.length,
})),
[
{
id: ThreadId.makeUnsafe("thread-active-only"),
title: "Active Thread",
messageCount: 1,
checkpointCount: 1,
},
],
);
}),
);
it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-context',
'Context Project',
'/tmp/context-workspace',
NULL,
'[]',
'2026-03-02T00:00:00.000Z',
'2026-03-02T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-context',
'project-context',
'Context Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
'feature/perf',
'/tmp/context-worktree',
NULL,
'2026-03-02T00:00:02.000Z',
'2026-03-02T00:00:03.000Z',
NULL,
NULL
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES
(
'thread-context',
'turn-1',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
1,
'checkpoint-a',
'ready',
'[]'
),
(
'thread-context',
'turn-2',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
2,
'checkpoint-b',
'ready',
'[]'
)
`;
const context = yield* snapshotQuery.getThreadCheckpointContext(
ThreadId.makeUnsafe("thread-context"),
);
assert.equal(context._tag, "Some");
if (context._tag === "Some") {
assert.deepEqual(context.value, {
threadId: ThreadId.makeUnsafe("thread-context"),
projectId: asProjectId("project-context"),
workspaceRoot: "/tmp/context-workspace",
worktreePath: "/tmp/context-worktree",
checkpoints: [
{
turnId: asTurnId("turn-1"),
checkpointTurnCount: 1,
checkpointRef: asCheckpointRef("checkpoint-a"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:04.000Z",
},
{
turnId: asTurnId("turn-2"),
checkpointTurnCount: 2,
checkpointRef: asCheckpointRef("checkpoint-b"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:05.000Z",
},
],
});
}
}),
);
});
File diff suppressed because it is too large. Load diff
@@ -30,6 +30,7 @@ import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
@@ -211,6 +212,7 @@ describe("ProviderCommandReactor", () => {
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -31,6 +31,7 @@ import {
} from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
@@ -197,6 +198,7 @@ describe("ProviderRuntimeIngestion", () => {
fs.mkdirSync(path.join(workspaceRoot, ".git"));
const provider = createProviderServiceHarness();
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -6,12 +6,33 @@
*
* @module ProjectionSnapshotQuery
*/
import type { OrchestrationReadModel } from "@t3tools/contracts";
import type {
OrchestrationArchivedThreadSummary,
OrchestrationCheckpointSummary,
OrchestrationProject,
OrchestrationReadModel,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
export interface ProjectionSnapshotCounts {
readonly projectCount: number;
readonly threadCount: number;
}
export interface ProjectionThreadCheckpointContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -23,6 +44,49 @@ export interface ProjectionSnapshotQueryShape {
* projector cursor state.
*/
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
/**
* Read the latest UI-facing orchestration snapshot, omitting archived and
* deleted threads plus their related child rows.
*/
readonly getActiveSnapshot: () => Effect.Effect<
OrchestrationReadModel,
ProjectionRepositoryError
>;
/**
* Read aggregate projection counts without hydrating the full read model.
*/
readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;
/**
* Read archived thread summaries for the archive settings page.
*/
readonly listArchivedThreads: () => Effect.Effect<
ReadonlyArray<OrchestrationArchivedThreadSummary>,
ProjectionRepositoryError
>;
/**
* Read the active project for an exact workspace root match.
*/
readonly getActiveProjectByWorkspaceRoot: (
workspaceRoot: string,
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
/**
* Read the earliest active thread for a project.
*/
readonly getFirstActiveThreadIdByProjectId: (
projectId: ProjectId,
) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;
/**
* Read the checkpoint context needed to resolve a single thread diff.
*/
readonly getThreadCheckpointContext: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
}
/**
@@ -55,6 +55,13 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "updated");
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "updated");
assert.deepEqual(rowById.value.attachments, persistedAttachments);
}
}),
);
@@ -1,10 +1,11 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
GetProjectionThreadMessageInput,
ProjectionThreadMessageRepository,
type ProjectionThreadMessageRepositoryShape,
DeleteProjectionThreadMessagesInput,
@@ -19,6 +20,22 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
}),
);
function toProjectionThreadMessage(
row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
): ProjectionThreadMessage {
return {
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
};
}
const makeProjectionThreadMessageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -74,6 +91,27 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
},
});
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
Request: GetProjectionThreadMessageInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ messageId }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE message_id = ${messageId}
LIMIT 1
`,
});
const listProjectionThreadMessageRows = SqlSchema.findAll({
Request: ListProjectionThreadMessagesInput,
Result: ProjectionThreadMessageDbRowSchema,
@@ -109,24 +147,20 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
),
Effect.map(Option.map(toProjectionThreadMessage)),
);
const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadMessageRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
),
Effect.map((rows) =>
rows.map((row) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
})),
),
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
);
const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) =>
@@ -138,6 +172,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
getByMessageId,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadMessageRepositoryShape;
@@ -31,6 +31,7 @@ import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -61,6 +62,7 @@ export const migrationEntries = [
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionSnapshotLookupIndexes", Migration0019],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,73 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("019_ProjectionSnapshotLookupIndexes", (it) => {
it.effect("creates indexes for targeted projection lookup filters", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 18 });
yield* runMigrations({ toMigrationInclusive: 19 });
const projectIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_projects)
`;
assert.ok(
projectIndexes.some(
(index) => index.name === "idx_projection_projects_workspace_root_deleted_at",
),
);
const projectIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_projects_workspace_root_deleted_at')
`;
assert.deepStrictEqual(
projectIndexColumns.map((column) => column.name),
["workspace_root", "deleted_at"],
);
const threadIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_threads)
`;
assert.ok(
threadIndexes.some(
(index) => index.name === "idx_projection_threads_project_deleted_created",
),
);
const threadIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_threads_project_deleted_created')
`;
assert.deepStrictEqual(
threadIndexColumns.map((column) => column.name),
["project_id", "deleted_at", "created_at"],
);
}),
);
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at
ON projection_projects(workspace_root, deleted_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created
ON projection_threads(project_id, deleted_at, created_at)
`;
});
@@ -8,13 +8,14 @@
*/
import {
ChatAttachment,
OrchestrationMessageRole,
MessageId,
OrchestrationMessageRole,
ThreadId,
TurnId,
IsoDateTime,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -37,6 +38,11 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({
});
export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;
export const GetProjectionThreadMessageInput = Schema.Struct({
messageId: MessageId,
});
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
threadId: ThreadId,
});
@@ -55,6 +61,13 @@ export interface ProjectionThreadMessageRepositoryShape {
message: ProjectionThreadMessage,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Read a projected thread message by id.
*/
readonly getByMessageId: (
input: GetProjectionThreadMessageInput,
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
/**
* List projected thread messages for a thread.
*
+29
View File
@@ -217,6 +217,8 @@ const buildAppUnderTest = (options?: {
Layer.provide(
Layer.mock(ProjectionSnapshotQuery)({
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
getActiveSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
listArchivedThreads: () => Effect.succeed([]),
...options?.layers?.projectionSnapshotQuery,
}),
),
@@ -1098,11 +1100,26 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
],
};
const archivedThreads = [
{
threadId: ThreadId.makeUnsafe("thread-archived"),
projectId: ProjectId.makeUnsafe("project-a"),
projectTitle: "Project A",
workspaceRoot: "/tmp/project-a",
title: "Archived Thread",
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: now,
},
];
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshot: () => Effect.succeed(snapshot),
getActiveSnapshot: () => Effect.succeed(snapshot),
listArchivedThreads: () => Effect.succeed(archivedThreads),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 7 }),
@@ -1133,6 +1150,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.equal(snapshotResult.snapshotSequence, 1);
const activeSnapshotResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getActiveSnapshot]({})),
);
assert.equal(activeSnapshotResult.snapshotSequence, 1);
const dispatchResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
@@ -1166,6 +1188,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.equal(fullDiffResult.diff, "full-diff");
const archivedThreadsResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.listArchivedThreads]({}),
),
);
assert.deepEqual(archivedThreadsResult, archivedThreads);
const replayResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.replayEvents]({
+39 -4
View File
@@ -1,8 +1,13 @@
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Fiber, Ref } from "effect";
import { TestClock } from "effect/testing";
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
import { makeCommandGate, ServerRuntimeStartupError } from "./serverRuntimeStartup.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import {
launchStartupHeartbeat,
makeCommandGate,
ServerRuntimeStartupError,
} from "./serverRuntimeStartup.ts";
it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
Effect.scoped(
@@ -14,7 +19,7 @@ it.effect("enqueueCommand waits for readiness and then drains queued work", () =
.enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1))
.pipe(Effect.forkScoped);
yield* TestClock.adjust("50 millis");
yield* Effect.yieldNow;
assert.equal(yield* Ref.get(executionCount), 0);
yield* commandGate.signalCommandReady;
@@ -47,3 +52,33 @@ it.effect("enqueueCommand fails queued work when readiness fails", () =>
}),
),
);
it.effect("launchStartupHeartbeat does not block the caller while counts are loading", () =>
Effect.scoped(
Effect.gen(function* () {
const releaseCounts = yield* Deferred.make<void, never>();
yield* launchStartupHeartbeat.pipe(
Effect.provideService(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.die("unused"),
getActiveSnapshot: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
Effect.as({
projectCount: 2,
threadCount: 3,
}),
),
listArchivedThreads: () => Effect.succeed([]),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
Effect.provideService(AnalyticsService, {
record: () => Effect.void,
flush: Effect.void,
}),
);
}),
),
);
+34 -20
View File
@@ -5,7 +5,19 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Data, Deferred, Effect, Exit, Layer, Path, Queue, Ref, Scope, ServiceMap } from "effect";
import {
Data,
Deferred,
Effect,
Exit,
Layer,
Option,
Path,
Queue,
Ref,
Scope,
ServiceMap,
} from "effect";
import { ServerConfig } from "./config";
import { Keybindings } from "./keybindings";
@@ -105,17 +117,15 @@ export const makeCommandGate = Effect.gen(function* () {
} satisfies CommandGate;
});
const recordStartupHeartbeat = Effect.gen(function* () {
export const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.map((snapshot) => ({
threadCount: snapshot.threads.length,
projectCount: snapshot.projects.length,
})),
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
Effect.logWarning("failed to gather startup projection counts for telemetry", {
cause,
}).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
@@ -130,6 +140,12 @@ const recordStartupHeartbeat = Effect.gen(function* () {
});
});
export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
Effect.asVoid,
);
const autoBootstrapWelcome = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
@@ -141,14 +157,13 @@ const autoBootstrapWelcome = Effect.gen(function* () {
if (serverConfig.autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null,
const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
serverConfig.cwd,
);
let nextProjectId: ProjectId;
let nextProjectDefaultModelSelection: ModelSelection;
if (!existingProject) {
if (Option.isNone(existingProject)) {
const createdAt = new Date().toISOString();
nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
@@ -166,17 +181,16 @@ const autoBootstrapWelcome = Effect.gen(function* () {
createdAt,
});
} else {
nextProjectId = existingProject.id;
nextProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
nextProjectId = existingProject.value.id;
nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? {
provider: "codex",
model: "gpt-5-codex",
};
}
const existingThread = snapshot.threads.find(
(thread) => thread.projectId === nextProjectId && thread.deletedAt === null,
);
if (!existingThread) {
const existingThreadId =
yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
if (Option.isNone(existingThreadId)) {
const createdAt = new Date().toISOString();
const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID());
yield* orchestrationEngine.dispatch({
@@ -196,7 +210,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
bootstrapThreadId = createdThreadId;
} else {
bootstrapProjectId = nextProjectId;
bootstrapThreadId = existingThread.id;
bootstrapThreadId = existingThreadId.value;
}
});
}
@@ -314,7 +328,7 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
});
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* recordStartupHeartbeat;
yield* launchStartupHeartbeat;
yield* Effect.logDebug("startup phase: browser open check");
yield* maybeOpenBrowser;
yield* Effect.logDebug("startup phase: complete");
+22
View File
@@ -4,7 +4,9 @@ import {
type GitManagerServiceError,
OrchestrationDispatchCommandError,
type OrchestrationEvent,
OrchestrationGetActiveSnapshotError,
OrchestrationGetFullThreadDiffError,
OrchestrationListArchivedThreadsError,
OrchestrationGetSnapshotError,
OrchestrationGetTurnDiffError,
ORCHESTRATION_WS_METHODS,
@@ -82,6 +84,16 @@ const WsRpcLayer = WsRpcGroup.toLayer(
}),
),
),
[ORCHESTRATION_WS_METHODS.getActiveSnapshot]: (_input) =>
projectionSnapshotQuery.getActiveSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetActiveSnapshotError({
message: "Failed to load active orchestration snapshot",
cause,
}),
),
),
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
@@ -116,6 +128,16 @@ const WsRpcLayer = WsRpcGroup.toLayer(
}),
),
),
[ORCHESTRATION_WS_METHODS.listArchivedThreads]: (_input) =>
projectionSnapshotQuery.listArchivedThreads().pipe(
Effect.mapError(
(cause) =>
new OrchestrationListArchivedThreadsError({
message: "Failed to load archived threads",
cause,
}),
),
),
[ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
Stream.runCollect(
orchestrationEngine.readEvents(
+4 -1
View File
@@ -622,7 +622,10 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
return customResult;
}
const tag = body._tag;
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
if (
tag === ORCHESTRATION_WS_METHODS.getSnapshot ||
tag === ORCHESTRATION_WS_METHODS.getActiveSnapshot
) {
return fixture.snapshot;
}
if (tag === WS_METHODS.serverGetConfig) {
@@ -147,7 +147,10 @@ function buildFixture(): TestFixture {
}
function resolveWsRpc(tag: string): unknown {
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
if (
tag === ORCHESTRATION_WS_METHODS.getSnapshot ||
tag === ORCHESTRATION_WS_METHODS.getActiveSnapshot
) {
return fixture.snapshot;
}
if (tag === WS_METHODS.serverGetConfig) {
@@ -9,7 +9,7 @@ import {
Undo2Icon,
XIcon,
} from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
PROVIDER_DISPLAY_NAMES,
@@ -40,13 +40,13 @@ import {
setDesktopUpdateStateQueryData,
useDesktopUpdateState,
} from "../../lib/desktopUpdateReactQuery";
import { archivedThreadsQueryOptions } from "../../lib/orchestrationReactQuery";
import {
MAX_CUSTOM_MODEL_LENGTH,
getCustomModelOptionsByProvider,
resolveAppModelSelectionState,
} from "../../modelSelection";
import { ensureNativeApi, readNativeApi } from "../../nativeApi";
import { useStore } from "../../store";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
@@ -1414,24 +1414,46 @@ export function GeneralSettingsPanel() {
}
export function ArchivedThreadsPanel() {
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();
const {
data: archivedThreads = [],
error: archivedThreadsError,
isPending: archivedThreadsPending,
} = useQuery(archivedThreadsQueryOptions());
const { unarchiveThread, deleteArchivedThread } = useThreadActions();
const archivedGroups = useMemo(() => {
const projectById = new Map(projects.map((project) => [project.id, project] as const));
return [...projectById.values()]
.map((project) => ({
project,
threads: threads
.filter((thread) => thread.projectId === project.id && thread.archivedAt !== null)
.toSorted((left, right) => {
const leftKey = left.archivedAt ?? left.createdAt;
const rightKey = right.archivedAt ?? right.createdAt;
return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);
}),
}))
.filter((group) => group.threads.length > 0);
}, [projects, threads]);
const groups = new Map<
string,
{
project: { id: string; name: string; cwd: string };
threads: Array<(typeof archivedThreads)[number]>;
}
>();
for (const thread of archivedThreads) {
const existing = groups.get(thread.projectId);
if (existing) {
existing.threads.push(thread);
continue;
}
groups.set(thread.projectId, {
project: {
id: thread.projectId,
name: thread.projectTitle,
cwd: thread.workspaceRoot,
},
threads: [thread],
});
}
return Array.from(groups.values(), (group) => {
group.threads.sort(
(left, right) =>
right.archivedAt.localeCompare(left.archivedAt) ||
right.threadId.localeCompare(left.threadId),
);
return group;
});
}, [archivedThreads]);
const handleArchivedThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
@@ -1459,15 +1481,43 @@ export function ArchivedThreadsPanel() {
}
if (clicked === "delete") {
await confirmAndDeleteThread(threadId);
const thread = archivedThreads.find((entry) => entry.threadId === threadId);
if (!thread) {
return;
}
await deleteArchivedThread(thread, archivedThreads);
}
},
[confirmAndDeleteThread, unarchiveThread],
[archivedThreads, deleteArchivedThread, unarchiveThread],
);
return (
<SettingsPageContainer>
{archivedGroups.length === 0 ? (
{archivedThreadsError ? (
<SettingsSection title="Archived threads">
<Empty className="min-h-88">
<EmptyHeader>
<EmptyTitle>Could not load archived threads</EmptyTitle>
<EmptyDescription>
{archivedThreadsError instanceof Error
? archivedThreadsError.message
: "An error occurred while loading archived threads."}
</EmptyDescription>
</EmptyHeader>
</Empty>
</SettingsSection>
) : null}
{!archivedThreadsError && archivedThreadsPending ? (
<SettingsSection title="Archived threads">
<Empty className="min-h-88">
<EmptyHeader>
<EmptyTitle>Loading archived threads</EmptyTitle>
<EmptyDescription>Fetching archived thread summaries.</EmptyDescription>
</EmptyHeader>
</Empty>
</SettingsSection>
) : null}
{!archivedThreadsError && !archivedThreadsPending && archivedGroups.length === 0 ? (
<SettingsSection title="Archived threads">
<Empty className="min-h-88">
<EmptyMedia variant="icon">
@@ -1479,56 +1529,58 @@ export function ArchivedThreadsPanel() {
</EmptyHeader>
</Empty>
</SettingsSection>
) : (
archivedGroups.map(({ project, threads: projectThreads }) => (
<SettingsSection
key={project.id}
title={project.name}
icon={<ProjectFavicon cwd={project.cwd} />}
>
{projectThreads.map((thread) => (
<div
key={thread.id}
className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"
onContextMenu={(event) => {
event.preventDefault();
void handleArchivedThreadContextMenu(thread.id, {
x: event.clientX,
y: event.clientY,
});
}}
>
<div className="min-w-0 flex-1">
<h3 className="truncate text-sm font-medium text-foreground">{thread.title}</h3>
<p className="text-xs text-muted-foreground">
Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)}
{" \u00b7 Created "}
{formatRelativeTimeLabel(thread.createdAt)}
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(thread.id).catch((error) => {
toastManager.add({
type: "error",
title: "Failed to unarchive thread",
description: error instanceof Error ? error.message : "An error occurred.",
});
})
}
) : null}
{!archivedThreadsError && !archivedThreadsPending && archivedGroups.length > 0
? archivedGroups.map(({ project, threads: projectThreads }) => (
<SettingsSection
key={project.id}
title={project.name}
icon={<ProjectFavicon cwd={project.cwd} />}
>
{projectThreads.map((thread) => (
<div
key={thread.threadId}
className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"
onContextMenu={(event) => {
event.preventDefault();
void handleArchivedThreadContextMenu(thread.threadId, {
x: event.clientX,
y: event.clientY,
});
}}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
</Button>
</div>
))}
</SettingsSection>
))
)}
<div className="min-w-0 flex-1">
<h3 className="truncate text-sm font-medium text-foreground">{thread.title}</h3>
<p className="text-xs text-muted-foreground">
Archived {formatRelativeTimeLabel(thread.archivedAt)}
{" \u00b7 Created "}
{formatRelativeTimeLabel(thread.createdAt)}
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
onClick={() =>
void unarchiveThread(thread.threadId).catch((error) => {
toastManager.add({
type: "error",
title: "Failed to unarchive thread",
description:
error instanceof Error ? error.message : "An error occurred.",
});
})
}
>
<ArchiveX className="size-3.5" />
<span>Unarchive</span>
</Button>
</div>
))}
</SettingsSection>
))
: null}
</SettingsPageContainer>
);
}
+123 -11
View File
@@ -1,4 +1,4 @@
import { ThreadId } from "@t3tools/contracts";
import { ThreadId, type OrchestrationArchivedThreadSummary } from "@t3tools/contracts";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useCallback } from "react";
@@ -7,6 +7,7 @@ import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "./useHandleNewThread";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { orchestrationQueryKeys } from "../lib/orchestrationReactQuery";
import { newCommandId } from "../lib/utils";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
@@ -46,23 +47,28 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId,
});
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
if (routeThreadId === threadId) {
await handleNewThread(thread.projectId);
}
},
[handleNewThread, routeThreadId],
[handleNewThread, queryClient, routeThreadId],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
await api.orchestration.dispatchCommand({
type: "thread.unarchive",
commandId: newCommandId(),
threadId,
});
}, []);
const unarchiveThread = useCallback(
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
await api.orchestration.dispatchCommand({
type: "thread.unarchive",
commandId: newCommandId(),
threadId,
});
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
},
[queryClient],
);
const deleteThread = useCallback(
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
@@ -123,6 +129,7 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId,
});
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
@@ -172,6 +179,110 @@ export function useThreadActions() {
navigate,
removeWorktreeMutation,
routeThreadId,
queryClient,
],
);
const deleteArchivedThread = useCallback(
async (
thread: OrchestrationArchivedThreadSummary,
archivedThreads: ReadonlyArray<OrchestrationArchivedThreadSummary>,
) => {
const api = readNativeApi();
if (!api) return;
const { projects, threads } = useStore.getState();
const threadProject = projects.find((project) => project.id === thread.projectId);
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
`Delete thread "${thread.title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
);
if (!confirmed) {
return;
}
}
const normalizedWorktreePath = thread.worktreePath?.trim() || null;
const hasSharedWorktree =
normalizedWorktreePath !== null &&
(threads.some(
(entry) =>
entry.id !== thread.threadId &&
(entry.worktreePath?.trim() || null) === normalizedWorktreePath,
) ||
archivedThreads.some(
(entry) =>
entry.threadId !== thread.threadId &&
(entry.worktreePath?.trim() || null) === normalizedWorktreePath,
));
const orphanedWorktreePath = hasSharedWorktree ? null : normalizedWorktreePath;
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
try {
await api.terminal.close({ threadId: thread.threadId, deleteHistory: true });
} catch {
// Terminal may already be closed.
}
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: thread.threadId,
});
clearComposerDraftForThread(thread.threadId);
clearProjectDraftThreadById(thread.projectId, thread.threadId);
clearTerminalState(thread.threadId);
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after archived thread deletion", {
threadId: thread.threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
});
}
},
[
appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
queryClient,
removeWorktreeMutation,
],
);
@@ -203,6 +314,7 @@ export function useThreadActions() {
archiveThread,
unarchiveThread,
deleteThread,
deleteArchivedThread,
confirmAndDeleteThread,
};
}
@@ -0,0 +1,21 @@
import { queryOptions } from "@tanstack/react-query";
import { ensureNativeApi } from "~/nativeApi";
export const orchestrationQueryKeys = {
all: ["orchestration"] as const,
archivedThreads: () => ["orchestration", "archived-threads"] as const,
};
const DEFAULT_ARCHIVED_THREADS_STALE_TIME = 15_000;
export function archivedThreadsQueryOptions() {
return queryOptions({
queryKey: orchestrationQueryKeys.archivedThreads(),
queryFn: async () => {
const api = ensureNativeApi();
return api.orchestration.listArchivedThreads();
},
staleTime: DEFAULT_ARCHIVED_THREADS_STALE_TIME,
placeholderData: (previous) => previous,
});
}
+36 -5
View File
@@ -39,6 +39,7 @@ import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
import { orchestrationQueryKeys } from "../lib/orchestrationReactQuery";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
@@ -309,10 +310,21 @@ function EventRouter() {
},
);
const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
const applyEventBatch = (
events: ReadonlyArray<OrchestrationEvent>,
): "applied" | "snapshot-recovery-needed" => {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length === 0) {
return;
return "applied";
}
const knownThreadIds = new Set(useStore.getState().threads.map((thread) => thread.id));
const needsActiveSnapshotRecovery = nextEvents.some(
(event) =>
event.type === "thread.unarchived" && !knownThreadIds.has(event.payload.threadId),
);
if (needsActiveSnapshotRecovery) {
return "snapshot-recovery-needed";
}
const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
@@ -327,6 +339,16 @@ function EventRouter() {
needsProviderInvalidation = true;
void queryInvalidationThrottler.maybeExecute();
}
if (
nextEvents.some(
(event) =>
event.type === "thread.archived" ||
event.type === "thread.unarchived" ||
event.type === "thread.deleted",
)
) {
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
}
applyOrchestrationEvents(nextEvents);
if (needsProjectUiSync) {
@@ -356,6 +378,7 @@ function EventRouter() {
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
removeTerminalState(threadId);
}
return "applied";
};
const recoverFromSequenceGap = async (): Promise<void> => {
@@ -366,7 +389,12 @@ function EventRouter() {
try {
const events = await api.orchestration.replayEvents(recovery.getState().latestSequence);
if (!disposed) {
applyEventBatch(events);
const result = applyEventBatch(events);
if (result === "snapshot-recovery-needed") {
recovery.failReplayRecovery();
void fallbackToSnapshotRecovery();
return;
}
}
} catch {
recovery.failReplayRecovery();
@@ -385,7 +413,7 @@ function EventRouter() {
}
try {
const snapshot = await api.orchestration.getSnapshot();
const snapshot = await api.orchestration.getActiveSnapshot();
if (!disposed) {
syncServerReadModel(snapshot);
reconcileSnapshotDerivedState();
@@ -410,7 +438,10 @@ function EventRouter() {
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
applyEventBatch([event]);
const result = applyEventBatch([event]);
if (result === "snapshot-recovery-needed") {
void fallbackToSnapshotRecovery();
}
return;
}
if (action === "recover") {
+2
View File
@@ -76,6 +76,8 @@ const rpcClientMock = {
},
orchestration: {
getSnapshot: vi.fn(),
getActiveSnapshot: vi.fn(),
listArchivedThreads: vi.fn(),
dispatchCommand: vi.fn(),
getTurnDiff: vi.fn(),
getFullThreadDiff: vi.fn(),
+2
View File
@@ -91,6 +91,8 @@ export function createWsNativeApi(): NativeApi {
},
orchestration: {
getSnapshot: rpcClient.orchestration.getSnapshot,
getActiveSnapshot: rpcClient.orchestration.getActiveSnapshot,
listArchivedThreads: rpcClient.orchestration.listArchivedThreads,
dispatchCommand: rpcClient.orchestration.dispatchCommand,
getTurnDiff: rpcClient.orchestration.getTurnDiff,
getFullThreadDiff: rpcClient.orchestration.getFullThreadDiff,
+10
View File
@@ -87,9 +87,15 @@ export interface WsRpcClient {
};
readonly orchestration: {
readonly getSnapshot: RpcUnaryNoArgMethod<typeof ORCHESTRATION_WS_METHODS.getSnapshot>;
readonly getActiveSnapshot: RpcUnaryNoArgMethod<
typeof ORCHESTRATION_WS_METHODS.getActiveSnapshot
>;
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
readonly getFullThreadDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getFullThreadDiff>;
readonly listArchivedThreads: RpcUnaryNoArgMethod<
typeof ORCHESTRATION_WS_METHODS.listArchivedThreads
>;
readonly replayEvents: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.replayEvents>;
readonly onDomainEvent: RpcStreamMethod<typeof WS_METHODS.subscribeOrchestrationDomainEvents>;
};
@@ -187,12 +193,16 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
orchestration: {
getSnapshot: () =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})),
getActiveSnapshot: () =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getActiveSnapshot]({})),
dispatchCommand: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand](input)),
getTurnDiff: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)),
getFullThreadDiff: (input) =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)),
listArchivedThreads: () =>
transport.request((client) => client[ORCHESTRATION_WS_METHODS.listArchivedThreads]({})),
replayEvents: (input) =>
transport
.request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input))
+3
View File
@@ -44,6 +44,7 @@ import type {
OrchestrationGetFullThreadDiffResult,
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
OrchestrationListArchivedThreadsResult,
OrchestrationEvent,
OrchestrationReadModel,
} from "./orchestration";
@@ -174,6 +175,8 @@ export interface NativeApi {
};
orchestration: {
getSnapshot: () => Promise<OrchestrationReadModel>;
getActiveSnapshot: () => Promise<OrchestrationReadModel>;
listArchivedThreads: () => Promise<OrchestrationListArchivedThreadsResult>;
dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;
getTurnDiff: (input: OrchestrationGetTurnDiffInput) => Promise<OrchestrationGetTurnDiffResult>;
getFullThreadDiff: (
+51
View File
@@ -17,9 +17,11 @@ import {
export const ORCHESTRATION_WS_METHODS = {
getSnapshot: "orchestration.getSnapshot",
getActiveSnapshot: "orchestration.getActiveSnapshot",
dispatchCommand: "orchestration.dispatchCommand",
getTurnDiff: "orchestration.getTurnDiff",
getFullThreadDiff: "orchestration.getFullThreadDiff",
listArchivedThreads: "orchestration.listArchivedThreads",
replayEvents: "orchestration.replayEvents",
} as const;
@@ -985,6 +987,31 @@ export type OrchestrationGetSnapshotInput = typeof OrchestrationGetSnapshotInput
const OrchestrationGetSnapshotResult = OrchestrationReadModel;
export type OrchestrationGetSnapshotResult = typeof OrchestrationGetSnapshotResult.Type;
export const OrchestrationGetActiveSnapshotInput = Schema.Struct({});
export type OrchestrationGetActiveSnapshotInput = typeof OrchestrationGetActiveSnapshotInput.Type;
const OrchestrationGetActiveSnapshotResult = OrchestrationReadModel;
export type OrchestrationGetActiveSnapshotResult = typeof OrchestrationGetActiveSnapshotResult.Type;
export const OrchestrationArchivedThreadSummary = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
projectTitle: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
title: TrimmedNonEmptyString,
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
archivedAt: IsoDateTime,
});
export type OrchestrationArchivedThreadSummary = typeof OrchestrationArchivedThreadSummary.Type;
export const OrchestrationListArchivedThreadsInput = Schema.Struct({});
export type OrchestrationListArchivedThreadsInput =
typeof OrchestrationListArchivedThreadsInput.Type;
const OrchestrationListArchivedThreadsResult = Schema.Array(OrchestrationArchivedThreadSummary);
export type OrchestrationListArchivedThreadsResult =
typeof OrchestrationListArchivedThreadsResult.Type;
export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
Struct.assign({ threadId: ThreadId }),
{ unsafePreserveChecks: true },
@@ -1016,6 +1043,10 @@ export const OrchestrationRpcSchemas = {
input: OrchestrationGetSnapshotInput,
output: OrchestrationGetSnapshotResult,
},
getActiveSnapshot: {
input: OrchestrationGetActiveSnapshotInput,
output: OrchestrationGetActiveSnapshotResult,
},
dispatchCommand: {
input: ClientOrchestrationCommand,
output: DispatchResult,
@@ -1028,6 +1059,10 @@ export const OrchestrationRpcSchemas = {
input: OrchestrationGetFullThreadDiffInput,
output: OrchestrationGetFullThreadDiffResult,
},
listArchivedThreads: {
input: OrchestrationListArchivedThreadsInput,
output: OrchestrationListArchivedThreadsResult,
},
replayEvents: {
input: OrchestrationReplayEventsInput,
output: OrchestrationReplayEventsResult,
@@ -1042,6 +1077,14 @@ export class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass<Orche
},
) {}
export class OrchestrationGetActiveSnapshotError extends Schema.TaggedErrorClass<OrchestrationGetActiveSnapshotError>()(
"OrchestrationGetActiveSnapshotError",
{
message: TrimmedNonEmptyString,
cause: Schema.optional(Schema.Defect),
},
) {}
export class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass<OrchestrationDispatchCommandError>()(
"OrchestrationDispatchCommandError",
{
@@ -1066,6 +1109,14 @@ export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass
},
) {}
export class OrchestrationListArchivedThreadsError extends Schema.TaggedErrorClass<OrchestrationListArchivedThreadsError>()(
"OrchestrationListArchivedThreadsError",
{
message: TrimmedNonEmptyString,
cause: Schema.optional(Schema.Defect),
},
) {}
export class OrchestrationReplayEventsError extends Schema.TaggedErrorClass<OrchestrationReplayEventsError>()(
"OrchestrationReplayEventsError",
{
+24
View File
@@ -31,12 +31,16 @@ import {
OrchestrationEvent,
ORCHESTRATION_WS_METHODS,
OrchestrationDispatchCommandError,
OrchestrationGetActiveSnapshotError,
OrchestrationGetActiveSnapshotInput,
OrchestrationGetFullThreadDiffError,
OrchestrationGetFullThreadDiffInput,
OrchestrationGetSnapshotError,
OrchestrationGetSnapshotInput,
OrchestrationGetTurnDiffError,
OrchestrationGetTurnDiffInput,
OrchestrationListArchivedThreadsError,
OrchestrationListArchivedThreadsInput,
OrchestrationReplayEventsError,
OrchestrationReplayEventsInput,
OrchestrationRpcSchemas,
@@ -263,6 +267,15 @@ export const WsOrchestrationGetSnapshotRpc = Rpc.make(ORCHESTRATION_WS_METHODS.g
error: OrchestrationGetSnapshotError,
});
export const WsOrchestrationGetActiveSnapshotRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getActiveSnapshot,
{
payload: OrchestrationGetActiveSnapshotInput,
success: OrchestrationRpcSchemas.getActiveSnapshot.output,
error: OrchestrationGetActiveSnapshotError,
},
);
export const WsOrchestrationDispatchCommandRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.dispatchCommand,
{
@@ -287,6 +300,15 @@ export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(
},
);
export const WsOrchestrationListArchivedThreadsRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.listArchivedThreads,
{
payload: OrchestrationListArchivedThreadsInput,
success: OrchestrationRpcSchemas.listArchivedThreads.output,
error: OrchestrationListArchivedThreadsError,
},
);
export const WsOrchestrationReplayEventsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.replayEvents, {
payload: OrchestrationReplayEventsInput,
success: OrchestrationRpcSchemas.replayEvents.output,
@@ -352,8 +374,10 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeServerConfigRpc,
WsSubscribeServerLifecycleRpc,
WsOrchestrationGetSnapshotRpc,
WsOrchestrationGetActiveSnapshotRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationListArchivedThreadsRpc,
WsOrchestrationReplayEventsRpc,
);