Compare commits

...
Author SHA1 Message Date
Cursor Agent 5407e0b61e fix: remove empty-array placeholderData so archived threads loading state is reachable
placeholderData with a fallback to an empty array caused TanStack Query v5
to start in 'success' status, making isPending always false. The loading UI
was dead code and users saw a misleading 'No archived threads' flash.

Now placeholderData only returns the previous value (undefined on first
load), so the query correctly starts in pending status.
2026-04-01 22:19:57 +00:00
Julius Marmingeandcodex 3b01bbe18f Move archived threads off the main read path
Co-authored-by: codex <[email protected]>
2026-04-01 15:08:04 -07:00
Julius Marmingeandcodex 823d69f621 perf(server): bootstrap engine from persisted projections (#1648)
Co-authored-by: codex <[email protected]>
2026-04-01 15:07:15 -07:00
Julius Marmingeandcodex 4963fccb05 perf(server): avoid thread-wide scans for message projection (#1647)
Co-authored-by: codex <[email protected]>
2026-04-01 14:48:39 -07:00
Julius Marmingeandcodex dd89d5ce1a perf(server): add targeted projection queries (#1646)
Co-authored-by: codex <[email protected]>
2026-04-01 14:41:03 -07:00
Julius Marmingeandcodex 9132c37c86 [codex] migrate Effect.fn in apps/server/src/persistence/NodeSqliteClient.ts (#1633)
Co-authored-by: codex <[email protected]>
2026-04-01 16:34:52 +00:00
Julius Marmingeandcodex b9c7ea0581 [codex] migrate Effect.fn in apps/server/src/orchestration/Layers/ProviderCommandReactor.ts (#1629)
Co-authored-by: codex <[email protected]>
2026-04-01 16:26:52 +00:00
Julius Marmingeandcodex 556a195c9d [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderService.ts (#1639)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:38 +00:00
Julius Marmingeandcodex 80b282ece7 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderRegistry.ts (#1638)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:36 +00:00
Julius Marmingeandcodex d15075b32d [codex] migrate Effect.fn in apps/server/src/provider/Layers/EventNdjsonLogger.ts (#1636)
Co-authored-by: codex <[email protected]>
2026-04-01 16:14:55 +00:00
Julius Marmingeandcodex 9f6686a13d [codex] migrate Effect.fn in apps/server/src/persistence/Layers/Sqlite.ts (#1631)
Co-authored-by: codex <[email protected]>
2026-04-01 16:14:26 +00:00
Julius Marmingeandcodex c6ff7c0d5b [codex] migrate Effect.fn in apps/server/src/provider/makeManagedServerProvider.ts (#1640)
Co-authored-by: codex <[email protected]>
2026-04-01 16:03:08 +00:00
Julius Marmingeandcodex a9e5a84c03 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderAdapterRegistry.ts (#1637)
Co-authored-by: codex <[email protected]>
2026-04-01 08:58:04 -07:00
Julius Marmingeandcodex 67ca528fea [codex] migrate Effect.fn in apps/server/src/provider/Layers/ClaudeProvider.ts (#1634)
Co-authored-by: codex <[email protected]>
2026-04-01 15:57:31 +00:00
Julius Marmingeandcodex 6d9b21c5d0 [codex] migrate Effect.fn in apps/server/src/provider/Layers/CodexProvider.ts (#1635)
Co-authored-by: codex <[email protected]>
2026-04-01 08:56:04 -07:00
Julius Marmingeandcodex ddffdfc095 [codex] migrate Effect.fn in apps/server/src/telemetry/Layers/AnalyticsService.ts (#1642)
Co-authored-by: codex <[email protected]>
2026-04-01 08:53:55 -07:00
Julius Marmingeandcodex a58290ed79 [codex] migrate Effect.fn in apps/server/src/git/Layers/CodexTextGeneration.ts (#1624)
Co-authored-by: codex <[email protected]>
2026-04-01 15:53:25 +00:00
Julius Marmingeandcodex 3488ca3570 [codex] migrate Effect.fn in apps/server/src/persistence/Migrations.ts (#1632)
Co-authored-by: codex <[email protected]>
2026-04-01 08:44:49 -07:00
Julius Marmingeandcodex c542ce3369 [codex] migrate Effect.fn in apps/server/src/git/Layers/ClaudeTextGeneration.ts (#1625)
Co-authored-by: codex <[email protected]>
2026-04-01 15:44:38 +00:00
Julius Marmingeandcodex 15f0be848d [codex] migrate Effect.fn in apps/server/src/checkpointing/Layers/CheckpointStore.ts (#1623)
Co-authored-by: codex <[email protected]>
2026-04-01 08:39:23 -07:00
Julius Marmingeandcodex 1c3fa67374 [codex] migrate Effect.fn in apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts (#1622)
Co-authored-by: codex <[email protected]>
2026-04-01 08:35:54 -07:00
Lars Nieuwenhuis 0ac59d569d Feat: Added Trae IDE support for opening current working directory (#1656) 2026-04-01 15:19:12 +00:00
54 changed files with 3808 additions and 1856 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,
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
@@ -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) {
@@ -149,7 +147,8 @@ const make = Effect.gen(function* () {
}
return turnDiff;
});
},
);
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
@@ -86,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
(tempDir) =>
Effect.gen(function* () {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.restoreCheckpoint";
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
if (!commitOid) {
return false;
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
@@ -247,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () {
});
return result.stdout;
});
},
);
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.deleteCheckpointRefs";
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
return {
isGitRepository,
+105 -111
View File
@@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = <S extends Schema.Top>({
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -82,131 +82,125 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.gen(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
),
);
),
],
{ concurrency: "unbounded" },
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError(
"claude",
operation,
cause,
"Failed to read Claude CLI exit code",
),
),
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
],
{ concurrency: "unbounded" },
);
onSome: (value) => Effect.succeed(value),
}),
),
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
);
),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
);
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
),
);
});
// ---------------------------------------------------------------------------
// TextGenerationShape methods
+152 -154
View File
@@ -85,44 +85,43 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = (
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
attachments: BranchNameGenerationInput["attachments"],
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
imagePaths.push(resolvedPath);
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
return { imagePaths };
});
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
imagePaths.push(resolvedPath);
}
return { imagePaths };
});
const runCodexJson = <S extends Schema.Top>({
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -142,138 +141,137 @@ const makeCodexTextGeneration = Effect.gen(function* () {
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: CodexModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
});
const cleanup = Effect.all(
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
concurrency: "unbounded",
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
).pipe(Effect.asVoid);
);
return yield* Effect.gen(function* () {
yield* runCodexCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
});
const cleanup = Effect.all(
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
{
concurrency: "unbounded",
},
).pipe(Effect.asVoid);
return yield* Effect.gen(function* () {
yield* runCodexCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
}),
),
);
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: "Failed to read Codex output file.",
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Codex returned invalid structured output.",
cause,
}),
),
);
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: "Failed to read Codex output file.",
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Codex returned invalid structured output.",
cause,
}),
),
),
);
}).pipe(Effect.ensuring(cleanup));
});
),
);
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
+20 -1
View File
@@ -31,6 +31,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["/tmp/workspace"],
});
const traeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLaunch, {
command: "trae",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
@@ -89,6 +98,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const traeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLineAndColumn, {
command: "trae",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
@@ -256,6 +274,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
@@ -263,7 +282,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
@@ -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,28 @@ 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 previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
});
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
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
: previousMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
@@ -649,7 +653,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
createdAt: previousMessage?.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),
@@ -724,39 +724,40 @@ const make = Effect.gen(function* () {
});
});
const processDomainEvent = (event: ProviderIntentEvent) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
return;
}
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
event: ProviderIntentEvent,
) {
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
return;
}
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
return;
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
return;
}
});
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
return;
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
}
});
const processDomainEventSafely = (event: ProviderIntentEvent) =>
processDomainEvent(event).pipe(
@@ -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;
+15 -15
View File
@@ -16,15 +16,14 @@ const defaultSqliteClientLoaders = {
node: () => import("../NodeSqliteClient.ts"),
} satisfies Record<string, () => Promise<Loader>>;
const makeRuntimeSqliteLayer = (
const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
config: RuntimeSqliteLayerConfig,
): Layer.Layer<SqlClient.SqlClient> =>
Effect.gen(function* () {
const runtime = process.versions.bun !== undefined ? "bun" : "node";
const loader = defaultSqliteClientLoaders[runtime];
const clientModule = yield* Effect.promise<Loader>(loader);
return clientModule.layer(config);
}).pipe(Layer.unwrap);
) {
const runtime = process.versions.bun !== undefined ? "bun" : "node";
const loader = defaultSqliteClientLoaders[runtime];
const clientModule = yield* Effect.promise<Loader>(loader);
return clientModule.layer(config);
}, Layer.unwrap);
const setup = Layer.effectDiscard(
Effect.gen(function* () {
@@ -35,14 +34,15 @@ const setup = Layer.effectDiscard(
}),
);
export const makeSqlitePersistenceLive = (dbPath: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
dbPath: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
}).pipe(Layer.unwrap);
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
+16 -13
View File
@@ -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) =>
@@ -92,19 +94,20 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
Effect.gen(function* () {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
export const runMigrations = Effect.fn("runMigrations")(function* ({
toMigrationInclusive,
}: RunMigrationsOptions = {}) {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
/**
* Layer that runs migrations when the layer is built.
@@ -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)
`;
});
+127 -134
View File
@@ -72,160 +72,153 @@ const checkNodeSqliteCompat = () => {
return Effect.void;
};
const makeWithDatabase = (
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Effect.gen(function* () {
yield* checkNodeSqliteCompat();
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
yield* checkNodeSqliteCompat();
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
: undefined;
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
: undefined;
const makeConnection = Effect.gen(function* () {
const scope = yield* Effect.scope;
const db = openDatabase();
yield* Scope.addFinalizer(
scope,
Effect.sync(() => db.close()),
);
const makeConnection = Effect.gen(function* () {
const scope = yield* Effect.scope;
const db = openDatabase();
yield* Scope.addFinalizer(
scope,
Effect.sync(() => db.close()),
);
const statementReaderCache = new WeakMap<StatementSync, boolean>();
const hasRows = (statement: StatementSync): boolean => {
const cached = statementReaderCache.get(statement);
if (cached !== undefined) {
return cached;
}
const value = statement.columns().length > 0;
statementReaderCache.set(statement, value);
return value;
};
const statementReaderCache = new WeakMap<StatementSync, boolean>();
const hasRows = (statement: StatementSync): boolean => {
const cached = statementReaderCache.get(statement);
if (cached !== undefined) {
return cached;
}
const value = statement.columns().length > 0;
statementReaderCache.set(statement, value);
return value;
};
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
}),
}),
}),
});
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
}
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
const runStatement = (
statement: StatementSync,
params: ReadonlyArray<unknown>,
raw: boolean,
) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
}
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
Effect.acquireUseRelease(
Cache.get(prepareCache, sql),
(statement) =>
Effect.try({
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
}
statement.run(...(params as any));
return [];
},
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
Effect.acquireUseRelease(
Cache.get(prepareCache, sql),
(statement) =>
Effect.try({
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
}
statement.run(...(params as any));
return [];
},
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
}),
(statement) =>
Effect.sync(() => {
if (hasRows(statement)) {
statement.setReturnArrays(false);
}
}),
);
return identity<Connection>({
execute(sql, params, rowTransform) {
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
},
executeRaw(sql, params) {
return run(sql, params, true);
},
executeValues(sql, params) {
return runValues(sql, params);
},
executeUnprepared(sql, params, rowTransform) {
const effect = runStatement(db.prepare(sql), params ?? [], false);
return rowTransform ? Effect.map(effect, rowTransform) : effect;
},
executeStream(_sql, _params) {
return Stream.die("executeStream not implemented");
},
});
});
const semaphore = yield* Semaphore.make(1);
const connection = yield* makeConnection;
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () =>
Scope.addFinalizer(scope, semaphore.release(1)),
),
connection,
}),
(statement) =>
Effect.sync(() => {
if (hasRows(statement)) {
statement.setReturnArrays(false);
}
}),
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
return identity<Connection>({
execute(sql, params, rowTransform) {
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
},
executeRaw(sql, params) {
return run(sql, params, true);
},
executeValues(sql, params) {
return runValues(sql, params);
},
executeUnprepared(sql, params, rowTransform) {
const effect = runStatement(db.prepare(sql), params ?? [], false);
return rowTransform ? Effect.map(effect, rowTransform) : effect;
},
executeStream(_sql, _params) {
return Stream.die("executeStream not implemented");
},
});
});
const semaphore = yield* Semaphore.make(1);
const connection = yield* makeConnection;
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
connection,
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
});
});
const make = (
options: SqliteClientConfig,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
@@ -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.
*
@@ -427,17 +427,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
);
};
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
@@ -306,21 +306,20 @@ const probeCodexCapabilities = (input: {
}),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const settingsService = yield* ServerSettingsService;
const codexSettings = yield* settingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
);
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
shell: process.platform === "win32",
env: {
...process.env,
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
});
return yield* spawnAndCollect(codexSettings.binaryPath, command);
const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {
const settingsService = yield* ServerSettingsService;
const codexSettings = yield* settingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
);
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
shell: process.platform === "win32",
env: {
...process.env,
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
});
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
resolveAccount?: (input: {
@@ -74,184 +74,180 @@ function resolveStreamLabel(stream: EventNdjsonStream): string {
}
}
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
return Effect.gen(function* () {
const serialized = yield* Effect.sync(() => {
try {
return { ok: true as const, value: JSON.stringify(event) };
} catch (error) {
return { ok: false as const, error };
}
});
if (!serialized.ok) {
yield* logWarning("failed to serialize provider event log record", {
error: serialized.error,
});
return undefined;
const toLogMessage = Effect.fn("toLogMessage")(function* (
event: unknown,
): Effect.fn.Return<string | undefined> {
const serialized = yield* Effect.sync(() => {
try {
return { ok: true as const, value: JSON.stringify(event) };
} catch (error) {
return { ok: false as const, error };
}
if (typeof serialized.value !== "string") {
return undefined;
}
return serialized.value;
});
}
function makeThreadWriter(input: {
if (!serialized.ok) {
yield* logWarning("failed to serialize provider event log record", {
error: serialized.error,
});
return undefined;
}
if (typeof serialized.value !== "string") {
return undefined;
}
return serialized.value;
});
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
}): Effect.Effect<ThreadWriter | undefined> {
return Effect.gen(function* () {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
}
});
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: (messages) =>
Effect.gen(function* () {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
}
}): Effect.fn.Return<ThreadWriter | undefined> {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
};
} catch (error) {
return { ok: false as const, error };
}
});
}
export function makeEventNdjsonLogger(
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.Effect<EventNdjsonLogger | undefined> {
return Effect.gen(function* () {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
): Effect.fn.Return<EventNdjsonLogger | undefined> {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
});
return undefined;
}
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
Effect.gen(function* () {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
});
return {
filePath,
write(event: unknown, threadId: ThreadId | null) {
return Effect.gen(function* () {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
},
close() {
return Effect.gen(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
},
} satisfies EventNdjsonLogger;
threadWriters.set(threadSegment, writer);
return writer;
});
}
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
const close = Effect.fn("close")(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
return {
filePath,
write,
close,
} satisfies EventNdjsonLogger;
});
@@ -22,30 +22,31 @@ export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
}
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
const adapter = byProvider.get(provider);
if (!adapter) {
return Effect.fail(new ProviderUnsupportedError({ provider }));
}
return Effect.succeed(adapter);
};
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
const adapter = byProvider.get(provider);
if (!adapter) {
return Effect.fail(new ProviderUnsupportedError({ provider }));
}
return Effect.succeed(adapter);
};
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
Effect.sync(() => Array.from(byProvider.keys()));
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
Effect.sync(() => Array.from(byProvider.keys()));
return {
getByProvider,
listProviders,
} satisfies ProviderAdapterRegistryShape;
});
return {
getByProvider,
listProviders,
} satisfies ProviderAdapterRegistryShape;
});
export const ProviderAdapterRegistryLive = Layer.effect(
ProviderAdapterRegistry,
@@ -40,18 +40,19 @@ export const ProviderRegistryLive = Layer.effect(
yield* loadProviders(codexProvider, claudeProvider),
);
const syncProviders = (options?: { readonly publish?: boolean }) =>
Effect.gen(function* () {
const previousProviders = yield* Ref.get(providersRef);
const providers = yield* loadProviders(codexProvider, claudeProvider);
yield* Ref.set(providersRef, providers);
const syncProviders = Effect.fn("syncProviders")(function* (options?: {
readonly publish?: boolean;
}) {
const previousProviders = yield* Ref.get(providersRef);
const providers = yield* loadProviders(codexProvider, claudeProvider);
yield* Ref.set(providersRef, providers);
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
return providers;
});
return providers;
});
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
Effect.forkScoped,
@@ -60,28 +61,30 @@ export const ProviderRegistryLive = Layer.effect(
Effect.forkScoped,
);
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
switch (provider) {
case "codex":
yield* codexProvider.refresh;
break;
case "claudeAgent":
yield* claudeProvider.refresh;
break;
default:
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
concurrency: "unbounded",
});
break;
}
return yield* syncProviders();
});
return {
getProviders: syncProviders({ publish: false }).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
refresh: (provider?: ProviderKind) =>
Effect.gen(function* () {
switch (provider) {
case "codex":
yield* codexProvider.refresh;
break;
case "claudeAgent":
yield* claudeProvider.refresh;
break;
default:
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
concurrency: "unbounded",
});
break;
}
return yield* syncProviders();
}).pipe(
refresh(provider).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
+457 -459
View File
@@ -131,472 +131,470 @@ function readPersistedCwd(
return trimmed.length > 0 ? trimmed : undefined;
}
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const analytics = yield* Effect.service(AnalyticsService);
const serverSettings = yield* ServerSettingsService;
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const makeProviderService = Effect.fn("makeProviderService")(function* (
options?: ProviderServiceLiveOptions,
) {
const analytics = yield* Effect.service(AnalyticsService);
const serverSettings = yield* ServerSettingsService;
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Effect.succeed(event).pipe(
Effect.tap((canonicalEvent) =>
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
);
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelSelection?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
) =>
directory.upsert({
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
});
const providers = yield* registry.listProviders();
const adapters = yield* Effect.forEach(providers, (provider) =>
registry.getByProvider(provider),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
const worker = Effect.forever(
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
);
yield* Effect.forkScoped(worker);
yield* Effect.forEach(adapters, (adapter) =>
Stream.runForEach(adapter.streamEvents, (event) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
const recoverSessionForThread = (input: {
readonly binding: ProviderRuntimeBinding;
readonly operation: string;
}) =>
Effect.gen(function* () {
const adapter = yield* registry.getByProvider(input.binding.provider);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
}
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
});
const resolveRoutableSession = (input: {
readonly threadId: ThreadId;
readonly operation: string;
readonly allowRecovery: boolean;
}) =>
Effect.gen(function* () {
const bindingOption = yield* directory.getBinding(input.threadId);
const binding = Option.getOrUndefined(bindingOption);
if (!binding) {
return yield* toValidationError(
input.operation,
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const adapter = yield* registry.getByProvider(binding.provider);
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
if (hasRequestedSession) {
return { adapter, threadId: input.threadId, isActive: true } as const;
}
if (!input.allowRecovery) {
return { adapter, threadId: input.threadId, isActive: false } as const;
}
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
Effect.gen(function* () {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.startSession",
schema: ProviderSessionStartInput,
payload: rawInput,
});
const input = {
...parsed,
threadId,
provider: parsed.provider ?? "codex",
};
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
"ProviderService.startSession",
`Failed to load provider settings: ${error.message}`,
error,
),
),
);
if (!settings.providers[input.provider].enabled) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider '${input.provider}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
if (session.provider !== adapter.provider) {
return yield* toValidationError(
"ProviderService.startSession",
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
);
}
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
});
return session;
});
const sendTurn: ProviderServiceShape["sendTurn"] = (rawInput) =>
Effect.gen(function* () {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.sendTurn",
schema: ProviderSendTurnInput,
payload: rawInput,
});
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
});
const interruptTurn: ProviderServiceShape["interruptTurn"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.interruptTurn",
schema: ProviderInterruptTurnInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.interruptTurn",
allowRecovery: true,
});
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
});
const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToRequest",
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
});
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToUserInput",
schema: ProviderRespondToUserInputInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
});
const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.stopSession",
schema: ProviderStopSessionInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.stopSession",
allowRecovery: false,
});
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.threadId);
}
yield* directory.remove(input.threadId);
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
});
const listSessions: ProviderServiceShape["listSessions"] = () =>
Effect.gen(function* () {
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
);
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
const persistedBindings = yield* directory.listThreadIds().pipe(
Effect.flatMap((threadIds) =>
Effect.forEach(
threadIds,
(threadId) =>
directory
.getBinding(threadId)
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
{ concurrency: "unbounded" },
),
),
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
);
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
for (const bindingOption of persistedBindings) {
const binding = Option.getOrUndefined(bindingOption);
if (binding) {
bindingsByThreadId.set(binding.threadId, binding);
}
}
return activeSessions.map((session) => {
const binding = bindingsByThreadId.get(session.threadId);
if (!binding) {
return session;
}
const overrides: {
resumeCursor?: ProviderSession["resumeCursor"];
runtimeMode?: ProviderSession["runtimeMode"];
} = {};
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
overrides.resumeCursor = binding.resumeCursor;
}
if (binding.runtimeMode !== undefined) {
overrides.runtimeMode = binding.runtimeMode;
}
return Object.assign({}, session, overrides);
});
});
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.rollbackConversation",
schema: ProviderRollbackConversationInput,
payload: rawInput,
});
if (input.numTurns === 0) {
return;
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
});
const runStopAll = () =>
Effect.gen(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
);
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
Effect.flatMap((provider) =>
directory.upsert({
threadId,
provider,
status: "stopped",
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
},
}),
),
),
).pipe(Effect.asVoid);
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
yield* analytics.flush;
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Effect.succeed(event).pipe(
Effect.tap((canonicalEvent) =>
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
Effect.asVoid,
);
return {
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
getCapabilities,
rollbackConversation,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
// independently receive all runtime events.
get streamEvents(): ProviderServiceShape["streamEvents"] {
return Stream.fromPubSub(runtimeEventPubSub);
},
} satisfies ProviderServiceShape;
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelSelection?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
) =>
directory.upsert({
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
});
const providers = yield* registry.listProviders();
const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
const worker = Effect.forever(
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
);
yield* Effect.forkScoped(worker);
yield* Effect.forEach(adapters, (adapter) =>
Stream.runForEach(adapter.streamEvents, (event) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
readonly binding: ProviderRuntimeBinding;
readonly operation: string;
}) {
const adapter = yield* registry.getByProvider(input.binding.provider);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
}
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
});
const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
readonly threadId: ThreadId;
readonly operation: string;
readonly allowRecovery: boolean;
}) {
const bindingOption = yield* directory.getBinding(input.threadId);
const binding = Option.getOrUndefined(bindingOption);
if (!binding) {
return yield* toValidationError(
input.operation,
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const adapter = yield* registry.getByProvider(binding.provider);
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
if (hasRequestedSession) {
return { adapter, threadId: input.threadId, isActive: true } as const;
}
if (!input.allowRecovery) {
return { adapter, threadId: input.threadId, isActive: false } as const;
}
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
function* (threadId, rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.startSession",
schema: ProviderSessionStartInput,
payload: rawInput,
});
const input = {
...parsed,
threadId,
provider: parsed.provider ?? "codex",
};
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
"ProviderService.startSession",
`Failed to load provider settings: ${error.message}`,
error,
),
),
);
if (!settings.providers[input.provider].enabled) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider '${input.provider}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
if (session.provider !== adapter.provider) {
return yield* toValidationError(
"ProviderService.startSession",
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
);
}
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
});
return session;
},
);
const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) {
const parsed = yield* decodeInputOrValidationError({
operation: "ProviderService.sendTurn",
schema: ProviderSendTurnInput,
payload: rawInput,
});
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
});
const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.interruptTurn",
schema: ProviderInterruptTurnInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.interruptTurn",
allowRecovery: true,
});
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
},
);
const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToRequest",
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
},
);
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn(
"respondToUserInput",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToUserInput",
schema: ProviderRespondToUserInputInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
});
const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.stopSession",
schema: ProviderStopSessionInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.stopSession",
allowRecovery: false,
});
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.threadId);
}
yield* directory.remove(input.threadId);
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
},
);
const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
function* () {
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
);
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
const persistedBindings = yield* directory.listThreadIds().pipe(
Effect.flatMap((threadIds) =>
Effect.forEach(
threadIds,
(threadId) =>
directory
.getBinding(threadId)
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
{ concurrency: "unbounded" },
),
),
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
);
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
for (const bindingOption of persistedBindings) {
const binding = Option.getOrUndefined(bindingOption);
if (binding) {
bindingsByThreadId.set(binding.threadId, binding);
}
}
return activeSessions.map((session) => {
const binding = bindingsByThreadId.get(session.threadId);
if (!binding) {
return session;
}
const overrides: {
resumeCursor?: ProviderSession["resumeCursor"];
runtimeMode?: ProviderSession["runtimeMode"];
} = {};
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
overrides.resumeCursor = binding.resumeCursor;
}
if (binding.runtimeMode !== undefined) {
overrides.runtimeMode = binding.runtimeMode;
}
return Object.assign({}, session, overrides);
});
},
);
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(
"rollbackConversation",
)(function* (rawInput) {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.rollbackConversation",
schema: ProviderRollbackConversationInput,
payload: rawInput,
});
if (input.numTurns === 0) {
return;
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
});
const runStopAll = Effect.fn("runStopAll")(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
Effect.flatMap((provider) =>
directory.upsert({
threadId,
provider,
status: "stopped",
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
},
}),
),
),
).pipe(Effect.asVoid);
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
yield* analytics.flush;
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
),
);
return {
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
getCapabilities,
rollbackConversation,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
// independently receive all runtime events.
get streamEvents(): ProviderServiceShape["streamEvents"] {
return Stream.fromPubSub(runtimeEventPubSub);
},
} satisfies ProviderServiceShape;
});
export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
@@ -5,68 +5,70 @@ import * as Semaphore from "effect/Semaphore";
import type { ServerProviderShape } from "./Services/ServerProvider";
import { ServerSettingsError } from "@t3tools/contracts";
export function makeManagedServerProvider<Settings>(input: {
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
Settings,
>(input: {
readonly getSettings: Effect.Effect<Settings>;
readonly streamSettings: Stream.Stream<Settings>;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
readonly refreshInterval?: Duration.Input;
}): Effect.Effect<ServerProviderShape, ServerSettingsError, Scope.Scope> {
return Effect.gen(function* () {
const refreshSemaphore = yield* Semaphore.make(1);
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ServerProvider>(),
PubSub.shutdown,
);
const initialSettings = yield* input.getSettings;
const initialSnapshot = yield* input.checkProvider;
const snapshotRef = yield* Ref.make(initialSnapshot);
const settingsRef = yield* Ref.make(initialSettings);
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
const refreshSemaphore = yield* Semaphore.make(1);
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ServerProvider>(),
PubSub.shutdown,
);
const initialSettings = yield* input.getSettings;
const initialSnapshot = yield* input.checkProvider;
const snapshotRef = yield* Ref.make(initialSnapshot);
const settingsRef = yield* Ref.make(initialSettings);
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
refreshSemaphore.withPermits(1)(
Effect.gen(function* () {
const forceRefresh = options?.forceRefresh === true;
const previousSettings = yield* Ref.get(settingsRef);
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
yield* Ref.set(settingsRef, nextSettings);
return yield* Ref.get(snapshotRef);
}
const applySnapshotBase = Effect.fn("applySnapshot")(function* (
nextSettings: Settings,
options?: { readonly forceRefresh?: boolean },
) {
const forceRefresh = options?.forceRefresh === true;
const previousSettings = yield* Ref.get(settingsRef);
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
yield* Ref.set(settingsRef, nextSettings);
return yield* Ref.get(snapshotRef);
}
const nextSnapshot = yield* input.checkProvider;
yield* Ref.set(settingsRef, nextSettings);
yield* Ref.set(snapshotRef, nextSnapshot);
yield* PubSub.publish(changesPubSub, nextSnapshot);
return nextSnapshot;
}),
);
const refreshSnapshot = Effect.gen(function* () {
const nextSettings = yield* input.getSettings;
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
Effect.asVoid(applySnapshot(nextSettings)),
).pipe(Effect.forkScoped);
yield* Effect.forever(
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
Effect.flatMap(() => refreshSnapshot),
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
return {
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
refresh: refreshSnapshot.pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ServerProviderShape;
const nextSnapshot = yield* input.checkProvider;
yield* Ref.set(settingsRef, nextSettings);
yield* Ref.set(snapshotRef, nextSnapshot);
yield* PubSub.publish(changesPubSub, nextSnapshot);
return nextSnapshot;
});
}
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
const nextSettings = yield* input.getSettings;
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
Effect.asVoid(applySnapshot(nextSettings)),
).pipe(Effect.forkScoped);
yield* Effect.forever(
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
Effect.flatMap(() => refreshSnapshot()),
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
return {
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ServerProviderShape;
});
+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]({
+18 -6
View File
@@ -99,12 +99,24 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(RuntimeReceiptBusLive),
);
const OrchestrationLayerLive = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(OrchestrationEngineLive),
Layer.provideMerge(OrchestrationProjectionPipelineLive),
Layer.provideMerge(OrchestrationEventStoreLive),
Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive),
const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
OrchestrationCommandReceiptRepositoryLive,
);
const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(
Layer.provide(OrchestrationEventStoreLive),
);
const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),
);
const CheckpointingLayerLive = Layer.empty.pipe(
+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");
@@ -70,34 +70,35 @@ const makeAnalyticsService = Effect.gen(function* () {
}),
);
const sendBatch = (events: ReadonlyArray<BufferedAnalyticsEvent>) =>
Effect.gen(function* () {
if (!telemetryConfig.enabled || !identifier) return;
const sendBatch = Effect.fn("sendBatch")(function* (
events: ReadonlyArray<BufferedAnalyticsEvent>,
) {
if (!telemetryConfig.enabled || !identifier) return;
const payload = {
api_key: telemetryConfig.posthogKey,
batch: events.map((event) => ({
event: event.event,
distinct_id: identifier,
properties: {
...event.properties,
$process_person_profile: false,
platform: process.platform,
wsl: process.env.WSL_DISTRO_NAME,
arch: process.arch,
t3CodeVersion: version,
clientType,
},
timestamp: event.capturedAt,
})),
};
const payload = {
api_key: telemetryConfig.posthogKey,
batch: events.map((event) => ({
event: event.event,
distinct_id: identifier,
properties: {
...event.properties,
$process_person_profile: false,
platform: process.platform,
wsl: process.env.WSL_DISTRO_NAME,
arch: process.arch,
t3CodeVersion: version,
clientType,
},
timestamp: event.capturedAt,
})),
};
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
HttpClientRequest.bodyJson(payload),
Effect.flatMap(httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
);
});
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
HttpClientRequest.bodyJson(payload),
Effect.flatMap(httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
);
});
const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
while (true) {
+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(
+50 -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) {
@@ -1407,6 +1410,52 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("opens the project cwd with Trae when it is the only available editor", async () => {
setDraftThreadWithoutWorktree();
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
availableEditors: ["trae"],
};
},
});
try {
await waitForServerConfigToApply();
const openButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Open",
) as HTMLButtonElement | null,
"Unable to find Open button.",
);
await vi.waitFor(() => {
expect(openButton.disabled).toBe(false);
});
openButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.shellOpenInEditor,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.shellOpenInEditor,
cwd: "/repo/project",
editor: "trae",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("filters the open picker menu and opens VSCodium from the menu", async () => {
setDraftThreadWithoutWorktree();
+14
View File
@@ -20,6 +20,20 @@ export const CursorIcon: Icon = (props) => (
</svg>
);
export const TraeIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
<rect x="1" y="4" width="3" height="14" />
<rect x="4" y="18" width="18" height="3" />
{/* Front frame: top bar + right bar only — left and bottom are replaced by the back strips above */}
<rect x="4" y="4" width="18" height="3" />
<rect x="19" y="7" width="3" height="11" />
{/* Two diamonds, offset slightly to the right within the open area */}
<path d="M11 10L13 12L11 14L9 12Z" />
<path d="M16 10L18 12L16 14L14 12Z" />
</svg>
);
export const VisualStudioCode: Icon = (props) => {
const id = useId();
const maskId = `${id}-vscode-a`;
@@ -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) {
@@ -6,7 +6,7 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
@@ -17,6 +17,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
Icon: CursorIcon,
value: "cursor",
},
{
label: "Trae",
Icon: TraeIcon,
value: "trae",
},
{
label: "VS Code",
Icon: VisualStudioCode,
@@ -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>
);
}
+132 -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";
@@ -17,6 +18,7 @@ import { useSettings } from "./useSettings";
export function useThreadActions() {
const appSettings = useSettings();
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
@@ -31,6 +33,13 @@ export function useThreadActions() {
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
const refreshActiveSnapshot = useCallback(async () => {
const api = readNativeApi();
if (!api) return;
const snapshot = await api.orchestration.getActiveSnapshot();
syncServerReadModel(snapshot);
}, [syncServerReadModel]);
const archiveThread = useCallback(
async (threadId: ThreadId) => {
const api = readNativeApi();
@@ -46,23 +55,29 @@ 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,
});
await refreshActiveSnapshot();
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
},
[queryClient, refreshActiveSnapshot],
);
const deleteThread = useCallback(
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
@@ -123,6 +138,7 @@ export function useThreadActions() {
commandId: newCommandId(),
threadId,
});
void queryClient.invalidateQueries({ queryKey: orchestrationQueryKeys.archivedThreads() });
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
@@ -172,6 +188,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 +323,7 @@ export function useThreadActions() {
archiveThread,
unarchiveThread,
deleteThread,
deleteArchivedThread,
confirmAndDeleteThread,
};
}
@@ -0,0 +1,20 @@
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))
+1
View File
@@ -3,6 +3,7 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
export const EDITORS = [
{ id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true },
{ id: "trae", label: "Trae", command: "trae", supportsGoto: true },
{ id: "vscode", label: "VS Code", command: "code", supportsGoto: true },
{
id: "vscode-insiders",
+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,
);