diff --git a/.plans/21-orchestration-v2-application-integration.md b/.plans/21-orchestration-v2-application-integration.md index 3e5811e836..2e310df21f 100644 --- a/.plans/21-orchestration-v2-application-integration.md +++ b/.plans/21-orchestration-v2-application-integration.md @@ -4,6 +4,8 @@ Make Orchestration V2 the only orchestration system used by the server, web app, and mobile app. Preserve reusable platform infrastructure, remove V1 orchestration as each replacement becomes authoritative, and leave legacy persistence untouched until a separate state-migration plan is chosen. +In this plan, "Orchestration V2" means the agent orchestrator: provider sessions, runs, attempts, runtime requests, and external agent effects. It does not replace the application event-sourcing data plane. Projects and threads remain first-class application aggregates in one durable, globally ordered event source, and the shell remains a projection of that source. + The work is split into four sequential architectural shapes. Finish and validate one shape before beginning the next. These shapes are implementation checkpoints only: they exist to keep the work reviewable and easier to reason about, not to define rollout stages or supported compatibility windows. There will be no users until after Shape 4 is complete. No intermediate shape is released, deployed for users, or expected to provide a usable mixed-version application. The first user-facing build uses the completed V2-only server and V2-native clients. @@ -12,6 +14,8 @@ Execution rules: - Do not dual-write V1 and V2 state. - Do not mirror production commands into both runtimes. +- Do not write core entity projection tables directly. Project and thread mutations commit application events first; projections are derived transactionally and remain replayable. +- Preserve one application event cursor across project and thread shell changes. - Shapes 1 and 2 may keep V1 runnable as a development reference while V2 is completed through direct and replay-backed tests; this is not a supported user path or rollout strategy. - Shape 3 performs the backend hard cut and intentionally breaks the old client protocol. - Shape 4 updates web and mobile to the final protocol. No intermediate backend/client compatibility adapter is required because no users consume the intermediate shapes. @@ -299,20 +303,20 @@ Implementation status: complete. The production WebSocket/client cutover remains Recreate the application behavior currently hidden in V1 reactors and WebSocket handlers using explicit V2 services and durable workflows. -### 1. Standalone project domain +### 1. Project domain service -Create a `ProjectService` outside orchestration that owns: +Create a `ProjectService` outside the agent orchestrator that owns project validation and application commands for: - create, update, and delete - lookup by ID and workspace root -- project list and snapshot +- project lookup and snapshot queries over the event-derived projection - repository identity - setup-script configuration - favicon metadata - startup auto-bootstrap -- project change subscriptions +- project event planning -Reuse `projection_projects` initially instead of migrating project data. Stop treating project commands as orchestration commands. +Reuse `projection_projects` initially instead of migrating project data. Project commands are application-domain commands, not agent-orchestrator commands, but they still commit to the shared application event source. `ProjectService` must not mutate `projection_projects` directly or own a standalone in-memory change stream. Reuse existing project infrastructure: @@ -519,9 +523,11 @@ Direct service-level integration tests must cover: ## Shape 3: V2-Only Backend Ownership +Implementation status: complete. The revision removes the V1 agent runtime, restores the existing application event-sourcing data plane, and installs V2 behind it instead of replacing it. + ### Goal -Make V2 the only live orchestration runtime and remove V1 from the server. +Make V2 the only live agent orchestration runtime while preserving the event-sourced application backend. This shape intentionally breaks the old client protocol. That is acceptable because the shapes are implementation chunks and there are no users or releases between them. @@ -529,8 +535,7 @@ This shape intentionally breaks the old client protocol. That is acceptable beca Replace V1 and debug V2 endpoints with one production API containing: -- project snapshot and subscription -- thread shell snapshot and subscription +- one shell snapshot and subscription containing projects, active threads, and archived threads - archived-thread query and subscription - full thread projection snapshot and subscription - thread launch @@ -547,14 +552,21 @@ Replace V1 and debug V2 endpoints with one production API containing: Use final unversioned method names. Do not retain compatibility aliases. +The shell stream uses one durable application-event cursor. Project and thread deltas cannot be split into independently ordered streams. + +The project HTTP API may remain as a CLI command/query transport, but it must call the same event-sourced `ProjectService`. It is not a second project state source, and the WebSocket protocol must not expose a separate project snapshot or subscription. + Move the debug route's projection reducer into a shared pure client-runtime module. Backend behavior must not depend on debugger state. ### 2. Replace server runtime composition In `apps/server/src/server.ts`: -- remove `OrchestrationLayerLive` -- remove V1 reactor composition +- remove the V1 agent reactors and provider runtime from the composition, but retain the existing `OrchestrationLayerLive` application event/projection infrastructure +- retain `orchestration_events` and `orchestration_command_receipts` as the generic application event log and receipt store; their historical names do not make them V1-only tables +- migrate the isolated `orchestration_v2_events` and `orchestration_v2_command_receipts` rows into that shared log, then treat the V2-specific tables as read-only legacy storage +- preserve or rename the generic projection, replay, and shell-query infrastructure +- remove only V1 agent/provider reactor composition - remove the V1 provider runtime layer - install V2 application services - install the durable effect worker @@ -573,6 +585,29 @@ In `apps/server/src/serverRuntimeStartup.ts`, establish this startup order: No V1 reactor or provider-session reaper starts. +The resulting ownership boundary is: + +```text +application commands + -> application event transaction + -> project/shell/thread projections + -> Agent Orchestrator V2 durable effects + -> provider execution + -> additional application events +``` + +The event transaction remains responsible for ordered append, command idempotency, projection updates, effect-outbox enqueue, and the committed sequence. + +This is an integration, not a replacement data plane. Restore and adapt the existing components: + +- `OrchestrationEventStore` remains the one durable event source and gains V2 thread-event codecs; V2 `EventStore` is an adapter over it, not a second SQL implementation. +- `OrchestrationCommandReceiptRepository` remains the command-idempotency store; the V2 receipt service adapts to it. +- `OrchestrationEngine` retains its serialized project-command transaction, decider, and projector path. Its production command surface is narrowed to project commands instead of restoring V1 agent execution. +- `OrchestrationProjectionPipeline` remains responsible for project projection replay and cursor advancement. +- `ProjectionSnapshotQuery` remains the source of project shell rows and is composed with V2 thread projections for the unified shell. + +Do not introduce parallel `ApplicationEventStore`, `ProjectProjection`, or `ApplicationShellService` replacements for these components. + ### 3. Update backend consumers Rewrite or redirect: @@ -589,7 +624,7 @@ Rewrite or redirect: Delete: -- `apps/server/src/orchestration/**` +- V1-only files under `apps/server/src/orchestration/**`, while keeping the existing event transaction, project decider/projector, projection pipeline, and snapshot query - V1 orchestration HTTP routes - V1 WebSocket handlers - V1 reactor and startup wiring @@ -599,9 +634,11 @@ Delete: - V1 high-level provider adapters and services after import analysis confirms no remaining consumers - corresponding tests and duplicate service interfaces +Do not delete infrastructure merely because it lived under the old `orchestration` namespace. Retain or relocate code whose responsibility is generic application event append/replay, command receipts, project/shell projection, cursor catch-up, or projection rebuild. + Retain low-level provider infrastructure imported by V2, including provider instance configuration, SDK and ACP transports, environment setup, logging, and runtime utilities. -Add an import-boundary test preventing production code from importing the deleted V1 namespace. +Add an import-boundary test preventing production code from importing the deleted V1 agent reactors and provider services. Imports of the retained application event/projection services are expected. ### 5. Preserve legacy storage @@ -621,6 +658,9 @@ Add backend integration coverage for: - startup ordering and command readiness - V2-only provider session creation - shell and thread snapshot reconnects +- project and thread changes sharing one ordered shell cursor +- project command idempotency and projection replay +- proof that project commands cannot bypass the application event store - CLI project operations - MCP send, wait, interrupt, fork, and merge flows - agent-awareness output @@ -633,9 +673,11 @@ Add backend integration coverage for: - Server startup does not construct any V1 orchestration or provider runtime. - Every production orchestration endpoint targets V2. +- Projects and threads are committed through one application event source and exposed through one shell stream. +- `projection_projects` and core thread projections are only changed by event projection/rebuild code. - CLI, MCP, checkpoints, awareness, startup, and telemetry use V2. -- No production import references `apps/server/src/orchestration`. -- No writes occur to legacy orchestration tables. +- No production import references the deleted V1 agent reactors, provider runtime ingestion, provider command handling, or session-reaper services. +- New writes go only to the retained application event/receipt tables and event-derived projections; the retired V1-only projection/runtime tables and isolated `orchestration_v2_*` event/receipt tables remain untouched. - Backend integration and restart tests pass. - Old clients are expected to be incompatible at this boundary. - `vp check`, `vp run typecheck`, and `vp test` pass. diff --git a/apps/server/integration/fixtures/providerRuntime.ts b/apps/server/integration/fixtures/providerRuntime.ts deleted file mode 100644 index e1258c4cc6..0000000000 --- a/apps/server/integration/fixtures/providerRuntime.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts"; -import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts"; - -const PROVIDER = ProviderDriverKind.make("codex"); -const SESSION_ID = "fixture-session"; -const THREAD_ID = "fixture-thread"; -const TURN_ID = "fixture-turn"; -const REQUEST_ID = RuntimeRequestId.make("req-1"); - -function baseEvent( - eventId: string, - createdAt: string, -): Pick { - return { - eventId: EventId.make(eventId), - provider: PROVIDER, - sessionId: SESSION_ID, - createdAt, - }; -} - -export const codexTurnTextFixture = [ - { - type: "turn.started", - ...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: {}, - }, - { - type: "content.delta", - ...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - streamKind: "assistant_text", - delta: "I will make a small update.\n", - }, - }, - { - type: "content.delta", - ...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - streamKind: "assistant_text", - delta: "Done.\n", - }, - }, - { - type: "turn.completed", - ...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - state: "completed", - }, - }, -] satisfies ReadonlyArray; - -export const codexTurnToolFixture = [ - { - type: "turn.started", - ...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: {}, - }, - { - type: "item.started", - ...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - itemType: "command_execution", - title: "Ran command", - detail: "echo integration", - }, - }, - { - type: "item.completed", - ...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - itemType: "command_execution", - status: "completed", - title: "Ran command", - detail: "echo integration", - }, - }, - { - type: "content.delta", - ...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - streamKind: "assistant_text", - delta: "Applied the requested edit.\n", - }, - }, - { - type: "turn.completed", - ...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - state: "completed", - }, - }, -] satisfies ReadonlyArray; - -export const codexTurnApprovalFixture = [ - { - type: "turn.started", - ...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: {}, - }, - { - type: "request.opened", - ...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - requestId: REQUEST_ID, - payload: { - requestType: "command_execution_approval", - detail: "Please approve command", - }, - }, - { - type: "request.resolved", - ...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - requestId: REQUEST_ID, - payload: { - requestType: "command_execution_approval", - decision: "accept", - }, - }, - { - type: "content.delta", - ...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - streamKind: "assistant_text", - delta: "Approval received and command executed.\n", - }, - }, - { - type: "turn.completed", - ...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"), - threadId: THREAD_ID, - turnId: TURN_ID, - payload: { - state: "completed", - }, - }, -] satisfies ReadonlyArray; diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts deleted file mode 100644 index c8382e6a28..0000000000 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ /dev/null @@ -1,1410 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodePath from "node:path"; - -import { - ApprovalRequestId, - CommandId, - defaultInstanceIdForDriver, - DEFAULT_PROVIDER_INTERACTION_MODE, - DEFAULT_MODEL, - DEFAULT_MODEL_BY_PROVIDER, - EventId, - MessageId, - ProjectId, - ProviderDriverKind, - ThreadId, - ModelSelection, - ProviderInstanceId, -} from "@t3tools/contracts"; -import { assert, it } from "@effect/vitest"; -import * as Clock from "effect/Clock"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts"; -import { - gitRefExists, - gitShowFileAtRef, - makeOrchestrationIntegrationHarness, - type OrchestrationIntegrationHarness, -} from "./OrchestrationEngineHarness.integration.ts"; -import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts"; -import type { - CheckpointDiffFinalizedReceipt, - TurnProcessingQuiescedReceipt, -} from "../src/orchestration/Services/RuntimeReceiptBus.ts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; - -const asMessageId = (value: string): MessageId => MessageId.make(value); -const asProjectId = (value: string): ProjectId => ProjectId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); - -const PROJECT_ID = asProjectId("project-1"); -const THREAD_ID = ThreadId.make("thread-1"); -const FIXTURE_TURN_ID = "fixture-turn"; -const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1"); -type IntegrationProvider = ProviderKind; - -function nowIso() { - return "2026-05-01T00:00:00.000Z"; -} - -class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass()( - "IntegrationWaitTimeoutError", - { - description: Schema.String, - }, -) {} - -function waitForSync( - read: () => A, - predicate: (value: A) => boolean, - description: string, - timeoutMs = 10_000, -): Effect.Effect { - return Effect.gen(function* () { - const deadline = (yield* Clock.currentTimeMillis) + timeoutMs; - - while (true) { - const value = read(); - if (predicate(value)) { - return value; - } - if ((yield* Clock.currentTimeMillis) >= deadline) { - return yield* Effect.die(new IntegrationWaitTimeoutError({ description })); - } - yield* Effect.sleep(10); - } - }); -} - -function runtimeBase( - eventId: string, - createdAt: string, - provider: IntegrationProvider = CODEX_PROVIDER, -) { - return { - eventId: asEventId(eventId), - provider, - createdAt, - }; -} - -function withHarness( - use: (harness: OrchestrationIntegrationHarness) => Effect.Effect, - provider: IntegrationProvider = CODEX_PROVIDER, -) { - return Effect.acquireUseRelease( - makeOrchestrationIntegrationHarness({ provider }), - use, - (harness) => harness.dispose, - ).pipe(Effect.provide(NodeServices.layer)); -} - -function withRealCodexHarness( - use: (harness: OrchestrationIntegrationHarness) => Effect.Effect, -) { - return Effect.acquireUseRelease( - makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }), - use, - (harness) => harness.dispose, - ).pipe(Effect.provide(NodeServices.layer)); -} - -const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => - Effect.gen(function* () { - const createdAt = nowIso(); - const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER; - const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL; - const instanceId = defaultInstanceIdForDriver(provider); - - yield* harness.engine.dispatch({ - type: "project.create", - commandId: CommandId.make("cmd-project-create"), - projectId: PROJECT_ID, - title: "Integration Project", - workspaceRoot: harness.workspaceDir, - defaultModelSelection: { - instanceId, - model: defaultModel, - }, - createdAt, - }); - - yield* harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create"), - threadId: THREAD_ID, - projectId: PROJECT_ID, - title: "Integration Thread", - modelSelection: { - instanceId, - model: defaultModel, - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: harness.workspaceDir, - createdAt, - }); - }); - -const startTurn = (input: { - readonly harness: OrchestrationIntegrationHarness; - readonly commandId: string; - readonly messageId: string; - readonly text: string; - readonly modelSelection?: ModelSelection; - readonly createdAt?: string; -}) => - input.harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make(input.commandId), - threadId: THREAD_ID, - message: { - messageId: asMessageId(input.messageId), - role: "user", - text: input.text, - attachments: [], - }, - ...(input.modelSelection !== undefined - ? { - modelSelection: input.modelSelection, - } - : {}), - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: input.createdAt ?? nowIso(), - }); - -it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () => - withHarness((harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - const turnResponse: TestTurnResponse = { - events: [ - { - type: "turn.started", - ...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Single turn response.\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }; - - yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse); - yield* startTurn({ - harness, - commandId: "cmd-turn-start-single", - messageId: "msg-user-single", - text: "Say hello", - }); - const finalizedReceipt = yield* harness.waitForReceipt( - (receipt): receipt is CheckpointDiffFinalizedReceipt => - receipt.type === "checkpoint.diff.finalized" && - receipt.threadId === THREAD_ID && - receipt.checkpointTurnCount === 1, - ); - if (finalizedReceipt.type !== "checkpoint.diff.finalized") { - throw new Error("Expected checkpoint.diff.finalized receipt."); - } - assert.equal(finalizedReceipt.status, "ready"); - yield* harness.waitForReceipt( - (receipt): receipt is TurnProcessingQuiescedReceipt => - receipt.type === "turn.processing.quiesced" && - receipt.threadId === THREAD_ID && - receipt.checkpointTurnCount === 1, - ); - - const thread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.session?.status === "ready" && - entry.messages.some( - (message) => message.role === "assistant" && message.streaming === false, - ) && - entry.checkpoints.length === 1, - ); - assert.equal(thread.checkpoints[0]?.status, "ready"); - assert.equal(thread.checkpoints[0]?.checkpointTurnCount, 1); - - const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ - threadId: THREAD_ID, - }); - assert.equal(checkpointRows.length, 1); - assert.equal(checkpointRows[0]?.checkpointTurnCount, 1); - assert.equal(checkpointRows[0]?.status, "ready"); - assert.deepEqual(checkpointRows[0]?.files, []); - - const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0); - const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1); - assert.equal(gitRefExists(harness.workspaceDir, ref0), true); - assert.equal(gitRefExists(harness.workspaceDir, ref1), true); - assert.equal(gitShowFileAtRef(harness.workspaceDir, ref0, "README.md"), "v1\n"); - assert.equal(gitShowFileAtRef(harness.workspaceDir, ref1, "README.md"), "v1\n"); - }), - ), -); - -it.live.skipIf(!process.env.CODEX_BINARY_PATH)( - "keeps the same Codex provider thread across runtime mode switches", - () => - withRealCodexHarness((harness) => - Effect.gen(function* () { - const createdAt = nowIso(); - - yield* harness.engine.dispatch({ - type: "project.create", - commandId: CommandId.make("cmd-project-create-real-codex"), - projectId: PROJECT_ID, - title: "Integration Project", - workspaceRoot: harness.workspaceDir, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.3-codex", - }, - createdAt, - }); - - yield* harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-real-codex"), - threadId: THREAD_ID, - projectId: PROJECT_ID, - title: "Integration Thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.3-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: harness.workspaceDir, - createdAt, - }); - - yield* harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-real-codex-1"), - threadId: THREAD_ID, - message: { - messageId: asMessageId("msg-real-codex-1"), - role: "user", - text: "Reply with exactly ALPHA.", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - createdAt: nowIso(), - }); - - const firstThread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.session?.status === "ready" && - entry.session.providerName === "codex" && - entry.messages.some( - (message) => message.role === "assistant" && message.streaming === false, - ), - 180_000, - ); - assert.equal(firstThread.session?.threadId, "thread-1"); - - yield* harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-real-codex-2"), - threadId: THREAD_ID, - message: { - messageId: asMessageId("msg-real-codex-2"), - role: "user", - text: "Reply with exactly BETA.", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: nowIso(), - }); - - const secondThread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.session?.status === "ready" && - entry.session.providerName === "codex" && - entry.session.runtimeMode === "approval-required" && - entry.messages.some( - (message) => message.role === "assistant" && message.text.includes("BETA"), - ), - 180_000, - ); - assert.equal(secondThread.session?.threadId, "thread-1"); - }), - ), -); - -it.live("runs multi-turn file edits and persists checkpoint diffs", () => - withHarness((harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "tool.started", - ...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - toolKind: "command", - title: "Edit file", - detail: "README.md", - }, - { - type: "tool.completed", - ...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - toolKind: "command", - title: "Edit file", - detail: "README.md", - }, - { - type: "message.delta", - ...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Updated README to v2.\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - mutateWorkspace: ({ cwd }) => - Effect.sync(() => { - NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v2\n", "utf8"); - }), - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-multi-1", - messageId: "msg-user-multi-1", - text: "Make first edit", - }); - yield* harness.waitForReceipt( - (receipt): receipt is CheckpointDiffFinalizedReceipt => - receipt.type === "checkpoint.diff.finalized" && - receipt.threadId === THREAD_ID && - receipt.checkpointTurnCount === 1, - ); - - yield* harness.waitForThread( - THREAD_ID, - (entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1", - ); - - yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, { - events: [ - { - type: "turn.started", - ...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Updated README to v3.\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - mutateWorkspace: ({ cwd }) => - Effect.sync(() => { - NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v3\n", "utf8"); - }), - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-multi-2", - messageId: "msg-user-multi-2", - text: "Make second edit", - }); - const secondReceipt = yield* harness.waitForReceipt( - (receipt): receipt is CheckpointDiffFinalizedReceipt => - receipt.type === "checkpoint.diff.finalized" && - receipt.threadId === THREAD_ID && - receipt.checkpointTurnCount === 2, - ); - if (secondReceipt.type !== "checkpoint.diff.finalized") { - throw new Error("Expected checkpoint.diff.finalized receipt."); - } - assert.equal(secondReceipt.status, "ready"); - yield* harness.waitForReceipt( - (receipt): receipt is TurnProcessingQuiescedReceipt => - receipt.type === "turn.processing.quiesced" && - receipt.threadId === THREAD_ID && - receipt.checkpointTurnCount === 2, - ); - - const secondTurnThread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.latestTurn?.turnId === "turn-2" && - entry.checkpoints.length === 2 && - entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2), - ); - const secondCheckpoint = secondTurnThread.checkpoints.find( - (checkpoint) => checkpoint.checkpointTurnCount === 2, - ); - assert.equal( - secondCheckpoint?.files.some((file) => file.path === "README.md"), - true, - ); - - const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ - threadId: THREAD_ID, - }); - assert.deepEqual( - checkpointRows.map((row) => row.checkpointTurnCount), - [1, 2], - ); - - const incrementalDiff = yield* harness.checkpointStore.diffCheckpoints({ - cwd: harness.workspaceDir, - fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1), - toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2), - fallbackFromToHead: false, - ignoreWhitespace: false, - }); - assert.equal(incrementalDiff.includes("README.md"), true); - - const fullDiff = yield* harness.checkpointStore.diffCheckpoints({ - cwd: harness.workspaceDir, - fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0), - toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2), - fallbackFromToHead: false, - ignoreWhitespace: false, - }); - assert.equal(fullDiff.includes("README.md"), true); - - assert.equal( - gitShowFileAtRef( - harness.workspaceDir, - checkpointRefForThreadTurn(THREAD_ID, 1), - "README.md", - ), - "v2\n", - ); - assert.equal( - gitShowFileAtRef( - harness.workspaceDir, - checkpointRefForThreadTurn(THREAD_ID, 2), - "README.md", - ), - "v3\n", - ); - }), - ), -); - -it.live("tracks approval requests and resolves pending approvals on user response", () => - withHarness((harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "approval.requested", - ...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - requestId: APPROVAL_REQUEST_ID, - requestKind: "command", - detail: "Approve command execution", - }, - { - type: "turn.completed", - ...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-approval", - messageId: "msg-user-approval", - text: "Run command needing approval", - }); - - const thread = yield* harness.waitForThread(THREAD_ID, (entry) => - entry.activities.some((activity) => activity.kind === "approval.requested"), - ); - assert.equal( - thread.activities.some((activity) => activity.kind === "approval.requested"), - true, - ); - - const pendingRow = yield* harness.waitForPendingApproval( - "req-approval-1", - (row) => row.status === "pending" && row.decision === null, - ); - assert.equal(pendingRow.status, "pending"); - - yield* harness.engine.dispatch({ - type: "thread.approval.respond", - commandId: CommandId.make("cmd-approval-respond"), - threadId: THREAD_ID, - requestId: APPROVAL_REQUEST_ID, - decision: "accept", - createdAt: nowIso(), - }); - - const resolvedRow = yield* harness.waitForPendingApproval( - "req-approval-1", - (row) => row.status === "resolved" && row.decision === "accept", - ); - assert.equal(resolvedRow.status, "resolved"); - assert.equal(resolvedRow.decision, "accept"); - - const approvalResponses = yield* waitForSync( - () => harness.adapterHarness!.getApprovalResponses(THREAD_ID), - (responses) => responses.length === 1, - "provider approval response", - ); - assert.equal(approvalResponses.length, 1); - assert.equal(approvalResponses[0]?.requestId, "req-approval-1"); - assert.equal(approvalResponses[0]?.decision, "accept"); - }), - ), -); - -it.live("records failed turn runtime state and checkpoint status as error", () => - withHarness((harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "content.delta", - ...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - payload: { - streamKind: "assistant_text", - delta: "Partial output before failure.\n", - }, - }, - { - type: "runtime.error", - ...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - payload: { - message: "Sandbox command failed.", - }, - }, - { - type: "turn.completed", - ...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - payload: { - state: "failed", - errorMessage: "Sandbox command failed.", - }, - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-failure", - messageId: "msg-user-failure", - text: "Run risky command", - }); - - const thread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.session?.status === "error" && - entry.session?.lastError === "Sandbox command failed." && - entry.activities.some((activity) => activity.kind === "runtime.error") && - entry.checkpoints.length === 1, - ); - assert.equal(thread.session?.status, "error"); - assert.equal(thread.checkpoints[0]?.status, "error"); - - const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({ - threadId: THREAD_ID, - checkpointTurnCount: 1, - }); - assert.equal(Option.isSome(checkpointRow), true); - if (Option.isSome(checkpointRow)) { - assert.equal(checkpointRow.value.status, "error"); - } - assert.equal( - gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)), - true, - ); - }), - ), -); - -it.live("reverts to an earlier checkpoint and trims checkpoint projections + git refs", () => - withHarness((harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "tool.started", - ...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - toolKind: "command", - title: "Edit file", - detail: "README.md", - }, - { - type: "tool.completed", - ...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - toolKind: "command", - title: "Edit file", - detail: "README.md", - }, - { - type: "message.delta", - ...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Updated README to v2.\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - mutateWorkspace: ({ cwd }) => - Effect.sync(() => { - fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8"); - }), - }); - yield* startTurn({ - harness, - commandId: "cmd-turn-start-revert-1", - messageId: "msg-user-revert-1", - text: "First edit", - }); - - yield* harness.waitForThread( - THREAD_ID, - (entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1, - ); - - yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, { - events: [ - { - type: "turn.started", - ...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "tool.started", - ...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - toolKind: "command", - title: "Edit file", - detail: "README.md", - }, - { - type: "tool.completed", - ...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - toolKind: "command", - title: "Edit file", - detail: "README.md", - }, - { - type: "message.delta", - ...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Updated README to v3.\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - mutateWorkspace: ({ cwd }) => - Effect.sync(() => { - fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8"); - }), - }); - yield* startTurn({ - harness, - commandId: "cmd-turn-start-revert-2", - messageId: "msg-user-revert-2", - text: "Second edit", - }); - - yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.latestTurn?.turnId === "turn-2" && - entry.checkpoints.length === 2 && - entry.activities.some((activity) => activity.turnId === "turn-2"), - 8000, - ); - - yield* harness.engine.dispatch({ - type: "thread.checkpoint.revert", - commandId: CommandId.make("cmd-checkpoint-revert"), - threadId: THREAD_ID, - turnCount: 1, - createdAt: nowIso(), - }); - - yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted"); - const revertedThread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1, - ); - assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1); - assert.deepEqual( - revertedThread.messages.map((message) => ({ role: message.role, text: message.text })), - [ - { role: "user", text: "First edit" }, - { role: "assistant", text: "Updated README to v2.\n" }, - ], - ); - assert.equal( - revertedThread.activities.some((activity) => activity.turnId === "turn-2"), - false, - ); - assert.equal( - revertedThread.activities.some( - (activity) => activity.turnId === "turn-1" && activity.kind === "tool.started", - ), - true, - ); - assert.equal( - revertedThread.activities.some( - (activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed", - ), - true, - ); - assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n"); - assert.equal( - gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)), - false, - ); - assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]); - - const checkpointRows = yield* harness.checkpointRepository.listByThreadId({ - threadId: THREAD_ID, - }); - assert.equal(checkpointRows.length, 1); - }), - ), -); - -it.live( - "appends checkpoint.revert.failed activity when revert is requested without an active session", - () => - withHarness((harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.engine.dispatch({ - type: "thread.checkpoint.revert", - commandId: CommandId.make("cmd-checkpoint-revert-no-session"), - threadId: THREAD_ID, - turnCount: 0, - createdAt: nowIso(), - }); - - const thread = yield* harness.waitForThread(THREAD_ID, (entry) => - entry.activities.some( - (activity) => - activity.kind === "checkpoint.revert.failed" && - typeof activity.payload === "object" && - activity.payload !== null, - ), - ); - const failureActivity = thread.activities.find( - (activity) => activity.kind === "checkpoint.revert.failed", - ); - assert.equal(failureActivity !== undefined, true); - assert.equal( - String( - (failureActivity?.payload as { readonly detail?: string } | undefined)?.detail, - ).includes("No active provider session"), - true, - ); - }), - ), -); - -it.live("starts a claudeAgent session on first turn when provider is requested", () => - withHarness( - (harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase( - "evt-claude-start-1", - "2026-02-24T10:10:00.000Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase( - "evt-claude-start-2", - "2026-02-24T10:10:00.050Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Claude first turn.\n", - }, - { - type: "turn.completed", - ...runtimeBase( - "evt-claude-start-3", - "2026-02-24T10:10:00.100Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-initial", - messageId: "msg-user-claude-initial", - text: "Use Claude", - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-sonnet-4-6", - }, - }); - - const thread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.session?.providerName === "claudeAgent" && - entry.session.status === "ready" && - entry.messages.some( - (message) => message.role === "assistant" && message.text === "Claude first turn.\n", - ), - ); - assert.equal(thread.session?.providerName, "claudeAgent"); - }), - CLAUDE_AGENT_PROVIDER, - ), -); - -it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () => - withHarness( - (harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase( - "evt-claude-recover-1", - "2026-02-24T10:11:00.000Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase( - "evt-claude-recover-2", - "2026-02-24T10:11:00.050Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Turn before restart.\n", - }, - { - type: "turn.completed", - ...runtimeBase( - "evt-claude-recover-3", - "2026-02-24T10:11:00.100Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-recover-1", - messageId: "msg-user-claude-recover-1", - text: "Before restart", - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-sonnet-4-6", - }, - }); - - yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1", - ); - - yield* harness.adapterHarness!.adapter.stopAll(); - yield* waitForSync( - () => harness.adapterHarness!.listActiveSessionIds(), - (sessionIds) => sessionIds.length === 0, - "provider stopAll", - ); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase( - "evt-claude-recover-4", - "2026-02-24T10:11:01.000Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase( - "evt-claude-recover-5", - "2026-02-24T10:11:01.050Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Turn after restart.\n", - }, - { - type: "turn.completed", - ...runtimeBase( - "evt-claude-recover-6", - "2026-02-24T10:11:01.100Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-recover-2", - messageId: "msg-user-claude-recover-2", - text: "After restart", - }); - yield* waitForSync( - () => harness.adapterHarness!.getStartCount(), - (count) => count === 2, - "claude provider recovery start", - ); - - const recoveredThread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.session?.providerName === "claudeAgent" && - entry.messages.some( - (message) => message.role === "user" && message.text === "After restart", - ) && - !entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"), - ); - assert.equal(recoveredThread.session?.providerName, "claudeAgent"); - assert.equal(recoveredThread.session?.threadId, "thread-1"); - }), - CLAUDE_AGENT_PROVIDER, - ), -); - -it.live("forwards claudeAgent approval responses to the provider session", () => - withHarness( - (harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase( - "evt-claude-approval-1", - "2026-02-24T10:12:00.000Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "approval.requested", - ...runtimeBase( - "evt-claude-approval-2", - "2026-02-24T10:12:00.050Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - requestId: APPROVAL_REQUEST_ID, - requestKind: "command", - detail: "Approve Claude tool call", - }, - { - type: "turn.completed", - ...runtimeBase( - "evt-claude-approval-3", - "2026-02-24T10:12:00.100Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-approval", - messageId: "msg-user-claude-approval", - text: "Need approval", - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-sonnet-4-6", - }, - }); - - const thread = yield* harness.waitForThread(THREAD_ID, (entry) => - entry.activities.some((activity) => activity.kind === "approval.requested"), - ); - assert.equal(thread.session?.threadId, "thread-1"); - - yield* harness.engine.dispatch({ - type: "thread.approval.respond", - commandId: CommandId.make("cmd-claude-approval-respond"), - threadId: THREAD_ID, - requestId: APPROVAL_REQUEST_ID, - decision: "accept", - createdAt: nowIso(), - }); - - yield* harness.waitForPendingApproval( - "req-approval-1", - (row) => row.status === "resolved" && row.decision === "accept", - ); - - const approvalResponses = yield* waitForSync( - () => harness.adapterHarness!.getApprovalResponses(THREAD_ID), - (responses) => responses.length === 1, - "claude provider approval response", - ); - assert.equal(approvalResponses[0]?.decision, "accept"); - }), - CLAUDE_AGENT_PROVIDER, - ), -); - -it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => - withHarness( - (harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase( - "evt-claude-interrupt-1", - "2026-02-24T10:13:00.000Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase( - "evt-claude-interrupt-2", - "2026-02-24T10:13:00.050Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "Long running output.\n", - }, - { - type: "turn.completed", - ...runtimeBase( - "evt-claude-interrupt-3", - "2026-02-24T10:13:00.100Z", - CLAUDE_AGENT_PROVIDER, - ), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-interrupt", - messageId: "msg-user-claude-interrupt", - text: "Start long turn", - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-sonnet-4-6", - }, - }); - - const thread = yield* harness.waitForThread( - THREAD_ID, - (entry) => entry.session?.threadId === "thread-1", - ); - assert.equal(thread.session?.threadId, "thread-1"); - - yield* harness.engine.dispatch({ - type: "thread.turn.interrupt", - commandId: CommandId.make("cmd-turn-interrupt-claude"), - threadId: THREAD_ID, - createdAt: nowIso(), - }); - yield* harness.waitForDomainEvent( - (event) => event.type === "thread.turn-interrupt-requested", - ); - - const interruptCalls = yield* waitForSync( - () => harness.adapterHarness!.getInterruptCalls(THREAD_ID), - (calls) => calls.length === 1, - "claude provider interrupt call", - ); - assert.equal(interruptCalls.length, 1); - }), - CLAUDE_AGENT_PROVIDER, - ), -); - -it.live("reverts claudeAgent turns and rolls back provider conversation state", () => - withHarness( - (harness) => - Effect.gen(function* () { - yield* seedProjectAndThread(harness); - - yield* harness.adapterHarness!.queueTurnResponseForNextSession({ - events: [ - { - type: "turn.started", - ...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "README -> v2\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - mutateWorkspace: ({ cwd }) => - Effect.sync(() => { - fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8"); - }), - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-revert-1", - messageId: "msg-user-claude-revert-1", - text: "First Claude edit", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - }, - }); - - yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1", - ); - - yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, { - events: [ - { - type: "turn.started", - ...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - }, - { - type: "message.delta", - ...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - delta: "README -> v3\n", - }, - { - type: "turn.completed", - ...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"), - threadId: THREAD_ID, - turnId: FIXTURE_TURN_ID, - status: "completed", - }, - ], - mutateWorkspace: ({ cwd }) => - Effect.sync(() => { - fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8"); - }), - }); - - yield* startTurn({ - harness, - commandId: "cmd-turn-start-claude-revert-2", - messageId: "msg-user-claude-revert-2", - text: "Second Claude edit", - }); - - yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.latestTurn?.turnId === "turn-2" && - entry.checkpoints.length === 2 && - entry.session?.providerName === "claudeAgent", - ); - - yield* harness.engine.dispatch({ - type: "thread.checkpoint.revert", - commandId: CommandId.make("cmd-checkpoint-revert-claude"), - threadId: THREAD_ID, - turnCount: 1, - createdAt: nowIso(), - }); - - const revertedThread = yield* harness.waitForThread( - THREAD_ID, - (entry) => - entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1, - ); - assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1); - assert.equal( - gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)), - true, - ); - assert.equal( - gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)), - false, - ); - assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]); - }), - "claudeAgent", - ), -); diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.ts deleted file mode 100644 index fcb662b9b7..0000000000 --- a/apps/server/src/bin.test.ts +++ /dev/null @@ -1,602 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries. -import * as NodeHttp from "node:http"; -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - -import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { - CommandId, - EnvironmentOrchestrationHttpApi, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; -import * as NetService from "@t3tools/shared/Net"; -import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as DateTime from "effect/DateTime"; -import * as Layer from "effect/Layer"; -import * as HttpRouter from "effect/unstable/http/HttpRouter"; -import * as HttpServer from "effect/unstable/http/HttpServer"; -import * as HttpApi from "effect/unstable/httpapi/HttpApi"; -import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; -import * as CliError from "effect/unstable/cli/CliError"; -import * as TestConsole from "effect/testing/TestConsole"; -import { Command } from "effect/unstable/cli"; - -import { cli, makeCli } from "./bin.ts"; -import * as ServerConfig from "./config.ts"; -import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; -import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts"; -import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts"; -import { orchestrationHttpApiLayer } from "./orchestration/http.ts"; -import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts"; -import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; -import { - makePersistedServerRuntimeState, - persistServerRuntimeState, -} from "./serverRuntimeState.ts"; -import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; -import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; -import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import { environmentAuthenticatedAuthLayer } from "./auth/http.ts"; - -const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); -class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {} - -const connectCli = makeCli({ cloudEnabled: true }); -const noConnectCli = makeCli({ cloudEnabled: false }); -const runCli = (args: ReadonlyArray, command = cli) => - Command.runWith(command, { version: "0.0.0" })(args); -const runConnectCli = (args: ReadonlyArray) => runCli(args, connectCli); -const runCliWithRuntime = (args: ReadonlyArray) => - runCli(args).pipe(Effect.provide(CliRuntimeLayer)); - -const captureStdout = (effect: Effect.Effect) => - Effect.gen(function* () { - const result = yield* effect; - const output = - (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ?? - ""; - return { result, output }; - }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))); - -const makeCliTestServerConfig = (baseDir: string) => - Effect.gen(function* () { - const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined); - return { - logLevel: "Info", - traceMinLevel: "Info", - traceTimingEnabled: true, - traceBatchWindowMs: 200, - traceMaxBytes: 10 * 1024 * 1024, - traceMaxFiles: 10, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpExportIntervalMs: 10_000, - otlpServiceName: "t3-server", - mode: "web", - port: 0, - host: "127.0.0.1", - cwd: process.cwd(), - baseDir, - ...derivedPaths, - staticDir: undefined, - devUrl: undefined, - devAllowedOrigins: [], - noBrowser: true, - startupPresentation: "browser", - desktopBootstrapToken: undefined, - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - } satisfies ServerConfig.ServerConfig["Service"]; - }); - -const makeProjectPersistenceLayer = (config: ServerConfig.ServerConfig["Service"]) => - Layer.mergeAll( - OrchestrationLayerLive.pipe( - Layer.provideMerge(RepositoryIdentityResolver.layer), - Layer.provideMerge(SqlitePersistenceLayerLive), - ), - WorkspacePaths.layer, - ).pipe(Layer.provideMerge(NodeServices.layer), Layer.provide(ServerConfig.layer(config))); - -const readPersistedSnapshot = (baseDir: string) => - Effect.gen(function* () { - const config = yield* makeCliTestServerConfig(baseDir); - return yield* Effect.gen(function* () { - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; - return yield* projectionSnapshotQuery.getSnapshot(); - }).pipe(Effect.provide(makeProjectPersistenceLayer(config))); - }); - -const withLiveProjectCliServer = (baseDir: string, run: () => Effect.Effect) => - Effect.gen(function* () { - const config = yield* makeCliTestServerConfig(baseDir); - const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe( - Layer.provide(orchestrationHttpApiLayer), - Layer.provide(environmentAuthenticatedAuthLayer), - ); - const appLayer = HttpRouter.serve(routesLayer, { - disableListenLog: true, - disableLogger: true, - }).pipe( - Layer.provideMerge( - EnvironmentAuth.layer.pipe( - Layer.provideMerge(SqlitePersistenceLayerLive), - Layer.provide(ServerSecretStore.layer), - ), - ), - Layer.provideMerge(makeProjectPersistenceLayer(config)), - Layer.provideMerge( - NodeHttpServer.layer(NodeHttp.createServer, { - host: "127.0.0.1", - port: 0, - }), - ), - Layer.provideMerge(NodeServices.layer), - Layer.provide(ServerConfig.layer(config)), - ); - - return yield* Effect.scoped( - Effect.gen(function* () { - const server = yield* HttpServer.HttpServer; - const address = server.address; - if (typeof address === "string" || !("port" in address)) { - assert.fail(`Expected TCP address, got ${address}`); - } - yield* persistServerRuntimeState({ - path: config.serverRuntimeStatePath, - state: yield* makePersistedServerRuntimeState({ - config, - port: address.port, - }), - }); - return yield* run(); - }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))), - ); - }); - -it.layer(NodeServices.layer)("bin cli parsing", (it) => { - it.effect("accepts the built-in lowercase log-level flag values", () => - runCliWithRuntime(["--log-level", "debug", "--version"]), - ); - - it.effect("accepts canonical --no- boolean negation", () => - runCliWithRuntime(["--no-log-websocket-events", "--version"]), - ); - - it.effect("rejects invalid log-level casing before launching the server", () => - Effect.gen(function* () { - const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip); - - if (!CliError.isCliError(error)) { - assert.fail(`Expected CliError, got ${String(error)}`); - } - if (error._tag !== "InvalidValue") { - assert.fail(`Expected InvalidValue, got ${error._tag}`); - } - assert.equal(error.option, "log-level"); - assert.equal(error.value, "Debug"); - }), - ); - - it.effect("rejects connect commands when public configuration is missing", () => - Effect.gen(function* () { - const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip); - - if (!CliError.isCliError(error)) { - assert.fail(`Expected CliError, got ${String(error)}`); - } - if (error._tag !== "ShowHelp") { - assert.fail(`Expected ShowHelp, got ${error._tag}`); - } - assert.deepEqual(error.commandPath, ["t3", "connect"]); - assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration"); - - const output = (yield* TestConsole.errorLines).join("\n"); - assert.include(output, "ERROR"); - assert.include(output, "missing T3 Connect public configuration"); - }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))), - ); - - it.effect("exposes service lifecycle commands without T3 Connect configuration", () => - Effect.gen(function* () { - const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli)); - - assert.include(output, "Manage the T3 Code background service."); - assert.include(output, "install"); - assert.include(output, "uninstall"); - assert.include(output, "update"); - assert.include(output, "status"); - }), - ); - - it.effect("reports fresh headless connect state without requiring local configuration", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-test-"), - ); - const { output } = yield* captureStdout( - runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO. - const status = JSON.parse(output) as { - readonly desired: boolean; - readonly authenticated: boolean; - readonly linked: boolean; - readonly cloudUserId: string | null; - readonly relayUrl: string | null; - }; - - assert.equal(status.desired, false); - assert.equal(status.authenticated, false); - assert.equal(status.linked, false); - assert.equal(status.cloudUserId, null); - assert.equal(status.relayUrl, null); - }), - ); - - it.effect("reports actionable human-readable headless connect state", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-human-test-"), - ); - const { output } = yield* captureStdout( - runConnectCli(["connect", "status", "--base-dir", baseDir]), - ); - - assert.include(output, "T3 Connect\n Exposure: disabled"); - assert.include(output, " Authorization: missing"); - assert.include(output, " Environment link: not provisioned"); - assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect."); - }), - ); - - it.effect("accepts the --headless login override without enabling access", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"), - ); - const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined); - NodeFS.mkdirSync(secretsDir, { recursive: true }); - NodeFS.writeFileSync( - NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"), - // @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation. - JSON.stringify({ - accessToken: "access-token", - refreshToken: "refresh-token", - expiresAtEpochMs: Number.MAX_SAFE_INTEGER, - }), - ); - - const login = yield* captureStdout( - runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]), - ); - const status = yield* captureStdout( - runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO. - const decoded = JSON.parse(status.output) as { - readonly desired: boolean; - readonly authenticated: boolean; - }; - - assert.equal(login.output, "✓ Signed in"); - assert.isFalse(decoded.desired); - assert.isTrue(decoded.authenticated); - }), - ); - - it.effect("disables headless connect without a running server", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-unlink-test-"), - ); - const { output } = yield* captureStdout( - runConnectCli(["connect", "unlink", "--base-dir", baseDir]), - ); - - assert.equal(output, "T3 Connect is disabled locally."); - }), - ); - - it.effect("logs out of headless connect and removes the stored CLI authorization", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-logout-test-"), - ); - const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined); - const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"); - NodeFS.mkdirSync(secretsDir, { recursive: true }); - NodeFS.writeFileSync(tokenPath, "invalid persisted token"); - - const { output } = yield* captureStdout( - runConnectCli(["connect", "logout", "--base-dir", baseDir]), - ); - - assert.equal( - output, - "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.", - ); - assert.isFalse(NodeFS.existsSync(tokenPath)); - }), - ); - - it.effect("executes auth pairing subcommands and redacts secrets from list output", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-pairing-test-"), - ); - - const createdOutput = yield* captureStdout( - runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - const created = JSON.parse(createdOutput.output) as { - readonly id: string; - readonly credential: string; - }; - const listedOutput = yield* captureStdout( - runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{ - readonly id: string; - readonly credential?: string; - }>; - - assert.equal(typeof created.id, "string"); - assert.equal(typeof created.credential, "string"); - assert.equal(created.credential.length > 0, true); - assert.equal(listed.length, 1); - assert.equal(listed[0]?.id, created.id); - assert.equal("credential" in (listed[0] ?? {}), false); - }), - ); - - it.effect("executes auth session subcommands and redacts secrets from list output", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-session-test-"), - ); - - const issuedOutput = yield* captureStdout( - runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - const issued = JSON.parse(issuedOutput.output) as { - readonly sessionId: string; - readonly token: string; - readonly scopes: ReadonlyArray; - }; - const listedOutput = yield* captureStdout( - runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{ - readonly sessionId: string; - readonly token?: string; - readonly scopes: ReadonlyArray; - }>; - - assert.equal(typeof issued.sessionId, "string"); - assert.equal(typeof issued.token, "string"); - assert.deepEqual(issued.scopes, [ - "orchestration:read", - "orchestration:operate", - "terminal:operate", - "review:write", - "relay:read", - "access:read", - "access:write", - "relay:write", - ]); - assert.equal(listed.length, 1); - assert.equal(listed[0]?.sessionId, issued.sessionId); - assert.deepEqual(listed[0]?.scopes, [ - "orchestration:read", - "orchestration:operate", - "terminal:operate", - "review:write", - "relay:read", - "access:read", - "access:write", - "relay:write", - ]); - assert.equal("token" in (listed[0] ?? {}), false); - }), - ); - - it.effect("rejects invalid ttl values before running auth commands", () => - Effect.gen(function* () { - const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe( - Effect.flip, - ); - - if (!CliError.isCliError(error)) { - assert.fail(`Expected CliError, got ${String(error)}`); - } - if (error._tag !== "ShowHelp") { - assert.fail(`Expected ShowHelp, got ${error._tag}`); - } - assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]); - const ttlError = error.errors[0] as CliError.CliError | undefined; - if (!ttlError || ttlError._tag !== "InvalidValue") { - assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`); - } - assert.equal(ttlError.option, "ttl"); - assert.equal(ttlError.value, "soon"); - assert.isTrue(ttlError.message.includes("Invalid duration")); - assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes")); - }), - ); - - it.effect("adds, renames, and removes projects offline through the orchestration engine", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-offline-test-"), - ); - const workspaceRoot = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-workspace-"), - ); - - yield* runCliWithRuntime([ - "project", - "add", - workspaceRoot, - "--title", - "Alpha", - "--base-dir", - baseDir, - ]); - const afterAdd = yield* readPersistedSnapshot(baseDir); - const addedProject = afterAdd.projects.find( - (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null, - ); - assert.isTrue(addedProject !== undefined); - assert.equal(addedProject?.title, "Alpha"); - - yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]); - const afterRename = yield* readPersistedSnapshot(baseDir); - const renamedProject = afterRename.projects.find( - (project) => project.id === addedProject?.id, - ); - assert.equal(renamedProject?.title, "Beta"); - assert.equal(renamedProject?.deletedAt, null); - - yield* runCliWithRuntime([ - "project", - "remove", - addedProject?.id ?? "", - "--base-dir", - baseDir, - ]); - const afterRemove = yield* readPersistedSnapshot(baseDir); - const removedProject = afterRemove.projects.find( - (project) => project.id === addedProject?.id, - ); - assert.isTrue((removedProject?.deletedAt ?? null) !== null); - }), - ); - - it.effect("force removes projects that still contain threads", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-test-"), - ); - const workspaceRoot = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-workspace-"), - ); - - yield* runCliWithRuntime(["project", "add", workspaceRoot, "--base-dir", baseDir]); - const afterAdd = yield* readPersistedSnapshot(baseDir); - const project = afterAdd.projects.find( - (candidate) => candidate.workspaceRoot === workspaceRoot && candidate.deletedAt === null, - ); - assert.isTrue(project !== undefined); - - const config = yield* makeCliTestServerConfig(baseDir); - yield* Effect.gen(function* () { - const engine = yield* OrchestrationEngine.OrchestrationEngineService; - yield* engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-cli-force-remove-thread"), - threadId: ThreadId.make("thread-cli-force-remove"), - projectId: project!.id, - title: "Thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "default", - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt: DateTime.formatIso(yield* DateTime.now), - }); - }).pipe(Effect.provide(makeProjectPersistenceLayer(config))); - - yield* runCliWithRuntime([ - "project", - "remove", - project!.id, - "--force", - "--base-dir", - baseDir, - ]); - const afterRemove = yield* readPersistedSnapshot(baseDir); - assert.isTrue( - (afterRemove.projects.find((candidate) => candidate.id === project!.id)?.deletedAt ?? - null) !== null, - ); - assert.isTrue( - (afterRemove.threads.find((thread) => thread.id === "thread-cli-force-remove")?.deletedAt ?? - null) !== null, - ); - }), - ); - - it.effect("routes project commands through a running server when runtime state is present", () => - Effect.gen(function* () { - const baseDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-test-"), - ); - const workspaceRoot = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-workspace-"), - ); - - yield* withLiveProjectCliServer(baseDir, () => - Effect.gen(function* () { - yield* runCliWithRuntime([ - "project", - "add", - workspaceRoot, - "--title", - "Live Project", - "--base-dir", - baseDir, - ]); - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; - const readModel = yield* projectionSnapshotQuery.getSnapshot(); - const addedProject = readModel.projects.find( - (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null, - ); - assert.isTrue(addedProject !== undefined); - assert.equal(addedProject?.title, "Live Project"); - }), - ); - }), - ); - - it.effect("rejects dev-url on project commands", () => - Effect.gen(function* () { - const workspaceRoot = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-unknown-option-workspace-"), - ); - const error = yield* runCliWithRuntime([ - "project", - "add", - workspaceRoot, - "--dev-url", - "http://127.0.0.1:5173", - ]).pipe(Effect.flip); - - if (!CliError.isCliError(error)) { - assert.fail(`Expected CliError, got ${String(error)}`); - } - if (error._tag !== "ShowHelp") { - assert.fail(`Expected ShowHelp, got ${error._tag}`); - } - assert.deepEqual(error.commandPath, ["t3", "project", "add"]); - const optionError = error.errors[0] as CliError.CliError | undefined; - if (!optionError || optionError._tag !== "UnrecognizedOption") { - assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`); - } - assert.equal(optionError.option, "--dev-url"); - }), - ); -}); diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index fe093c451e..2873070fdb 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -1,436 +1,158 @@ -import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; -import { it } from "@effect/vitest"; +import { assert, it, vi } from "@effect/vitest"; +import { + CheckpointRef, + CheckpointScopeId, + RunId, + ThreadId, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import { describe, expect } from "vite-plus/test"; -import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { checkpointRefForThreadTurn } from "./Utils.ts"; +import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts"; +import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts"; import * as CheckpointStore from "./CheckpointStore.ts"; -import { CheckpointThreadNotFoundError } from "./Errors.ts"; +import { + CheckpointRefUnavailableError, + CheckpointThreadNotFoundError, + CheckpointTurnRangeUnavailableError, +} from "./Errors.ts"; -function makeThreadCheckpointContext(input: { - readonly projectId: ProjectId; - readonly threadId: ThreadId; - readonly workspaceRoot: string; - readonly worktreePath: string | null; - readonly checkpointTurnCount: number; - readonly checkpointRef: CheckpointRef; -}): ProjectionSnapshotQuery.ProjectionThreadCheckpointContext { +const threadId = ThreadId.make("thread:checkpoint-diff-v2"); +const firstRunId = RunId.make("run:checkpoint-diff-v2:1"); +const secondRunId = RunId.make("run:checkpoint-diff-v2:2"); +const firstScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:1"); +const secondScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:2"); +const secondRef = CheckpointRef.make("refs/t3/test/second"); + +function makeProjection(): OrchestrationV2ThreadProjection { return { - threadId: input.threadId, - projectId: input.projectId, - workspaceRoot: input.workspaceRoot, - worktreePath: input.worktreePath, + runs: [ + { id: firstRunId, ordinal: 1 }, + { id: secondRunId, ordinal: 2 }, + ], + checkpointScopes: [ + { id: firstScopeId, runId: firstRunId, kind: "root_run", cwd: "/repo" }, + { id: secondScopeId, runId: secondRunId, kind: "root_run", cwd: "/repo" }, + ], checkpoints: [ { - turnId: TurnId.make("turn-1"), - checkpointTurnCount: input.checkpointTurnCount, - checkpointRef: input.checkpointRef, + scopeId: secondScopeId, + appRunOrdinal: 2, status: "ready", - files: [], - assistantMessageId: null, - completedAt: "2026-01-01T00:00:00.000Z", + ref: secondRef, }, ], - }; + } as unknown as OrchestrationV2ThreadProjection; } -describe("CheckpointDiffQuery.layer", () => { - it.effect("uses the narrow full-thread context lookup for all-turns diffs", () => - Effect.gen(function* () { - const projectId = ProjectId.make("project-full-thread"); - const threadId = ThreadId.make("thread-full-thread"); - const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4); - let getThreadCheckpointContextCalls = 0; - let getFullThreadDiffContextCalls = 0; - const diffCheckpointsCalls: Array<{ - readonly fromCheckpointRef: CheckpointRef; - readonly toCheckpointRef: CheckpointRef; - readonly cwd: string; - readonly ignoreWhitespace: boolean; - }> = []; - - const checkpointStore: CheckpointStore.CheckpointStore["Service"] = { - isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, - hasCheckpointRef: () => Effect.succeed(true), - restoreCheckpoint: () => Effect.succeed(true), - diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) => - Effect.sync(() => { - diffCheckpointsCalls.push({ - fromCheckpointRef, - toCheckpointRef, - cwd, - ignoreWhitespace, - }); - return "full thread diff patch"; - }), - deleteCheckpointRefs: () => Effect.void, - }; - - const layer = CheckpointDiffQuery.layer.pipe( - Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => - Effect.die("CheckpointDiffQuery should not request the command read model"), - getSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), - getShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"), - getArchivedShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request archived shell snapshots"), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => - Effect.sync(() => { - getThreadCheckpointContextCalls += 1; - return Option.none(); - }), - getFullThreadDiffContext: () => - Effect.sync(() => { - getFullThreadDiffContextCalls += 1; - return Option.some({ - threadId, - projectId, - workspaceRoot: "/tmp/workspace", - worktreePath: "/tmp/worktree", - latestCheckpointTurnCount: 4, - toCheckpointRef, - }); - }), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - ); - - const result = yield* Effect.gen(function* () { - const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; - return yield* query.getFullThreadDiff({ - threadId, - toTurnCount: 4, - ignoreWhitespace: true, - }); - }).pipe(Effect.provide(layer)); - - expect(getThreadCheckpointContextCalls).toBe(0); - expect(getFullThreadDiffContextCalls).toBe(1); - expect(diffCheckpointsCalls).toEqual([ - { - cwd: "/tmp/worktree", - fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0), - toCheckpointRef, - ignoreWhitespace: true, - }, - ]); - expect(result).toEqual({ - threadId, - fromTurnCount: 0, - toTurnCount: 4, - diff: "full thread diff patch", - }); - }), +function makeLayer(input: { + readonly projection: Effect.Effect; + readonly diffCheckpoints?: CheckpointStore.CheckpointStore["Service"]["diffCheckpoints"]; +}) { + return CheckpointDiffQuery.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadProjection: () => input.projection, + }), + Layer.mock(CheckpointStore.CheckpointStore)({ + diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")), + }), + ), + ), ); +} - it.effect("computes diffs using canonical turn-0 checkpoint refs", () => - Effect.gen(function* () { - const projectId = ProjectId.make("project-1"); - const threadId = ThreadId.make("thread-1"); - const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); - const diffCheckpointsCalls: Array<{ - readonly fromCheckpointRef: CheckpointRef; - readonly toCheckpointRef: CheckpointRef; - readonly cwd: string; - readonly ignoreWhitespace: boolean; - }> = []; - - const threadCheckpointContext = makeThreadCheckpointContext({ - projectId, - threadId, - workspaceRoot: "/tmp/workspace", - worktreePath: null, - checkpointTurnCount: 1, - checkpointRef: toCheckpointRef, - }); - - const checkpointStore: CheckpointStore.CheckpointStore["Service"] = { - isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, - hasCheckpointRef: () => Effect.succeed(true), - restoreCheckpoint: () => Effect.succeed(true), - diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) => - Effect.sync(() => { - diffCheckpointsCalls.push({ - fromCheckpointRef, - toCheckpointRef, - cwd, - ignoreWhitespace, - }); - return "diff patch"; - }), - deleteCheckpointRefs: () => Effect.void, - }; - - const layer = CheckpointDiffQuery.layer.pipe( - Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => - Effect.die("CheckpointDiffQuery should not request the command read model"), - getSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), - getShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"), - getArchivedShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request archived shell snapshots"), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), - getFullThreadDiffContext: () => Effect.die("unused"), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - ); - - const result = yield* Effect.gen(function* () { - const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; - return yield* query.getTurnDiff({ - threadId, - fromTurnCount: 0, - toTurnCount: 1, - ignoreWhitespace: true, - }); - }).pipe(Effect.provide(layer)); - - const expectedFromRef = checkpointRefForThreadTurn(threadId, 0); - expect(diffCheckpointsCalls).toEqual([ - { - cwd: "/tmp/workspace", - fromCheckpointRef: expectedFromRef, - toCheckpointRef, - ignoreWhitespace: true, - }, - ]); - expect(result).toEqual({ - threadId, - fromTurnCount: 0, - toTurnCount: 1, - diff: "diff patch", - }); - }), +it.effect("computes V2 run diffs from projected checkpoint scopes", () => { + const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) => + Effect.succeed("diff --git a/file b/file"), ); + const layer = makeLayer({ projection: Effect.succeed(makeProjection()), diffCheckpoints }); - it.effect("defaults to hide whitespace changes", () => - Effect.gen(function* () { - const projectId = ProjectId.make("project-default-whitespace"); - const threadId = ThreadId.make("thread-default-whitespace"); - const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); - const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = []; + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const result = yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 }); - const threadCheckpointContext = makeThreadCheckpointContext({ - projectId, - threadId, - workspaceRoot: "/tmp/workspace", - worktreePath: null, - checkpointTurnCount: 1, - checkpointRef: toCheckpointRef, - }); - - const checkpointStore: CheckpointStore.CheckpointStore["Service"] = { - isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, - hasCheckpointRef: () => Effect.succeed(true), - restoreCheckpoint: () => Effect.succeed(true), - diffCheckpoints: ({ ignoreWhitespace }) => - Effect.sync(() => { - diffCheckpointsCalls.push({ ignoreWhitespace }); - return "diff patch"; - }), - deleteCheckpointRefs: () => Effect.void, - }; - - const layer = CheckpointDiffQuery.layer.pipe( - Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => - Effect.die("CheckpointDiffQuery should not request the command read model"), - getSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), - getShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"), - getArchivedShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request archived shell snapshots"), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), - getFullThreadDiffContext: () => Effect.die("unused"), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - ); - - yield* Effect.gen(function* () { - const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; - return yield* query.getTurnDiff({ - threadId, - fromTurnCount: 0, - toTurnCount: 1, - }); - }).pipe(Effect.provide(layer)); - - expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]); - }), - ); - - it.effect("does not preflight checkpoint refs before diffing", () => - Effect.gen(function* () { - const projectId = ProjectId.make("project-no-preflight"); - const threadId = ThreadId.make("thread-no-preflight"); - const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); - let hasCheckpointRefCallCount = 0; - - const threadCheckpointContext = makeThreadCheckpointContext({ - projectId, - threadId, - workspaceRoot: "/tmp/workspace", - worktreePath: null, - checkpointTurnCount: 1, - checkpointRef: toCheckpointRef, - }); - - const checkpointStore: CheckpointStore.CheckpointStore["Service"] = { - isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, - hasCheckpointRef: () => - Effect.sync(() => { - hasCheckpointRefCallCount += 1; - return true; - }), - restoreCheckpoint: () => Effect.succeed(true), - diffCheckpoints: () => Effect.succeed("diff patch"), - deleteCheckpointRefs: () => Effect.void, - }; - - const layer = CheckpointDiffQuery.layer.pipe( - Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => - Effect.die("CheckpointDiffQuery should not request the command read model"), - getSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), - getShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"), - getArchivedShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request archived shell snapshots"), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)), - getFullThreadDiffContext: () => Effect.die("unused"), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - ); - - yield* Effect.gen(function* () { - const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; - return yield* query.getTurnDiff({ - threadId, - fromTurnCount: 0, - toTurnCount: 1, - ignoreWhitespace: true, - }); - }).pipe(Effect.provide(layer)); - - expect(hasCheckpointRefCallCount).toBe(0); - }), - ); - - it.effect("fails when the thread is missing from the snapshot", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-missing"); - - const checkpointStore: CheckpointStore.CheckpointStore["Service"] = { - isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, - hasCheckpointRef: () => Effect.succeed(true), - restoreCheckpoint: () => Effect.succeed(true), - diffCheckpoints: () => Effect.succeed(""), - deleteCheckpointRefs: () => Effect.void, - }; - - const layer = CheckpointDiffQuery.layer.pipe( - Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => - Effect.die("CheckpointDiffQuery should not request the command read model"), - getSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"), - getShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"), - getArchivedShellSnapshot: () => - Effect.die("CheckpointDiffQuery should not request archived shell snapshots"), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - getFullThreadDiffContext: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - ); - - const error = yield* Effect.gen(function* () { - const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; - return yield* query.getTurnDiff({ - threadId, - fromTurnCount: 0, - toTurnCount: 1, - }); - }).pipe(Effect.provide(layer), Effect.flip); - - expect(error).toBeInstanceOf(CheckpointThreadNotFoundError); - expect(error).toMatchObject({ - operation: "CheckpointDiffQuery.getTurnDiff", - threadId, - }); - expect(error.message).toBe( - "Checkpoint invariant violation in CheckpointDiffQuery.getTurnDiff: Thread 'thread-missing' not found.", - ); - }), - ); + assert.deepEqual(result, { + threadId, + fromTurnCount: 0, + toTurnCount: 2, + diff: "diff --git a/file b/file", + }); + assert.deepEqual(diffCheckpoints.mock.calls[0]?.[0], { + cwd: "/repo", + fromCheckpointRef: checkpointRefForScopeOrdinal({ + scopeId: firstScopeId, + ordinalWithinScope: 0, + }), + toCheckpointRef: secondRef, + fallbackFromToHead: false, + ignoreWhitespace: true, + }); + }).pipe(Effect.provide(layer)); +}); + +it.effect("preserves the typed missing-thread error contract", () => { + const layer = makeLayer({ + projection: Effect.fail(new OrchestratorProjectionError({ threadId })), + }); + + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const error = yield* query + .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 }) + .pipe(Effect.flip); + + assert.instanceOf(error, CheckpointThreadNotFoundError); + assert.deepEqual( + { operation: error.operation, threadId: error.threadId }, + { operation: "CheckpointDiffQuery.getTurnDiff", threadId }, + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect("preserves the typed unavailable-range error contract", () => { + const layer = makeLayer({ projection: Effect.succeed(makeProjection()) }); + + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const error = yield* query + .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 3 }) + .pipe(Effect.flip); + + assert.instanceOf(error, CheckpointTurnRangeUnavailableError); + assert.deepEqual( + { + requestedTurnCount: error.requestedTurnCount, + availableTurnCount: error.availableTurnCount, + }, + { requestedTurnCount: 3, availableTurnCount: 2 }, + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect("preserves the typed missing-baseline-ref error contract", () => { + const projection = makeProjection(); + const layer = makeLayer({ + projection: Effect.succeed({ + ...projection, + checkpointScopes: projection.checkpointScopes.filter((scope) => scope.id !== firstScopeId), + }), + }); + + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const error = yield* query + .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 }) + .pipe(Effect.flip); + + assert.instanceOf(error, CheckpointRefUnavailableError); + assert.deepEqual( + { checkpoint: error.checkpoint, turnCount: error.turnCount }, + { checkpoint: "from", turnCount: 0 }, + ); + }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index 077506ff3a..9950f6c8e0 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -7,7 +7,6 @@ * @module CheckpointDiffQuery */ import { - type CheckpointRef, OrchestrationGetTurnDiffResult, type OrchestrationGetFullThreadDiffInput, type OrchestrationGetFullThreadDiffResult, @@ -18,19 +17,18 @@ import { import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import { CheckpointDiffResultInvalidError, CheckpointRefUnavailableError, CheckpointThreadNotFoundError, CheckpointTurnRangeUnavailableError, CheckpointWorkspacePathMissingError, + type CheckpointServiceError, } from "./Errors.ts"; -import type { CheckpointServiceError } from "./Errors.ts"; -import { checkpointRefForThreadTurn } from "./Utils.ts"; import * as CheckpointStore from "./CheckpointStore.ts"; /** Service tag for checkpoint diff queries. */ @@ -76,7 +74,7 @@ function buildTurnDiffResult( } export const make = Effect.gen(function* () { - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const threads = yield* ThreadManagement.ThreadManagementService; const checkpointStore = yield* CheckpointStore.CheckpointStore; const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")( @@ -91,12 +89,7 @@ export const make = Effect.gen(function* () { }); if (input.fromTurnCount === input.toTurnCount) { - const emptyDiff: OrchestrationGetTurnDiffResultType = { - threadId: input.threadId, - fromTurnCount: input.fromTurnCount, - toTurnCount: input.toTurnCount, - diff: "", - }; + const emptyDiff = buildTurnDiffResult(input, ""); if (!isTurnDiffResult(emptyDiff)) { return yield* new CheckpointDiffResultInvalidError({ operation, @@ -106,18 +99,21 @@ export const make = Effect.gen(function* () { return emptyDiff; } - const threadContext = yield* projectionSnapshotQuery - .getThreadCheckpointContext(input.threadId) - .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext")); - if (Option.isNone(threadContext)) { - return yield* new CheckpointThreadNotFoundError({ - operation, - threadId: input.threadId, - }); - } - - const maxTurnCount = threadContext.value.checkpoints.reduce( - (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount), + const projection = yield* threads.getThreadProjection(input.threadId).pipe( + Effect.mapError( + () => + new CheckpointThreadNotFoundError({ + operation, + threadId: input.threadId, + }), + ), + Effect.withSpan("checkpoint.turnDiff.lookupProjection"), + ); + const readyCheckpoints = projection.checkpoints.filter( + (checkpoint) => checkpoint.status === "ready" && checkpoint.appRunOrdinal !== null, + ); + const maxTurnCount = readyCheckpoints.reduce( + (max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0), 0, ); if (input.toTurnCount > maxTurnCount) { @@ -129,33 +125,10 @@ export const make = Effect.gen(function* () { }); } - const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot; - if (!workspaceCwd) { - return yield* new CheckpointWorkspacePathMissingError({ - operation, - threadId: input.threadId, - }); - } - - const fromCheckpointRef = - input.fromTurnCount === 0 - ? checkpointRefForThreadTurn(input.threadId, 0) - : threadContext.value.checkpoints.find( - (checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount, - )?.checkpointRef; - if (!fromCheckpointRef) { - return yield* new CheckpointRefUnavailableError({ - operation, - threadId: input.threadId, - turnCount: input.fromTurnCount, - checkpoint: "from", - }); - } - - const toCheckpointRef = threadContext.value.checkpoints.find( - (checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount, - )?.checkpointRef; - if (!toCheckpointRef) { + const toCheckpoint = readyCheckpoints.find( + (checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount, + ); + if (toCheckpoint === undefined) { return yield* new CheckpointRefUnavailableError({ operation, threadId: input.threadId, @@ -164,11 +137,46 @@ export const make = Effect.gen(function* () { }); } + const toScope = projection.checkpointScopes.find( + (scope) => scope.id === toCheckpoint.scopeId, + ); + if (toScope === undefined) { + return yield* new CheckpointWorkspacePathMissingError({ + operation, + threadId: input.threadId, + }); + } + + const fromCheckpointRef = + input.fromTurnCount === 0 + ? (() => { + const firstRun = projection.runs.find((run) => run.ordinal === 1); + const firstScope = projection.checkpointScopes.find( + (scope) => scope.runId === firstRun?.id && scope.kind === "root_run", + ); + return firstScope === undefined + ? undefined + : checkpointRefForScopeOrdinal({ + scopeId: firstScope.id, + ordinalWithinScope: 0, + }); + })() + : readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount) + ?.ref; + if (fromCheckpointRef === undefined) { + return yield* new CheckpointRefUnavailableError({ + operation, + threadId: input.threadId, + turnCount: input.fromTurnCount, + checkpoint: "from", + }); + } + const diff = yield* checkpointStore .diffCheckpoints({ - cwd: workspaceCwd, + cwd: toScope.cwd, fromCheckpointRef, - toCheckpointRef, + toCheckpointRef: toCheckpoint.ref, fallbackFromToHead: false, ignoreWhitespace, }) @@ -217,61 +225,12 @@ export const make = Effect.gen(function* () { return emptyDiff satisfies OrchestrationGetFullThreadDiffResult; } - const threadContext = yield* projectionSnapshotQuery - .getFullThreadDiffContext(input.threadId, input.toTurnCount) - .pipe(Effect.withSpan("checkpoint.fullThread.lookupContext")); - - if (Option.isNone(threadContext)) { - return yield* new CheckpointThreadNotFoundError({ - operation, - threadId: input.threadId, - }); - } - - if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) { - return yield* new CheckpointTurnRangeUnavailableError({ - operation, - threadId: input.threadId, - requestedTurnCount: input.toTurnCount, - availableTurnCount: threadContext.value.latestCheckpointTurnCount, - }); - } - - const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot; - if (!workspaceCwd) { - return yield* new CheckpointWorkspacePathMissingError({ - operation, - threadId: input.threadId, - }); - } - - if (!threadContext.value.toCheckpointRef) { - return yield* new CheckpointRefUnavailableError({ - operation, - threadId: input.threadId, - turnCount: input.toTurnCount, - checkpoint: "to", - }); - } - - const diff = yield* checkpointStore - .diffCheckpoints({ - cwd: workspaceCwd, - fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0), - toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef, - fallbackFromToHead: false, - ignoreWhitespace, - }) - .pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints")); - - const turnDiff = buildTurnDiffResult( - { - threadId: input.threadId, - fromTurnCount: 0, - toTurnCount: input.toTurnCount, - }, - diff, - ); + const turnDiff = yield* getTurnDiff({ + threadId: input.threadId, + fromTurnCount: 0, + toTurnCount: input.toTurnCount, + ignoreWhitespace, + }); if (!isTurnDiffResult(turnDiff)) { return yield* new CheckpointDiffResultInvalidError({ operation, diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 5395592c88..26ed39e922 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -1,17 +1,89 @@ +// @effect-diagnostics nodeBuiltinImport:off - CLI integration uses temporary Node paths. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; - import { EnvironmentInternalError } from "@t3tools/contracts"; +import * as NetService from "@t3tools/shared/Net"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as References from "effect/References"; +import { Command } from "effect/unstable/cli"; +import { cli } from "../bin.ts"; +import * as ServerConfig from "../config.ts"; +import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts"; +import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts"; +import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import { ProjectLiveServerDeclaredResponseError, ProjectLiveServerRequestError, projectCommandErrorFromLiveServerRequest, } from "./project.ts"; +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); +const runCli = (args: ReadonlyArray) => + Command.runWith(cli, { version: "0.0.0" })(args).pipe(Effect.provide(CliRuntimeLayer)); + +const makeConfig = (baseDir: string) => + Effect.gen(function* () { + const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined); + return { + logLevel: "Info", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + mode: "web", + port: 0, + host: "127.0.0.1", + cwd: process.cwd(), + baseDir, + ...derivedPaths, + staticDir: undefined, + devUrl: undefined, + noBrowser: true, + startupPresentation: "browser", + desktopBootstrapToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + tailscaleServeEnabled: false, + tailscaleServePort: 443, + } satisfies ServerConfig.ServerConfig["Service"]; + }); + +const readProjects = (baseDir: string) => + Effect.gen(function* () { + const config = yield* makeConfig(baseDir); + const layer = ProjectServiceLayerLive.pipe( + Layer.provideMerge(RepositoryIdentityResolver.layer), + Layer.provideMerge(ProjectFaviconResolver.layer), + Layer.provideMerge(WorkspacePaths.layer), + Layer.provideMerge(SqlitePersistenceLayerLive), + Layer.provideMerge(NodeServices.layer), + Layer.provide(ServerConfig.layer(config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)), + ); + return yield* ProjectService.ProjectService.pipe( + Effect.flatMap((projects) => projects.snapshot), + Effect.provide(layer), + ); + }); + it("maps declared server failures into structural project command errors", () => { const cause = new EnvironmentInternalError({ code: "internal_error", - reason: "orchestration_snapshot_failed", + reason: "access_token_issuance_failed", traceId: "trace-123", }); @@ -35,3 +107,23 @@ it("preserves unexpected server failures without deriving the message from them" assert.strictEqual(error.message, "Failed to call the running server."); assert.strictEqual(error.cause, cause); }); + +it.effect("adds, renames, and removes projects through the V2 project CLI domain", () => + Effect.gen(function* () { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-cli-")); + const workspaceRoot = NodeFS.mkdtempSync( + NodePath.join(NodeOS.tmpdir(), "t3-v2-project-workspace-"), + ); + + yield* runCli(["project", "add", workspaceRoot, "--title", "Alpha", "--base-dir", baseDir]); + const added = (yield* readProjects(baseDir)).projects[0]; + assert.equal(added?.title, "Alpha"); + assert.equal(added?.workspaceRoot, workspaceRoot); + + yield* runCli(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]); + assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Beta"); + + yield* runCli(["project", "remove", added?.id ?? "", "--base-dir", baseDir]); + assert.deepEqual((yield* readProjects(baseDir)).projects, []); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 39b3b24311..871a7b0c74 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -1,15 +1,14 @@ import { - CommandId, AuthAdministrativeScopes, + CommandId, EnvironmentHttpApi, EnvironmentHttpCommonError, - type OrchestrationReadModel, + type ProjectMutation, + type ProjectSnapshot, ProjectId, - type ClientOrchestrationCommand, } from "@t3tools/contracts"; import * as Console from "effect/Console"; import * as Crypto from "effect/Crypto"; -import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -25,11 +24,11 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; -import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts"; -import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts"; import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts"; +import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts"; +import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as ProjectService from "../project/ProjectService.ts"; import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts"; import { clearPersistedServerRuntimeState, @@ -45,10 +44,7 @@ type ProjectMutationTarget = { }; type ProjectCommandExecutionMode = "live" | "offline"; -type ProjectCliDispatchCommand = Extract< - ClientOrchestrationCommand, - { type: "project.create" | "project.meta.update" | "project.delete" } ->; +type ProjectCliDispatchCommand = ProjectMutation; const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError); @@ -198,12 +194,11 @@ const projectCommandUuid = Crypto.Crypto.pipe( ), ); -const ProjectCliRuntimeLive = Layer.mergeAll( - WorkspacePaths.layer, - OrchestrationLayerLive.pipe( - Layer.provideMerge(RepositoryIdentityResolver.layer), - Layer.provideMerge(SqlitePersistenceLayerLive), - ), +const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe( + Layer.provideMerge(RepositoryIdentityResolver.layer), + Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))), + Layer.provideMerge(WorkspacePaths.layer), + Layer.provideMerge(SqlitePersistenceLayerLive), ); const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1); @@ -256,7 +251,7 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* ( }); const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: { - readonly snapshot: OrchestrationReadModel; + readonly snapshot: ProjectSnapshot; readonly identifier: string; }) { const trimmedIdentifier = input.identifier.trim(); @@ -311,7 +306,7 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* ( const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) => Effect.gen(function* () { const client = yield* makeLiveServerClient(origin); - return yield* client.orchestration.snapshot({ + return yield* client.projects.snapshot({ headers: { authorization: `Bearer ${bearerToken}` }, }); }).pipe( @@ -326,20 +321,18 @@ const dispatchLiveOrchestrationCommand = ( ) => Effect.gen(function* () { const client = yield* makeLiveServerClient(origin); - yield* client.orchestration.dispatch({ + yield* client.projects.mutate({ headers: { authorization: `Bearer ${bearerToken}` }, payload: command, - } as Parameters[0]); + } as Parameters[0]); }).pipe( withProjectCliLiveServerTimeout, Effect.mapError(projectCommandErrorFromLiveServerRequest), ); const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () { - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; - // Project commands only read the project list, so use the lightweight - // command read model instead of hydrating every thread body in the database. - return yield* projectionSnapshotQuery.getCommandReadModel(); + const projects = yield* ProjectService.ProjectService; + return yield* projects.snapshot; }); const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")( @@ -377,7 +370,7 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu const runProjectMutation = Effect.fn("runProjectMutation")(function* ( flags: CliAuthLocationFlags, run: (input: { - readonly snapshot: OrchestrationReadModel; + readonly snapshot: ProjectSnapshot; readonly dispatch: ( command: ProjectCliDispatchCommand, ) => Effect.Effect; @@ -422,10 +415,41 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* ( return yield* Effect.gen(function* () { const snapshot = yield* getOfflineSnapshot(); - const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService; + const projects = yield* ProjectService.ProjectService; const output = yield* run({ snapshot, - dispatch: (command) => orchestrationEngine.dispatch(command), + dispatch: (command) => + command.type === "project.create" + ? projects + .create({ + commandId: command.commandId, + projectId: command.projectId, + title: command.title, + workspaceRoot: command.workspaceRoot, + ...(command.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: command.defaultModelSelection }), + ...(command.scripts === undefined ? {} : { scripts: command.scripts }), + }) + .pipe(Effect.asVoid) + : command.type === "project.update" + ? projects + .update({ + commandId: command.commandId, + projectId: command.projectId, + ...(command.title === undefined ? {} : { title: command.title }), + ...(command.workspaceRoot === undefined + ? {} + : { workspaceRoot: command.workspaceRoot }), + ...(command.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: command.defaultModelSelection }), + ...(command.scripts === undefined ? {} : { scripts: command.scripts }), + }) + .pipe(Effect.asVoid) + : projects + .delete({ commandId: command.commandId, projectId: command.projectId }) + .pipe(Effect.asVoid), mode: "offline", }); yield* Console.log(output); @@ -456,7 +480,7 @@ const projectAddCommand = Command.make("add", { snapshot, dispatch, }: { - readonly snapshot: OrchestrationReadModel; + readonly snapshot: ProjectSnapshot; readonly dispatch: ( command: ProjectCliDispatchCommand, ) => Effect.Effect; @@ -482,7 +506,6 @@ const projectAddCommand = Command.make("add", { title, workspaceRoot, defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(), - createdAt: DateTime.formatIso(yield* DateTime.now), }); return `Added project ${projectId} (${title}) at ${workspaceRoot}.`; }), @@ -508,7 +531,7 @@ const projectRemoveCommand = Command.make("remove", { snapshot, dispatch, }: { - readonly snapshot: OrchestrationReadModel; + readonly snapshot: ProjectSnapshot; readonly dispatch: ( command: ProjectCliDispatchCommand, ) => Effect.Effect; @@ -544,7 +567,7 @@ const projectRenameCommand = Command.make("rename", { snapshot, dispatch, }: { - readonly snapshot: OrchestrationReadModel; + readonly snapshot: ProjectSnapshot; readonly dispatch: ( command: ProjectCliDispatchCommand, ) => Effect.Effect; @@ -559,7 +582,7 @@ const projectRenameCommand = Command.make("rename", { } yield* dispatch({ - type: "project.meta.update", + type: "project.update", commandId: CommandId.make(yield* projectCommandUuid), projectId: project.id, title: nextTitle, diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 2479a65a97..6e2c087d05 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -24,7 +24,7 @@ export class McpInvocationContext extends Context.Service< >()("t3/mcp/McpInvocationContext") {} export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* ( - capability: McpCapability, + capability: "preview", ) { const invocation = yield* McpInvocationContext; if (!invocation.capabilities.has(capability)) { diff --git a/apps/server/src/mcp/McpSessionRegistry.testkit.ts b/apps/server/src/mcp/McpSessionRegistry.testkit.ts index 71b0913274..a5dc099310 100644 --- a/apps/server/src/mcp/McpSessionRegistry.testkit.ts +++ b/apps/server/src/mcp/McpSessionRegistry.testkit.ts @@ -21,6 +21,6 @@ export const layer = Layer.succeed( resolve: () => Effect.succeed(undefined), revokeProviderSession: () => Effect.void, revokeThread: () => Effect.void, - revokeAll: Effect.succeed(undefined), + revokeAll: Effect.void, }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index cd2f55c053..370efeea42 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -154,7 +154,7 @@ export class CheckpointServiceV2 extends Context.Service< CheckpointServiceV2Shape >()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {} -function checkpointRefForScopeOrdinal(input: { +export function checkpointRefForScopeOrdinal(input: { readonly scopeId: CheckpointScopeId; readonly ordinalWithinScope: number; }): CheckpointRef { diff --git a/apps/server/src/orchestration-v2/CommandReceiptStore.ts b/apps/server/src/orchestration-v2/CommandReceiptStore.ts index 6f4b12541d..5cb413027b 100644 --- a/apps/server/src/orchestration-v2/CommandReceiptStore.ts +++ b/apps/server/src/orchestration-v2/CommandReceiptStore.ts @@ -5,7 +5,12 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { + OrchestrationCommandReceiptRepository, + type OrchestrationCommandReceipt, +} from "../persistence/Services/OrchestrationCommandReceipts.ts"; /** * ERRORS @@ -75,16 +80,6 @@ export class CommandReceiptStoreV2 extends Context.Service< /** * IMPLEMENTATIONS */ -type CommandReceiptRow = { - readonly command_id: string; - readonly thread_id: string; - readonly command_type: string; - readonly accepted_at: string; - readonly result_sequence: number; - readonly status: string; - readonly error: string | null; -}; - const decodeReceipt = Schema.decodeUnknownEffect( CommandReceiptV2.mapFields((fields) => ({ ...fields, @@ -92,121 +87,81 @@ const decodeReceipt = Schema.decodeUnknownEffect( })), ); -function rowToReceipt(row: CommandReceiptRow) { +function fromApplicationReceipt(receipt: OrchestrationCommandReceipt) { return decodeReceipt({ - commandId: row.command_id, - threadId: row.thread_id, - commandType: row.command_type, - acceptedAt: row.accepted_at, - resultSequence: row.result_sequence, - status: row.status, - error: row.error, + commandId: receipt.commandId, + threadId: receipt.aggregateId, + commandType: receipt.commandType, + acceptedAt: receipt.acceptedAt, + resultSequence: receipt.resultSequence, + status: receipt.status, + error: receipt.error, }); } -export const layer: Layer.Layer = Layer.effect( - CommandReceiptStoreV2, - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; +function toApplicationReceipt(receipt: CommandReceiptV2): OrchestrationCommandReceipt { + return { + commandId: receipt.commandId, + aggregateKind: "thread", + aggregateId: receipt.threadId, + commandType: receipt.commandType, + acceptedAt: DateTime.formatIso(receipt.acceptedAt), + resultSequence: receipt.resultSequence, + status: receipt.status, + error: receipt.error, + }; +} - return CommandReceiptStoreV2.of({ - insertIfAbsent: (receipt) => - sql<{ readonly command_id: string }>` - INSERT INTO orchestration_v2_command_receipts ( - command_id, - thread_id, - command_type, - accepted_at, - result_sequence, - status, - error - ) - VALUES ( - ${receipt.commandId}, - ${receipt.threadId}, - ${receipt.commandType}, - ${DateTime.formatIso(receipt.acceptedAt)}, - ${receipt.resultSequence}, - ${receipt.status}, - ${receipt.error} - ) - ON CONFLICT(command_id) DO NOTHING - RETURNING command_id - `.pipe( - Effect.map((rows) => rows.length === 1), - Effect.mapError( - (cause) => - new CommandReceiptStoreWriteError({ - commandId: receipt.commandId, - cause, - }), +const baseLayer: Layer.Layer = + Layer.effect( + CommandReceiptStoreV2, + Effect.gen(function* () { + const receipts = yield* OrchestrationCommandReceiptRepository; + + return CommandReceiptStoreV2.of({ + insertIfAbsent: (receipt) => + receipts.insertIfAbsent(toApplicationReceipt(receipt)).pipe( + Effect.mapError( + (cause) => + new CommandReceiptStoreWriteError({ + commandId: receipt.commandId, + cause, + }), + ), ), - ), - upsert: (receipt) => - sql` - INSERT INTO orchestration_v2_command_receipts ( - command_id, - thread_id, - command_type, - accepted_at, - result_sequence, - status, - error - ) - VALUES ( - ${receipt.commandId}, - ${receipt.threadId}, - ${receipt.commandType}, - ${DateTime.formatIso(receipt.acceptedAt)}, - ${receipt.resultSequence}, - ${receipt.status}, - ${receipt.error} - ) - ON CONFLICT(command_id) - DO UPDATE SET - thread_id = excluded.thread_id, - command_type = excluded.command_type, - accepted_at = excluded.accepted_at, - result_sequence = excluded.result_sequence, - status = excluded.status, - error = excluded.error - `.pipe( - Effect.asVoid, - Effect.mapError( - (cause) => - new CommandReceiptStoreWriteError({ - commandId: receipt.commandId, - cause, - }), + upsert: (receipt) => + receipts.upsert(toApplicationReceipt(receipt)).pipe( + Effect.mapError( + (cause) => + new CommandReceiptStoreWriteError({ + commandId: receipt.commandId, + cause, + }), + ), ), - ), - getByCommandId: (commandId) => - sql` - SELECT - command_id, - thread_id, - command_type, - accepted_at, - result_sequence, - status, - error - FROM orchestration_v2_command_receipts - WHERE command_id = ${commandId} - `.pipe( - Effect.flatMap((rows) => { - const row = rows[0]; - return row === undefined - ? Effect.succeed(Option.none()) - : rowToReceipt(row).pipe(Effect.map(Option.some)); - }), - Effect.mapError( - (cause) => - new CommandReceiptStoreReadError({ - commandId, - cause, + getByCommandId: (commandId) => + receipts.getByCommandId({ commandId }).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(Option.none()), + onSome: (receipt) => + receipt.aggregateKind !== "thread" + ? Effect.succeed(Option.none()) + : fromApplicationReceipt(receipt).pipe(Effect.map(Option.some)), }), + ), + Effect.mapError( + (cause) => + new CommandReceiptStoreReadError({ + commandId, + cause, + }), + ), ), - ), - } satisfies CommandReceiptStoreV2Shape); - }), -); + } satisfies CommandReceiptStoreV2Shape); + }), + ); + +export const layer = baseLayer.pipe(Layer.provide(OrchestrationCommandReceiptRepositoryLive)); + +export const layerFromApplicationReceipts = baseLayer; diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 0918dded75..86d092d7fa 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -346,21 +346,21 @@ export const layerWithOptions = ( export const layer = layerWithOptions(); -export const daemonLayer: Layer.Layer = - Layer.effectDiscard( - Effect.gen(function* () { - const worker = yield* OrchestrationEffectWorkerV2; - yield* Effect.forever( - worker.runOnce.pipe( - Effect.catchCause((cause) => - Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)), - ), - Effect.flatMap((worked) => - worked - ? Effect.yieldNow - : Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))), - ), - ), - ).pipe(Effect.forkScoped); - }), +export const runDaemon = Effect.gen(function* () { + const worker = yield* OrchestrationEffectWorkerV2; + return yield* Effect.forever( + worker.runOnce.pipe( + Effect.catchCause((cause) => + Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)), + ), + Effect.flatMap((worked) => + worked + ? Effect.yieldNow + : Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))), + ), + ), ); +}); + +export const daemonLayer: Layer.Layer = + Layer.effectDiscard(runDaemon.pipe(Effect.forkScoped)); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 76f69db12a..257b694db0 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -219,6 +219,7 @@ const baseLayer: Layer.Layer< if (input.effects.length > 0) { yield* effectOutbox.notifyAvailable; } + yield* eventStore.publishCommitted(storedEvents); yield* PubSub.publishAll(liveEvents, storedEvents); return storedEvents; }); @@ -287,6 +288,7 @@ const baseLayer: Layer.Layer< yield* effectOutbox.notifyAvailable; } if (result.committed) { + yield* eventStore.publishCommitted(result.storedEvents); yield* PubSub.publishAll(liveEvents, result.storedEvents); } return result; diff --git a/apps/server/src/orchestration-v2/EventStore.ts b/apps/server/src/orchestration-v2/EventStore.ts index 0f7ced986a..495fa4cbae 100644 --- a/apps/server/src/orchestration-v2/EventStore.ts +++ b/apps/server/src/orchestration-v2/EventStore.ts @@ -1,7 +1,6 @@ import { CommandId, OrchestrationV2DomainEvent, - OrchestrationV2DomainEventJson, OrchestrationV2StoredEvent, ThreadId, } from "@t3tools/contracts"; @@ -10,11 +9,11 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; +import type * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts"; +import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts"; -/** - * ERRORS - */ export class EventStoreAppendEventsError extends Schema.TaggedErrorClass()( "EventStoreAppendEventsError", { @@ -23,7 +22,7 @@ export class EventStoreAppendEventsError extends Schema.TaggedErrorClass Effect.Effect; + readonly publishCommitted: ( + events: ReadonlyArray, + ) => Effect.Effect; } export class EventStoreV2 extends Context.Service()( "t3/orchestration-v2/EventStore/EventStoreV2", ) {} -/** - * IMPLEMENTATIONS - */ -type EventRow = { - readonly sequence: number; - readonly event_id: string; - readonly command_id: string | null; - readonly thread_id: string; - readonly run_id: string | null; - readonly node_id: string | null; - readonly driver: string | null; - readonly provider_instance_id: string | null; - readonly raw_event_id: string | null; - readonly event_type: string; - readonly occurred_at: string; - readonly payload_json: string; -}; - -const encodeEventJson = Schema.encodeEffect(Schema.fromJsonString(OrchestrationV2DomainEventJson)); -const decodeEventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson); -const decodeStoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent); -const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); -const decodeUnknownJsonString = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); - -function parseJson(json: string): unknown { - return decodeUnknownJsonString(json); -} - -function compactUndefined(record: Record): Record { - return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)); -} - -export const layer: Layer.Layer = Layer.effect( +const baseLayer: Layer.Layer = Layer.effect( EventStoreV2, Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - - const rowToStoredEvent = ( - row: EventRow, - input?: { readonly afterSequence?: number; readonly threadId?: ThreadId }, - ) => - decodeEventJson( - compactUndefined({ - id: row.event_id, - threadId: row.thread_id, - runId: row.run_id ?? undefined, - nodeId: row.node_id ?? undefined, - driver: row.driver ?? undefined, - providerInstanceId: row.provider_instance_id ?? undefined, - rawEventId: row.raw_event_id ?? undefined, - type: row.event_type, - occurredAt: row.occurred_at, - payload: parseJson(row.payload_json), - }), - ).pipe( - Effect.flatMap((event) => - decodeStoredEvent({ - sequence: row.sequence, - commandId: row.command_id, - event, - }), - ), - Effect.mapError( - (cause) => - new EventStoreReadEventsError({ - ...(input?.afterSequence === undefined ? {} : { afterSequence: input.afterSequence }), - ...(input?.threadId === undefined ? {} : { threadId: input.threadId }), - cause, - }), - ), - ); - - const append: EventStoreV2Shape["append"] = (input) => - Effect.forEach( - input.events, - (event) => - Effect.gen(function* () { - const encoded = yield* encodeEventJson(event); - const normalized = parseJson(encoded) as { - readonly payload: unknown; - readonly occurredAt: string; - }; - - const rows = yield* sql` - INSERT INTO orchestration_v2_events ( - event_id, - command_id, - thread_id, - run_id, - node_id, - driver, - provider_instance_id, - raw_event_id, - event_type, - occurred_at, - payload_json - ) - VALUES ( - ${event.id}, - ${input.commandId ?? null}, - ${event.threadId}, - ${event.runId ?? null}, - ${event.nodeId ?? null}, - ${event.driver ?? null}, - ${event.providerInstanceId ?? null}, - ${event.rawEventId ?? null}, - ${event.type}, - ${normalized.occurredAt}, - ${encodeUnknownJsonString(normalized.payload)} - ) - RETURNING - sequence, - event_id, - command_id, - thread_id, - run_id, - node_id, - driver, - provider_instance_id, - raw_event_id, - event_type, - occurred_at, - payload_json - `; - const row = rows[0]; - if (!row) { - return yield* new EventStoreAppendEventsError({ - eventCount: input.events.length, - cause: "Insert did not return a stored event row.", - }); - } - return yield* rowToStoredEvent(row).pipe( - Effect.mapError( - (cause) => - new EventStoreAppendEventsError({ - eventCount: input.events.length, - cause, - }), - ), - ); - }), - { concurrency: 1 }, - ).pipe( - Effect.mapError( - (cause) => - new EventStoreAppendEventsError({ - eventCount: input.events.length, - cause, - }), - ), - ); + const applicationEvents = yield* OrchestrationEventStore; const read: EventStoreV2Shape["read"] = (input) => - Stream.fromEffect( - sql` - SELECT - sequence, - event_id, - command_id, - thread_id, - run_id, - node_id, - driver, - provider_instance_id, - raw_event_id, - event_type, - occurred_at, - payload_json - FROM orchestration_v2_events - WHERE sequence > ${input?.afterSequence ?? 0} - AND sequence <= ${input?.throughSequence ?? Number.MAX_SAFE_INTEGER} - AND (${input?.threadId ?? null} IS NULL OR thread_id = ${input?.threadId ?? null}) - ORDER BY sequence ASC - LIMIT ${input?.limit ?? 1000} - `.pipe( - Effect.mapError( + applicationEvents + .readAgentEvents({ + ...(input?.afterSequence === undefined ? {} : { afterSequence: input.afterSequence }), + ...(input?.throughSequence === undefined + ? {} + : { throughSequence: input.throughSequence }), + ...(input?.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input?.limit === undefined ? {} : { limit: input.limit }), + }) + .pipe( + Stream.mapError( (cause) => new EventStoreReadEventsError({ ...(input?.afterSequence === undefined @@ -259,65 +99,41 @@ export const layer: Layer.Layer = Laye cause, }), ), - ), - ).pipe( - Stream.flatMap(Stream.fromIterable), - Stream.mapEffect((row) => rowToStoredEvent(row, input)), - ); + ); - const readByCommandId: EventStoreV2Shape["readByCommandId"] = (input) => - Stream.fromEffect( - sql` - SELECT - sequence, - event_id, - command_id, - thread_id, - run_id, - node_id, - driver, - provider_instance_id, - raw_event_id, - event_type, - occurred_at, - payload_json - FROM orchestration_v2_events - WHERE command_id = ${input.commandId} - ORDER BY sequence ASC - `.pipe( + return EventStoreV2.of({ + append: (input) => + applicationEvents.appendAgentEvents(input).pipe( Effect.mapError( (cause) => - new EventStoreReadEventsError({ + new EventStoreAppendEventsError({ + eventCount: input.events.length, cause, }), ), ), - ).pipe( - Stream.flatMap(Stream.fromIterable), - Stream.mapEffect((row) => rowToStoredEvent(row)), - ); - - const latestSequence: EventStoreV2Shape["latestSequence"] = (input) => - sql<{ readonly sequence: number | null }>` - SELECT MAX(sequence) AS sequence - FROM orchestration_v2_events - WHERE ${input?.threadId ?? null} IS NULL OR thread_id = ${input?.threadId ?? null} - `.pipe( - Effect.map((rows) => rows[0]?.sequence ?? 0), - Effect.mapError( - (cause) => - new EventStoreReadEventsError({ - ...(input?.threadId === undefined ? {} : { threadId: input.threadId }), - cause, - }), - ), - ); - - return { - append, read, - readByCommandId, - latestSequence, - } satisfies EventStoreV2Shape; + readByCommandId: ({ commandId }) => + applicationEvents + .readAgentEvents({ commandId }) + .pipe(Stream.mapError((cause) => new EventStoreReadEventsError({ cause }))), + latestSequence: (input) => + applicationEvents.latestAgentSequence(input?.threadId).pipe( + Effect.mapError( + (cause) => + new EventStoreReadEventsError({ + ...(input?.threadId === undefined ? {} : { threadId: input.threadId }), + cause, + }), + ), + ), + publishCommitted: applicationEvents.publishCommitted, + }); }), ); + +export const layer: Layer.Layer = baseLayer.pipe( + Layer.provide(OrchestrationEventStoreLive), +); + +export const layerFromOrchestrationEventStore = baseLayer; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 877d947542..745122b3e6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15,7 +15,7 @@ import { type OrchestrationV2ProviderTurn, type OrchestrationV2Run, type OrchestrationV2RunAttempt, - type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadShellSnapshot, type OrchestrationV2StoredEvent, type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, @@ -145,7 +145,10 @@ export interface OrchestratorV2Shape { }, OrchestratorV2Error >; - readonly getShellSnapshot: () => Effect.Effect; + readonly getShellSnapshot: () => Effect.Effect< + OrchestrationV2ThreadShellSnapshot, + OrchestratorV2Error + >; readonly getThreadEventSequence: ( threadId: ThreadId, ) => Effect.Effect; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 3f035e786a..aeb97477c7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -2,7 +2,7 @@ import type { OrchestrationV2ConversationMessage, OrchestrationV2DomainEvent, OrchestrationV2ProjectedTurnItem, - OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadShellSnapshot, OrchestrationV2ShellThreadStatus, OrchestrationV2ThreadShell, OrchestrationV2ThreadProjection, @@ -100,7 +100,7 @@ export interface ProjectionStoreV2Shape { event: OrchestrationV2DomainEvent, ) => Effect.Effect; readonly getShellSnapshot: () => Effect.Effect< - OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadShellSnapshot, ProjectionStoreV2Error >; readonly getThreadProjection: ( @@ -1882,8 +1882,10 @@ export const layer: Layer.Layer = const projection = yield* getThreadProjection(threadId); const rows = yield* sql<{ readonly snapshot_sequence: number | null }>` SELECT MAX(sequence) AS snapshot_sequence - FROM orchestration_v2_events - WHERE thread_id = ${threadId} + FROM orchestration_events + WHERE application_event_version = 2 + AND aggregate_kind = 'thread' + AND stream_id = ${threadId} `; return { schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, @@ -1971,7 +1973,9 @@ export const layer: Layer.Layer = `, sql<{ readonly snapshot_sequence: number | null }>` SELECT MAX(sequence) AS snapshot_sequence - FROM orchestration_v2_events + FROM orchestration_events + WHERE application_event_version = 2 + AND aggregate_kind = 'thread' `, ]); diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts index c78a4679ba..6a600c9b8a 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts @@ -37,7 +37,6 @@ const makeInstance = ( displayName: String(instanceId), enabled: true, snapshot: {} as ProviderInstance["snapshot"], - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter, textGeneration: {} as ProviderInstance["textGeneration"], }); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index e878fe2d87..c9014b421b 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -194,9 +194,10 @@ it.effect("drains durable effects before reporting recovery complete", () => ), ), ); - const summary = yield* Effect.gen(function* () { - return yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover; - }).pipe(Effect.provide(layer)); + const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe( + Effect.flatMap((service) => service.recover), + Effect.provide(layer), + ); assert.deepEqual(summary, { resumedSessions: 0, terminalizedRuns: 0, executedEffects: 2 }); }), ); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 528415a7ed..fc63bf738f 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -1,5 +1,6 @@ import type { - OrchestrationV2ShellSnapshot, + OrchestrationV2ArchivedShellStreamItem, + OrchestrationV2ThreadShellSnapshot, OrchestrationV2ShellStreamItem, OrchestrationV2StoredEvent, } from "@t3tools/contracts"; @@ -7,7 +8,7 @@ import type { /** Converts a committed event and its resulting shell snapshot into one delta. */ export function shellStreamItemFromSnapshot(input: { readonly stored: OrchestrationV2StoredEvent; - readonly snapshot: OrchestrationV2ShellSnapshot; + readonly snapshot: OrchestrationV2ThreadShellSnapshot; }): Exclude { const active = input.snapshot.threads.find((thread) => thread.id === input.stored.event.threadId); if (active !== undefined) { @@ -41,3 +42,31 @@ export function shellStreamItemFromSnapshot(input: { threadId: input.stored.event.threadId, }; } + +/** Converts a committed event into an archive-only delta when it changes archive membership. */ +export function archivedShellStreamItemFromSnapshot(input: { + readonly stored: OrchestrationV2StoredEvent; + readonly snapshot: OrchestrationV2ThreadShellSnapshot; +}): Exclude | null { + const archived = input.snapshot.archivedThreads.find( + (thread) => thread.id === input.stored.event.threadId, + ); + if (archived !== undefined) { + return { + kind: "thread.updated", + sequence: input.stored.sequence, + thread: archived, + }; + } + if ( + input.stored.event.type === "thread.unarchived" || + (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null) + ) { + return { + kind: "thread.removed", + sequence: input.stored.sequence, + threadId: input.stored.event.threadId, + }; + } + return null; +} diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index ff5536eea6..e41b601650 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -12,7 +12,6 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Stream from "effect/Stream"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; @@ -126,7 +125,6 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup getById: (id) => Effect.succeed(id === projectId ? Option.some(project) : Option.none()), getByWorkspaceRoot: () => Effect.succeed(Option.some(project)), snapshot: Effect.die("unused"), - changes: Stream.empty, }), Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, removeWorktree }), Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, { diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 5805778a1a..821e324c5e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -8,7 +8,7 @@ import { type OrchestrationV2ConversationMessage, type OrchestrationV2CreationSource, type OrchestrationV2Run, - type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadShellSnapshot, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, type OrchestrationV2TurnItem, @@ -143,7 +143,10 @@ export interface ThreadManagementServiceShape { readonly projectId: ProjectId; readonly threadId: ThreadId; }) => Effect.Effect; - readonly getShellSnapshot: () => Effect.Effect; + readonly getShellSnapshot: () => Effect.Effect< + OrchestrationV2ThreadShellSnapshot, + OrchestratorV2Error + >; readonly listProjectThreads: (input: { readonly projectId: ProjectId; readonly includeSubagents: boolean; diff --git a/apps/server/src/orchestration-v2/V1ImportBoundary.test.ts b/apps/server/src/orchestration-v2/V1ImportBoundary.test.ts new file mode 100644 index 0000000000..9e7e45f00b --- /dev/null +++ b/apps/server/src/orchestration-v2/V1ImportBoundary.test.ts @@ -0,0 +1,38 @@ +// @effect-diagnostics nodeBuiltinImport:off - Static architecture test scans source files. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { assert, it } from "@effect/vitest"; + +const sourceRoot = NodePath.resolve(import.meta.dirname, ".."); +const forbiddenImport = + /from\s+["'][^"']*(?:ProviderService|ProviderSessionDirectory|ProviderSessionReaper|ProviderCommandReactor|ProviderRuntimeIngestion)[^"']*["']/; +const retiredAgentRuntimePaths = [ + "orchestration/Layers/ProviderCommandReactor.ts", + "orchestration/Layers/ProviderRuntimeIngestion.ts", + "orchestration/Services/ProviderCommandReactor.ts", + "orchestration/Services/ProviderRuntimeIngestion.ts", +] as const; + +function productionTypeScriptFiles(directory: string): ReadonlyArray { + return NodeFS.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = NodePath.join(directory, entry.name); + if (entry.isDirectory()) { + return entry.name === "legacy" ? [] : productionTypeScriptFiles(path); + } + return entry.isFile() && entry.name.endsWith(".ts") && !entry.name.includes(".test.") + ? [path] + : []; + }); +} + +it("retains the application data plane without restoring the V1 agent runtime", () => { + for (const relativePath of retiredAgentRuntimePaths) { + assert.isFalse(NodeFS.existsSync(NodePath.join(sourceRoot, relativePath))); + } + const violations = productionTypeScriptFiles(sourceRoot).flatMap((path) => { + const source = NodeFS.readFileSync(path, "utf8"); + return forbiddenImport.test(source) ? [NodePath.relative(sourceRoot, path)] : []; + }); + assert.deepEqual(violations, []); +}); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index c71edc1ccc..56144bbd95 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + type ApplicationStoredEvent, CommandId, type ModelSelection, ProjectId, @@ -10,12 +11,18 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import { ServerConfig } from "../config.ts"; -import { GitCoreLive } from "../git/Layers/GitCore.ts"; +import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts"; +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts"; import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts"; @@ -58,7 +65,6 @@ const providerInstance = { displayName: "Codex test", enabled: true, snapshot: {} as ProviderInstance["snapshot"], - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter, textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; @@ -82,6 +88,24 @@ const TestLayer = OrchestrationV2LayerLive.pipe( Layer.provide(NodeServices.layer), ); +const SharedApplicationDataPlaneTestLayer = Layer.merge( + OrchestrationLayerLive, + OrchestrationV2LayerLive, +).pipe( + Layer.provide( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: () => Effect.succeed(null), + }), + ), + Layer.provide(mcpSessionRegistryTestLayer), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provide(CheckpointStoreTestLayer), + Layer.provide(ServerConfigLayer), + Layer.provide(ServerSettingsService.layerTest()), + Layer.provide(TestProviderInstanceRegistry), + Layer.provide(NodeServices.layer), +); + it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => { it.effect("creates and reads a thread through the production V2 composition", () => Effect.gen(function* () { @@ -248,3 +272,83 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => { }), ); }); + +it.layer(SharedApplicationDataPlaneTestLayer)("shared application data plane", (it) => { + it.effect("orders retained project transactions and V2 thread transactions in one source", () => + Effect.gen(function* () { + const applicationEngine = yield* OrchestrationEngineService; + const applicationEvents = yield* OrchestrationEventStore; + const orchestrator = yield* OrchestratorV2; + const projectionSnapshot = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("runtime-layer-shared-project"); + const threadId = ThreadId.make("runtime-layer-shared-thread"); + const projectCommand = { + type: "project.create" as const, + commandId: CommandId.make("runtime-layer-shared-project-create"), + projectId, + title: "Shared application source", + workspaceRoot: "/tmp/runtime-layer-shared-project", + defaultModelSelection: modelSelection, + scripts: [], + createdAt: "2026-06-20T00:00:00.000Z", + }; + + const projectResult = yield* applicationEngine.dispatch(projectCommand); + const projectRetry = yield* applicationEngine.dispatch(projectCommand); + assert.equal(projectRetry.sequence, projectResult.sequence); + + const delivered = yield* Queue.unbounded(); + yield* applicationEvents.streamApplicationEvents().pipe( + Stream.take(2), + Stream.runForEach((event) => Queue.offer(delivered, event)), + Effect.forkScoped, + ); + + const projectEvent = yield* Queue.take(delivered); + assert.equal(projectEvent.sequence, projectResult.sequence); + + const threadResult = yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-shared-thread-create"), + threadId, + projectId, + title: "Shared thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const threadEvent = yield* Queue.take(delivered); + + assert.equal(threadEvent.sequence, threadResult.sequence); + assert.isAbove(threadEvent.sequence, projectEvent.sequence); + assert.isTrue("aggregateKind" in projectEvent); + assert.isTrue("event" in threadEvent); + assert.equal((yield* projectionSnapshot.getProjectShellById(projectId))._tag, "Some"); + + const retainedReceipts = yield* sql<{ + readonly aggregate_kind: string; + readonly aggregate_id: string; + }>` + SELECT aggregate_kind, aggregate_id + FROM orchestration_command_receipts + ORDER BY result_sequence ASC + `; + assert.deepEqual(retainedReceipts, [ + { aggregate_kind: "project", aggregate_id: projectId }, + { aggregate_kind: "thread", aggregate_id: threadId }, + ]); + + const retiredWrites = yield* sql<{ readonly count: number }>` + SELECT + (SELECT COUNT(*) FROM orchestration_v2_events) + + (SELECT COUNT(*) FROM orchestration_v2_command_receipts) AS count + `; + assert.equal(retiredWrites[0]?.count, 0); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index a7956b52de..a0966c87c2 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,19 +1,24 @@ import * as Layer from "effect/Layer"; -import * as Effect from "effect/Effect"; +import { + OrchestrationEventInfrastructureLayerLive, + OrchestrationLayerLive, +} from "../orchestration/runtimeLayer.ts"; +import { ProjectionProjectRepositoryLive } from "../persistence/Layers/ProjectionProjects.ts"; +import { layer as projectServiceLayer } from "../project/ProjectService.ts"; +import { layer as projectSetupScriptRunnerLayer } from "../project/ProjectSetupScriptRunner.ts"; import { layer as checkpointCaptureServiceLayer } from "./CheckpointCaptureService.ts"; import { layer as checkpointServiceLayer } from "./CheckpointService.ts"; import { layer as checkpointRollbackServiceLayer } from "./CheckpointRollbackService.ts"; import { layer as commandPolicyLayer } from "./CommandPolicy.ts"; -import { layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts"; +import { layerFromApplicationReceipts as commandReceiptStoreLayer } from "./CommandReceiptStore.ts"; import { layer as contextHandoffServiceLayer } from "./ContextHandoffService.ts"; import { layer as effectOutboxLayer } from "./EffectOutbox.ts"; import { - daemonLayer as effectWorkerDaemonLayer, executorLayer as effectExecutorLayer, layer as effectWorkerLayer, } from "./EffectWorker.ts"; import { layerFromStores as eventSinkLayer } from "./EventSink.ts"; -import { layer as eventStoreLayer } from "./EventStore.ts"; +import { layerFromOrchestrationEventStore as eventStoreLayer } from "./EventStore.ts"; import { layer as idAllocatorLayer } from "./IdAllocator.ts"; import { layer as orchestratorLayer } from "./Orchestrator.ts"; import { layer as projectionStoreLayer } from "./ProjectionStore.ts"; @@ -21,10 +26,7 @@ import { layer as projectionMaintenanceLayer } from "./ProjectionMaintenance.ts" import { layerFromProviderInstanceRegistry as providerAdapterRegistryLayerFromProviderInstances } from "./ProviderAdapterRegistry.ts"; import { layer as providerEventIngestorLayer } from "./ProviderEventIngestor.ts"; import { layer as providerSessionManagerLayer } from "./ProviderSessionManager.ts"; -import { - layer as providerRuntimeRecoveryLayer, - ProviderRuntimeRecoveryService, -} from "./ProviderRuntimeRecoveryService.ts"; +import { layer as providerRuntimeRecoveryLayer } from "./ProviderRuntimeRecoveryService.ts"; import { layer as providerSwitchServiceLayer } from "./ProviderSwitchService.ts"; import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlService.ts"; import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts"; @@ -33,13 +35,23 @@ import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.t import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts"; import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts"; import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts"; +import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts"; +import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.ts"; import { layer as threadForkServiceLayer } from "./ThreadForkService.ts"; import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts"; +const eventStoreProvided = eventStoreLayer.pipe( + Layer.provide(OrchestrationEventInfrastructureLayerLive), +); +const commandReceiptStoreProvided = commandReceiptStoreLayer.pipe( + Layer.provide(OrchestrationEventInfrastructureLayerLive), +); + const storesLayer = Layer.mergeAll( - eventStoreLayer, + OrchestrationEventInfrastructureLayerLive, + eventStoreProvided, projectionStoreLayer, - commandReceiptStoreLayer, + commandReceiptStoreProvided, effectOutboxLayer, turnItemPositionStoreLayer, ); @@ -47,8 +59,6 @@ const storesLayer = Layer.mergeAll( const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesLayer)); const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesLayer)); -const commandReceiptStoreProvided = commandReceiptStoreLayer; - const providerEventIngestorProvided = providerEventIngestorLayer.pipe( Layer.provide(Layer.mergeAll(eventSinkProvided, idAllocatorLayer)), ); @@ -153,10 +163,6 @@ const effectExecutorProvided = effectExecutorLayer.pipe( const effectWorkerProvided = effectWorkerLayer.pipe( Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)), ); -const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe( - Layer.provide(effectWorkerProvided), -); - const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe( Layer.provide( Layer.mergeAll( @@ -169,9 +175,6 @@ const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe( ), ), ); -const providerRuntimeRecoveryStartupProvided = Layer.effectDiscard( - Effect.flatMap(ProviderRuntimeRecoveryService, (recovery) => recovery.recover), -).pipe(Layer.provide(providerRuntimeRecoveryProvided)); const orchestratorProvided = orchestratorLayer.pipe( Layer.provide( @@ -194,11 +197,42 @@ const orchestratorProvided = orchestratorLayer.pipe( ), ), ); + +const threadManagementProvided = threadManagementServiceLayer.pipe( + Layer.provide(orchestratorProvided), +); +export const ProjectServiceLayerLive = projectServiceLayer.pipe( + Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)), +); +export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe( + Layer.provide(ProjectServiceLayerLive), +); +const threadLaunchProvided = threadLaunchServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + ProjectServiceLayerLive, + ProjectSetupScriptRunnerLayerLive, + threadManagementProvided, + idAllocatorLayer, + ), + ), +); +const threadLifecycleProvided = threadLifecycleServiceLayer.pipe( + Layer.provide(threadManagementProvided), +); + export const OrchestrationV2LayerLive = Layer.mergeAll( orchestratorProvided, - threadManagementServiceLayer.pipe(Layer.provide(orchestratorProvided)), - effectWorkerDaemonProvided, - providerRuntimeRecoveryStartupProvided, + threadManagementProvided, + effectWorkerProvided, providerRuntimeRecoveryProvided, projectionMaintenanceProvided, ); + +export const OrchestrationV2ProductionLayerLive = Layer.mergeAll( + OrchestrationLayerLive, + OrchestrationV2LayerLive, + ProjectServiceLayerLive, + threadLaunchProvided, + threadLifecycleProvided, +); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index f6d8fa6f16..0b596c0a98 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -3,7 +3,7 @@ import type { OrchestrationV2DomainEvent, OrchestrationV2RuntimeRequest, OrchestrationV2Run, - OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadShellSnapshot, OrchestrationV2StoredEvent, OrchestrationV2ThreadProjection, OrchestrationV2TurnItem, @@ -74,7 +74,7 @@ export interface OrchestratorV2ScenarioResult { readonly storedEvents: ReadonlyArray; readonly domainEvents: ReadonlyArray; readonly projections: ReadonlyMap; - readonly shellSnapshot: OrchestrationV2ShellSnapshot; + readonly shellSnapshot: OrchestrationV2ThreadShellSnapshot; } export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass()( diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts deleted file mode 100644 index 95adee0cf7..0000000000 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ /dev/null @@ -1,946 +0,0 @@ -import { - CommandId, - type CheckpointRef, - EventId, - MessageId, - type ProjectId, - ThreadId, - TurnId, - type OrchestrationEvent, - type ProviderRuntimeEvent, - type VcsStatusLocalResult, -} from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import type * as PlatformError from "effect/PlatformError"; -import * as Stream from "effect/Stream"; -import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; -import { isTemporaryWorktreeBranch } from "@t3tools/shared/git"; - -import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts"; -import { - checkpointRefForThreadTurn, - resolveThreadWorkspaceCwd, -} from "../../checkpointing/Utils.ts"; -import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts"; -import { ProviderService } from "../../provider/Services/ProviderService.ts"; -import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts"; -import { forkParked } from "../../serverActivation.ts"; -import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; -import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; -import type { CheckpointStoreError } from "../../checkpointing/Errors.ts"; -import type { OrchestrationDispatchError } from "../Errors.ts"; -import { isGitRepository } from "../../git/Utils.ts"; -import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts"; -import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts"; - -const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - -type ReactorInput = - | { - readonly source: "runtime"; - readonly event: ProviderRuntimeEvent; - } - | { - readonly source: "domain"; - readonly event: OrchestrationEvent; - }; - -function toTurnId(value: string | undefined): TurnId | null { - return value === undefined ? null : TurnId.make(String(value)); -} - -function sameId(left: string | null | undefined, right: string | null | undefined): boolean { - if (left === null || left === undefined || right === null || right === undefined) { - return false; - } - return left === right; -} - -function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" { - switch (status) { - case "failed": - return "error"; - case "cancelled": - case "interrupted": - return "missing"; - case "completed": - default: - return "ready"; - } -} - -const make = Effect.gen(function* () { - const crypto = yield* Crypto.Crypto; - const randomUUID = crypto.randomUUIDv4; - const serverEventId = randomUUID.pipe(Effect.map(EventId.make)); - const serverCommandId = (tag: string) => - randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`))); - const orchestrationEngine = yield* OrchestrationEngineService; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const providerService = yield* ProviderService; - const checkpointStore = yield* CheckpointStore.CheckpointStore; - const receiptBus = yield* RuntimeReceiptBus; - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const vcsStatusBroadcaster = yield* VcsStatusBroadcaster; - - const appendRevertFailureActivity = (input: { - readonly threadId: ThreadId; - readonly turnCount: number; - readonly detail: string; - readonly createdAt: string; - }) => - Effect.all({ - commandId: serverCommandId("checkpoint-revert-failure"), - activityId: serverEventId, - }).pipe( - Effect.flatMap(({ commandId, activityId }) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId, - threadId: input.threadId, - activity: { - id: activityId, - tone: "error", - kind: "checkpoint.revert.failed", - summary: "Checkpoint revert failed", - payload: { - turnCount: input.turnCount, - detail: input.detail, - }, - turnId: null, - createdAt: input.createdAt, - }, - createdAt: input.createdAt, - }), - ), - ); - - const appendCaptureFailureActivity = (input: { - readonly threadId: ThreadId; - readonly turnId: TurnId | null; - readonly detail: string; - readonly createdAt: string; - }) => - Effect.all({ - commandId: serverCommandId("checkpoint-capture-failure"), - activityId: serverEventId, - }).pipe( - Effect.flatMap(({ commandId, activityId }) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId, - threadId: input.threadId, - activity: { - id: activityId, - tone: "error", - kind: "checkpoint.capture.failed", - summary: "Checkpoint capture failed", - payload: { - detail: input.detail, - }, - turnId: input.turnId, - createdAt: input.createdAt, - }, - createdAt: input.createdAt, - }), - ), - ); - - const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* ( - threadId: ThreadId, - ): Effect.fn.Return> { - const sessions = yield* providerService.listSessions(); - const session = sessions.find((entry) => entry.threadId === threadId); - return session?.cwd - ? Option.some({ threadId: session.threadId, cwd: session.cwd }) - : Option.none(); - }); - - const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) { - return yield* projectionSnapshotQuery - .getThreadDetailById(threadId) - .pipe(Effect.map(Option.getOrUndefined)); - }); - - const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* ( - projectId: ProjectId, - ) { - const project = yield* projectionSnapshotQuery - .getProjectShellById(projectId) - .pipe(Effect.map(Option.getOrUndefined)); - return project ? [project] : []; - }); - - const isGitWorkspace = (cwd: string) => isGitRepository(cwd); - - // Resolves the workspace CWD for checkpoint operations, preferring the - // active provider session CWD and falling back to the thread/project config. - // Returns undefined when no CWD can be determined or the workspace is not - // a git repository. - const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: { - readonly threadId: ThreadId; - readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null }; - readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>; - readonly preferSessionRuntime: boolean; - }): Effect.fn.Return { - const fromSession = yield* resolveSessionRuntimeForThread(input.threadId); - const fromThread = resolveThreadWorkspaceCwd({ - thread: input.thread, - projects: input.projects, - }); - - const cwd = input.preferSessionRuntime - ? (Option.match(fromSession, { - onNone: () => undefined, - onSome: (runtime) => runtime.cwd, - }) ?? fromThread) - : (fromThread ?? - Option.match(fromSession, { - onNone: () => undefined, - onSome: (runtime) => runtime.cwd, - })); - - if (!cwd) { - return undefined; - } - if (!isGitWorkspace(cwd)) { - return undefined; - } - return cwd; - }); - - // Shared tail for both capture paths: creates the git checkpoint ref, diffs - // it against the previous turn, then dispatches the domain events to update - // the orchestration read model. - const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: { - readonly threadId: ThreadId; - readonly turnId: TurnId; - readonly thread: { - readonly messages: ReadonlyArray<{ - readonly id: MessageId; - readonly role: string; - readonly turnId: TurnId | null; - }>; - }; - readonly cwd: string; - readonly turnCount: number; - readonly status: "ready" | "missing" | "error"; - readonly assistantMessageId: MessageId | undefined; - readonly createdAt: string; - }) { - const fromTurnCount = Math.max(0, input.turnCount - 1); - const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount); - const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount); - - const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({ - cwd: input.cwd, - checkpointRef: fromCheckpointRef, - }); - if (!fromCheckpointExists) { - yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", { - threadId: input.threadId, - turnId: input.turnId, - fromTurnCount, - }); - } - - yield* checkpointStore.captureCheckpoint({ - cwd: input.cwd, - checkpointRef: targetCheckpointRef, - }); - - // Refresh the workspace entry index so the @-mention file picker - // reflects files created or deleted during this turn. - yield* workspaceEntries.refresh(input.cwd); - - const files = yield* checkpointStore - .diffCheckpoints({ - cwd: input.cwd, - fromCheckpointRef, - toCheckpointRef: targetCheckpointRef, - fallbackFromToHead: false, - ignoreWhitespace: false, - }) - .pipe( - Effect.map((diff) => - parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({ - path: file.path, - kind: "modified" as const, - additions: file.additions, - deletions: file.deletions, - })), - ), - Effect.tapError((error) => - appendCaptureFailureActivity({ - threadId: input.threadId, - turnId: input.turnId, - detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`, - createdAt: input.createdAt, - }), - ), - Effect.catch((error) => - Effect.logWarning("failed to derive checkpoint file summary", { - threadId: input.threadId, - turnId: input.turnId, - turnCount: input.turnCount, - detail: error.message, - }).pipe(Effect.as([])), - ), - ); - - const assistantMessageId = - input.assistantMessageId ?? - input.thread.messages - .toReversed() - .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ?? - MessageId.make(`assistant:${input.turnId}`); - - yield* orchestrationEngine.dispatch({ - type: "thread.turn.diff.complete", - commandId: yield* serverCommandId("checkpoint-turn-diff-complete"), - threadId: input.threadId, - turnId: input.turnId, - completedAt: input.createdAt, - checkpointRef: targetCheckpointRef, - status: input.status, - files, - assistantMessageId, - checkpointTurnCount: input.turnCount, - createdAt: input.createdAt, - }); - yield* receiptBus.publish({ - type: "checkpoint.diff.finalized", - threadId: input.threadId, - turnId: input.turnId, - checkpointTurnCount: input.turnCount, - checkpointRef: targetCheckpointRef, - status: input.status, - createdAt: input.createdAt, - }); - yield* receiptBus.publish({ - type: "turn.processing.quiesced", - threadId: input.threadId, - turnId: input.turnId, - checkpointTurnCount: input.turnCount, - createdAt: input.createdAt, - }); - - yield* orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId: yield* serverCommandId("checkpoint-captured-activity"), - threadId: input.threadId, - activity: { - id: EventId.make(yield* randomUUID), - tone: "info", - kind: "checkpoint.captured", - summary: "Checkpoint captured", - payload: { - turnCount: input.turnCount, - status: input.status, - }, - turnId: input.turnId, - createdAt: input.createdAt, - }, - createdAt: input.createdAt, - }); - }); - - // Captures a real git checkpoint when a turn completes via a runtime event. - const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")( - function* (event: Extract) { - const turnId = toTurnId(event.turnId); - if (!turnId) { - return; - } - - const thread = yield* resolveThreadDetail(event.threadId); - if (!thread) { - return; - } - - // When a primary turn is active, only that turn may produce completion checkpoints. - if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) { - return; - } - - // Only skip if a real (non-placeholder) checkpoint already exists for this turn. - // ProviderRuntimeIngestion may insert placeholder entries with status "missing" - // before this reactor runs; those must not prevent real git capture. - if ( - thread.checkpoints.some( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", - ) - ) { - return; - } - - const projects = yield* resolveThreadProjects(thread.projectId); - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId: thread.id, - thread, - projects, - preferSessionRuntime: true, - }); - if (!checkpointCwd) { - return; - } - - // If a placeholder checkpoint exists for this turn, reuse its turn count - // instead of incrementing past it. - const existingPlaceholder = thread.checkpoints.find( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing", - ); - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - const nextTurnCount = existingPlaceholder - ? existingPlaceholder.checkpointTurnCount - : currentTurnCount + 1; - - yield* captureAndDispatchCheckpoint({ - threadId: thread.id, - turnId, - thread, - cwd: checkpointCwd, - turnCount: nextTurnCount, - status: checkpointStatusFromRuntime(event.payload.state), - assistantMessageId: undefined, - createdAt: event.createdAt, - }); - }, - ); - - // Captures a real git checkpoint when a placeholder checkpoint (status "missing") - // is detected via a domain event. This replaces the placeholder with a real - // git-ref-based checkpoint. - // - // ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated - // events from the Codex runtime. This handler fires when the corresponding - // domain event arrives, allowing the reactor to capture the actual filesystem - // state into a git ref and dispatch a replacement checkpoint. - const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* ( - event: Extract, - ) { - const { threadId, turnId, checkpointTurnCount, status } = event.payload; - - // Only replace placeholders; skip events from our own real captures. - if (status !== "missing") { - return; - } - - const thread = yield* resolveThreadDetail(threadId); - if (!thread) { - yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", { - threadId, - }); - return; - } - - // If a real checkpoint already exists for this turn, skip. - if ( - thread.checkpoints.some( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", - ) - ) { - yield* Effect.logDebug( - "checkpoint capture from placeholder skipped: real checkpoint already exists", - { threadId, turnId }, - ); - return; - } - - const projects = yield* resolveThreadProjects(thread.projectId); - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId, - thread, - projects, - preferSessionRuntime: true, - }); - if (!checkpointCwd) { - return; - } - - yield* captureAndDispatchCheckpoint({ - threadId, - turnId, - thread, - cwd: checkpointCwd, - turnCount: checkpointTurnCount, - status: "ready", - assistantMessageId: event.payload.assistantMessageId ?? undefined, - createdAt: event.payload.completedAt, - }); - }); - - const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")( - function* (event: Extract) { - const turnId = toTurnId(event.turnId); - if (!turnId) { - return; - } - - const thread = yield* resolveThreadDetail(event.threadId); - if (!thread) { - return; - } - - const projects = yield* resolveThreadProjects(thread.projectId); - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId: thread.id, - thread, - projects, - preferSessionRuntime: false, - }); - if (!checkpointCwd) { - return; - } - - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - if (baselineExists) { - return; - } - - yield* checkpointStore.captureCheckpoint({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - yield* receiptBus.publish({ - type: "checkpoint.baseline.captured", - threadId: thread.id, - checkpointTurnCount: currentTurnCount, - checkpointRef: baselineCheckpointRef, - createdAt: event.createdAt, - }); - }, - ); - - const refreshLocalGitStatusFromTurnCompletion = Effect.fn( - "refreshLocalGitStatusFromTurnCompletion", - )(function* (event: Extract) { - const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId); - if (Option.isNone(sessionRuntime)) { - return; - } - - const local = yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe( - Effect.catch((error) => - Effect.logWarning("failed to refresh local git status after turn completion", { - threadId: event.threadId, - turnId: event.turnId ?? null, - cwd: sessionRuntime.value.cwd, - detail: error.message, - }).pipe(Effect.as(null)), - ), - ); - if (local !== null) { - yield* followWorktreeBranchDrift({ - threadId: event.threadId, - cwd: sessionRuntime.value.cwd, - local, - }); - } - }); - - // A `git checkout` run inside a thread's dedicated worktree (by an agent or - // the user) bypasses T3's commands, so the thread's recorded branch goes - // stale. Since #4460 the client only attributes PR state to a thread when - // the checked-out branch equals the recorded one, so stale metadata silently - // orphans the thread's PR. Follow the drift here: adopt the checked-out - // branch as the thread's branch, but only when the worktree belongs to - // exactly this thread — for shared cwds the strict matching is the point. - const followWorktreeBranchDrift = Effect.fn("followWorktreeBranchDrift")(function* (input: { - readonly threadId: ThreadId; - readonly cwd: string; - readonly local: VcsStatusLocalResult; - }) { - // Detached HEAD has no branch to adopt; a temporary placeholder checkout - // means the first-turn auto-rename is still in flight — don't race it. - const checkedOutBranch = input.local.refName; - if (checkedOutBranch === null || isTemporaryWorktreeBranch(checkedOutBranch)) { - return; - } - - yield* Effect.gen(function* () { - const thread = yield* projectionSnapshotQuery - .getThreadShellById(input.threadId) - .pipe(Effect.map(Option.getOrUndefined)); - if ( - !thread || - thread.branch === null || - thread.branch === checkedOutBranch || - thread.worktreePath === null || - thread.worktreePath !== input.cwd || - isTemporaryWorktreeBranch(thread.branch) - ) { - return; - } - - const shell = yield* projectionSnapshotQuery.getShellSnapshot(); - const worktreeIsShared = shell.threads.some( - (other) => other.id !== thread.id && other.worktreePath === thread.worktreePath, - ); - if (worktreeIsShared) { - return; - } - - // expectedBranch makes this a compare-and-swap in the decider: if the - // recorded branch moved between our read and the dispatch (rename, - // concurrent drift-follow), the stale update is dropped. - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: yield* serverCommandId("worktree-branch-drift"), - threadId: thread.id, - branch: checkedOutBranch, - expectedBranch: thread.branch, - }); - yield* Effect.logInfo("thread branch followed worktree checkout", { - threadId: thread.id, - previousBranch: thread.branch, - branch: checkedOutBranch, - }); - }).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning("failed to follow worktree branch drift", { - threadId: input.threadId, - cause: Cause.pretty(cause), - }); - }), - ); - }); - - const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn( - "ensurePreTurnBaselineFromDomainTurnStart", - )(function* ( - event: Extract< - OrchestrationEvent, - { type: "thread.turn-start-requested" | "thread.message-sent" } - >, - ) { - if (event.type === "thread.message-sent") { - if ( - event.payload.role !== "user" || - event.payload.streaming || - event.payload.turnId !== null - ) { - return; - } - } - - const threadId = event.payload.threadId; - const thread = yield* resolveThreadDetail(threadId); - if (!thread) { - return; - } - - const projects = yield* resolveThreadProjects(thread.projectId); - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId, - thread, - projects, - preferSessionRuntime: false, - }); - if (!checkpointCwd) { - return; - } - - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - if (baselineExists) { - return; - } - - yield* checkpointStore.captureCheckpoint({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - yield* receiptBus.publish({ - type: "checkpoint.baseline.captured", - threadId, - checkpointTurnCount: currentTurnCount, - checkpointRef: baselineCheckpointRef, - createdAt: event.occurredAt, - }); - }); - - const handleRevertRequested = Effect.fn("handleRevertRequested")(function* ( - event: Extract, - ) { - const now = DateTime.formatIso(yield* DateTime.now); - - const thread = yield* resolveThreadDetail(event.payload.threadId); - if (!thread) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: "Thread was not found in read model.", - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId); - if (Option.isNone(sessionRuntime)) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: "No active provider session with workspace cwd is bound to this thread.", - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - if (!isGitWorkspace(sessionRuntime.value.cwd)) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: "Checkpoints are unavailable because this project is not a git repository.", - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - - if (event.payload.turnCount > currentTurnCount) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`, - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - const targetCheckpointRef = - event.payload.turnCount === 0 - ? checkpointRefForThreadTurn(event.payload.threadId, 0) - : thread.checkpoints.find( - (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount, - )?.checkpointRef; - - if (!targetCheckpointRef) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`, - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - const restored = yield* checkpointStore.restoreCheckpoint({ - cwd: sessionRuntime.value.cwd, - checkpointRef: targetCheckpointRef, - fallbackToHead: event.payload.turnCount === 0, - }); - if (!restored) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`, - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - // Refresh the workspace entry index so the @-mention file picker - // reflects the reverted filesystem state. - yield* workspaceEntries.refresh(sessionRuntime.value.cwd); - - const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount); - if (rolledBackTurns > 0) { - yield* providerService.rollbackConversation({ - threadId: sessionRuntime.value.threadId, - numTurns: rolledBackTurns, - }); - } - - const staleCheckpointRefs: Array = []; - for (const checkpoint of thread.checkpoints) { - if (checkpoint.checkpointTurnCount > event.payload.turnCount) { - staleCheckpointRefs.push(checkpoint.checkpointRef); - } - } - - if (staleCheckpointRefs.length > 0) { - yield* checkpointStore.deleteCheckpointRefs({ - cwd: sessionRuntime.value.cwd, - checkpointRefs: staleCheckpointRefs, - }); - } - - yield* orchestrationEngine - .dispatch({ - type: "thread.revert.complete", - commandId: yield* serverCommandId("checkpoint-revert-complete"), - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - createdAt: now, - }) - .pipe( - Effect.catch((error) => - appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: error.message, - createdAt: now, - }), - ), - Effect.asVoid, - ); - }); - - const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) { - if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") { - yield* ensurePreTurnBaselineFromDomainTurnStart(event); - return; - } - - if (event.type === "thread.checkpoint-revert-requested") { - yield* handleRevertRequested(event).pipe( - Effect.catch((error) => - Effect.flatMap(nowIso, (createdAt) => - appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: error.message, - createdAt, - }), - ), - ), - ); - return; - } - - // When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing") - // from a turn.diff.updated runtime event, capture the real git checkpoint to - // replace it. The providerService.streamEvents PubSub does not reliably deliver - // turn.completed runtime events to this reactor (shared subscription), so - // reacting to the domain event is the reliable path. - if (event.type === "thread.turn-diff-completed") { - yield* captureCheckpointFromPlaceholder(event).pipe( - Effect.catch((error) => - Effect.flatMap(nowIso, (createdAt) => - appendCaptureFailureActivity({ - threadId: event.payload.threadId, - turnId: event.payload.turnId, - detail: error.message, - createdAt, - }).pipe(Effect.catch(() => Effect.void)), - ), - ), - ); - } - }); - - const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( - event: ProviderRuntimeEvent, - ) { - if (event.type === "turn.started") { - yield* ensurePreTurnBaselineFromTurnStart(event); - return; - } - - if (event.type === "turn.completed") { - const turnId = toTurnId(event.turnId); - yield* refreshLocalGitStatusFromTurnCompletion(event); - yield* captureCheckpointFromTurnCompletion(event).pipe( - Effect.catch((error) => - Effect.flatMap(nowIso, (createdAt) => - appendCaptureFailureActivity({ - threadId: event.threadId, - turnId, - detail: error.message, - createdAt, - }).pipe(Effect.catch(() => Effect.void)), - ), - ), - ); - return; - } - }); - - const processInput = ( - input: ReactorInput, - ): Effect.Effect< - void, - CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError, - never - > => - input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event); - - const processInputSafely = (input: ReactorInput) => - processInput(input).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning("checkpoint reactor failed to process input", { - source: input.source, - eventType: input.event.type, - cause: Cause.pretty(cause), - }); - }), - ); - - const worker = yield* makeDrainableWorker(processInputSafely); - - const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () { - yield* forkParked( - Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { - if ( - event.type !== "thread.turn-start-requested" && - event.type !== "thread.message-sent" && - event.type !== "thread.checkpoint-revert-requested" && - event.type !== "thread.turn-diff-completed" - ) { - return Effect.void; - } - return worker.enqueue({ source: "domain", event }); - }), - ); - - yield* forkParked( - Stream.runForEach(providerService.streamEvents, (event) => { - if (event.type !== "turn.started" && event.type !== "turn.completed") { - return Effect.void; - } - return worker.enqueue({ source: "runtime", event }); - }), - ); - }); - - return { - start, - drain: worker.drain, - } satisfies CheckpointReactorShape; -}); - -export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make); diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index 19184915ac..0b00f9372f 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -2,9 +2,8 @@ import type { OrchestrationEvent, OrchestrationReadModel, ProjectId, - ThreadId, + ProjectOrchestrationCommand, } from "@t3tools/contracts"; -import { OrchestrationCommand } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Crypto from "effect/Crypto"; @@ -51,29 +50,16 @@ const isOrchestrationCommandPreviouslyRejectedError = Schema.is( const isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError); interface CommandEnvelope { - command: OrchestrationCommand; + command: ProjectOrchestrationCommand; result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>; startedAtMs: number; } -function commandToAggregateRef(command: OrchestrationCommand): { - readonly aggregateKind: "project" | "thread"; - readonly aggregateId: ProjectId | ThreadId; +function commandToAggregateRef(command: ProjectOrchestrationCommand): { + readonly aggregateKind: "project"; + readonly aggregateId: ProjectId; } { - switch (command.type) { - case "project.create": - case "project.meta.update": - case "project.delete": - return { - aggregateKind: "project", - aggregateId: command.projectId, - }; - default: - return { - aggregateKind: "thread", - aggregateId: command.threadId, - }; - } + return { aggregateKind: "project", aggregateId: command.projectId }; } const makeOrchestrationEngine = Effect.gen(function* () { @@ -120,6 +106,15 @@ const makeOrchestrationEngine = Effect.gen(function* () { commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents); + yield* eventStore.publishCommitted( + persistedEvents.filter( + (event) => + event.type === "project.created" || + event.type === "project.meta-updated" || + event.type === "project.deleted", + ), + ); + for (const persistedEvent of persistedEvents) { yield* PubSub.publish(eventPubSub, persistedEvent); } @@ -191,6 +186,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { commandId: envelope.command.commandId, aggregateKind: lastSavedEvent.aggregateKind, aggregateId: lastSavedEvent.aggregateId, + commandType: envelope.command.type, acceptedAt: lastSavedEvent.occurredAt, resultSequence: lastSavedEvent.sequence, status: "accepted", @@ -213,6 +209,14 @@ const makeOrchestrationEngine = Effect.gen(function* () { ); commandReadModel = committedCommand.nextCommandReadModel; + yield* eventStore.publishCommitted( + committedCommand.committedEvents.filter( + (event) => + event.type === "project.created" || + event.type === "project.meta-updated" || + event.type === "project.deleted", + ), + ); for (const [index, event] of committedCommand.committedEvents.entries()) { yield* PubSub.publish(eventPubSub, event); if (index === 0) { @@ -282,6 +286,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { commandId: envelope.command.commandId, aggregateKind: aggregateRef.aggregateKind, aggregateId: aggregateRef.aggregateId, + commandType: envelope.command.type, acceptedAt: yield* nowIso, resultSequence: commandReadModel.snapshotSequence, status: "rejected", diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts deleted file mode 100644 index 300d1526bb..0000000000 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Layer from "effect/Layer"; -import * as ManagedRuntime from "effect/ManagedRuntime"; -import * as Scope from "effect/Scope"; -import { afterEach, describe, expect, it } from "vite-plus/test"; - -import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; -import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; -import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; -import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; -import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts"; -import { makeOrchestrationReactor } from "./OrchestrationReactor.ts"; -import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; - -describe("OrchestrationReactor", () => { - let runtime: ManagedRuntime.ManagedRuntime | null = null; - - afterEach(async () => { - if (runtime) { - await runtime.dispose(); - } - runtime = null; - }); - - it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => { - const started: string[] = []; - - runtime = ManagedRuntime.make( - Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe( - Layer.provideMerge( - Layer.succeed(ProviderRuntimeIngestionService, { - start: () => { - started.push("provider-runtime-ingestion"); - return Effect.void; - }, - drain: Effect.void, - }), - ), - Layer.provideMerge( - Layer.succeed(ProviderCommandReactor, { - start: () => { - started.push("provider-command-reactor"); - return Effect.void; - }, - drain: Effect.void, - }), - ), - Layer.provideMerge( - Layer.succeed(CheckpointReactor, { - start: () => { - started.push("checkpoint-reactor"); - return Effect.void; - }, - drain: Effect.void, - }), - ), - Layer.provideMerge( - Layer.succeed(ThreadDeletionReactor, { - start: () => { - started.push("thread-deletion-reactor"); - return Effect.void; - }, - drain: Effect.void, - }), - ), - Layer.provideMerge( - Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, { - publishThread: () => Effect.void, - start: () => { - started.push("agent-awareness-relay"); - return Effect.void; - }, - }), - ), - ), - ); - - const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor)); - const scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); - - expect(started).toEqual([ - "provider-runtime-ingestion", - "provider-command-reactor", - "checkpoint-reactor", - "thread-deletion-reactor", - "agent-awareness-relay", - ]); - - await Effect.runPromise(Scope.close(scope, Exit.void)); - }); -}); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts deleted file mode 100644 index fb7543e31a..0000000000 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts +++ /dev/null @@ -1,37 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { - OrchestrationReactor, - type OrchestrationReactorShape, -} from "../Services/OrchestrationReactor.ts"; -import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; -import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; -import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; -import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; -import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; - -export const makeOrchestrationReactor = Effect.gen(function* () { - const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService; - const providerCommandReactor = yield* ProviderCommandReactor; - const checkpointReactor = yield* CheckpointReactor; - const threadDeletionReactor = yield* ThreadDeletionReactor; - const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; - - const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () { - yield* providerRuntimeIngestion.start(); - yield* providerCommandReactor.start(); - yield* checkpointReactor.start(); - yield* threadDeletionReactor.start(); - yield* agentAwarenessRelay.start(); - }); - - return { - start, - } satisfies OrchestrationReactorShape; -}); - -export const OrchestrationReactorLive = Layer.effect( - OrchestrationReactor, - makeOrchestrationReactor, -); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts deleted file mode 100644 index 36d7a41094..0000000000 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ /dev/null @@ -1,1444 +0,0 @@ -import { - type ChatAttachment, - CommandId, - EventId, - type ModelSelection, - type OrchestrationEvent, - ProviderDriverKind, - type ProjectId, - type OrchestrationSession, - ThreadId, - type ProviderSession, - type RuntimeMode, - type TurnId, -} from "@t3tools/contracts"; -import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git"; -import * as Cache from "effect/Cache"; -import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Equal from "effect/Equal"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; - -import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; -import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts"; -import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; -import type { ProviderServiceError } from "../../provider/Errors.ts"; -import { TextGeneration } from "../../textGeneration/TextGeneration.ts"; -import { ProviderService } from "../../provider/Services/ProviderService.ts"; -import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts"; -import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; -import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -import { - ProviderCommandReactor, - type ProviderCommandReactorShape, -} from "../Services/ProviderCommandReactor.ts"; -import { forkParked, ServerActivation } from "../../serverActivation.ts"; -import { - resolveSourceControlWriterModelSelection, - ServerSettingsService, -} from "../../serverSettings.ts"; -import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts"; -import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; -const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError); -const isProviderDriverKind = Schema.is(ProviderDriverKind); - -type ProviderIntentEvent = Extract< - OrchestrationEvent, - { - type: - | "thread.meta-updated" - | "thread.runtime-mode-set" - | "thread.turn-start-requested" - | "thread.turn-interrupt-requested" - | "thread.approval-response-requested" - | "thread.user-input-response-requested" - | "thread.session-stop-requested"; - } ->; - -function toNonEmptyProviderInput(value: string | undefined): string | undefined { - const normalized = value?.trim(); - return normalized && normalized.length > 0 ? normalized : undefined; -} - -function mapProviderSessionStatusToOrchestrationStatus( - status: "connecting" | "ready" | "running" | "error" | "closed", -): OrchestrationSession["status"] { - switch (status) { - case "connecting": - return "starting"; - case "running": - return "running"; - case "error": - return "error"; - case "closed": - return "stopped"; - case "ready": - default: - return "ready"; - } -} - -const turnStartKeyForEvent = (event: ProviderIntentEvent): string => - event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`; - -const HANDLED_TURN_START_KEY_MAX = 10_000; -const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30); -const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; -const DEFAULT_THREAD_TITLE = "New thread"; -const MAX_REGENERATION_ATTACHMENTS = 4; -const MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000; -const MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000; -const THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n"; -const FIRST_USER_CONTEXT_TRUNCATION_MARKER = "\n[First user message truncated]"; - -type ThreadTitleMessage = { - readonly role: "user" | "assistant" | "system"; - readonly text: string; - readonly attachments?: ReadonlyArray | undefined; -}; - -function formatThreadTitleSection(message: ThreadTitleMessage): string | undefined { - if (message.role === "system") { - return undefined; - } - const text = message.text.trim(); - const attachmentSummary = (message.attachments ?? []) - .map((attachment) => attachment.name) - .join(", "); - const contents = [ - ...(text.length > 0 ? [text] : []), - ...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []), - ].join("\n"); - return contents.length > 0 ? `${message.role.toUpperCase()}:\n${contents}` : undefined; -} - -function limitFirstUserSection(section: string): string { - if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) { - return section; - } - return `${section.slice( - 0, - MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length, - )}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`; -} - -function collectRecentThreadTitleContext( - messages: ReadonlyArray, - maxChars: number, -): { - readonly context: string; - readonly attachments: ReadonlyArray; - readonly truncated: boolean; -} { - let context = ""; - let truncated = false; - const retainedAttachments: Array = []; - - for (const message of messages.toReversed()) { - const section = formatThreadTitleSection(message); - if (section === undefined) { - continue; - } - - const separator = context.length > 0 ? "\n\n" : ""; - const available = maxChars - context.length - separator.length; - if (section.length > available) { - if (available > 0) { - context = `${section.slice(-available)}${separator}${context}`; - retainedAttachments.unshift(...(message.attachments ?? [])); - } - truncated = true; - break; - } - context = `${section}${separator}${context}`; - retainedAttachments.unshift(...(message.attachments ?? [])); - } - - return { context, attachments: retainedAttachments, truncated }; -} - -function formatThreadTitleContext(messages: ReadonlyArray): { - readonly message: string; - readonly attachments: ReadonlyArray; -} { - const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS); - if (!recent.truncated) { - return { - message: recent.context, - attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS), - }; - } - - const firstUserMessage = messages.find( - (message) => message.role === "user" && formatThreadTitleSection(message), - ); - const firstUserSection = firstUserMessage - ? formatThreadTitleSection(firstUserMessage) - : undefined; - if (!firstUserMessage || !firstUserSection) { - return { - message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`, - attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS), - }; - } - - const pinnedSection = limitFirstUserSection(firstUserSection); - const recentContextBudget = - MAX_THREAD_TITLE_CONTEXT_CHARS - - pinnedSection.length - - "\n\n".length - - THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length; - const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget); - const pinnedAttachment = firstUserMessage.attachments?.[0]; - const recentAttachments = retainedRecent.attachments.filter( - (attachment) => attachment.id !== pinnedAttachment?.id, - ); - - return { - message: `${pinnedSection}\n\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`, - attachments: [ - ...(pinnedAttachment ? [pinnedAttachment] : []), - ...recentAttachments.slice( - -(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)), - ), - ], - }; -} - -export function providerErrorLabel(value: string | undefined): string { - const normalized = value?.trim(); - return normalized && normalized.length > 0 ? normalized : "unknown"; -} - -export function providerErrorLabelFromInstanceHint(input: { - readonly instanceId?: string | undefined; - readonly modelSelectionInstanceId?: string | undefined; - readonly sessionProvider?: string | undefined; -}): string { - return providerErrorLabel( - input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider, - ); -} - -function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean { - const trimmedCurrentTitle = currentTitle.trim(); - if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) { - return true; - } - - const trimmedTitleSeed = titleSeed?.trim(); - return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0 - ? trimmedCurrentTitle === trimmedTitleSeed - : false; -} - -function findProviderAdapterRequestError( - cause: Cause.Cause, -): ProviderAdapterRequestError | undefined { - const failReason = cause.reasons.find(Cause.isFailReason); - return isProviderAdapterRequestError(failReason?.error) ? failReason.error : undefined; -} - -function isUnknownPendingApprovalRequestError(cause: Cause.Cause): boolean { - const error = findProviderAdapterRequestError(cause); - if (error) { - const detail = error.detail.toLowerCase(); - return ( - detail.includes("unknown pending approval request") || - detail.includes("unknown pending permission request") - ); - } - const message = Cause.pretty(cause); - return ( - message.includes("unknown pending approval request") || - message.includes("unknown pending permission request") - ); -} - -function isUnknownPendingUserInputRequestError(cause: Cause.Cause): boolean { - const error = findProviderAdapterRequestError(cause); - if (error) { - return error.detail.toLowerCase().includes("unknown pending user-input request"); - } - const message = Cause.pretty(cause).toLowerCase(); - return ( - message.includes("unknown pending user-input request") || - message.includes("unknown pending user input request") || - message.includes("unknown pending codex user input request") - ); -} - -function stalePendingRequestDetail( - requestKind: "approval" | "user-input", - requestId: string, -): string { - return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`; -} - -function buildGeneratedWorktreeBranchName(raw: string): string { - const normalized = raw - .trim() - .toLowerCase() - .replace(/^refs\/heads\//, "") - .replace(/['"`]/g, ""); - - const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`) - ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length) - : normalized; - - const branchFragment = withoutPrefix - .replace(/[^a-z0-9/_-]+/g, "-") - .replace(/\/+/g, "/") - .replace(/-+/g, "-") - .replace(/^[./_-]+|[./_-]+$/g, "") - .slice(0, 64) - .replace(/[./_-]+$/g, ""); - - const safeFragment = branchFragment.length > 0 ? branchFragment : "update"; - return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`; -} - -const make = Effect.gen(function* () { - const crypto = yield* Crypto.Crypto; - const orchestrationEngine = yield* OrchestrationEngineService; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const providerService = yield* ProviderService; - const providerRegistry = yield* ProviderRegistry; - const gitWorkflow = yield* GitWorkflowService; - const vcsStatusBroadcaster = yield* VcsStatusBroadcaster; - const textGeneration = yield* TextGeneration; - const serverSettingsService = yield* ServerSettingsService; - const serverCommandId = (tag: string) => - crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`))); - const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make)); - const handledTurnStartKeys = yield* Cache.make({ - capacity: HANDLED_TURN_START_KEY_MAX, - timeToLive: HANDLED_TURN_START_KEY_TTL, - lookup: () => Effect.succeed(true), - }); - - const hasHandledTurnStartRecently = (key: string) => - Cache.getOption(handledTurnStartKeys, key).pipe( - Effect.flatMap((cached) => - Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))), - ), - ); - - const threadModelSelections = new Map(); - - const appendProviderFailureActivity = (input: { - readonly threadId: ThreadId; - readonly kind: - | "provider.turn.start.failed" - | "provider.turn.interrupt.failed" - | "provider.approval.respond.failed" - | "provider.user-input.respond.failed" - | "provider.session.stop.failed"; - readonly summary: string; - readonly detail: string; - readonly turnId: TurnId | null; - readonly createdAt: string; - readonly requestId?: string; - }) => - Effect.all({ - commandId: serverCommandId("provider-failure-activity"), - eventId: serverEventId(), - }).pipe( - Effect.flatMap(({ commandId, eventId }) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId, - threadId: input.threadId, - activity: { - id: eventId, - tone: "error", - kind: input.kind, - summary: input.summary, - payload: { - detail: input.detail, - ...(input.requestId ? { requestId: input.requestId } : {}), - }, - turnId: input.turnId, - createdAt: input.createdAt, - }, - createdAt: input.createdAt, - }), - ), - ); - - const formatFailureDetail = (cause: Cause.Cause): string => { - const failReason = cause.reasons.find(Cause.isFailReason); - const providerError = isProviderAdapterRequestError(failReason?.error) - ? failReason.error - : undefined; - if (providerError) { - return providerError.detail; - } - return Cause.pretty(cause); - }; - - const setThreadSession = (input: { - readonly threadId: ThreadId; - readonly session: OrchestrationSession; - readonly createdAt: string; - }) => - serverCommandId("provider-session-set").pipe( - Effect.flatMap((commandId) => - orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId, - threadId: input.threadId, - session: input.session, - createdAt: input.createdAt, - }), - ), - ); - - const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: { - readonly threadId: ThreadId; - readonly detail: string; - readonly createdAt: string; - }) { - const thread = yield* resolveThread(input.threadId); - if (!thread) { - return; - } - const session = thread.session; - yield* setThreadSession({ - threadId: input.threadId, - session: { - ...(session ?? { - threadId: input.threadId, - providerName: null, - providerInstanceId: thread.modelSelection.instanceId, - runtimeMode: thread.runtimeMode, - }), - status: session?.status === "stopped" ? "stopped" : "error", - activeTurnId: null, - lastError: input.detail, - updatedAt: input.createdAt, - }, - createdAt: input.createdAt, - }); - }); - - const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) { - return yield* projectionSnapshotQuery - .getProjectShellById(projectId) - .pipe(Effect.map(Option.getOrUndefined)); - }); - - const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) { - return yield* projectionSnapshotQuery - .getThreadDetailById(threadId) - .pipe(Effect.map(Option.getOrUndefined)); - }); - - const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: { - readonly threadId: ThreadId; - readonly currentModelSelection: ModelSelection; - readonly requestedModelSelection: ModelSelection | undefined; - }) { - const requestedModelSelection = input.requestedModelSelection; - if ( - requestedModelSelection === undefined || - (input.currentModelSelection.instanceId === requestedModelSelection.instanceId && - input.currentModelSelection.model === requestedModelSelection.model) - ) { - return; - } - const providers = yield* providerRegistry.getProviders; - const requiresNewThread = - providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId) - ?.requiresNewThreadForModelChange === true || - providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId) - ?.requiresNewThreadForModelChange === true; - if (!requiresNewThread) { - return; - } - return yield* new ProviderAdapterRequestError({ - provider: providerErrorLabelFromInstanceHint({ - instanceId: String(requestedModelSelection.instanceId), - modelSelectionInstanceId: String(input.currentModelSelection.instanceId), - }), - method: "thread.turn.start", - detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`, - }); - }); - - const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* ( - threadId: ThreadId, - createdAt: string, - options?: { - readonly modelSelection?: ModelSelection; - readonly pendingTurnStart?: boolean; - }, - ) { - const thread = yield* resolveThread(threadId); - if (!thread) { - return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`)); - } - - const desiredRuntimeMode = thread.runtimeMode; - const requestedModelSelection = options?.modelSelection; - const resolveActiveSession = (threadId: ThreadId) => - providerService - .listSessions() - .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId))); - - const activeSession = yield* resolveActiveSession(threadId); - const activeThreadSession = - thread.session !== null && thread.session.status !== "stopped" && activeSession - ? thread.session - : null; - if ( - activeThreadSession !== null && - activeSession !== undefined && - (activeThreadSession.providerInstanceId === undefined || - activeSession.providerInstanceId === undefined) - ) { - return yield* new ProviderAdapterRequestError({ - provider: providerErrorLabel(activeThreadSession.providerName ?? undefined), - method: "thread.turn.start", - detail: `Thread '${threadId}' has an active provider session without a provider instance id.`, - }); - } - const currentInstanceId = - activeThreadSession !== null && - activeSession !== undefined && - activeSession.providerInstanceId !== undefined - ? activeSession.providerInstanceId - : thread.modelSelection.instanceId; - const desiredModelSelection = requestedModelSelection ?? thread.modelSelection; - const desiredInstanceId = desiredModelSelection.instanceId; - const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe( - Effect.mapError( - () => - new ProviderAdapterRequestError({ - provider: providerErrorLabelFromInstanceHint({ - instanceId: String(currentInstanceId), - modelSelectionInstanceId: String(thread.modelSelection.instanceId), - sessionProvider: thread.session?.providerName ?? undefined, - }), - method: "thread.turn.start", - detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`, - }), - ), - ); - const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe( - Effect.mapError( - () => - new ProviderAdapterRequestError({ - provider: providerErrorLabelFromInstanceHint({ - instanceId: String(desiredModelSelection.instanceId), - }), - method: "thread.turn.start", - detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`, - }), - ), - ); - const desiredDriverKind = desiredInfo.driverKind; - if (!isProviderDriverKind(desiredDriverKind)) { - return yield* new ProviderAdapterRequestError({ - provider: providerErrorLabel(String(desiredDriverKind)), - method: "thread.turn.start", - detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`, - }); - } - const preferredProvider: ProviderDriverKind = desiredDriverKind; - if (options?.pendingTurnStart === true && thread.session?.status !== "running") { - yield* setThreadSession({ - threadId, - session: { - threadId, - status: "starting", - providerName: activeSession?.provider ?? preferredProvider, - providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId, - runtimeMode: desiredRuntimeMode, - activeTurnId: null, - lastError: null, - updatedAt: createdAt, - }, - createdAt, - }); - } - if (thread.session !== null) { - yield* rejectStartedThreadModelChangeIfRequired({ - threadId, - currentModelSelection: - activeSession?.model !== undefined - ? { - ...thread.modelSelection, - instanceId: currentInstanceId, - model: activeSession.model, - } - : thread.modelSelection, - requestedModelSelection, - }); - } - if ( - thread.session !== null && - requestedModelSelection !== undefined && - requestedModelSelection.instanceId !== currentInstanceId - ) { - if (currentInfo.driverKind !== desiredInfo.driverKind) { - return yield* new ProviderAdapterRequestError({ - provider: preferredProvider, - method: "thread.turn.start", - detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`, - }); - } - if ( - currentInfo.continuationIdentity.continuationKey !== - desiredInfo.continuationIdentity.continuationKey - ) { - return yield* new ProviderAdapterRequestError({ - provider: preferredProvider, - method: "thread.turn.start", - detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`, - }); - } - } - const project = yield* resolveProject(thread.projectId); - const effectiveCwd = resolveThreadWorkspaceCwd({ - thread, - projects: project ? [project] : [], - }); - - const startProviderSession = (input?: { - readonly resumeCursor?: unknown; - readonly provider?: ProviderDriverKind; - }) => - providerService.startSession(threadId, { - threadId, - ...(preferredProvider ? { provider: preferredProvider } : {}), - providerInstanceId: desiredInstanceId, - ...(effectiveCwd ? { cwd: effectiveCwd } : {}), - modelSelection: desiredModelSelection, - ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}), - runtimeMode: desiredRuntimeMode, - }); - - const bindSessionToThread = (session: ProviderSession) => - Effect.gen(function* () { - if (session.providerInstanceId === undefined) { - return yield* new ProviderAdapterRequestError({ - provider: providerErrorLabel(session.provider), - method: "thread.turn.start", - detail: `Provider session '${session.threadId}' started without a provider instance id.`, - }); - } - yield* setThreadSession({ - threadId, - session: { - threadId, - status: - options?.pendingTurnStart === true && session.status === "ready" - ? "starting" - : mapProviderSessionStatusToOrchestrationStatus(session.status), - providerName: session.provider, - providerInstanceId: session.providerInstanceId, - runtimeMode: desiredRuntimeMode, - // Provider turn ids are not orchestration turn ids. - activeTurnId: null, - lastError: session.lastError ?? null, - updatedAt: session.updatedAt, - }, - createdAt, - }); - }); - - const existingSessionThreadId = - thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null; - if (existingSessionThreadId) { - const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode; - const sessionModelSwitch = - currentProvider === undefined - ? "in-session" - : (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch; - const modelChanged = - requestedModelSelection !== undefined && - requestedModelSelection.model !== activeSession?.model; - const instanceChanged = - requestedModelSelection !== undefined && - activeSession?.providerInstanceId !== requestedModelSelection.instanceId; - const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported"; - const previousModelSelection = threadModelSelections.get(threadId); - const shouldRestartForModelSelectionChange = - preferredProvider === "claudeAgent" && - requestedModelSelection !== undefined && - !Equal.equals(previousModelSelection, requestedModelSelection); - - if ( - !runtimeModeChanged && - !shouldRestartForModelChange && - !shouldRestartForModelSelectionChange - ) { - return existingSessionThreadId; - } - - const resumeCursor = shouldRestartForModelChange - ? undefined - : (activeSession?.resumeCursor ?? undefined); - yield* Effect.logInfo("provider command reactor restarting provider session", { - threadId, - existingSessionThreadId, - currentProvider: activeSession?.provider, - currentInstanceId, - desiredInstanceId, - desiredProvider: desiredModelSelection.instanceId, - currentRuntimeMode: thread.session?.runtimeMode, - desiredRuntimeMode: thread.runtimeMode, - runtimeModeChanged, - modelChanged, - instanceChanged, - shouldRestartForModelChange, - shouldRestartForModelSelectionChange, - hasResumeCursor: resumeCursor !== undefined, - }); - const restartedSession = yield* startProviderSession( - resumeCursor !== undefined ? { resumeCursor } : undefined, - ); - yield* Effect.logInfo("provider command reactor restarted provider session", { - threadId, - previousSessionId: existingSessionThreadId, - restartedSessionThreadId: restartedSession.threadId, - provider: restartedSession.provider, - runtimeMode: restartedSession.runtimeMode, - cwd: restartedSession.cwd, - }); - yield* bindSessionToThread(restartedSession); - return restartedSession.threadId; - } - - const startedSession = yield* startProviderSession(undefined); - yield* bindSessionToThread(startedSession); - return startedSession.threadId; - }); - - const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: { - readonly threadId: ThreadId; - readonly messageText: string; - readonly attachments?: ReadonlyArray; - readonly modelSelection?: ModelSelection; - readonly interactionMode?: "default" | "plan"; - readonly createdAt: string; - }) { - const thread = yield* resolveThread(input.threadId); - if (!thread) { - return yield* Effect.die( - new Error(`Thread '${input.threadId}' was not found in read model.`), - ); - } - yield* ensureSessionForThread(input.threadId, input.createdAt, { - ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), - pendingTurnStart: true, - }); - if (input.modelSelection !== undefined) { - threadModelSelections.set(input.threadId, input.modelSelection); - } - const normalizedInput = toNonEmptyProviderInput(input.messageText); - const normalizedAttachments = input.attachments ?? []; - const activeSession = yield* providerService - .listSessions() - .pipe( - Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)), - ); - const sessionModelSwitch = - activeSession === undefined - ? "in-session" - : activeSession.providerInstanceId === undefined - ? yield* new ProviderAdapterRequestError({ - provider: providerErrorLabel(activeSession.provider), - method: "thread.turn.start", - detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`, - }) - : (yield* providerService.getCapabilities(activeSession.providerInstanceId)) - .sessionModelSwitch; - const requestedModelSelection = - input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection; - const modelForTurn = - sessionModelSwitch === "unsupported" && input.modelSelection === undefined - ? activeSession?.model !== undefined - ? { - ...requestedModelSelection, - model: activeSession.model, - } - : requestedModelSelection - : input.modelSelection; - - return { - threadId: input.threadId, - ...(normalizedInput ? { input: normalizedInput } : {}), - ...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}), - ...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}), - ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), - }; - }); - - const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn( - "maybeGenerateAndRenameWorktreeBranchForFirstTurn", - )(function* (input: { - readonly threadId: ThreadId; - readonly branch: string | null; - readonly worktreePath: string | null; - readonly messageText: string; - readonly attachments?: ReadonlyArray; - }) { - if (!input.branch || !input.worktreePath) { - return; - } - if (!isTemporaryWorktreeBranch(input.branch)) { - return; - } - - const oldBranch = input.branch; - const cwd = input.worktreePath; - const attachments = input.attachments ?? []; - yield* Effect.gen(function* () { - const settings = yield* serverSettingsService.getSettings; - const modelSelection = - settings.sourceControlWriterModelSelection === null - ? settings.textGenerationModelSelection - : resolveSourceControlWriterModelSelection( - settings, - yield* providerRegistry.getProviders, - ); - - const generated = yield* textGeneration.generateBranchName({ - cwd, - message: input.messageText, - ...(attachments.length > 0 ? { attachments } : {}), - modelSelection, - }); - if (!generated) return; - - const targetBranch = buildGeneratedWorktreeBranchName(generated.branch); - if (targetBranch === oldBranch) return; - - const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch }); - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: yield* serverCommandId("worktree-branch-rename"), - threadId: input.threadId, - branch: renamed.branch, - worktreePath: cwd, - }); - yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true })); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("provider command reactor failed to generate or rename worktree branch", { - threadId: input.threadId, - cwd, - oldBranch, - cause: Cause.pretty(cause), - }), - ), - ); - }); - - const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")( - function* (input: { - readonly threadId: ThreadId; - readonly cwd: string; - readonly messageText: string; - readonly attachments?: ReadonlyArray; - readonly titleSeed?: string; - }) { - const attachments = input.attachments ?? []; - yield* Effect.gen(function* () { - const { textGenerationModelSelection: modelSelection } = - yield* serverSettingsService.getSettings; - - const generated = yield* textGeneration.generateThreadTitle({ - cwd: input.cwd, - message: input.messageText, - ...(attachments.length > 0 ? { attachments } : {}), - modelSelection, - }); - if (!generated) return; - - const thread = yield* resolveThread(input.threadId); - if (!thread) return; - if (!canReplaceThreadTitle(thread.title, input.titleSeed)) { - return; - } - - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: yield* serverCommandId("thread-title-rename"), - threadId: input.threadId, - title: generated.title, - }); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("provider command reactor failed to generate or rename thread title", { - threadId: input.threadId, - cwd: input.cwd, - cause: Cause.pretty(cause), - }), - ), - ); - }, - ); - - const regenerateThreadTitle = Effect.fn("regenerateThreadTitle")(function* ( - event: Extract, - requestId: CommandId, - ) { - if (event.payload.regenerateTitle !== true) { - return { _tag: "Superseded" } as const; - } - - const thread = yield* resolveThread(event.payload.threadId); - if (!thread || thread.titleRegeneration?.requestId !== requestId) { - return { _tag: "Superseded" } as const; - } - - const { message, attachments } = formatThreadTitleContext(thread.messages); - if (message.length === 0) { - return { _tag: "Completed", title: undefined } as const; - } - - const previousTitle = event.payload.previousTitle ?? thread.title; - if (thread.title !== previousTitle) { - return { _tag: "Superseded" } as const; - } - const project = yield* resolveProject(thread.projectId); - const cwd = - resolveThreadWorkspaceCwd({ - thread, - projects: project ? [project] : [], - }) ?? process.cwd(); - const { textGenerationModelSelection: modelSelection } = - yield* serverSettingsService.getSettings; - const generated = yield* textGeneration.generateThreadTitle({ - cwd, - message, - previousTitle, - ...(attachments.length > 0 ? { attachments } : {}), - modelSelection, - }); - if (generated.title === DEFAULT_THREAD_TITLE || generated.title === previousTitle) { - return { _tag: "Completed", title: undefined } as const; - } - - const latestThread = yield* resolveThread(event.payload.threadId); - if ( - !latestThread || - latestThread.titleRegeneration?.requestId !== requestId || - latestThread.title !== previousTitle - ) { - return { _tag: "Superseded" } as const; - } - - return { _tag: "Completed", title: generated.title } as const; - }); - const dispatchThreadTitleRegenerationCompletion = Effect.fn( - "dispatchThreadTitleRegenerationCompletion", - )(function* (input: { - readonly threadId: ThreadId; - readonly requestId: CommandId; - readonly title?: string; - }) { - yield* orchestrationEngine.dispatch({ - type: "thread.title.regeneration.complete", - commandId: yield* serverCommandId("thread-title-regeneration-complete"), - threadId: input.threadId, - requestId: input.requestId, - ...(input.title !== undefined ? { title: input.title } : {}), - }); - }); - const findInterruptedThreadTitleRegenerations = Effect.fn( - "findInterruptedThreadTitleRegenerations", - )(function* () { - const readModel = yield* projectionSnapshotQuery.getCommandReadModel(); - return readModel.threads.flatMap((thread) => { - const requestId = thread.titleRegeneration?.requestId; - return requestId === undefined ? [] : [{ threadId: thread.id, requestId }]; - }); - }); - const clearInterruptedThreadTitleRegenerations = Effect.fn( - "clearInterruptedThreadTitleRegenerations", - )(function* ( - interrupted: ReadonlyArray<{ readonly threadId: ThreadId; readonly requestId: CommandId }>, - ) { - yield* Effect.forEach( - interrupted, - ({ threadId, requestId }) => { - return dispatchThreadTitleRegenerationCompletion({ - threadId, - requestId, - }).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.interrupt; - } - return Effect.logWarning( - "provider command reactor failed to clear interrupted title regeneration", - { - threadId, - cause: Cause.pretty(cause), - }, - ); - }), - ); - }, - { discard: true }, - ); - }); - const processThreadTitleRegenerationSafely = Effect.fn("processThreadTitleRegenerationSafely")( - function* (event: Extract) { - if (event.payload.regenerateTitle !== true) { - return; - } - - const requestId = event.payload.titleRegeneration?.requestId ?? event.commandId; - if (requestId === null) { - return; - } - const result = yield* regenerateThreadTitle(event, requestId).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning("provider command reactor failed to regenerate thread title", { - threadId: event.payload.threadId, - cause: Cause.pretty(cause), - }).pipe(Effect.as({ _tag: "Completed", title: undefined } as const)); - }), - ); - if (result._tag === "Superseded") { - return; - } - - const completion = { - threadId: event.payload.threadId, - requestId, - ...(result.title !== undefined ? { title: result.title } : {}), - }; - yield* dispatchThreadTitleRegenerationCompletion(completion).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning( - "provider command reactor retrying title regeneration completion", - { - threadId: event.payload.threadId, - cause: Cause.pretty(cause), - }, - ).pipe(Effect.andThen(dispatchThreadTitleRegenerationCompletion(completion))); - }), - ); - }, - (effect, event) => - effect.pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning( - "provider command reactor failed to complete title regeneration", - { - threadId: event.payload.threadId, - cause: Cause.pretty(cause), - }, - ); - }), - ), - ); - const threadTitleRegenerationWorker = yield* makeDrainableWorker( - processThreadTitleRegenerationSafely, - ); - - const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* ( - event: Extract, - ) { - const key = turnStartKeyForEvent(event); - if (yield* hasHandledTurnStartRecently(key)) { - return; - } - - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - - const message = thread.messages.find((entry) => entry.id === event.payload.messageId); - if (!message || message.role !== "user") { - yield* appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.turn.start.failed", - summary: "Provider turn start failed", - detail: `User message '${event.payload.messageId}' was not found for turn start request.`, - turnId: null, - createdAt: event.payload.createdAt, - }); - return; - } - - const isFirstUserMessageTurn = - thread.messages.filter((entry) => entry.role === "user").length === 1; - if (isFirstUserMessageTurn) { - const project = yield* resolveProject(thread.projectId); - const generationCwd = - resolveThreadWorkspaceCwd({ - thread, - projects: project ? [project] : [], - }) ?? process.cwd(); - const generationInput = { - messageText: message.text, - ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), - ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}), - }; - - yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({ - threadId: event.payload.threadId, - branch: thread.branch, - worktreePath: thread.worktreePath, - ...generationInput, - }).pipe(Effect.forkScoped); - - if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) { - yield* maybeGenerateThreadTitleForFirstTurn({ - threadId: event.payload.threadId, - cwd: generationCwd, - ...generationInput, - }).pipe(Effect.forkScoped); - } - } - - const handleTurnStartFailure = (cause: Cause.Cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.void; - } - const detail = formatFailureDetail(cause); - return setThreadSessionErrorOnTurnStartFailure({ - threadId: event.payload.threadId, - detail, - createdAt: event.payload.createdAt, - }).pipe( - Effect.flatMap(() => - appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.turn.start.failed", - summary: "Provider turn start failed", - detail, - turnId: null, - createdAt: event.payload.createdAt, - }), - ), - Effect.asVoid, - ); - }; - - const recoverTurnStartFailure = (cause: Cause.Cause) => - handleTurnStartFailure(cause).pipe( - Effect.catchCause((recoveryCause) => - Effect.logWarning("provider command reactor failed to recover turn start failure", { - eventType: event.type, - threadId: event.payload.threadId, - cause: Cause.pretty(recoveryCause), - originalCause: Cause.pretty(cause), - }), - ), - ); - - const sendTurnRequest = yield* buildSendTurnRequestForThread({ - threadId: event.payload.threadId, - messageText: message.text, - ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), - ...(event.payload.modelSelection !== undefined - ? { modelSelection: event.payload.modelSelection } - : {}), - interactionMode: event.payload.interactionMode, - createdAt: event.payload.createdAt, - }).pipe( - Effect.map(Option.some), - Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))), - ); - - if (Option.isNone(sendTurnRequest)) { - return; - } - - yield* providerService - .sendTurn(sendTurnRequest.value) - .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped); - }); - - const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* ( - event: Extract, - ) { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - const hasSession = thread.session && thread.session.status !== "stopped"; - if (!hasSession) { - return yield* appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.turn.interrupt.failed", - summary: "Provider turn interrupt failed", - detail: "No active provider session is bound to this thread.", - turnId: event.payload.turnId ?? null, - createdAt: event.payload.createdAt, - }); - } - - // Orchestration turn ids are not provider turn ids, so interrupt by session. - yield* providerService.interruptTurn({ threadId: event.payload.threadId }); - }); - - const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* ( - event: Extract, - ) { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - const hasSession = thread.session && thread.session.status !== "stopped"; - if (!hasSession) { - return yield* appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - detail: "No active provider session is bound to this thread.", - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }); - } - - yield* providerService - .respondToRequest({ - threadId: event.payload.threadId, - requestId: event.payload.requestId, - decision: event.payload.decision, - }) - .pipe( - Effect.catchCause((cause) => - appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - detail: isUnknownPendingApprovalRequestError(cause) - ? stalePendingRequestDetail("approval", event.payload.requestId) - : Cause.pretty(cause), - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }), - ), - ); - }); - - const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")( - function* ( - event: Extract, - ) { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - const hasSession = thread.session && thread.session.status !== "stopped"; - if (!hasSession) { - return yield* appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - detail: "No active provider session is bound to this thread.", - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }); - } - - yield* providerService - .respondToUserInput({ - threadId: event.payload.threadId, - requestId: event.payload.requestId, - answers: event.payload.answers, - }) - .pipe( - Effect.catchCause((cause) => - appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - detail: isUnknownPendingUserInputRequestError(cause) - ? stalePendingRequestDetail("user-input", event.payload.requestId) - : Cause.pretty(cause), - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }), - ), - ); - }, - ); - - const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* ( - event: Extract, - ) { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - - const now = event.payload.createdAt; - if (thread.session && thread.session.status !== "stopped") { - yield* providerService.stopSession({ threadId: thread.id }); - } - - yield* setThreadSession({ - threadId: thread.id, - session: { - threadId: thread.id, - status: "stopped", - providerName: thread.session?.providerName ?? null, - ...(thread.session?.providerInstanceId !== undefined - ? { providerInstanceId: thread.session.providerInstanceId } - : {}), - runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE, - activeTurnId: null, - lastError: thread.session?.lastError ?? null, - updatedAt: now, - }, - createdAt: now, - }); - }); - - const processDomainEvent = Effect.fn("processDomainEvent")(function* ( - event: ProviderIntentEvent, - ) { - yield* Effect.annotateCurrentSpan({ - "orchestration.event_type": event.type, - "orchestration.thread_id": event.payload.threadId, - ...(event.commandId ? { "orchestration.command_id": event.commandId } : {}), - }); - yield* increment(orchestrationEventsProcessedTotal, { - eventType: event.type, - }); - switch (event.type) { - case "thread.meta-updated": - yield* threadTitleRegenerationWorker.enqueue(event); - return; - 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 } : {}, - ); - 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( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.interrupt; - } - return Effect.logWarning("provider command reactor failed to process event", { - eventType: event.type, - cause: Cause.pretty(cause), - }); - }), - ); - - const worker = yield* makeDrainableWorker(processDomainEventSafely); - - const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () { - const interruptedTitleRegenerations = yield* findInterruptedThreadTitleRegenerations().pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.interrupt; - } - return Effect.logWarning( - "provider command reactor failed to find interrupted title regenerations", - { cause: Cause.pretty(cause) }, - ).pipe(Effect.as([])); - }), - ); - const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) { - if ( - (event.type === "thread.meta-updated" && event.payload.regenerateTitle === true) || - event.type === "thread.runtime-mode-set" || - event.type === "thread.turn-start-requested" || - event.type === "thread.turn-interrupt-requested" || - event.type === "thread.approval-response-requested" || - event.type === "thread.user-input-response-requested" || - event.type === "thread.session-stop-requested" - ) { - return yield* worker.enqueue(event); - } - }); - - yield* forkParked(Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent)); - - // The domain event stream is hot, so work pending before this reactor - // starts cannot be resumed. Correlated completions only clear the request - // captured here, leaving any newer request untouched. - const clearInterrupted = clearInterruptedThreadTitleRegenerations( - interruptedTitleRegenerations, - ).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.interrupt; - } - return Effect.logWarning( - "provider command reactor failed to clear interrupted title regenerations", - { - cause: Cause.pretty(cause), - }, - ); - }), - ); - const activation = yield* ServerActivation; - if (activation === undefined) { - yield* clearInterrupted; - } else { - yield* forkParked(clearInterrupted); - } - }); - - return { - start, - drain: Effect.gen(function* () { - yield* worker.drain; - yield* threadTitleRegenerationWorker.drain; - }), - } satisfies ProviderCommandReactorShape; -}); - -export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make); diff --git a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts deleted file mode 100644 index 586281dc9c..0000000000 --- a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * RuntimeReceiptBus layers. - * - * `RuntimeReceiptBusLive` is the production default and intentionally does not - * retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory - * PubSub-backed implementation used by integration tests that need to await - * checkpoint-reactor milestones precisely. - * - * @module RuntimeReceiptBus - */ -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as PubSub from "effect/PubSub"; -import * as Stream from "effect/Stream"; - -import { - RuntimeReceiptBus, - type RuntimeReceiptBusShape, - type OrchestrationRuntimeReceipt, -} from "../Services/RuntimeReceiptBus.ts"; - -const makeRuntimeReceiptBus = Effect.succeed({ - publish: () => Effect.void, - streamEventsForTest: Stream.empty, -} satisfies RuntimeReceiptBusShape); - -const makeRuntimeReceiptBusTest = Effect.gen(function* () { - const pubSub = yield* PubSub.unbounded(); - - return { - publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid), - get streamEventsForTest() { - return Stream.fromPubSub(pubSub); - }, - } satisfies RuntimeReceiptBusShape; -}); - -export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus); -export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest); diff --git a/apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts b/apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts deleted file mode 100644 index 34b1b995a3..0000000000 --- a/apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { ThreadId } from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import { describe, expect, it } from "vite-plus/test"; - -import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts"; - -describe("logCleanupCauseUnlessInterrupted", () => { - const threadId = ThreadId.make("thread-deletion-reactor-test"); - - it("swallows ordinary cleanup failures", async () => { - const exit = await Effect.runPromiseExit( - logCleanupCauseUnlessInterrupted({ - effect: Effect.fail("cleanup failed"), - message: "thread deletion cleanup skipped provider session stop", - threadId, - }), - ); - - expect(Exit.isSuccess(exit)).toBe(true); - }); - - it("preserves interrupt causes", async () => { - const exit = await Effect.runPromiseExit( - logCleanupCauseUnlessInterrupted({ - effect: Effect.interrupt, - message: "thread deletion cleanup skipped provider session stop", - threadId, - }), - ); - - expect(Exit.isFailure(exit)).toBe(true); - if (Exit.isFailure(exit)) { - expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true); - } - }); -}); diff --git a/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts b/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts deleted file mode 100644 index a026f5ad81..0000000000 --- a/apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts +++ /dev/null @@ -1,100 +0,0 @@ -import type { OrchestrationEvent } from "@t3tools/contracts"; -import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; -import * as Cause from "effect/Cause"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Stream from "effect/Stream"; - -import { ProviderService } from "../../provider/Services/ProviderService.ts"; -import * as TerminalManager from "../../terminal/Manager.ts"; -import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; -import { - ThreadDeletionReactor, - type ThreadDeletionReactorShape, -} from "../Services/ThreadDeletionReactor.ts"; -import { forkParked } from "../../serverActivation.ts"; - -type ThreadDeletedEvent = Extract; - -export const logCleanupCauseUnlessInterrupted = ({ - effect, - message, - threadId, -}: { - readonly effect: Effect.Effect; - readonly message: string; - readonly threadId: ThreadDeletedEvent["payload"]["threadId"]; -}): Effect.Effect => - effect.pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logDebug(message, { - threadId, - cause: Cause.pretty(cause), - }); - }), - ); - -const make = Effect.gen(function* () { - const orchestrationEngine = yield* OrchestrationEngineService; - const providerService = yield* ProviderService; - const terminalManager = yield* TerminalManager.TerminalManager; - - const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) => - logCleanupCauseUnlessInterrupted({ - effect: providerService.stopSession({ threadId }), - message: "thread deletion cleanup skipped provider session stop", - threadId, - }); - - const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) => - logCleanupCauseUnlessInterrupted({ - effect: terminalManager.close({ threadId, deleteHistory: true }), - message: "thread deletion cleanup skipped terminal close", - threadId, - }); - - const processThreadDeleted = Effect.fn("processThreadDeleted")(function* ( - event: ThreadDeletedEvent, - ) { - const { threadId } = event.payload; - yield* stopProviderSession(threadId); - yield* closeThreadTerminals(threadId); - }); - - const processThreadDeletedSafely = (event: ThreadDeletedEvent) => - processThreadDeleted(event).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning("thread deletion reactor failed to process event", { - eventType: event.type, - threadId: event.payload.threadId, - cause: Cause.pretty(cause), - }); - }), - ); - - const worker = yield* makeDrainableWorker(processThreadDeletedSafely); - - const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () { - yield* forkParked( - Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { - if (event.type !== "thread.deleted") { - return Effect.void; - } - return worker.enqueue(event); - }), - ); - }); - - return { - start, - drain: worker.drain, - } satisfies ThreadDeletionReactorShape; -}); - -export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make); diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.ts deleted file mode 100644 index 24c65900b2..0000000000 --- a/apps/server/src/orchestration/Normalizer.ts +++ /dev/null @@ -1,179 +0,0 @@ -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; -import { - type ClientOrchestrationCommand, - type IsoDateTime, - type OrchestrationCommand, - OrchestrationDispatchCommandError, - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, -} from "@t3tools/contracts"; - -import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts"; -import { ServerConfig } from "../config.ts"; -import { parseBase64DataUrl } from "../imageMime.ts"; -import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; - -export const canonicalizeClientCommandTimestamps = ( - command: ClientOrchestrationCommand, - receivedAt: IsoDateTime, -): ClientOrchestrationCommand => { - const canonicalCommand = - "createdAt" in command - ? { - ...command, - createdAt: receivedAt, - } - : command; - - if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) { - return canonicalCommand; - } - - return { - ...canonicalCommand, - bootstrap: { - ...canonicalCommand.bootstrap, - createThread: { - ...canonicalCommand.bootstrap.createThread, - createdAt: receivedAt, - }, - }, - }; -}; - -export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) => - Effect.gen(function* () { - const receivedAt = DateTime.formatIso(yield* DateTime.now); - const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; - const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - - const normalizeProjectWorkspaceRoot = (workspaceRoot: string) => - workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe( - Effect.mapError( - (cause) => - new OrchestrationDispatchCommandError({ - message: cause.message, - }), - ), - ); - - const normalizeProjectWorkspaceRootForCreate = ( - workspaceRoot: string, - createIfMissing: boolean | undefined, - ) => - workspacePaths - .normalizeWorkspaceRoot(workspaceRoot, { - createIfMissing: createIfMissing === true, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestrationDispatchCommandError({ - message: cause.message, - }), - ), - ); - - if (canonicalCommand.type === "project.create") { - return { - ...canonicalCommand, - workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate( - canonicalCommand.workspaceRoot, - canonicalCommand.createWorkspaceRootIfMissing, - ), - createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true, - } satisfies OrchestrationCommand; - } - - if ( - canonicalCommand.type === "project.meta.update" && - canonicalCommand.workspaceRoot !== undefined - ) { - return { - ...canonicalCommand, - workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot), - } satisfies OrchestrationCommand; - } - - if (canonicalCommand.type !== "thread.turn.start") { - return canonicalCommand as OrchestrationCommand; - } - - const normalizedAttachments = yield* Effect.forEach( - canonicalCommand.message.attachments, - (attachment) => - Effect.gen(function* () { - const parsed = parseBase64DataUrl(attachment.dataUrl); - if (!parsed || !parsed.mimeType.startsWith("image/")) { - return yield* new OrchestrationDispatchCommandError({ - message: `Invalid image attachment payload for '${attachment.name}'.`, - }); - } - - const bytes = Buffer.from(parsed.base64, "base64"); - if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - return yield* new OrchestrationDispatchCommandError({ - message: `Image attachment '${attachment.name}' is empty or too large.`, - }); - } - - const attachmentId = createAttachmentId(canonicalCommand.threadId); - if (!attachmentId) { - return yield* new OrchestrationDispatchCommandError({ - message: "Failed to create a safe attachment id.", - }); - } - - const persistedAttachment = { - type: "image" as const, - id: attachmentId, - name: attachment.name, - mimeType: parsed.mimeType.toLowerCase(), - sizeBytes: bytes.byteLength, - }; - - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment: persistedAttachment, - }); - if (!attachmentPath) { - return yield* new OrchestrationDispatchCommandError({ - message: `Failed to resolve persisted path for '${attachment.name}'.`, - }); - } - - yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe( - Effect.mapError( - () => - new OrchestrationDispatchCommandError({ - message: `Failed to create attachment directory for '${attachment.name}'.`, - }), - ), - ); - yield* fileSystem.writeFile(attachmentPath, bytes).pipe( - Effect.mapError( - () => - new OrchestrationDispatchCommandError({ - message: `Failed to persist attachment '${attachment.name}'.`, - }), - ), - ); - - return persistedAttachment; - }), - { concurrency: 1 }, - ); - - return { - ...canonicalCommand, - message: { - ...canonicalCommand.message, - attachments: normalizedAttachments, - }, - } satisfies OrchestrationCommand; - }); diff --git a/apps/server/src/orchestration/Services/CheckpointReactor.ts b/apps/server/src/orchestration/Services/CheckpointReactor.ts deleted file mode 100644 index bd3ee3e88f..0000000000 --- a/apps/server/src/orchestration/Services/CheckpointReactor.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * CheckpointReactor - Checkpoint reaction service interface. - * - * Owns background workers that react to orchestration checkpoint lifecycle - * events and apply checkpoint side effects. - * - * @module CheckpointReactor - */ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Scope from "effect/Scope"; - -/** - * CheckpointReactorShape - Service API for checkpoint reactor lifecycle. - */ -export interface CheckpointReactorShape { - /** - * Start the checkpoint reactor. - * - * The returned effect must be run in a scope so all worker fibers can be - * finalized on shutdown. - * - * Consumes both orchestration-domain and provider-runtime events via an - * internal queue. - */ - readonly start: () => Effect.Effect; - - /** - * Resolves when the internal processing queue is empty and idle. - * Intended for test use to replace timing-sensitive sleeps. - */ - readonly drain: Effect.Effect; -} - -/** - * CheckpointReactor - Service tag for checkpoint reactor workers. - */ -export class CheckpointReactor extends Context.Service()( - "t3/orchestration/Services/CheckpointReactor", -) {} diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.ts index f8bcfd76ac..035aba9418 100644 --- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts @@ -1,16 +1,16 @@ /** - * OrchestrationEngineService - Service interface for orchestration command handling. + * Historical name for the application event-sourcing engine. * - * Owns command validation/dispatch and in-memory read-model updates backed by - * `OrchestrationEventStore` persistence. It does not own provider process - * management or transport concerns (e.g. websocket request parsing). + * This is not the agent orchestrator. It retains serialized project-command + * validation, append, receipt, and projection transactions. Agent execution is + * owned by orchestration V2, whose thread events use the same event store. * * Uses Effect `Context.Service` for dependency injection. Command dispatch, * replay, and unknown-input decoding all return typed domain errors. * * @module OrchestrationEngineService */ -import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts"; +import type { OrchestrationEvent, ProjectOrchestrationCommand } from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; import type * as Stream from "effect/Stream"; @@ -47,7 +47,7 @@ export interface OrchestrationEngineShape { * command receipts. */ readonly dispatch: ( - command: OrchestrationCommand, + command: ProjectOrchestrationCommand, ) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>; /** diff --git a/apps/server/src/orchestration/Services/OrchestrationReactor.ts b/apps/server/src/orchestration/Services/OrchestrationReactor.ts deleted file mode 100644 index eb2d95954b..0000000000 --- a/apps/server/src/orchestration/Services/OrchestrationReactor.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * OrchestrationReactor - Composite orchestration reactor service interface. - * - * Coordinates startup of orchestration runtime reactors that translate domain - * events into downstream side effects. - * - * @module OrchestrationReactor - */ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Scope from "effect/Scope"; - -/** - * OrchestrationReactorShape - Service API for orchestration reactor lifecycle. - */ -export interface OrchestrationReactorShape { - /** - * Start orchestration-side reactors for provider/runtime/checkpoint flows. - * - * The returned effect must be run in a scope so all worker fibers can be - * finalized on shutdown. - */ - readonly start: () => Effect.Effect; -} - -/** - * OrchestrationReactor - Service tag for orchestration reactor coordination. - */ -export class OrchestrationReactor extends Context.Service< - OrchestrationReactor, - OrchestrationReactorShape ->()("t3/orchestration/Services/OrchestrationReactor") {} diff --git a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts deleted file mode 100644 index 65aa9949fe..0000000000 --- a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * ProviderCommandReactor - Provider command reaction service interface. - * - * Owns background workers that react to orchestration intent events and - * dispatch provider-side command execution. - * - * @module ProviderCommandReactor - */ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Scope from "effect/Scope"; - -/** - * ProviderCommandReactorShape - Service API for provider command reactors. - */ -export interface ProviderCommandReactorShape { - /** - * Start reacting to provider-intent orchestration domain events. - * - * The returned effect must be run in a scope so all worker fibers can be - * finalized on shutdown. - * - * Filters orchestration domain events to provider-intent types before - * processing. - */ - readonly start: () => Effect.Effect; - - /** - * Resolves when the internal processing queue is empty and idle. - * Intended for test use to replace timing-sensitive sleeps. - */ - readonly drain: Effect.Effect; -} - -/** - * ProviderCommandReactor - Service tag for provider command reaction workers. - */ -export class ProviderCommandReactor extends Context.Service< - ProviderCommandReactor, - ProviderCommandReactorShape ->()("t3/orchestration/Services/ProviderCommandReactor") {} diff --git a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts deleted file mode 100644 index b6fa2711b9..0000000000 --- a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * ProviderRuntimeIngestionService - Provider runtime ingestion service interface. - * - * Owns background workers that consume provider runtime streams and emit - * orchestration commands/events. - * - * @module ProviderRuntimeIngestionService - */ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Scope from "effect/Scope"; - -/** - * ProviderRuntimeIngestionShape - Service API for runtime ingestion lifecycle. - */ -export interface ProviderRuntimeIngestionShape { - /** - * Start ingesting provider runtime events into orchestration commands. - * - * The returned effect must be run in a scope so all worker fibers can be - * finalized on shutdown. - * - * Uses an internal queue and continues after non-interrupt failures by - * logging warnings. - */ - readonly start: () => Effect.Effect; - - /** - * Resolves when the internal processing queue is empty and idle. - * Intended for test use to replace timing-sensitive sleeps. - */ - readonly drain: Effect.Effect; -} - -/** - * ProviderRuntimeIngestionService - Service tag for runtime ingestion workers. - */ -export class ProviderRuntimeIngestionService extends Context.Service< - ProviderRuntimeIngestionService, - ProviderRuntimeIngestionShape ->()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {} diff --git a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts deleted file mode 100644 index 0b880ee699..0000000000 --- a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts. - * - * This service exists to expose short-lived orchestration milestones that are - * useful in tests and harnesses but are not part of the production runtime - * event model. `CheckpointReactor` publishes receipts such as baseline capture, - * diff finalization, and turn-processing quiescence so integration tests can - * wait for those exact points without inferring them indirectly from persisted - * state. - * - * Production code should only call `publish`. Test code may subscribe via - * `streamEventsForTest`, which is intentionally named to make the intended - * usage explicit. - * - * @module RuntimeReceiptBus - */ -import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts"; -import * as Schema from "effect/Schema"; -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Stream from "effect/Stream"; - -export const CheckpointBaselineCapturedReceipt = Schema.Struct({ - type: Schema.Literal("checkpoint.baseline.captured"), - threadId: ThreadId, - checkpointTurnCount: NonNegativeInt, - checkpointRef: CheckpointRef, - createdAt: IsoDateTime, -}); -export type CheckpointBaselineCapturedReceipt = typeof CheckpointBaselineCapturedReceipt.Type; - -export const CheckpointDiffFinalizedReceipt = Schema.Struct({ - type: Schema.Literal("checkpoint.diff.finalized"), - threadId: ThreadId, - turnId: TurnId, - checkpointTurnCount: NonNegativeInt, - checkpointRef: CheckpointRef, - status: Schema.Literals(["ready", "missing", "error"]), - createdAt: IsoDateTime, -}); -export type CheckpointDiffFinalizedReceipt = typeof CheckpointDiffFinalizedReceipt.Type; - -export const TurnProcessingQuiescedReceipt = Schema.Struct({ - type: Schema.Literal("turn.processing.quiesced"), - threadId: ThreadId, - turnId: TurnId, - checkpointTurnCount: NonNegativeInt, - createdAt: IsoDateTime, -}); -export type TurnProcessingQuiescedReceipt = typeof TurnProcessingQuiescedReceipt.Type; - -export const OrchestrationRuntimeReceipt = Schema.Union([ - CheckpointBaselineCapturedReceipt, - CheckpointDiffFinalizedReceipt, - TurnProcessingQuiescedReceipt, -]); -export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Type; - -export interface RuntimeReceiptBusShape { - readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect; - readonly streamEventsForTest: Stream.Stream; -} - -export class RuntimeReceiptBus extends Context.Service()( - "t3/orchestration/Services/RuntimeReceiptBus", -) {} diff --git a/apps/server/src/orchestration/Services/ThreadDeletionReactor.ts b/apps/server/src/orchestration/Services/ThreadDeletionReactor.ts deleted file mode 100644 index 7c6718965a..0000000000 --- a/apps/server/src/orchestration/Services/ThreadDeletionReactor.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * ThreadDeletionReactor - Thread deletion cleanup reactor service interface. - * - * Owns background workers that react to thread deletion domain events and - * perform best-effort runtime cleanup for provider sessions and terminals. - * - * @module ThreadDeletionReactor - */ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Scope from "effect/Scope"; - -/** - * ThreadDeletionReactorShape - Service API for thread deletion cleanup. - */ -export interface ThreadDeletionReactorShape { - /** - * Start reacting to thread.deleted orchestration domain events. - * - * The returned effect must be run in a scope so all worker fibers can be - * finalized on shutdown. - */ - readonly start: () => Effect.Effect; - - /** - * Resolves when the internal processing queue is empty and idle. - * Intended for test use to replace timing-sensitive sleeps. - */ - readonly drain: Effect.Effect; -} - -/** - * ThreadDeletionReactor - Service tag for thread deletion cleanup workers. - */ -export class ThreadDeletionReactor extends Context.Service< - ThreadDeletionReactor, - ThreadDeletionReactorShape ->()("t3/orchestration/Services/ThreadDeletionReactor") {} diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts deleted file mode 100644 index 9531cd5c3a..0000000000 --- a/apps/server/src/orchestration/commandInvariants.test.ts +++ /dev/null @@ -1,223 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { - MessageId, - CommandId, - DEFAULT_PROVIDER_INTERACTION_MODE, - ProjectId, - ThreadId, - type OrchestrationCommand, - type OrchestrationReadModel, - ProviderInstanceId, -} from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; - -import { - findThreadById, - listThreadsByProjectId, - requireNonNegativeInteger, - requireThread, - requireThreadAbsent, -} from "./commandInvariants.ts"; - -const now = "2026-01-01T00:00:00.000Z"; - -const readModel: OrchestrationReadModel = { - snapshotSequence: 2, - updatedAt: now, - projects: [ - { - id: ProjectId.make("project-a"), - title: "Project A", - workspaceRoot: "/tmp/project-a", - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - { - id: ProjectId.make("project-b"), - title: "Project B", - workspaceRoot: "/tmp/project-b", - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: [ - { - id: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - title: "Thread A", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestTurn: null, - messages: [], - session: null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - }, - { - id: ThreadId.make("thread-2"), - projectId: ProjectId.make("project-b"), - title: "Thread B", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestTurn: null, - messages: [], - session: null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - }, - ], -}; - -const messageSendCommand: OrchestrationCommand = { - type: "thread.turn.start", - commandId: CommandId.make("cmd-1"), - threadId: ThreadId.make("thread-1"), - message: { - messageId: MessageId.make("msg-1"), - role: "user", - text: "hello", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: now, -}; - -describe("commandInvariants", () => { - it("finds threads by id and project", () => { - expect(findThreadById(readModel, ThreadId.make("thread-1"))?.projectId).toBe("project-a"); - expect(findThreadById(readModel, ThreadId.make("missing"))).toBeUndefined(); - expect( - listThreadsByProjectId(readModel, ProjectId.make("project-b")).map((thread) => thread.id), - ).toEqual([ThreadId.make("thread-2")]); - }); - - it("requires existing thread", async () => { - const thread = await Effect.runPromise( - requireThread({ - readModel, - command: messageSendCommand, - threadId: ThreadId.make("thread-1"), - }), - ); - expect(thread.id).toBe(ThreadId.make("thread-1")); - - await expect( - Effect.runPromise( - requireThread({ - readModel, - command: messageSendCommand, - threadId: ThreadId.make("missing"), - }), - ), - ).rejects.toThrow("does not exist"); - }); - - it("requires missing thread for create flows", async () => { - await Effect.runPromise( - requireThreadAbsent({ - readModel, - command: { - type: "thread.create", - commandId: CommandId.make("cmd-2"), - threadId: ThreadId.make("thread-3"), - projectId: ProjectId.make("project-a"), - title: "new", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - }, - threadId: ThreadId.make("thread-3"), - }), - ); - - await expect( - Effect.runPromise( - requireThreadAbsent({ - readModel, - command: { - type: "thread.create", - commandId: CommandId.make("cmd-3"), - threadId: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - title: "dup", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - }, - threadId: ThreadId.make("thread-1"), - }), - ), - ).rejects.toThrow("already exists"); - }); - - it("requires non-negative integers", async () => { - await Effect.runPromise( - requireNonNegativeInteger({ - commandType: "thread.checkpoint.revert", - field: "turnCount", - value: 0, - }), - ); - - await expect( - Effect.runPromise( - requireNonNegativeInteger({ - commandType: "thread.checkpoint.revert", - field: "turnCount", - value: -1, - }), - ), - ).rejects.toThrow("greater than or equal to 0"); - }); -}); diff --git a/apps/server/src/orchestration/decider.delete.test.ts b/apps/server/src/orchestration/decider.delete.test.ts deleted file mode 100644 index fea36b5717..0000000000 --- a/apps/server/src/orchestration/decider.delete.test.ts +++ /dev/null @@ -1,217 +0,0 @@ -import { - CommandId, - DEFAULT_PROVIDER_INTERACTION_MODE, - EventId, - ProjectId, - ThreadId, - type OrchestrationCommand, - type OrchestrationEvent, - ProviderInstanceId, -} from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { expect, it } from "@effect/vitest"; - -import { decideOrchestrationCommand } from "./decider.ts"; -import { createEmptyReadModel, projectEvent } from "./projector.ts"; - -const asCommandId = (value: string): CommandId => CommandId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asProjectId = (value: string): ProjectId => ProjectId.make(value); -const asThreadId = (value: string): ThreadId => ThreadId.make(value); - -const seedReadModel = Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const withProject = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create"), - aggregateKind: "project", - aggregateId: asProjectId("project-delete"), - type: "project.created", - occurredAt: now, - commandId: asCommandId("cmd-project-create"), - causationEventId: null, - correlationId: asCommandId("cmd-project-create"), - metadata: {}, - payload: { - projectId: asProjectId("project-delete"), - title: "Project Delete", - workspaceRoot: "/tmp/project-delete", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - const withFirstThread = yield* projectEvent(withProject, { - sequence: 2, - eventId: asEventId("evt-thread-create-1"), - aggregateKind: "thread", - aggregateId: asThreadId("thread-delete-1"), - type: "thread.created", - occurredAt: now, - commandId: asCommandId("cmd-thread-create-1"), - causationEventId: null, - correlationId: asCommandId("cmd-thread-create-1"), - metadata: {}, - payload: { - threadId: asThreadId("thread-delete-1"), - projectId: asProjectId("project-delete"), - title: "Thread Delete 1", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - return yield* projectEvent(withFirstThread, { - sequence: 3, - eventId: asEventId("evt-thread-create-2"), - aggregateKind: "thread", - aggregateId: asThreadId("thread-delete-2"), - type: "thread.created", - occurredAt: now, - commandId: asCommandId("cmd-thread-create-2"), - causationEventId: null, - correlationId: asCommandId("cmd-thread-create-2"), - metadata: {}, - payload: { - threadId: asThreadId("thread-delete-2"), - projectId: asProjectId("project-delete"), - title: "Thread Delete 2", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); -}); - -type PlannedEvent = Omit; - -function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray) { - const events = Array.isArray(event) ? event : [event]; - return events.map((entry) => { - switch (entry.type) { - case "thread.deleted": - return { - type: entry.type, - aggregateKind: entry.aggregateKind, - aggregateId: entry.aggregateId, - commandId: entry.commandId, - correlationId: entry.correlationId, - payload: { - threadId: entry.payload.threadId, - }, - }; - case "project.deleted": - return { - type: entry.type, - aggregateKind: entry.aggregateKind, - aggregateId: entry.aggregateId, - commandId: entry.commandId, - correlationId: entry.correlationId, - payload: { - projectId: entry.payload.projectId, - }, - }; - default: - return entry; - } - }); -} - -it.layer(NodeServices.layer)("decider deletion flows", (it) => { - it.effect("rejects deleting a non-empty project without force", () => - Effect.gen(function* () { - const readModel = yield* seedReadModel; - const error = yield* Effect.flip( - decideOrchestrationCommand({ - command: { - type: "project.delete", - commandId: asCommandId("cmd-project-delete-no-force"), - projectId: asProjectId("project-delete"), - }, - readModel, - }), - ); - expect(error.message).toContain("cannot be deleted without force=true"); - }), - ); - - it.effect("reuses thread.delete semantics when force-deleting a non-empty project", () => - Effect.gen(function* () { - const readModel = yield* seedReadModel; - const projectDeleteCommand: Extract = { - type: "project.delete", - commandId: asCommandId("cmd-project-delete-force"), - projectId: asProjectId("project-delete"), - force: true, - }; - - const forcedResult = yield* decideOrchestrationCommand({ - command: projectDeleteCommand, - readModel, - }); - const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult]; - - expect(forcedEvents.map((event) => event.type)).toEqual([ - "thread.deleted", - "thread.deleted", - "project.deleted", - ]); - - let sequentialReadModel = readModel; - let nextSequence = readModel.snapshotSequence; - const sequentialEvents: PlannedEvent[] = []; - for (const nextCommand of [ - { - type: "thread.delete", - commandId: projectDeleteCommand.commandId, - threadId: asThreadId("thread-delete-1"), - }, - { - type: "thread.delete", - commandId: projectDeleteCommand.commandId, - threadId: asThreadId("thread-delete-2"), - }, - { - type: "project.delete", - commandId: projectDeleteCommand.commandId, - projectId: asProjectId("project-delete"), - }, - ] satisfies ReadonlyArray) { - const decided = yield* decideOrchestrationCommand({ - command: nextCommand, - readModel: sequentialReadModel, - }); - const nextEvents = Array.isArray(decided) ? decided : [decided]; - sequentialEvents.push(...nextEvents); - for (const nextEvent of nextEvents) { - nextSequence += 1; - sequentialReadModel = yield* projectEvent(sequentialReadModel, { - ...nextEvent, - sequence: nextSequence, - }); - } - } - - expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents)); - }), - ); -}); diff --git a/apps/server/src/orchestration/decider.projectScripts.test.ts b/apps/server/src/orchestration/decider.projectScripts.test.ts deleted file mode 100644 index a0c0684073..0000000000 --- a/apps/server/src/orchestration/decider.projectScripts.test.ts +++ /dev/null @@ -1,460 +0,0 @@ -import { - CommandId, - DEFAULT_PROVIDER_INTERACTION_MODE, - EventId, - MessageId, - ProjectId, - ThreadId, - ProviderInstanceId, -} from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; -import { expect, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as NodeServices from "@effect/platform-node/NodeServices"; - -import { decideOrchestrationCommand } from "./decider.ts"; -import { createEmptyReadModel, projectEvent } from "./projector.ts"; - -const asEventId = (value: string): EventId => EventId.make(value); -const asProjectId = (value: string): ProjectId => ProjectId.make(value); -const asMessageId = (value: string): MessageId => MessageId.make(value); -it.layer(NodeServices.layer)("decider project scripts", (it) => { - it.effect("emits empty scripts on project.create", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const readModel = createEmptyReadModel(now); - - const result = yield* decideOrchestrationCommand({ - command: { - type: "project.create", - commandId: CommandId.make("cmd-project-create-scripts"), - projectId: asProjectId("project-scripts"), - title: "Scripts", - workspaceRoot: "/tmp/scripts", - createdAt: now, - }, - readModel, - }); - - const event = Array.isArray(result) ? result[0] : result; - expect(event.type).toBe("project.created"); - expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]); - }), - ); - - it.effect("propagates scripts in project.meta.update payload", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const readModel = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create-scripts"), - aggregateKind: "project", - aggregateId: asProjectId("project-scripts"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create-scripts"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create-scripts"), - metadata: {}, - payload: { - projectId: asProjectId("project-scripts"), - title: "Scripts", - workspaceRoot: "/tmp/scripts", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - const scripts = [ - { - id: "lint", - name: "Lint", - command: "bun run lint", - icon: "lint", - runOnWorktreeCreate: false, - }, - ] as const; - - const result = yield* decideOrchestrationCommand({ - command: { - type: "project.meta.update", - commandId: CommandId.make("cmd-project-update-scripts"), - projectId: asProjectId("project-scripts"), - scripts: Array.from(scripts), - }, - readModel, - }); - - const event = Array.isArray(result) ? result[0] : result; - expect(event.type).toBe("project.meta-updated"); - expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts); - }), - ); - - it.effect("rejects project.create for an active workspace root that already exists", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const readModel = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create"), - aggregateKind: "project", - aggregateId: asProjectId("project-existing"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create"), - metadata: {}, - payload: { - projectId: asProjectId("project-existing"), - title: "Project", - workspaceRoot: "/tmp/project", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - const failure = yield* Effect.flip( - decideOrchestrationCommand({ - command: { - type: "project.create", - commandId: CommandId.make("cmd-project-create-duplicate-root"), - projectId: asProjectId("project-duplicate-root"), - title: "Duplicate Project", - workspaceRoot: "/tmp/project/", - createdAt: now, - }, - readModel, - }), - ); - - expect(failure.message).toContain( - "Active project 'project-existing' already exists for workspace root '/tmp/project'.", - ); - }), - ); - - it.effect("rejects project.meta.update when moving onto another active workspace root", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const withFirstProject = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create-first"), - aggregateKind: "project", - aggregateId: asProjectId("project-first"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create-first"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create-first"), - metadata: {}, - payload: { - projectId: asProjectId("project-first"), - title: "First", - workspaceRoot: "/tmp/project-first", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - const readModel = yield* projectEvent(withFirstProject, { - sequence: 2, - eventId: asEventId("evt-project-create-second"), - aggregateKind: "project", - aggregateId: asProjectId("project-second"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create-second"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create-second"), - metadata: {}, - payload: { - projectId: asProjectId("project-second"), - title: "Second", - workspaceRoot: "/tmp/project-second", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - const failure = yield* Effect.flip( - decideOrchestrationCommand({ - command: { - type: "project.meta.update", - commandId: CommandId.make("cmd-project-update-duplicate-root"), - projectId: asProjectId("project-second"), - workspaceRoot: "/tmp/project-first", - }, - readModel, - }), - ); - - expect(failure.message).toContain( - "Active project 'project-first' already exists for workspace root '/tmp/project-first'.", - ); - }), - ); - - it.effect("emits user message and turn-start-requested events for thread.turn.start", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const withProject = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create"), - aggregateKind: "project", - aggregateId: asProjectId("project-1"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create"), - metadata: {}, - payload: { - projectId: asProjectId("project-1"), - title: "Project", - workspaceRoot: "/tmp/project", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - const readModel = yield* projectEvent(withProject, { - sequence: 2, - eventId: asEventId("evt-thread-create"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.created", - occurredAt: now, - commandId: CommandId.make("cmd-thread-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-thread-create"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - projectId: asProjectId("project-1"), - title: "Thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - const result = yield* decideOrchestrationCommand({ - command: { - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start"), - threadId: ThreadId.make("thread-1"), - message: { - messageId: asMessageId("message-user-1"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ - { id: "reasoningEffort", value: "high" }, - { id: "fastMode", value: true }, - ]), - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: now, - }, - readModel, - }); - - expect(Array.isArray(result)).toBe(true); - const events = Array.isArray(result) ? result : [result]; - expect(events).toHaveLength(2); - expect(events[0]?.type).toBe("thread.message-sent"); - const turnStartEvent = events[1]; - expect(turnStartEvent?.type).toBe("thread.turn-start-requested"); - expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null); - if (turnStartEvent?.type !== "thread.turn-start-requested") { - return; - } - expect(turnStartEvent.payload).toMatchObject({ - threadId: ThreadId.make("thread-1"), - messageId: asMessageId("message-user-1"), - modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ - { id: "reasoningEffort", value: "high" }, - { id: "fastMode", value: true }, - ]), - runtimeMode: "approval-required", - }); - }), - ); - - it.effect("emits thread.runtime-mode-set from thread.runtime-mode.set", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const withProject = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create"), - aggregateKind: "project", - aggregateId: asProjectId("project-1"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create"), - metadata: {}, - payload: { - projectId: asProjectId("project-1"), - title: "Project", - workspaceRoot: "/tmp/project", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - const readModel = yield* projectEvent(withProject, { - sequence: 2, - eventId: asEventId("evt-thread-create"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.created", - occurredAt: now, - commandId: CommandId.make("cmd-thread-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-thread-create"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - projectId: asProjectId("project-1"), - title: "Thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - const result = yield* decideOrchestrationCommand({ - command: { - type: "thread.runtime-mode.set", - commandId: CommandId.make("cmd-runtime-mode-set"), - threadId: ThreadId.make("thread-1"), - runtimeMode: "approval-required", - createdAt: now, - }, - readModel, - }); - - const singleResult = Array.isArray(result) ? null : result; - if (singleResult === null) { - throw new Error("Expected a single runtime-mode-set event."); - } - expect(singleResult).toMatchObject({ - type: "thread.runtime-mode-set", - payload: { - threadId: ThreadId.make("thread-1"), - runtimeMode: "approval-required", - }, - }); - }), - ); - - it.effect("emits thread.interaction-mode-set from thread.interaction-mode.set", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const initial = createEmptyReadModel(now); - const withProject = yield* projectEvent(initial, { - sequence: 1, - eventId: asEventId("evt-project-create"), - aggregateKind: "project", - aggregateId: asProjectId("project-1"), - type: "project.created", - occurredAt: now, - commandId: CommandId.make("cmd-project-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-project-create"), - metadata: {}, - payload: { - projectId: asProjectId("project-1"), - title: "Project", - workspaceRoot: "/tmp/project", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - const readModel = yield* projectEvent(withProject, { - sequence: 2, - eventId: asEventId("evt-thread-create"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.created", - occurredAt: now, - commandId: CommandId.make("cmd-thread-create"), - causationEventId: null, - correlationId: CommandId.make("cmd-thread-create"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - projectId: asProjectId("project-1"), - title: "Thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - const result = yield* decideOrchestrationCommand({ - command: { - type: "thread.interaction-mode.set", - commandId: CommandId.make("cmd-interaction-mode-set"), - threadId: ThreadId.make("thread-1"), - interactionMode: "plan", - createdAt: now, - }, - readModel, - }); - - const singleResult = Array.isArray(result) ? null : result; - if (singleResult === null) { - throw new Error("Expected a single interaction-mode-set event."); - } - expect(singleResult).toMatchObject({ - type: "thread.interaction-mode-set", - payload: { - threadId: ThreadId.make("thread-1"), - interactionMode: "plan", - }, - }); - }), - ); -}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 5e5579ae93..9ece61aa0a 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -250,7 +250,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" title: command.title, workspaceRoot: command.workspaceRoot, defaultModelSelection: command.defaultModelSelection ?? null, - scripts: [], + scripts: command.scripts ?? [], createdAt: command.createdAt, updatedAt: command.createdAt, }, diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts deleted file mode 100644 index 9c07a31202..0000000000 --- a/apps/server/src/orchestration/projector.test.ts +++ /dev/null @@ -1,959 +0,0 @@ -import { - CommandId, - EventId, - ProjectId, - ProviderDriverKind, - ThreadId, - type OrchestrationEvent, -} from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import { describe, expect, it } from "vite-plus/test"; - -import { createEmptyReadModel, projectEvent } from "./projector.ts"; - -function makeEvent(input: { - sequence: number; - type: OrchestrationEvent["type"]; - occurredAt: string; - aggregateKind: OrchestrationEvent["aggregateKind"]; - aggregateId: string; - commandId: string | null; - payload: unknown; -}): OrchestrationEvent { - return { - sequence: input.sequence, - eventId: EventId.make(`event-${input.sequence}`), - type: input.type, - aggregateKind: input.aggregateKind, - aggregateId: - input.aggregateKind === "project" - ? ProjectId.make(input.aggregateId) - : ThreadId.make(input.aggregateId), - occurredAt: input.occurredAt, - commandId: input.commandId === null ? null : CommandId.make(input.commandId), - causationEventId: null, - correlationId: null, - metadata: {}, - payload: input.payload as never, - } as OrchestrationEvent; -} - -describe("orchestration projector", () => { - it("applies thread.created events", async () => { - const now = "2026-01-01T00:00:00.000Z"; - const model = createEmptyReadModel(now); - - const next = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: now, - commandId: "cmd-thread-create", - payload: { - threadId: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }), - ), - ); - - expect(next.snapshotSequence).toBe(1); - expect(next.threads).toEqual([ - { - id: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - instanceId: "codex", - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - snoozedUntil: null, - snoozedAt: null, - deletedAt: null, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - session: null, - }, - ]); - }); - - it("fails when event payload cannot be decoded by runtime schema", async () => { - const now = "2026-01-01T00:00:00.000Z"; - const model = createEmptyReadModel(now); - - await expect( - Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: now, - commandId: "cmd-invalid", - payload: { - // missing required threadId - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5-codex", - }, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }), - ), - ), - ).rejects.toBeDefined(); - }); - - it("applies thread.archived and thread.unarchived events", async () => { - const now = "2026-01-01T00:00:00.000Z"; - const later = "2026-01-01T00:00:01.000Z"; - const created = await Effect.runPromise( - projectEvent( - createEmptyReadModel(now), - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: now, - commandId: "cmd-thread-create", - payload: { - threadId: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }), - ), - ); - - const archived = await Effect.runPromise( - projectEvent( - created, - makeEvent({ - sequence: 2, - type: "thread.archived", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: later, - commandId: "cmd-thread-archive", - payload: { - threadId: "thread-1", - archivedAt: later, - updatedAt: later, - }, - }), - ), - ); - expect(archived.threads[0]?.archivedAt).toBe(later); - - const unarchived = await Effect.runPromise( - projectEvent( - archived, - makeEvent({ - sequence: 3, - type: "thread.unarchived", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: later, - commandId: "cmd-thread-unarchive", - payload: { - threadId: "thread-1", - updatedAt: later, - }, - }), - ), - ); - expect(unarchived.threads[0]?.archivedAt).toBeNull(); - }); - - it("keeps projector forward-compatible for unhandled event types", async () => { - const now = "2026-01-01T00:00:00.000Z"; - const model = createEmptyReadModel(now); - - const next = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 7, - type: "thread.turn-start-requested", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-01-01T00:00:00.000Z", - commandId: "cmd-unhandled", - payload: { - threadId: "thread-1", - messageId: "message-1", - runtimeMode: "approval-required", - createdAt: "2026-01-01T00:00:00.000Z", - }, - }), - ), - ); - - expect(next.snapshotSequence).toBe(7); - expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z"); - expect(next.threads).toEqual([]); - }); - - it("tracks latest turn id from session lifecycle events", async () => { - const createdAt = "2026-02-23T08:00:00.000Z"; - const startedAt = "2026-02-23T08:00:05.000Z"; - const model = createEmptyReadModel(createdAt); - - const afterCreate = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: createdAt, - commandId: "cmd-create", - payload: { - threadId: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5.3-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - updatedAt: createdAt, - }, - }), - ), - ); - - const settledAt = "2026-02-23T08:01:00.000Z"; - const [afterRunning, afterReady] = await Effect.runPromise( - Effect.flatMap( - projectEvent( - afterCreate, - makeEvent({ - sequence: 2, - type: "thread.session-set", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: startedAt, - commandId: "cmd-running", - payload: { - threadId: "thread-1", - session: { - threadId: "thread-1", - status: "running", - providerName: "codex", - providerSessionId: "session-1", - providerThreadId: "provider-thread-1", - runtimeMode: "approval-required", - activeTurnId: "turn-1", - lastError: null, - updatedAt: startedAt, - }, - }, - }), - ), - (running) => - Effect.map( - projectEvent( - running, - makeEvent({ - sequence: 3, - type: "thread.session-set", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: settledAt, - commandId: "cmd-ready", - payload: { - threadId: "thread-1", - session: { - threadId: "thread-1", - status: "ready", - providerName: "codex", - providerSessionId: "session-1", - providerThreadId: "provider-thread-1", - runtimeMode: "approval-required", - activeTurnId: null, - lastError: null, - updatedAt: settledAt, - }, - }, - }), - ), - (ready) => [running, ready] as const, - ), - ), - ); - - const thread = afterRunning.threads[0]; - expect(thread?.latestTurn?.turnId).toBe("turn-1"); - expect(thread?.session?.status).toBe("running"); - - // Leaving the "running" session status settles the running turn with the - // session timestamp as the turn end. - const settledThread = afterReady.threads[0]; - expect(settledThread?.latestTurn?.turnId).toBe("turn-1"); - expect(settledThread?.latestTurn?.state).toBe("completed"); - expect(settledThread?.latestTurn?.completedAt).toBe(settledAt); - }); - - it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => { - const createdAt = "2026-02-23T08:00:00.000Z"; - const updatedAt = "2026-02-23T08:00:05.000Z"; - const model = createEmptyReadModel(createdAt); - - const afterCreate = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: createdAt, - commandId: "cmd-create", - payload: { - threadId: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5.3-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - updatedAt: createdAt, - }, - }), - ), - ); - - const afterUpdate = await Effect.runPromise( - projectEvent( - afterCreate, - makeEvent({ - sequence: 2, - type: "thread.runtime-mode-set", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: updatedAt, - commandId: "cmd-runtime-mode-set", - payload: { - threadId: "thread-1", - runtimeMode: "approval-required", - updatedAt, - }, - }), - ), - ); - - expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required"); - expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt); - }); - - it("marks assistant messages completed with non-streaming updates", async () => { - const createdAt = "2026-02-23T09:00:00.000Z"; - const deltaAt = "2026-02-23T09:00:01.000Z"; - const completeAt = "2026-02-23T09:00:03.500Z"; - const model = createEmptyReadModel(createdAt); - - const afterCreate = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: createdAt, - commandId: "cmd-create", - payload: { - threadId: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5.3-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - updatedAt: createdAt, - }, - }), - ), - ); - - const afterDelta = await Effect.runPromise( - projectEvent( - afterCreate, - makeEvent({ - sequence: 2, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: deltaAt, - commandId: "cmd-delta", - payload: { - threadId: "thread-1", - messageId: "assistant:msg-1", - role: "assistant", - text: "hello", - turnId: "turn-1", - streaming: true, - createdAt: deltaAt, - updatedAt: deltaAt, - }, - }), - ), - ); - - const afterComplete = await Effect.runPromise( - projectEvent( - afterDelta, - makeEvent({ - sequence: 3, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: completeAt, - commandId: "cmd-complete", - payload: { - threadId: "thread-1", - messageId: "assistant:msg-1", - role: "assistant", - text: "", - turnId: "turn-1", - streaming: false, - createdAt: completeAt, - updatedAt: completeAt, - }, - }), - ), - ); - - const message = afterComplete.threads[0]?.messages[0]; - expect(message?.id).toBe("assistant:msg-1"); - expect(message?.text).toBe("hello"); - expect(message?.streaming).toBe(false); - expect(message?.updatedAt).toBe(completeAt); - }); - - it("prunes reverted turn messages from in-memory thread snapshot", async () => { - const createdAt = "2026-02-23T10:00:00.000Z"; - const model = createEmptyReadModel(createdAt); - - const afterCreate = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: createdAt, - commandId: "cmd-create", - payload: { - threadId: "thread-1", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5.3-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - updatedAt: createdAt, - }, - }), - ), - ); - - const events: ReadonlyArray = [ - makeEvent({ - sequence: 2, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:01.000Z", - commandId: "cmd-user-1", - payload: { - threadId: "thread-1", - messageId: "user-msg-1", - role: "user", - text: "First edit", - turnId: null, - streaming: false, - createdAt: "2026-02-23T10:00:01.000Z", - updatedAt: "2026-02-23T10:00:01.000Z", - }, - }), - makeEvent({ - sequence: 3, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:02.000Z", - commandId: "cmd-assistant-1", - payload: { - threadId: "thread-1", - messageId: "assistant-msg-1", - role: "assistant", - text: "Updated README to v2.\n", - turnId: "turn-1", - streaming: false, - createdAt: "2026-02-23T10:00:02.000Z", - updatedAt: "2026-02-23T10:00:02.000Z", - }, - }), - makeEvent({ - sequence: 4, - type: "thread.turn-diff-completed", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:02.500Z", - commandId: "cmd-turn-1-complete", - payload: { - threadId: "thread-1", - turnId: "turn-1", - checkpointTurnCount: 1, - checkpointRef: "refs/t3/checkpoints/thread-1/turn/1", - status: "ready", - files: [], - assistantMessageId: "assistant-msg-1", - completedAt: "2026-02-23T10:00:02.500Z", - }, - }), - makeEvent({ - sequence: 5, - type: "thread.activity-appended", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:02.750Z", - commandId: "cmd-activity-1", - payload: { - threadId: "thread-1", - activity: { - id: "activity-1", - tone: "tool", - kind: "tool.started", - summary: "Edit file started", - payload: { toolKind: "command" }, - turnId: "turn-1", - createdAt: "2026-02-23T10:00:02.750Z", - }, - }, - }), - makeEvent({ - sequence: 6, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:03.000Z", - commandId: "cmd-user-2", - payload: { - threadId: "thread-1", - messageId: "user-msg-2", - role: "user", - text: "Second edit", - turnId: null, - streaming: false, - createdAt: "2026-02-23T10:00:03.000Z", - updatedAt: "2026-02-23T10:00:03.000Z", - }, - }), - makeEvent({ - sequence: 7, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:04.000Z", - commandId: "cmd-assistant-2", - payload: { - threadId: "thread-1", - messageId: "assistant-msg-2", - role: "assistant", - text: "Updated README to v3.\n", - turnId: "turn-2", - streaming: false, - createdAt: "2026-02-23T10:00:04.000Z", - updatedAt: "2026-02-23T10:00:04.000Z", - }, - }), - makeEvent({ - sequence: 8, - type: "thread.turn-diff-completed", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:04.500Z", - commandId: "cmd-turn-2-complete", - payload: { - threadId: "thread-1", - turnId: "turn-2", - checkpointTurnCount: 2, - checkpointRef: "refs/t3/checkpoints/thread-1/turn/2", - status: "ready", - files: [], - assistantMessageId: "assistant-msg-2", - completedAt: "2026-02-23T10:00:04.500Z", - }, - }), - makeEvent({ - sequence: 9, - type: "thread.activity-appended", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:04.750Z", - commandId: "cmd-activity-2", - payload: { - threadId: "thread-1", - activity: { - id: "activity-2", - tone: "tool", - kind: "tool.completed", - summary: "Edit file complete", - payload: { toolKind: "command" }, - turnId: "turn-2", - createdAt: "2026-02-23T10:00:04.750Z", - }, - }, - }), - makeEvent({ - sequence: 10, - type: "thread.reverted", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: "2026-02-23T10:00:05.000Z", - commandId: "cmd-revert", - payload: { - threadId: "thread-1", - turnCount: 1, - }, - }), - ]; - - const afterRevert = await events.reduce>>( - (statePromise, event) => - statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), - Promise.resolve(afterCreate), - ); - - const thread = afterRevert.threads[0]; - expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual( - [ - { role: "user", text: "First edit" }, - { role: "assistant", text: "Updated README to v2.\n" }, - ], - ); - expect( - thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })), - ).toEqual([{ id: "activity-1", turnId: "turn-1" }]); - expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]); - expect(thread?.latestTurn?.turnId).toBe("turn-1"); - }); - - it("does not fallback-retain messages tied to removed turn IDs", async () => { - const createdAt = "2026-02-26T12:00:00.000Z"; - const model = createEmptyReadModel(createdAt); - - const afterCreate = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: createdAt, - commandId: "cmd-create-revert", - payload: { - threadId: "thread-revert", - projectId: "project-1", - title: "demo", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5.3-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - updatedAt: createdAt, - }, - }), - ), - ); - - const events: ReadonlyArray = [ - makeEvent({ - sequence: 2, - type: "thread.turn-diff-completed", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: "2026-02-26T12:00:01.000Z", - commandId: "cmd-turn-1", - payload: { - threadId: "thread-revert", - turnId: "turn-1", - checkpointTurnCount: 1, - checkpointRef: "refs/t3/checkpoints/thread-revert/turn/1", - status: "ready", - files: [], - assistantMessageId: "assistant-keep", - completedAt: "2026-02-26T12:00:01.000Z", - }, - }), - makeEvent({ - sequence: 3, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: "2026-02-26T12:00:01.100Z", - commandId: "cmd-assistant-keep", - payload: { - threadId: "thread-revert", - messageId: "assistant-keep", - role: "assistant", - text: "kept", - turnId: "turn-1", - streaming: false, - createdAt: "2026-02-26T12:00:01.100Z", - updatedAt: "2026-02-26T12:00:01.100Z", - }, - }), - makeEvent({ - sequence: 4, - type: "thread.turn-diff-completed", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: "2026-02-26T12:00:02.000Z", - commandId: "cmd-turn-2", - payload: { - threadId: "thread-revert", - turnId: "turn-2", - checkpointTurnCount: 2, - checkpointRef: "refs/t3/checkpoints/thread-revert/turn/2", - status: "ready", - files: [], - assistantMessageId: "assistant-remove", - completedAt: "2026-02-26T12:00:02.000Z", - }, - }), - makeEvent({ - sequence: 5, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: "2026-02-26T12:00:02.050Z", - commandId: "cmd-user-remove", - payload: { - threadId: "thread-revert", - messageId: "user-remove", - role: "user", - text: "removed", - turnId: "turn-2", - streaming: false, - createdAt: "2026-02-26T12:00:02.050Z", - updatedAt: "2026-02-26T12:00:02.050Z", - }, - }), - makeEvent({ - sequence: 6, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: "2026-02-26T12:00:02.100Z", - commandId: "cmd-assistant-remove", - payload: { - threadId: "thread-revert", - messageId: "assistant-remove", - role: "assistant", - text: "removed", - turnId: "turn-2", - streaming: false, - createdAt: "2026-02-26T12:00:02.100Z", - updatedAt: "2026-02-26T12:00:02.100Z", - }, - }), - makeEvent({ - sequence: 7, - type: "thread.reverted", - aggregateKind: "thread", - aggregateId: "thread-revert", - occurredAt: "2026-02-26T12:00:03.000Z", - commandId: "cmd-revert", - payload: { - threadId: "thread-revert", - turnCount: 1, - }, - }), - ]; - - const afterRevert = await events.reduce>>( - (statePromise, event) => - statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), - Promise.resolve(afterCreate), - ); - - const thread = afterRevert.threads[0]; - expect( - thread?.messages.map((message) => ({ - id: message.id, - role: message.role, - turnId: message.turnId, - })), - ).toEqual([{ id: "assistant-keep", role: "assistant", turnId: "turn-1" }]); - }); - - it("caps message and checkpoint retention for long-lived threads", async () => { - const createdAt = "2026-03-01T10:00:00.000Z"; - const model = createEmptyReadModel(createdAt); - - const afterCreate = await Effect.runPromise( - projectEvent( - model, - makeEvent({ - sequence: 1, - type: "thread.created", - aggregateKind: "thread", - aggregateId: "thread-capped", - occurredAt: createdAt, - commandId: "cmd-create-capped", - payload: { - threadId: "thread-capped", - projectId: "project-1", - title: "capped", - modelSelection: { - provider: ProviderDriverKind.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - updatedAt: createdAt, - }, - }), - ), - ); - - const messageEvents: ReadonlyArray = Array.from( - { length: 2_100 }, - (_, index) => - makeEvent({ - sequence: index + 2, - type: "thread.message-sent", - aggregateKind: "thread", - aggregateId: "thread-capped", - occurredAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`, - commandId: `cmd-message-${index}`, - payload: { - threadId: "thread-capped", - messageId: `msg-${index}`, - role: "assistant", - text: `message-${index}`, - turnId: `turn-${index}`, - streaming: false, - createdAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`, - updatedAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`, - }, - }), - ); - const afterMessages = await messageEvents.reduce< - Promise> - >( - (statePromise, event) => - statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), - Promise.resolve(afterCreate), - ); - - const checkpointEvents: ReadonlyArray = Array.from( - { length: 600 }, - (_, index) => - makeEvent({ - sequence: index + 2_102, - type: "thread.turn-diff-completed", - aggregateKind: "thread", - aggregateId: "thread-capped", - occurredAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`, - commandId: `cmd-checkpoint-${index}`, - payload: { - threadId: "thread-capped", - turnId: `turn-${index}`, - checkpointTurnCount: index + 1, - checkpointRef: `refs/t3/checkpoints/thread-capped/turn/${index + 1}`, - status: "ready", - files: [], - assistantMessageId: `msg-${index}`, - completedAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`, - }, - }), - ); - const finalState = await checkpointEvents.reduce< - Promise> - >( - (statePromise, event) => - statePromise.then((state) => Effect.runPromise(projectEvent(state, event))), - Promise.resolve(afterMessages), - ); - - const thread = finalState.threads[0]; - expect(thread?.messages).toHaveLength(2_000); - expect(thread?.messages[0]?.id).toBe("msg-100"); - expect(thread?.messages.at(-1)?.id).toBe("msg-2099"); - expect(thread?.checkpoints).toHaveLength(500); - expect(thread?.checkpoints[0]?.turnId).toBe("turn-100"); - expect(thread?.checkpoints.at(-1)?.turnId).toBe("turn-599"); - }); -}); diff --git a/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts index 989f5d78f8..33ebeb8a2b 100644 --- a/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts +++ b/apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts @@ -23,6 +23,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { command_id, aggregate_kind, aggregate_id, + command_type, accepted_at, result_sequence, status, @@ -32,6 +33,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { ${receipt.commandId}, ${receipt.aggregateKind}, ${receipt.aggregateId}, + ${receipt.commandType}, ${receipt.acceptedAt}, ${receipt.resultSequence}, ${receipt.status}, @@ -40,7 +42,8 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { ON CONFLICT (command_id) DO UPDATE SET aggregate_kind = excluded.aggregate_kind, - aggregate_id = excluded.aggregate_id, + aggregate_id = excluded.aggregate_id, + command_type = excluded.command_type, accepted_at = excluded.accepted_at, result_sequence = excluded.result_sequence, status = excluded.status, @@ -57,6 +60,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { command_id AS "commandId", aggregate_kind AS "aggregateKind", aggregate_id AS "aggregateId", + command_type AS "commandType", accepted_at AS "acceptedAt", result_sequence AS "resultSequence", status, @@ -71,6 +75,37 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { Effect.mapError(toPersistenceSqlError("OrchestrationCommandReceiptRepository.upsert:query")), ); + const insertIfAbsent: OrchestrationCommandReceiptRepositoryShape["insertIfAbsent"] = (receipt) => + sql<{ readonly command_id: string }>` + INSERT INTO orchestration_command_receipts ( + command_id, + aggregate_kind, + aggregate_id, + command_type, + accepted_at, + result_sequence, + status, + error + ) + VALUES ( + ${receipt.commandId}, + ${receipt.aggregateKind}, + ${receipt.aggregateId}, + ${receipt.commandType}, + ${receipt.acceptedAt}, + ${receipt.resultSequence}, + ${receipt.status}, + ${receipt.error} + ) + ON CONFLICT(command_id) DO NOTHING + RETURNING command_id + `.pipe( + Effect.map((rows) => rows.length === 1), + Effect.mapError( + toPersistenceSqlError("OrchestrationCommandReceiptRepository.insertIfAbsent:query"), + ), + ); + const getByCommandId: OrchestrationCommandReceiptRepositoryShape["getByCommandId"] = (input) => findReceiptByCommandId(input).pipe( Effect.mapError( @@ -79,6 +114,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () { ); return { + insertIfAbsent, upsert, getByCommandId, } satisfies OrchestrationCommandReceiptRepositoryShape; diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts index 2bac5de920..88979fae04 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts @@ -1,5 +1,6 @@ -import { CommandId, EventId, ProjectId } from "@t3tools/contracts"; +import { CommandId, EventId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -120,4 +121,96 @@ layer("OrchestrationEventStore", (it) => { } }), ); + + it.effect("orders project and V2 agent events in the retained application event source", () => + Effect.gen(function* () { + const eventStore = yield* OrchestrationEventStore; + const projectId = ProjectId.make("project-shared-stream"); + const threadId = ThreadId.make("thread-shared-stream"); + const providerInstanceId = ProviderInstanceId.make("codex"); + const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z"); + const now = DateTime.formatIso(occurredAt); + const baselineSequence = yield* eventStore.latestApplicationSequence; + + const projectEvent = yield* eventStore.append({ + type: "project.created", + eventId: EventId.make("event-project-shared-stream"), + aggregateKind: "project", + aggregateId: projectId, + occurredAt: now, + commandId: CommandId.make("command-project-shared-stream"), + causationEventId: null, + correlationId: CommandId.make("command-project-shared-stream"), + metadata: {}, + payload: { + projectId, + title: "Shared stream", + workspaceRoot: "/tmp/shared-stream", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + const [threadEvent] = yield* eventStore.appendAgentEvents({ + commandId: CommandId.make("command-thread-shared-stream"), + events: [ + { + id: EventId.make("event-thread-shared-stream"), + type: "thread.created", + threadId, + providerInstanceId, + occurredAt, + payload: { + id: threadId, + projectId, + title: "Thread", + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + rootThreadId: threadId, + parentThreadId: null, + relationshipToParent: null, + }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: occurredAt, + updatedAt: occurredAt, + archivedAt: null, + deletedAt: null, + }, + }, + ], + }); + + const applicationEvents = yield* eventStore + .streamApplicationEvents({ afterSequence: baselineSequence }) + .pipe( + Stream.take(2), + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + ); + assert.deepEqual( + applicationEvents.map((event) => event.sequence), + [projectEvent.sequence, threadEvent!.sequence], + ); + assert.isTrue("aggregateKind" in applicationEvents[0]!); + assert.isTrue("event" in applicationEvents[1]!); + + const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe( + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + ); + assert.deepEqual( + legacyReplay.map((event) => event.type), + ["project.created"], + ); + }), + ); }); diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts index 18d0e9aa57..e303b84a60 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts @@ -1,4 +1,5 @@ import { + type ApplicationStoredEvent, CommandId, EventId, IsoDateTime, @@ -8,13 +9,17 @@ import { OrchestrationEvent, OrchestrationEventMetadata, OrchestrationEventType, + OrchestrationV2DomainEventJson, + OrchestrationV2StoredEvent, ProjectId, ThreadId, + type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as SqlSchema from "effect/unstable/sql/SqlSchema"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; @@ -44,6 +49,7 @@ const AppendEventRequestSchema = Schema.Struct({ commandId: Schema.NullOr(CommandId), payloadJson: UnknownFromJsonString, metadataJson: EventMetadataFromJsonString, + applicationEventVersion: Schema.Number, }); const OrchestrationEventPersistedRowSchema = Schema.Struct({ @@ -67,6 +73,99 @@ const ReadFromSequenceRequestSchema = Schema.Struct({ const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000; const READ_PAGE_SIZE = 500; +interface ApplicationEventRow { + readonly sequence: number; + readonly event_id: string; + readonly command_id: string | null; + readonly aggregate_kind: "project" | "thread"; + readonly stream_id: string; + readonly event_type: string; + readonly occurred_at: string; + readonly payload_json: string; + readonly metadata_json: string; + readonly application_event_version: number; + readonly causation_event_id: string | null; + readonly correlation_id: string | null; +} + +const decodeV2EventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson); +const encodeV2EventJson = Schema.encodeEffect(OrchestrationV2DomainEventJson); +const decodeV2StoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent); +const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString); +const encodeJson = Schema.encodeEffect(Schema.UnknownFromJsonString); + +function metadataForV2Event(event: OrchestrationV2DomainEvent): Record { + return { + ...(event.runId === undefined ? {} : { runId: event.runId }), + ...(event.nodeId === undefined ? {} : { nodeId: event.nodeId }), + ...(event.driver === undefined ? {} : { driver: event.driver }), + ...(event.providerInstanceId === undefined + ? {} + : { providerInstanceId: event.providerInstanceId }), + ...(event.rawEventId === undefined ? {} : { rawEventId: event.rawEventId }), + }; +} + +const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent")(function* ( + row: ApplicationEventRow, +) { + const payload = yield* decodeJson(row.payload_json); + const metadata = yield* decodeJson(row.metadata_json); + const values = + typeof metadata === "object" && metadata !== null ? (metadata as Record) : {}; + const event = yield* decodeV2EventJson({ + id: row.event_id, + threadId: row.stream_id, + type: row.event_type, + occurredAt: row.occurred_at, + payload, + ...(values.runId === undefined ? {} : { runId: values.runId }), + ...(values.nodeId === undefined ? {} : { nodeId: values.nodeId }), + ...(values.driver === undefined ? {} : { driver: values.driver }), + ...(values.providerInstanceId === undefined + ? {} + : { providerInstanceId: values.providerInstanceId }), + ...(values.rawEventId === undefined ? {} : { rawEventId: values.rawEventId }), + }); + return yield* decodeV2StoredEvent({ + sequence: row.sequence, + commandId: row.command_id, + event, + }); +}); + +const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* ( + row: ApplicationEventRow, +) { + const event = yield* decodeEvent({ + sequence: row.sequence, + eventId: row.event_id, + type: row.event_type, + aggregateKind: row.aggregate_kind, + aggregateId: row.stream_id, + occurredAt: row.occurred_at, + commandId: row.command_id, + causationEventId: row.causation_event_id, + correlationId: row.correlation_id, + payload: yield* decodeJson(row.payload_json), + metadata: yield* decodeJson(row.metadata_json), + }); + switch (event.type) { + case "project.created": + case "project.meta-updated": + case "project.deleted": + return event; + default: + return yield* Effect.die(`Expected a project event, received '${event.type}'.`); + } +}); + +function rowToApplicationStoredEvent( + row: ApplicationEventRow, +): Effect.Effect { + return row.aggregate_kind === "project" ? rowToProjectEvent(row) : rowToV2StoredEvent(row); +} + function inferActorKind( event: Omit, ): Schema.Schema.Type { @@ -98,6 +197,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st const makeEventStore = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const committedEvents = yield* PubSub.unbounded(); const appendEventRow = SqlSchema.findOne({ Request: AppendEventRequestSchema, @@ -117,6 +217,7 @@ const makeEventStore = Effect.gen(function* () { actor_kind, payload_json, metadata_json + , application_event_version ) VALUES ( ${request.eventId}, @@ -141,6 +242,7 @@ const makeEventStore = Effect.gen(function* () { ${request.actorKind}, ${request.payloadJson}, ${request.metadataJson} + , ${request.applicationEventVersion} ) RETURNING sequence, @@ -176,6 +278,7 @@ const makeEventStore = Effect.gen(function* () { metadata_json AS "metadata" FROM orchestration_events WHERE sequence > ${request.sequenceExclusive} + AND (application_event_version = 1 OR aggregate_kind = 'project') ORDER BY sequence ASC LIMIT ${request.limit} `, @@ -194,6 +297,7 @@ const makeEventStore = Effect.gen(function* () { commandId: event.commandId, payloadJson: event.payload, metadataJson: event.metadata, + applicationEventVersion: event.aggregateKind === "project" ? 2 : 1, }).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( @@ -260,10 +364,229 @@ const makeEventStore = Effect.gen(function* () { return readPage(sequenceExclusive, normalizedLimit); }; + const readApplicationRows = (input: { + readonly afterSequence: number; + readonly throughSequence?: number; + readonly threadId?: ThreadId; + readonly commandId?: CommandId; + readonly onlyAgentEvents?: boolean; + readonly limit: number; + }) => + sql` + SELECT + sequence, + event_id, + command_id, + aggregate_kind, + stream_id, + event_type, + occurred_at, + payload_json, + metadata_json, + application_event_version, + causation_event_id, + correlation_id + FROM orchestration_events + WHERE sequence > ${input.afterSequence} + AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER} + AND ( + (${input.onlyAgentEvents === true ? 1 : 0} = 0 AND aggregate_kind = 'project') + OR (application_event_version = 2 AND aggregate_kind = 'thread') + ) + AND (${input.threadId ?? null} IS NULL OR stream_id = ${input.threadId ?? null}) + AND (${input.commandId ?? null} IS NULL OR command_id = ${input.commandId ?? null}) + ORDER BY sequence ASC + LIMIT ${input.limit} + `; + + const appendAgentEvents: OrchestrationEventStoreShape["appendAgentEvents"] = (input) => + Effect.forEach( + input.events, + (event) => + Effect.gen(function* () { + const encoded = yield* encodeV2EventJson(event); + const rows = yield* sql<{ readonly sequence: number }>` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json, + application_event_version + ) + VALUES ( + ${event.id}, + 'thread', + ${event.threadId}, + COALESCE( + ( + SELECT MAX(stream_version) + 1 + FROM orchestration_events + WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId} + ), + 0 + ), + ${event.type}, + ${encoded.occurredAt}, + ${input.commandId ?? null}, + NULL, + ${input.commandId ?? null}, + ${event.rawEventId === undefined ? "server" : "provider"}, + ${yield* encodeJson(encoded.payload)}, + ${yield* encodeJson(metadataForV2Event(event))}, + 2 + ) + RETURNING sequence + `; + return yield* decodeV2StoredEvent({ + sequence: rows[0]?.sequence, + commandId: input.commandId ?? null, + event, + }); + }), + { concurrency: 1 }, + ).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "OrchestrationEventStore.appendAgentEvents:insert", + "OrchestrationEventStore.appendAgentEvents:decode", + ), + ), + ); + + const readAgentEvents: OrchestrationEventStoreShape["readAgentEvents"] = (input) => + Stream.fromEffect( + readApplicationRows({ + afterSequence: input?.afterSequence ?? 0, + ...(input?.throughSequence === undefined ? {} : { throughSequence: input.throughSequence }), + ...(input?.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input?.commandId === undefined ? {} : { commandId: input.commandId }), + onlyAgentEvents: true, + limit: input?.limit ?? DEFAULT_READ_FROM_SEQUENCE_LIMIT, + }).pipe( + Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")), + ), + ).pipe( + Stream.flatMap(Stream.fromIterable), + Stream.mapEffect((row) => + rowToV2StoredEvent(row).pipe( + Effect.mapError( + toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"), + ), + ), + ), + ); + + const latestAgentSequence: OrchestrationEventStoreShape["latestAgentSequence"] = (threadId) => + sql<{ readonly sequence: number | null }>` + SELECT MAX(sequence) AS sequence + FROM orchestration_events + WHERE application_event_version = 2 + AND aggregate_kind = 'thread' + AND (${threadId ?? null} IS NULL OR stream_id = ${threadId ?? null}) + `.pipe( + Effect.map((rows) => rows[0]?.sequence ?? 0), + Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")), + ); + + const latestApplicationSequence = sql<{ readonly sequence: number | null }>` + SELECT MAX(sequence) AS sequence + FROM orchestration_events + WHERE aggregate_kind = 'project' + OR (application_event_version = 2 AND aggregate_kind = 'thread') + `.pipe( + Effect.map((rows) => rows[0]?.sequence ?? 0), + Effect.mapError( + toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"), + ), + ); + + const readApplicationEvents = (input: { + readonly afterSequence: number; + readonly throughSequence: number; + readonly limit: number; + }): Stream.Stream => + Stream.fromEffect( + readApplicationRows(input).pipe( + Effect.mapError( + toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"), + ), + ), + ).pipe( + Stream.flatMap(Stream.fromIterable), + Stream.mapEffect((row) => + rowToApplicationStoredEvent(row).pipe( + Effect.mapError( + toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"), + ), + ), + ), + ); + + const catchUpApplicationEvents = (input: { + readonly afterSequence: number; + readonly throughSequence: number; + }): Stream.Stream => { + const loop = ( + afterSequence: number, + ): Stream.Stream => + Stream.unwrap( + readApplicationEvents({ + afterSequence, + throughSequence: input.throughSequence, + limit: READ_PAGE_SIZE, + }).pipe( + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + Effect.map((events) => { + if (events.length === 0) return Stream.empty; + const current = Stream.fromIterable(events); + const last = events.at(-1)?.sequence ?? input.throughSequence; + return events.length < READ_PAGE_SIZE || last >= input.throughSequence + ? current + : Stream.concat(current, loop(last)); + }), + ), + ); + return loop(input.afterSequence); + }; + + const streamApplicationEvents: OrchestrationEventStoreShape["streamApplicationEvents"] = ( + input, + ) => + Stream.unwrap( + Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(committedEvents); + const highWater = yield* latestApplicationSequence; + const afterSequence = input?.afterSequence ?? 0; + const replay = catchUpApplicationEvents({ + afterSequence, + throughSequence: highWater, + }); + const live = Stream.fromSubscription(subscription).pipe( + Stream.filter((event) => event.sequence > Math.max(highWater, afterSequence)), + ); + return Stream.concat(replay, live); + }), + ); + return { append, readFromSequence, readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER), + appendAgentEvents, + readAgentEvents, + latestAgentSequence, + latestApplicationSequence, + publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid), + streamApplicationEvents, } satisfies OrchestrationEventStoreShape; }); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index d673a8ac98..7939dece96 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -55,6 +55,7 @@ import Migration034V2 from "./Migrations/034_OrchestrationV2Subagents.ts"; import Migration035V2 from "./Migrations/035_OrchestrationV2Foundation.ts"; import Migration036V2 from "./Migrations/036_OrchestrationV2ProviderSessionBindings.ts"; import Migration037V2 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts"; +import Migration038V2 from "./Migrations/038_ApplicationEventSource.ts"; /** * Migration loader with all migrations defined inline. @@ -103,12 +104,21 @@ export const migrationEntries = [ [34, "ProjectionThreadsSnoozed", Migration0034], [35, "ProjectionThreadTitleRegeneration", Migration0035], [36, "ProjectionThreadsPinned", Migration0036], +<<<<<<< HEAD [37, "ProjectionTurnsKeysetIndex", Migration0037], [38, "OrchestrationV2", Migration033V2], [39, "OrchestrationV2Subagents", Migration034V2], [40, "OrchestrationV2Foundation", Migration035V2], [41, "OrchestrationV2ProviderSessionBindings", Migration036V2], [42, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2], +======= + [37, "OrchestrationV2", Migration0026V2], + [38, "OrchestrationV2Subagents", Migration0034V2], + [39, "OrchestrationV2Foundation", Migration0035V2], + [40, "OrchestrationV2ProviderSessionBindings", Migration036V2], + [41, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2], + [42, "ApplicationEventSource", Migration038V2], +>>>>>>> 56f9a4b262 (Integrate orchestration v2 with the application runtime) ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/038_ApplicationEventSource.test.ts b/apps/server/src/persistence/Migrations/038_ApplicationEventSource.test.ts new file mode 100644 index 0000000000..8919c6840a --- /dev/null +++ b/apps/server/src/persistence/Migrations/038_ApplicationEventSource.test.ts @@ -0,0 +1,135 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +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("038_ApplicationEventSource", (it) => { + it.effect("moves V2 events and current project state behind one global sequence", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 37 }); + + yield* sql` + INSERT INTO orchestration_v2_events ( + event_id, + command_id, + thread_id, + run_id, + node_id, + provider, + driver, + provider_instance_id, + raw_event_id, + event_type, + occurred_at, + payload_json + ) VALUES ( + 'event:v2:existing', + 'command:v2:existing', + 'thread:v2:existing', + NULL, + NULL, + 'codex', + 'codex', + 'codex', + NULL, + 'thread.created', + '2026-06-20T00:00:00.000Z', + '{}' + ) + `; + yield* sql` + INSERT INTO orchestration_v2_command_receipts ( + command_id, + thread_id, + command_type, + accepted_at, + result_sequence, + status, + error + ) VALUES ( + 'command:v2:existing', + 'thread:v2:existing', + 'thread.create', + '2026-06-20T00:00:00.000Z', + 1, + 'accepted', + NULL + ) + `; + 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:existing', + 'Existing project', + '/work/existing', + '{"instanceId":"codex","model":"gpt-5.4"}', + '[]', + '2026-06-19T00:00:00.000Z', + '2026-06-20T00:00:00.000Z', + NULL + ) + `; + + yield* runMigrations({ toMigrationInclusive: 38 }); + + const events = yield* sql<{ + readonly sequence: number; + readonly aggregate_kind: string; + readonly stream_id: string; + readonly event_type: string; + readonly application_event_version: number; + }>` + SELECT + sequence, + aggregate_kind, + stream_id, + event_type, + application_event_version + FROM orchestration_events + WHERE application_event_version = 2 + ORDER BY sequence ASC + `; + assert.deepStrictEqual( + events.map((event) => [event.aggregate_kind, event.stream_id, event.event_type]), + [ + ["thread", "thread:v2:existing", "thread.created"], + ["project", "project:existing", "project.created"], + ], + ); + assert.ok(events[0]!.sequence < events[1]!.sequence); + + const receipts = yield* sql<{ + readonly aggregate_kind: string; + readonly aggregate_id: string; + readonly command_type: string; + readonly result_sequence: number; + }>` + SELECT aggregate_kind, aggregate_id, command_type, result_sequence + FROM orchestration_command_receipts + WHERE command_id = 'command:v2:existing' + `; + assert.deepStrictEqual(receipts, [ + { + aggregate_kind: "thread", + aggregate_id: "thread:v2:existing", + command_type: "thread.create", + result_sequence: events[0]!.sequence, + }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/038_ApplicationEventSource.ts b/apps/server/src/persistence/Migrations/038_ApplicationEventSource.ts new file mode 100644 index 0000000000..e1ddef62cd --- /dev/null +++ b/apps/server/src/persistence/Migrations/038_ApplicationEventSource.ts @@ -0,0 +1,281 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +interface LegacyV2EventRow { + readonly event_id: string; + readonly command_id: string | null; + readonly thread_id: string; + readonly run_id: string | null; + readonly node_id: string | null; + readonly driver: string | null; + readonly provider_instance_id: string | null; + readonly raw_event_id: string | null; + readonly event_type: string; + readonly occurred_at: string; + readonly payload_json: string; +} + +interface ProjectProjectionRow { + readonly project_id: string; + readonly title: string; + readonly workspace_root: string; + readonly default_model_selection_json: string | null; + readonly scripts_json: string; + readonly created_at: string; + readonly updated_at: string; + readonly deleted_at: string | null; +} + +const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString); +const encodeJson = Schema.encodeEffect(Schema.UnknownFromJsonString); + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + ALTER TABLE orchestration_events + ADD COLUMN application_event_version INTEGER NOT NULL DEFAULT 1 + `; + yield* sql` + CREATE INDEX idx_orchestration_events_application_sequence + ON orchestration_events(application_event_version, sequence) + `; + yield* sql` + ALTER TABLE orchestration_command_receipts + ADD COLUMN command_type TEXT NOT NULL DEFAULT 'legacy' + `; + + const legacyV2Events = yield* sql` + SELECT + event_id, + command_id, + thread_id, + run_id, + node_id, + driver, + provider_instance_id, + raw_event_id, + event_type, + occurred_at, + payload_json + FROM orchestration_v2_events + ORDER BY sequence ASC + `; + + yield* Effect.forEach( + legacyV2Events, + (event) => + Effect.gen(function* () { + const metadata = yield* encodeJson({ + applicationEventVersion: 2, + ...(event.run_id === null ? {} : { runId: event.run_id }), + ...(event.node_id === null ? {} : { nodeId: event.node_id }), + ...(event.driver === null ? {} : { driver: event.driver }), + ...(event.provider_instance_id === null + ? {} + : { providerInstanceId: event.provider_instance_id }), + ...(event.raw_event_id === null ? {} : { rawEventId: event.raw_event_id }), + }); + yield* sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json, + application_event_version + ) + SELECT + ${event.event_id}, + 'thread', + ${event.thread_id}, + COALESCE( + ( + SELECT MAX(stream_version) + 1 + FROM orchestration_events + WHERE aggregate_kind = 'thread' AND stream_id = ${event.thread_id} + ), + 0 + ), + ${event.event_type}, + ${event.occurred_at}, + ${event.command_id}, + NULL, + ${event.command_id}, + ${event.raw_event_id === null ? "server" : "provider"}, + ${event.payload_json}, + ${metadata}, + 2 + WHERE NOT EXISTS ( + SELECT 1 FROM orchestration_events WHERE event_id = ${event.event_id} + ) + `; + }), + { concurrency: 1, discard: true }, + ); + + // ProjectService wrote this projection directly before the application event + // boundary was restored. Re-baseline every current row into the shared log so + // projection rebuilds preserve the exact pre-migration project state. + const projectRows = yield* sql` + SELECT + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + FROM projection_projects + ORDER BY created_at ASC, project_id ASC + `; + yield* Effect.forEach( + projectRows, + (project) => + Effect.gen(function* () { + const createdEventId = `migration:38:project:${project.project_id}:baseline`; + const createdPayload = { + projectId: project.project_id, + title: project.title, + workspaceRoot: project.workspace_root, + defaultModelSelection: + project.default_model_selection_json === null + ? null + : yield* decodeJson(project.default_model_selection_json), + scripts: yield* decodeJson(project.scripts_json), + createdAt: project.created_at, + updatedAt: project.updated_at, + }; + const createdPayloadJson = yield* encodeJson(createdPayload); + const migrationMetadataJson = yield* encodeJson({ + applicationEventVersion: 2, + migration: 38, + }); + yield* sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json, + application_event_version + ) + VALUES ( + ${createdEventId}, + 'project', + ${project.project_id}, + COALESCE( + ( + SELECT MAX(stream_version) + 1 + FROM orchestration_events + WHERE aggregate_kind = 'project' AND stream_id = ${project.project_id} + ), + 0 + ), + 'project.created', + ${project.updated_at}, + NULL, + NULL, + NULL, + 'server', + ${createdPayloadJson}, + ${migrationMetadataJson}, + 2 + ) + `; + + if (project.deleted_at !== null) { + const deletedPayloadJson = yield* encodeJson({ + projectId: project.project_id, + deletedAt: project.deleted_at, + }); + yield* sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json, + application_event_version + ) + VALUES ( + ${`migration:38:project:${project.project_id}:deleted`}, + 'project', + ${project.project_id}, + ( + SELECT MAX(stream_version) + 1 + FROM orchestration_events + WHERE aggregate_kind = 'project' AND stream_id = ${project.project_id} + ), + 'project.deleted', + ${project.deleted_at}, + NULL, + ${createdEventId}, + NULL, + 'server', + ${deletedPayloadJson}, + ${migrationMetadataJson}, + 2 + ) + `; + } + }), + { concurrency: 1, discard: true }, + ); + + yield* sql` + INSERT INTO orchestration_command_receipts ( + command_id, + aggregate_kind, + aggregate_id, + accepted_at, + result_sequence, + status, + error, + command_type + ) + SELECT + command_id, + 'thread', + thread_id, + accepted_at, + COALESCE( + ( + SELECT MAX(events.sequence) + FROM orchestration_events events + WHERE events.application_event_version = 2 + AND events.command_id = receipts.command_id + ), + 0 + ), + status, + error, + command_type + FROM orchestration_v2_command_receipts receipts + WHERE TRUE + ON CONFLICT(command_id) DO NOTHING + `; +}); diff --git a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts index 1498984827..5c4eef2cc5 100644 --- a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts +++ b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts @@ -26,6 +26,7 @@ export const OrchestrationCommandReceipt = Schema.Struct({ commandId: CommandId, aggregateKind: OrchestrationAggregateKind, aggregateId: Schema.Union([ProjectId, ThreadId]), + commandType: Schema.String, acceptedAt: IsoDateTime, resultSequence: NonNegativeInt, status: OrchestrationCommandReceiptStatus, @@ -42,6 +43,10 @@ export type GetByCommandIdInput = typeof GetByCommandIdInput.Type; * OrchestrationCommandReceiptRepositoryShape - Service API for command receipts. */ export interface OrchestrationCommandReceiptRepositoryShape { + readonly insertIfAbsent: ( + receipt: OrchestrationCommandReceipt, + ) => Effect.Effect; + /** * Insert or replace a command receipt row. * diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.ts index 8b465e7713..85f108bae5 100644 --- a/apps/server/src/persistence/Services/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts @@ -1,15 +1,23 @@ /** - * OrchestrationEventStore - Event store interface for orchestration events. + * Historical name for the shared application event store. * - * Owns durable append/replay access to the orchestration event stream. It does - * not reduce events into read models or apply command validation rules. + * Owns durable append/replay access for project events and V2 agent-thread + * events under one global sequence. It does not reduce events into read models + * or apply command validation rules. * * Uses Effect `Context.Service` for dependency injection and exposes typed * persistence/decode errors for event append and replay operations. * * @module OrchestrationEventStore */ -import { OrchestrationEvent } from "@t3tools/contracts"; +import type { + ApplicationStoredEvent, + CommandId, + OrchestrationEvent, + OrchestrationV2DomainEvent, + OrchestrationV2StoredEvent, + ThreadId, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; import type * as Stream from "effect/Stream"; @@ -52,6 +60,35 @@ export interface OrchestrationEventStoreShape { * @returns Stream containing all stored events. */ readonly readAll: () => Stream.Stream; + + /** Append V2 agent events to the same globally ordered application log. */ + readonly appendAgentEvents: (input: { + readonly commandId?: CommandId; + readonly events: ReadonlyArray; + }) => Effect.Effect, OrchestrationEventStoreError>; + + /** Read only V2 thread events from the application log. */ + readonly readAgentEvents: (input?: { + readonly afterSequence?: number; + readonly throughSequence?: number; + readonly threadId?: ThreadId; + readonly commandId?: CommandId; + readonly limit?: number; + }) => Stream.Stream; + + readonly latestAgentSequence: ( + threadId?: ThreadId, + ) => Effect.Effect; + + readonly latestApplicationSequence: Effect.Effect; + + /** Publish only after the surrounding event/projection transaction commits. */ + readonly publishCommitted: (events: ReadonlyArray) => Effect.Effect; + + /** Race-free replay-to-live stream for project and V2 thread events. */ + readonly streamApplicationEvents: (input?: { + readonly afterSequence?: number; + }) => Stream.Stream; } /** diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 5b20b3348b..7ee869bcac 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -1,13 +1,14 @@ import { assert, it } from "@effect/vitest"; -import { ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { CommandId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Stream from "effect/Stream"; import { TestClock } from "effect/testing"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; -import * as ProjectionProjects from "../persistence/Layers/ProjectionProjects.ts"; +import { ServerConfig } from "../config.ts"; +import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; @@ -38,11 +39,12 @@ const metadataLayer = Layer.merge( }), ); -const TestLayer = ProjectService.layer.pipe( - Layer.provideMerge(ProjectionProjects.ProjectionProjectRepositoryLive), +const TestLayer = ProjectServiceLayerLive.pipe( Layer.provideMerge(workspacePathsLayer), Layer.provideMerge(metadataLayer), Layer.provideMerge(SqlitePersistenceMemory), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })), + Layer.provide(NodeServices.layer), ); it.layer(TestLayer)("ProjectService", (it) => { @@ -56,14 +58,8 @@ it.layer(TestLayer)("ProjectService", (it) => { } as const; yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z")); - const changesFiber = yield* service.changes.pipe( - Stream.take(3), - Stream.runCollect, - Effect.forkChild, - ); - yield* Effect.yieldNow; - const created = yield* service.create({ + commandId: CommandId.make("command:project:create"), projectId, title: "Project", workspaceRoot: "/work/project/", @@ -82,7 +78,11 @@ it.layer(TestLayer)("ProjectService", (it) => { assert.equal(created.repositoryIdentity?.canonicalKey, "github.com/t3tools/project"); assert.equal(created.faviconPath, "/work/project/favicon.svg"); - const updated = yield* service.update({ projectId, title: "Renamed" }); + const updated = yield* service.update({ + commandId: CommandId.make("command:project:update"), + projectId, + title: "Renamed", + }); assert.equal(updated.title, "Renamed"); assert.equal(updated.createdAt, created.createdAt); @@ -96,16 +96,25 @@ it.layer(TestLayer)("ProjectService", (it) => { [projectId], ); - const deleted = yield* service.delete(projectId); + const deleted = yield* service.delete({ + commandId: CommandId.make("command:project:delete"), + projectId, + }); assert.isNotNull(deleted.deletedAt); assert.isTrue(Option.isNone(yield* service.getById(projectId))); assert.isTrue(Option.isSome(yield* service.getById(projectId, { includeDeleted: true }))); assert.deepEqual((yield* service.snapshot).projects, []); - const changes = Array.from(yield* Fiber.join(changesFiber)); + const sql = yield* SqlClient.SqlClient; + const changes = yield* sql<{ readonly event_type: string }>` + SELECT event_type + FROM orchestration_events + WHERE aggregate_kind = 'project' AND stream_id = ${projectId} + ORDER BY sequence ASC + `; assert.deepEqual( - changes.map((change) => change.type), - ["project.upserted", "project.upserted", "project.deleted"], + changes.map((change) => change.event_type), + ["project.created", "project.meta-updated", "project.deleted"], ); }), ); @@ -115,12 +124,14 @@ it.layer(TestLayer)("ProjectService", (it) => { const service = yield* ProjectService.ProjectService; yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z")); yield* service.create({ + commandId: CommandId.make("command:collision:first"), projectId: ProjectId.make("project:collision:first"), title: "First", workspaceRoot: "/work/shared", }); const error = yield* service .create({ + commandId: CommandId.make("command:collision:second"), projectId: ProjectId.make("project:collision:second"), title: "Second", workspaceRoot: "/work/shared", @@ -135,6 +146,7 @@ it.layer(TestLayer)("ProjectService", (it) => { const service = yield* ProjectService.ProjectService; yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z")); const input = { + commandId: CommandId.make("command:bootstrap:first"), projectId: ProjectId.make("project:bootstrap"), title: "Bootstrap", workspaceRoot: "/work/bootstrap/", @@ -142,6 +154,7 @@ it.layer(TestLayer)("ProjectService", (it) => { const first = yield* service.bootstrap(input); const second = yield* service.bootstrap({ ...input, + commandId: CommandId.make("command:bootstrap:second"), projectId: ProjectId.make("project:bootstrap:unused"), }); assert.isTrue(first.created); diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 4bcf60fec4..1f3d9869f5 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -1,6 +1,6 @@ import { + type CommandId, ModelSelection, - ProjectChange, ProjectId, type Project, type ProjectScript, @@ -11,16 +11,16 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; +import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; export interface ProjectCreateInput { + readonly commandId: CommandId; readonly projectId: ProjectId; readonly title: string; readonly workspaceRoot: string; @@ -30,6 +30,7 @@ export interface ProjectCreateInput { } export interface ProjectUpdateInput { + readonly commandId: CommandId; readonly projectId: ProjectId; readonly title?: string; readonly workspaceRoot?: string; @@ -39,6 +40,11 @@ export interface ProjectUpdateInput { export interface ProjectBootstrapInput extends ProjectCreateInput {} +export interface ProjectDeleteInput { + readonly commandId: CommandId; + readonly projectId: ProjectId; +} + export class ProjectNotFoundError extends Schema.TaggedErrorClass()( "ProjectNotFoundError", { projectId: ProjectId }, @@ -68,7 +74,7 @@ export class ProjectOperationError extends Schema.TaggedErrorClass; readonly update: (input: ProjectUpdateInput) => Effect.Effect; - readonly delete: (projectId: ProjectId) => Effect.Effect; + readonly delete: (input: ProjectDeleteInput) => Effect.Effect; readonly getById: ( projectId: ProjectId, options?: { readonly includeDeleted?: boolean }, @@ -107,16 +113,15 @@ export class ProjectService extends Context.Service< options?: { readonly includeDeleted?: boolean }, ) => Effect.Effect, ProjectOperationError>; readonly snapshot: Effect.Effect; - readonly changes: Stream.Stream; } >()("t3/project/ProjectService") {} export const make = Effect.gen(function* () { + const engine = yield* OrchestrationEngineService; const projects = yield* ProjectionProjects.ProjectionProjectRepository; const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - const changesPubSub = yield* PubSub.unbounded(); const hydrate = Effect.fn("ProjectService.hydrate")(function* ( row: ProjectionProjects.ProjectionProject, @@ -194,24 +199,40 @@ export const make = Effect.gen(function* () { return row === undefined ? Option.none() : Option.some(yield* hydrate(row)); }); - const persist = Effect.fn("ProjectService.persist")(function* ( - row: ProjectionProjects.ProjectionProject, - ) { - yield* projects.upsert(row).pipe( + const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) { + const row = yield* projects + .getById({ projectId }) + .pipe( + Effect.mapError( + (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }), + ), + ); + if (Option.isNone(row)) { + return yield* new ProjectOperationError({ + operation: "read-project", + projectId, + cause: "The accepted project command did not produce a project projection.", + }); + } + return yield* hydrate(row.value); + }); + + const dispatch = ( + projectId: ProjectId, + command: Parameters[0], + onCommitted: Effect.Effect, + ) => + engine.dispatch(command).pipe( Effect.mapError( (cause) => new ProjectOperationError({ - operation: "persist-project", - projectId: row.projectId, - workspaceRoot: row.workspaceRoot, + operation: "dispatch-project-command", + projectId, cause, }), ), + Effect.andThen(onCommitted), ); - const project = yield* hydrate(row); - yield* PubSub.publish(changesPubSub, { type: "project.upserted", project }); - return project; - }); const assertWorkspaceAvailable = Effect.fn("ProjectService.assertWorkspaceAvailable")(function* ( projectId: ProjectId, @@ -250,27 +271,21 @@ export const make = Effect.gen(function* () { ), ); yield* assertWorkspaceAvailable(input.projectId, workspaceRoot); - const existing = yield* projects.getById({ projectId: input.projectId }).pipe( - Effect.mapError( - (cause) => - new ProjectOperationError({ - operation: "read-project", - projectId: input.projectId, - cause, - }), - ), - ); const now = DateTime.formatIso(yield* DateTime.now); - return yield* persist({ - projectId: input.projectId, - title: input.title, - workspaceRoot, - defaultModelSelection: input.defaultModelSelection ?? null, - scripts: [...(input.scripts ?? [])], - createdAt: Option.isSome(existing) ? existing.value.createdAt : now, - updatedAt: now, - deletedAt: null, - }); + return yield* dispatch( + input.projectId, + { + type: "project.create", + commandId: input.commandId, + projectId: input.projectId, + title: input.title, + workspaceRoot, + defaultModelSelection: input.defaultModelSelection ?? null, + scripts: [...(input.scripts ?? [])], + createdAt: now, + }, + readCommitted(input.projectId), + ); }, ); @@ -304,16 +319,21 @@ export const make = Effect.gen(function* () { ), ); yield* assertWorkspaceAvailable(input.projectId, workspaceRoot); - return yield* persist({ - ...existing.value, - ...(input.title === undefined ? {} : { title: input.title }), - workspaceRoot, - ...(input.defaultModelSelection === undefined - ? {} - : { defaultModelSelection: input.defaultModelSelection }), - ...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }), - updatedAt: DateTime.formatIso(yield* DateTime.now), - }); + return yield* dispatch( + input.projectId, + { + type: "project.meta.update", + commandId: input.commandId, + projectId: input.projectId, + ...(input.title === undefined ? {} : { title: input.title }), + ...(workspaceRoot === existing.value.workspaceRoot ? {} : { workspaceRoot }), + ...(input.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: input.defaultModelSelection }), + ...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }), + }, + readCommitted(input.projectId), + ); }, ); @@ -326,7 +346,8 @@ export const make = Effect.gen(function* () { ); const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")( - function* (projectId) { + function* (input) { + const { projectId } = input; const existing = yield* projects .getById({ projectId }) .pipe( @@ -337,22 +358,15 @@ export const make = Effect.gen(function* () { if (Option.isNone(existing) || existing.value.deletedAt !== null) { return yield* new ProjectNotFoundError({ projectId }); } - const deletedAt = DateTime.formatIso(yield* DateTime.now); - const row = { ...existing.value, updatedAt: deletedAt, deletedAt }; - yield* projects.upsert(row).pipe( - Effect.mapError( - (cause) => - new ProjectOperationError({ - operation: "persist-project", - projectId, - workspaceRoot: row.workspaceRoot, - cause, - }), - ), + return yield* dispatch( + projectId, + { + type: "project.delete", + commandId: input.commandId, + projectId, + }, + readCommitted(projectId), ); - const project = yield* hydrate(row); - yield* PubSub.publish(changesPubSub, { type: "project.deleted", projectId, deletedAt }); - return project; }, ); @@ -373,7 +387,6 @@ export const make = Effect.gen(function* () { getById, getByWorkspaceRoot, snapshot, - changes: Stream.fromPubSub(changesPubSub), }); }); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 5c5da4666b..734627df09 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -1,200 +1,79 @@ -import { describe, expect, it, vi } from "@effect/vitest"; -import { type OrchestrationProject, ProjectId } from "@t3tools/contracts"; +import { assert, it, vi } from "@effect/vitest"; +import { ProjectId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import * as TerminalManager from "../terminal/Manager.ts"; +import * as ProjectService from "./ProjectService.ts"; import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts"; -const isProjectSetupScriptOperationError = Schema.is( - ProjectSetupScriptRunner.ProjectSetupScriptOperationError, -); - -const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({ - id: ProjectId.make("project-1"), - title: "Project", - workspaceRoot: "/repo/project", - defaultModelSelection: null, - scripts, - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - deletedAt: null, -}); - -const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) => - Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }), - getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: (workspaceRoot) => - Effect.succeed( - workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(), - ), - getProjectShellById: (projectId) => - Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), - getThreadCheckpointContext: () => Effect.die("unused"), - getFullThreadDiffContext: () => Effect.die("unused"), - getThreadShellById: () => Effect.die("unused"), - getThreadDetailById: () => Effect.die("unused"), - getThreadDetailSnapshot: () => Effect.die("unused"), - searchThreads: () => Effect.succeed({ matches: [] }), - }); - -const makeTerminalManagerLayer = ( - overrides: Pick, -) => - Layer.succeed(TerminalManager.TerminalManager, { - ...overrides, - attachStream: () => Effect.die(new Error("unused")), - resize: () => Effect.void, - clear: () => Effect.void, - restart: () => Effect.die(new Error("unused")), - close: () => Effect.void, - subscribe: () => Effect.succeed(() => undefined), - subscribeMetadata: () => Effect.succeed(() => undefined), - }); - -const testLayer = ( - project: OrchestrationProject, - terminal: Pick, -) => - ProjectSetupScriptRunner.layer.pipe( - Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)), - Layer.provideMerge(makeTerminalManagerLayer(terminal)), +it.effect("resolves setup scripts through the standalone project service", () => { + const open = vi.fn((input: Parameters[0]) => + Effect.succeed({ + threadId: input.threadId, + terminalId: input.terminalId, + cwd: input.cwd, + worktreePath: input.worktreePath ?? null, + status: "running" as const, + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + label: "Shell", + updatedAt: "2026-06-20T00:00:00.000Z", + }), ); - -describe("ProjectSetupScriptRunner", () => { - it.effect("returns no-script when no setup script exists", () => { - const open = vi.fn(() => Effect.die("unexpected open")); - const write = vi.fn(() => Effect.die("unexpected write")); - const project = makeProject([]); - - return Effect.gen(function* () { - const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; - const result = yield* runner.runForThread({ - threadId: "thread-1", - projectId: "project-1", - worktreePath: "/repo/worktrees/a", - }); - - expect(result).toEqual({ status: "no-script" }); - expect(open).not.toHaveBeenCalled(); - expect(write).not.toHaveBeenCalled(); - }).pipe(Effect.provide(testLayer(project, { open, write }))); - }); - - it.effect( - "opens the deterministic setup terminal with worktree env and writes the command", - () => { - const open = vi.fn(() => - Effect.succeed({ - threadId: "thread-1", - terminalId: "setup-setup", - cwd: "/repo/worktrees/a", - worktreePath: "/repo/worktrees/a", - status: "running" as const, - pid: 123, - history: "", - exitCode: null, - exitSignal: null, - label: "setup-setup", - updatedAt: "2026-01-01T00:00:00.000Z", - }), - ); - const write = vi.fn(() => Effect.void); - const project = makeProject([ - { - id: "setup", - name: "Setup", - command: "bun install", - icon: "configure", - runOnWorktreeCreate: true, - }, - ]); - - return Effect.gen(function* () { - const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; - const result = yield* runner.runForThread({ - threadId: "thread-1", - projectCwd: "/repo/project", - worktreePath: "/repo/worktrees/a", - }); - - expect(result).toEqual({ - status: "started", - scriptId: "setup", - scriptName: "Setup", - terminalId: "setup-setup", - cwd: "/repo/worktrees/a", - }); - expect(open).toHaveBeenCalledWith({ - threadId: "thread-1", - terminalId: "setup-setup", - cwd: "/repo/worktrees/a", - worktreePath: "/repo/worktrees/a", - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - T3CODE_WORKTREE_PATH: "/repo/worktrees/a", - }, - }); - expect(write).toHaveBeenCalledWith({ - threadId: "thread-1", - terminalId: "setup-setup", - data: "bun install\r", - }); - }).pipe(Effect.provide(testLayer(project, { open, write }))); - }, + const write = vi.fn( + (_input: Parameters[0]) => Effect.void, ); - - it.effect("keeps terminal failures as the exact cause of a structured operation error", () => { - const rootCause = new Error("stat failed"); - const terminalError = new TerminalManager.TerminalCwdStatError({ - cwd: "/repo/worktrees/a", - cause: rootCause, - }); - const project = makeProject([ + const projectId = ProjectId.make("project:setup-runner-v2"); + const project = { + id: projectId, + title: "Project", + workspaceRoot: "/repo", + repositoryIdentity: null, + faviconPath: null, + defaultModelSelection: null, + scripts: [ { id: "setup", name: "Setup", - command: "bun install", - icon: "configure", + command: "vp install", + icon: "configure" as const, runOnWorktreeCreate: true, }, - ]); - - return Effect.gen(function* () { - const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; - const error = yield* runner - .runForThread({ - threadId: "thread-1", - projectId: "project-1", - worktreePath: "/repo/worktrees/a", - }) - .pipe(Effect.flip); - - expect(isProjectSetupScriptOperationError(error)).toBe(true); - if (isProjectSetupScriptOperationError(error)) { - expect(error.operation).toBe("openTerminal"); - expect(error.threadId).toBe("thread-1"); - expect(error.projectId).toBe("project-1"); - expect(error.worktreePath).toBe("/repo/worktrees/a"); - expect(error.cause).toBe(terminalError); - expect(terminalError.cause).toBe(rootCause); - } - }).pipe( - Effect.provide( - testLayer(project, { - open: () => Effect.fail(terminalError), - write: () => Effect.die("unexpected write"), + ], + createdAt: "2026-06-20T00:00:00.000Z", + updatedAt: "2026-06-20T00:00:00.000Z", + deletedAt: null, + }; + const layer = ProjectSetupScriptRunner.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ProjectService.ProjectService)({ + getById: () => Effect.succeed(Option.some(project)), }), + Layer.mock(TerminalManager.TerminalManager)({ open, write }), ), - ); - }); + ), + ); + + return Effect.gen(function* () { + const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; + const result = yield* runner.runForThread({ + threadId: "thread-1", + projectId, + worktreePath: "/repo-worktree", + }); + assert.deepEqual(result, { + status: "started", + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/repo-worktree", + }); + assert.equal(open.mock.calls[0]?.[0].cwd, "/repo-worktree"); + assert.equal(write.mock.calls[0]?.[0].data, "vp install\r"); + }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index e894fed8e4..eb997265eb 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -6,8 +6,8 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import * as TerminalManager from "../terminal/Manager.ts"; +import * as ProjectService from "./ProjectService.ts"; export interface ProjectSetupScriptRunnerResultNoScript { readonly status: "no-script"; @@ -83,7 +83,7 @@ export class ProjectSetupScriptRunner extends Context.Service< >()("t3/project/ProjectSetupScriptRunner") {} export const make = Effect.gen(function* () { - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const projects = yield* ProjectService.ProjectService; const terminalManager = yield* TerminalManager.TerminalManager; const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn( @@ -99,7 +99,7 @@ export const make = Effect.gen(function* () { const projectById = suppliedProject ?? (input.projectId - ? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe( + ? yield* projects.getById(ProjectId.make(input.projectId)).pipe( Effect.map(Option.getOrUndefined), Effect.mapError( (cause) => @@ -115,7 +115,7 @@ export const make = Effect.gen(function* () { suppliedProject ?? projectById ?? (input.projectCwd - ? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe( + ? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe( Effect.map(Option.getOrUndefined), Effect.mapError( (cause) => diff --git a/apps/server/src/project/http.ts b/apps/server/src/project/http.ts new file mode 100644 index 0000000000..c7c19f087f --- /dev/null +++ b/apps/server/src/project/http.ts @@ -0,0 +1,78 @@ +import { + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + EnvironmentHttpApi, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; + +import { + annotateEnvironmentRequest, + failEnvironmentInternal, + requireEnvironmentScope, +} from "../auth/http.ts"; +import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts"; +import { ProjectService } from "./ProjectService.ts"; + +export const projectHttpApiLayer = HttpApiBuilder.group( + EnvironmentHttpApi, + "projects", + Effect.fnUntraced(function* (handlers) { + const projects = yield* ProjectService; + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + + return handlers + .handle( + "snapshot", + Effect.fn("environment.projects.snapshot")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationReadScope); + return yield* projects.snapshot.pipe( + Effect.catch((cause) => failEnvironmentInternal("project_snapshot_failed", cause)), + ); + }), + ) + .handle( + "mutate", + Effect.fn("environment.projects.mutate")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationOperateScope); + const mutation = args.payload; + const operation = + mutation.type === "project.create" + ? projects.create({ + commandId: mutation.commandId, + projectId: mutation.projectId, + title: mutation.title, + workspaceRoot: mutation.workspaceRoot, + ...(mutation.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: mutation.defaultModelSelection }), + ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }), + }) + : mutation.type === "project.update" + ? projects.update({ + commandId: mutation.commandId, + projectId: mutation.projectId, + ...(mutation.title === undefined ? {} : { title: mutation.title }), + ...(mutation.workspaceRoot === undefined + ? {} + : { workspaceRoot: mutation.workspaceRoot }), + ...(mutation.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: mutation.defaultModelSelection }), + ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }), + }) + : projects.delete({ + commandId: mutation.commandId, + projectId: mutation.projectId, + }); + return yield* startup + .enqueueCommand(operation) + .pipe( + Effect.catch((cause) => failEnvironmentInternal("project_mutation_failed", cause)), + ); + }), + ); + }), +); diff --git a/apps/server/src/provider/Drivers/AcpRegistryDriver.ts b/apps/server/src/provider/Drivers/AcpRegistryDriver.ts index 682c85dde9..20a7e5b5ce 100644 --- a/apps/server/src/provider/Drivers/AcpRegistryDriver.ts +++ b/apps/server/src/provider/Drivers/AcpRegistryDriver.ts @@ -14,7 +14,7 @@ import { type AcpRegistryAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/AcpRegistryAdapterV2.ts"; import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts"; -import { ProviderAdapterRequestError, ProviderDriverError } from "../Errors.ts"; +import { ProviderDriverError } from "../Errors.ts"; import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts"; import { defaultProviderContinuationIdentity, @@ -25,32 +25,6 @@ import { const DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const decodeSettings = Schema.decodeSync(AcpRegistrySettings); -const unsupportedLegacyCall = (operation: string) => - Effect.fail( - new ProviderAdapterRequestError({ - provider: DRIVER_KIND, - method: operation, - detail: "ACP Registry instances are available through orchestration V2 only.", - }), - ); - -const makeLegacyAdapter = (): ProviderInstance["adapter"] => ({ - provider: DRIVER_KIND, - capabilities: { sessionModelSwitch: "unsupported" }, - startSession: () => unsupportedLegacyCall("startSession"), - sendTurn: () => unsupportedLegacyCall("sendTurn"), - interruptTurn: () => unsupportedLegacyCall("interruptTurn"), - respondToRequest: () => unsupportedLegacyCall("respondToRequest"), - respondToUserInput: () => unsupportedLegacyCall("respondToUserInput"), - stopSession: () => Effect.void, - listSessions: () => Effect.succeed([]), - hasSession: () => Effect.succeed(false), - readThread: () => unsupportedLegacyCall("readThread"), - rollbackThread: () => unsupportedLegacyCall("rollbackThread"), - stopAll: () => Effect.void, - streamEvents: Stream.empty, -}); - const makeUnsupportedTextGeneration = (): TextGenerationShape => { const unsupported = (operation: string) => Effect.fail( @@ -163,7 +137,6 @@ export const AcpRegistryDriver: ProviderDriver = { const { cwd } = yield* ServerConfig; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; - const eventLoggers = yield* ProviderEventLoggers; const processEnv = mergeProviderInstanceEnvironment(environment); const fallbackContinuationIdentity = defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, @@ -146,12 +142,6 @@ export const ClaudeDriver: ProviderDriver = { continuationGroupKey, }); - const adapterOptions = { - instanceId, - environment: processEnv, - ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), - }; - const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions); const orchestrationAdapter = yield* ClaudeAdapterV2Driver.create({ instanceId, displayName, @@ -235,7 +225,6 @@ export const ClaudeDriver: ProviderDriver = { accentColor, enabled, snapshot, - adapter, orchestrationAdapter, textGeneration, } satisfies ProviderInstance; diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 66f6d9670b..43c93e47f3 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -38,9 +38,7 @@ import { type CodexAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; -import { makeCodexAdapter } from "../Layers/CodexAdapter.ts"; import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts"; -import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts"; import type { ServerProviderDraft } from "../providerSnapshot.ts"; @@ -82,7 +80,6 @@ export type CodexDriverEnv = | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path - | ProviderEventLoggers | ServerConfig | ServerSettingsService; @@ -121,7 +118,6 @@ export const CodexDriver: ProviderDriver = { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; - const eventLoggers = yield* ProviderEventLoggers; const processEnv = mergeProviderInstanceEnvironment(environment); const homeLayout = yield* resolveCodexHomeLayout(config); const continuationIdentity = codexContinuationIdentity(homeLayout); @@ -152,17 +148,6 @@ export const CodexDriver: ProviderDriver = { env: processEnv, }); - // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error - // channels at construction time — their failure modes are all on the - // per-operation closures they return. No `mapError` wrapper is needed - // here; the registry only has to worry about snapshot-build and - // spawner-availability failures surfaced from `checkCodexProviderStatus` - // below. - const adapter = yield* makeCodexAdapter(effectiveConfig, { - instanceId, - environment: processEnv, - ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), - }); const orchestrationAdapter = yield* CodexAdapterV2Driver.create({ instanceId, displayName, @@ -227,7 +212,6 @@ export const CodexDriver: ProviderDriver = { accentColor, enabled, snapshot, - adapter, orchestrationAdapter, textGeneration, } satisfies ProviderInstance; diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts index 802b280843..e071c8a374 100644 --- a/apps/server/src/provider/Drivers/CursorDriver.ts +++ b/apps/server/src/provider/Drivers/CursorDriver.ts @@ -29,14 +29,12 @@ import { type CursorAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/CursorAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; -import { makeCursorAdapter } from "../Layers/CursorAdapter.ts"; import { buildInitialCursorProviderSnapshot, checkCursorProviderStatus, enrichCursorSnapshot, } from "../Layers/CursorProvider.ts"; import { CursorSdkCatalogLive } from "../Layers/CursorSdkCatalog.ts"; -import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { defaultProviderContinuationIdentity, @@ -76,7 +74,6 @@ export type CursorDriverEnv = | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path - | ProviderEventLoggers | ServerConfig | ServerSettingsService; @@ -112,7 +109,6 @@ export const CursorDriver: ProviderDriver = { const path = yield* Path.Path; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; - const eventLoggers = yield* ProviderEventLoggers; const processEnv = mergeProviderInstanceEnvironment(environment); const continuationIdentity = defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, @@ -130,11 +126,6 @@ export const CursorDriver: ProviderDriver = { env: processEnv, }); - const adapter = yield* makeCursorAdapter(effectiveConfig, { - environment: processEnv, - ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), - instanceId, - }); const orchestrationAdapter = yield* CursorAdapterV2Driver.create({ instanceId, displayName, @@ -204,7 +195,6 @@ export const CursorDriver: ProviderDriver = { accentColor, enabled, snapshot, - adapter, orchestrationAdapter, textGeneration, } satisfies ProviderInstance; diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.ts index 149ea429d6..7b6d78aaab 100644 --- a/apps/server/src/provider/Drivers/GrokDriver.ts +++ b/apps/server/src/provider/Drivers/GrokDriver.ts @@ -16,13 +16,11 @@ import { type GrokAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/GrokAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; -import { makeGrokAdapter } from "../Layers/GrokAdapter.ts"; import { buildInitialGrokProviderSnapshot, checkGrokProviderStatus, enrichGrokSnapshot, } from "../Layers/GrokProvider.ts"; -import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { defaultProviderContinuationIdentity, @@ -58,7 +56,6 @@ export type GrokDriverEnv = | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path - | ProviderEventLoggers | ServerConfig | ServerSettingsService; @@ -92,7 +89,6 @@ export const GrokDriver: ProviderDriver = { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; - const eventLoggers = yield* ProviderEventLoggers; const processEnv = mergeProviderInstanceEnvironment(environment); const continuationIdentity = defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, @@ -110,11 +106,6 @@ export const GrokDriver: ProviderDriver = { env: processEnv, }); - const adapter = yield* makeGrokAdapter(effectiveConfig, { - environment: processEnv, - ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), - instanceId, - }); const orchestrationAdapter = yield* GrokAdapterV2Driver.create({ instanceId, displayName, @@ -178,7 +169,6 @@ export const GrokDriver: ProviderDriver = { accentColor, enabled, snapshot, - adapter, orchestrationAdapter, textGeneration, } satisfies ProviderInstance; diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts index 3a6ba24178..30077d97c1 100644 --- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -29,12 +29,10 @@ import { type OpenCodeAdapterV2DriverEnv, } from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; -import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts"; import { checkOpenCodeProviderStatus, makePendingOpenCodeProvider, } from "../Layers/OpenCodeProvider.ts"; -import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { OpenCodeRuntime } from "../opencodeRuntime.ts"; import { @@ -87,7 +85,6 @@ export type OpenCodeDriverEnv = | HttpClient.HttpClient | OpenCodeRuntime | Path.Path - | ProviderEventLoggers | ServerConfig | ServerSettingsService; @@ -121,7 +118,6 @@ export const OpenCodeDriver: ProviderDriver const serverConfig = yield* ServerConfig; const httpClient = yield* HttpClient.HttpClient; const serverSettings = yield* ServerSettingsService; - const eventLoggers = yield* ProviderEventLoggers; const processEnv = mergeProviderInstanceEnvironment(environment); const continuationIdentity = defaultProviderContinuationIdentity({ driverKind: DRIVER_KIND, @@ -139,11 +135,6 @@ export const OpenCodeDriver: ProviderDriver env: processEnv, }); - const adapter = yield* makeOpenCodeAdapter(effectiveConfig, { - instanceId, - environment: processEnv, - ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), - }); const orchestrationAdapter = yield* OpenCodeAdapterV2Driver.create({ instanceId, displayName, @@ -208,7 +199,6 @@ export const OpenCodeDriver: ProviderDriver accentColor, enabled, snapshot, - adapter, orchestrationAdapter, textGeneration, } satisfies ProviderInstance; diff --git a/apps/server/src/provider/Errors.ts b/apps/server/src/provider/Errors.ts index 0cf1522399..35244cc715 100644 --- a/apps/server/src/provider/Errors.ts +++ b/apps/server/src/provider/Errors.ts @@ -1,126 +1,10 @@ import * as Schema from "effect/Schema"; -import type { CheckpointServiceError } from "../checkpointing/Errors.ts"; - -/** - * ProviderAdapterValidationError - Invalid adapter API input. - */ -export class ProviderAdapterValidationError extends Schema.TaggedErrorClass()( - "ProviderAdapterValidationError", - { - provider: Schema.String, - operation: Schema.String, - issue: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Provider adapter validation failed (${this.provider}) in ${this.operation}: ${this.issue}`; - } -} - -/** - * ProviderAdapterSessionNotFoundError - Adapter-owned session id is unknown. - */ -export class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass()( - "ProviderAdapterSessionNotFoundError", - { - provider: Schema.String, - threadId: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Unknown ${this.provider} adapter thread: ${this.threadId}`; - } -} - -/** - * ProviderAdapterSessionClosedError - Adapter session exists but is closed. - */ -export class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass()( - "ProviderAdapterSessionClosedError", - { - provider: Schema.String, - threadId: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `${this.provider} adapter thread is closed: ${this.threadId}`; - } -} - -/** - * ProviderAdapterRequestError - Provider protocol request failed or timed out. - */ -export class ProviderAdapterRequestError extends Schema.TaggedErrorClass()( - "ProviderAdapterRequestError", - { - provider: Schema.String, - method: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`; - } -} - -/** - * ProviderAdapterProcessError - Provider process lifecycle failure. - */ -export class ProviderAdapterProcessError extends Schema.TaggedErrorClass()( - "ProviderAdapterProcessError", - { - provider: Schema.String, - threadId: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`; - } -} - -/** - * ProviderValidationError - Invalid provider API input. - */ -export class ProviderValidationError extends Schema.TaggedErrorClass()( - "ProviderValidationError", - { - operation: Schema.String, - issue: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Provider validation failed in ${this.operation}: ${this.issue}`; - } -} - -/** - * ProviderUnsupportedError - Requested provider is not implemented. - */ -export class ProviderUnsupportedError extends Schema.TaggedErrorClass()( - "ProviderUnsupportedError", - { - provider: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Provider '${this.provider}' is not implemented`; - } -} - /** * ProviderInstanceNotFoundError - Lookup against the instance registry failed. * - * Distinct from `ProviderUnsupportedError`: the driver is registered, but no - * instance with the requested id has been bootstrapped — typically because + * The driver may be registered, but no instance with the requested id has + * been bootstrapped — typically because * the persisted instance id refers to an instance the user removed from * settings, or because routing is asked for an instance before the registry * has finished its first reload. @@ -155,50 +39,3 @@ export class ProviderDriverError extends Schema.TaggedErrorClass()( - "ProviderSessionNotFoundError", - { - threadId: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Unknown provider thread: ${this.threadId}`; - } -} - -/** - * ProviderSessionDirectoryPersistenceError - Session directory persistence failure. - */ -export class ProviderSessionDirectoryPersistenceError extends Schema.TaggedErrorClass()( - "ProviderSessionDirectoryPersistenceError", - { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Provider session directory persistence error in ${this.operation}: ${this.detail}`; - } -} - -export type ProviderAdapterError = - | ProviderAdapterValidationError - | ProviderAdapterSessionNotFoundError - | ProviderAdapterSessionClosedError - | ProviderAdapterRequestError - | ProviderAdapterProcessError; - -export type ProviderServiceError = - | ProviderValidationError - | ProviderUnsupportedError - | ProviderInstanceNotFoundError - | ProviderSessionNotFoundError - | ProviderSessionDirectoryPersistenceError - | ProviderAdapterError - | CheckpointServiceError; diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts deleted file mode 100644 index ebfbbe6489..0000000000 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ /dev/null @@ -1,1203 +0,0 @@ -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { - ApprovalRequestId, - CodexSettings, - EventId, - ProviderDriverKind, - ProviderInstanceId, - ProviderItemId, - type ProviderApprovalDecision, - type ProviderEvent, - type ProviderSession, - type ProviderTurnStartResult, - type ProviderUserInputAnswers, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it, vi } from "@effect/vitest"; - -import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect"; -import * as CodexErrors from "effect-codex-app-server/errors"; - -import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import { ProviderAdapterValidationError } from "../Errors.ts"; -import type { CodexAdapterShape } from "../Services/CodexAdapter.ts"; -import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; -import { - type CodexSessionRuntimeOptions, - type CodexSessionRuntimeSendTurnInput, - type CodexSessionRuntimeShape, - type CodexThreadSnapshot, -} from "../codex/CodexSessionRuntime.ts"; -import { makeCodexAdapterLive } from "./CodexAdapter.ts"; - -const asThreadId = (value: string): ThreadId => ThreadId.make(value); -const asTurnId = (value: string): TurnId => TurnId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value); - -class FakeCodexRuntime implements CodexSessionRuntimeShape { - private readonly eventQueue = Effect.runSync(Queue.unbounded()); - private readonly now = new Date().toISOString(); - - public readonly startImpl = vi.fn(() => - Promise.resolve({ - provider: "codex" as const, - status: "ready" as const, - runtimeMode: this.options.runtimeMode, - threadId: this.options.threadId, - cwd: this.options.cwd, - ...(this.options.model ? { model: this.options.model } : {}), - createdAt: this.now, - updatedAt: this.now, - } satisfies ProviderSession), - ); - - public readonly sendTurnImpl = vi.fn( - (_input: CodexSessionRuntimeSendTurnInput): Promise => - Promise.resolve({ - threadId: this.options.threadId, - turnId: asTurnId("turn-1"), - }), - ); - - public readonly interruptTurnImpl = vi.fn( - (_turnId?: TurnId): Promise => Promise.resolve(undefined), - ); - - public readonly readThreadImpl = vi.fn( - (): Promise => - Promise.resolve({ - threadId: "provider-thread-1", - turns: [], - }), - ); - - public readonly rollbackThreadImpl = vi.fn( - (_numTurns: number): Promise => - Promise.resolve({ - threadId: "provider-thread-1", - turns: [], - }), - ); - - public readonly respondToRequestImpl = vi.fn( - (_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise => - Promise.resolve(undefined), - ); - - public readonly respondToUserInputImpl = vi.fn( - (_requestId: ApprovalRequestId, _answers: ProviderUserInputAnswers): Promise => - Promise.resolve(undefined), - ); - - public readonly closeImpl = vi.fn(() => Promise.resolve(undefined)); - - readonly options: CodexSessionRuntimeOptions; - - constructor(options: CodexSessionRuntimeOptions) { - this.options = options; - } - - start() { - return Effect.promise(() => this.startImpl()); - } - - getSession = Effect.promise(() => this.startImpl()); - - sendTurn(input: CodexSessionRuntimeSendTurnInput) { - return Effect.promise(() => this.sendTurnImpl(input)); - } - - interruptTurn(turnId?: TurnId) { - return Effect.promise(() => this.interruptTurnImpl(turnId)); - } - - readThread = Effect.promise(() => this.readThreadImpl()); - - rollbackThread(numTurns: number) { - return Effect.promise(() => this.rollbackThreadImpl(numTurns)); - } - - respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) { - return Effect.promise(() => this.respondToRequestImpl(requestId, decision)); - } - - respondToUserInput(requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) { - return Effect.promise(() => this.respondToUserInputImpl(requestId, answers)); - } - - get events() { - return Stream.fromQueue(this.eventQueue); - } - - close = Effect.promise(() => this.closeImpl()); - - emit(event: ProviderEvent) { - return Queue.offer(this.eventQueue, event).pipe(Effect.asVoid); - } -} - -function makeRuntimeFactory() { - const runtimes: Array = []; - const factory = vi.fn((options: CodexSessionRuntimeOptions) => { - const runtime = new FakeCodexRuntime(options); - runtimes.push(runtime); - return Effect.succeed(runtime); - }); - - return { - factory, - get lastRuntime(): FakeCodexRuntime | undefined { - return runtimes.at(-1); - }, - }; -} - -function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolean }) { - const runtimes: Array = []; - const releasedThreadIds: Array = []; - - const factory = vi.fn((runtimeOptions: CodexSessionRuntimeOptions) => - Effect.gen(function* () { - yield* Scope.Scope; - yield* Effect.addFinalizer(() => - Effect.sync(() => { - releasedThreadIds.push(runtimeOptions.threadId); - }), - ); - - if (options?.failConstruction) { - return yield* new CodexErrors.CodexAppServerSpawnError({ - command: `${runtimeOptions.binaryPath} app-server`, - cause: new Error("runtime construction failed"), - }); - } - - const runtime = new FakeCodexRuntime(runtimeOptions); - runtimes.push(runtime); - return runtime; - }), - ); - - return { - factory, - releasedThreadIds, - get lastRuntime(): FakeCodexRuntime | undefined { - return runtimes.at(-1); - }, - }; -} - -const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, { - upsert: () => Effect.void, - getProvider: () => - Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")), - getBinding: () => Effect.succeed(Option.none()), - listThreadIds: () => Effect.succeed([]), - listBindings: () => Effect.succeed([]), -}); - -const validationRuntimeFactory = makeRuntimeFactory(); -const validationLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ), -); - -validationLayer("CodexAdapterLive validation", (it) => { - it.effect("returns validation error for non-codex provider on startSession", () => - Effect.gen(function* () { - const adapter = yield* CodexAdapter; - const result = yield* adapter - .startSession({ - provider: ProviderDriverKind.make("claudeAgent"), - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }) - .pipe(Effect.result); - - NodeAssert.equal(result._tag, "Failure"); - NodeAssert.deepStrictEqual( - result.failure, - new ProviderAdapterValidationError({ - provider: ProviderDriverKind.make("codex"), - operation: "startSession", - issue: "Expected provider 'codex' but received 'claudeAgent'.", - }), - ); - assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0); - }), - ); - it.effect("maps codex model options before starting a session", () => - Effect.gen(function* () { - validationRuntimeFactory.factory.mockClear(); - const adapter = yield* CodexAdapter; - - yield* adapter.startSession({ - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ - { id: "serviceTier", value: "priority" }, - ]), - runtimeMode: "full-access", - }); - - assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], { - binaryPath: "codex", - cwd: process.cwd(), - model: "gpt-5.3-codex", - serviceTier: "fast", - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - }), - ); -}); - -const sessionRuntimeFactory = makeRuntimeFactory(); -const sessionErrorLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ), -); - -sessionErrorLayer("CodexAdapterLive session errors", (it) => { - it.effect("maps missing adapter sessions to ProviderAdapterSessionNotFoundError", () => - Effect.gen(function* () { - const adapter = yield* CodexAdapter; - const result = yield* adapter - .sendTurn({ - threadId: asThreadId("sess-missing"), - input: "hello", - attachments: [], - }) - .pipe(Effect.result); - - assert.equal(result._tag, "Failure"); - assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError"); - assert.equal(result.failure.provider, "codex"); - assert.equal(result.failure.threadId, "sess-missing"); - }), - ); - - it.effect("maps codex model options before sending a turn", () => - Effect.gen(function* () { - const adapter = yield* CodexAdapter; - yield* adapter.startSession({ - provider: "codex", - threadId: asThreadId("sess-missing"), - runtimeMode: "full-access", - }); - const runtime = sessionRuntimeFactory.lastRuntime; - assert.ok(runtime); - runtime.sendTurnImpl.mockClear(); - - yield* Effect.ignore( - adapter.sendTurn({ - threadId: asThreadId("sess-missing"), - input: "hello", - modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ - { id: "reasoningEffort", value: "high" }, - { id: "serviceTier", value: "priority" }, - ]), - attachments: [], - }), - ); - - assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], { - input: "hello", - model: "gpt-5.3-codex", - effort: "high", - serviceTier: "priority", - }); - }), - ); - - it.effect("passes configured launch args into the session runtime", () => { - const runtimeFactory = makeRuntimeFactory(); - const layer = Layer.effect( - CodexAdapter, - Effect.gen(function* () { - const codexConfig = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" }); - return yield* makeCodexAdapter(codexConfig, { - makeRuntime: runtimeFactory.factory, - }); - }), - ).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* CodexAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("sess-launch-args"), - runtimeMode: "full-access", - }); - - const runtime = runtimeFactory.lastRuntime; - NodeAssert.ok(runtime); - NodeAssert.equal(runtime.options.launchArgs, "--strict-config --enable foo"); - }).pipe(Effect.provide(layer)); - }); - - it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for the session runtime", () => { - const runtimeFactory = makeRuntimeFactory(); - const layer = Layer.effect( - CodexAdapter, - Effect.gen(function* () { - const codexConfig = decodeCodexSettings({ launchArgs: "--enable settings-feature" }); - return yield* makeCodexAdapter(codexConfig, { - environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --enable env-feature " }, - makeRuntime: runtimeFactory.factory, - }); - }), - ).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* CodexAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("sess-launch-args-env"), - runtimeMode: "full-access", - }); - - const runtime = runtimeFactory.lastRuntime; - NodeAssert.ok(runtime); - NodeAssert.equal(runtime.options.launchArgs, "--strict-config --enable env-feature"); - }).pipe(Effect.provide(layer)); - }); - - it.effect("maps codex model options for the adapter's bound custom instance id", () => { - const customInstanceId = ProviderInstanceId.make("codex_personal"); - const customRuntimeFactory = makeRuntimeFactory(); - const customLayer = Layer.effect( - CodexAdapter, - Effect.gen(function* () { - const codexConfig = decodeCodexSettings({}); - return yield* makeCodexAdapter(codexConfig, { - instanceId: customInstanceId, - makeRuntime: customRuntimeFactory.factory, - }); - }), - ).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* CodexAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("sess-custom-instance"), - runtimeMode: "full-access", - }); - const runtime = customRuntimeFactory.lastRuntime; - NodeAssert.ok(runtime); - runtime.sendTurnImpl.mockClear(); - - yield* Effect.ignore( - adapter.sendTurn({ - threadId: asThreadId("sess-custom-instance"), - input: "hello", - modelSelection: createModelSelection( - ProviderInstanceId.make("codex_personal"), - "gpt-5.3-codex", - [ - { id: "reasoningEffort", value: "high" }, - { id: "serviceTier", value: "flex" }, - ], - ), - attachments: [], - }), - ); - - NodeAssert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], { - input: "hello", - model: "gpt-5.3-codex", - effort: "high", - serviceTier: "flex", - }); - }).pipe(Effect.provide(customLayer)); - }); -}); - -const lifecycleRuntimeFactory = makeRuntimeFactory(); -const lifecycleLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ), -); - -function startLifecycleRuntime() { - return Effect.gen(function* () { - const adapter = yield* CodexAdapter; - yield* adapter.startSession({ - provider: "codex", - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - const runtime = lifecycleRuntimeFactory.lastRuntime; - assert.ok(runtime); - return { adapter, runtime }; - }); -} - -lifecycleLayer("CodexAdapterLive lifecycle", (it) => { - it.effect("maps completed agent message items to canonical item.completed events", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - const event: ProviderEvent = { - id: asEventId("evt-msg-complete"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/completed", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), - itemId: asItemId("msg_1"), - payload: { - threadId: "thread-1", - turnId: "turn-1", - item: { - type: "agentMessage", - id: "msg_1", - text: "done", - }, - }, - }; - - yield* runtime.emit(event); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "item.completed"); - if (firstEvent.value.type !== "item.completed") { - return; - } - NodeAssert.equal(firstEvent.value.itemId, "msg_1"); - NodeAssert.equal(firstEvent.value.turnId, "turn-1"); - NodeAssert.equal(firstEvent.value.payload.itemType, "assistant_message"); - }), - ); - - it.effect("labels MCP lifecycle entries with server and tool names", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - yield* runtime.emit({ - id: asEventId("evt-mcp-complete"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/completed", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), - itemId: asItemId("mcp_1"), - payload: { - completedAtMs: 1_778_000_000_000, - threadId: "thread-1", - turnId: "turn-1", - item: { - type: "mcpToolCall", - id: "mcp_1", - server: "t3-code", - tool: "preview_status", - arguments: {}, - durationMs: 12, - error: null, - result: { content: [{ type: "text", text: "attached" }] }, - status: "completed", - }, - }, - }); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some" || firstEvent.value.type !== "item.completed") { - return; - } - NodeAssert.equal(firstEvent.value.payload.itemType, "mcp_tool_call"); - NodeAssert.equal(firstEvent.value.payload.title, "t3-code · preview_status"); - NodeAssert.deepStrictEqual(firstEvent.value.payload.data, { - completedAtMs: 1_778_000_000_000, - threadId: "thread-1", - turnId: "turn-1", - item: { - type: "mcpToolCall", - id: "mcp_1", - server: "t3-code", - tool: "preview_status", - arguments: {}, - durationMs: 12, - error: null, - result: { content: [{ type: "text", text: "attached" }] }, - status: "completed", - }, - }); - }), - ); - - it.effect("maps completed plan items to canonical proposed-plan completion events", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - const event: ProviderEvent = { - id: asEventId("evt-plan-complete"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/completed", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), - itemId: asItemId("plan_1"), - payload: { - threadId: "thread-1", - turnId: "turn-1", - item: { - type: "plan", - id: "plan_1", - text: "## Final plan\n\n- one\n- two", - }, - }, - }; - - yield* runtime.emit(event); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "turn.proposed.completed"); - if (firstEvent.value.type !== "turn.proposed.completed") { - return; - } - NodeAssert.equal(firstEvent.value.turnId, "turn-1"); - NodeAssert.equal(firstEvent.value.payload.planMarkdown, "## Final plan\n\n- one\n- two"); - }), - ); - - it.effect("maps plan deltas to canonical proposed-plan delta events", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - yield* runtime.emit({ - id: asEventId("evt-plan-delta"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/plan/delta", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), - itemId: asItemId("plan_1"), - payload: { - threadId: "thread-1", - turnId: "turn-1", - itemId: "plan_1", - delta: "## Final plan", - }, - } satisfies ProviderEvent); - - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "turn.proposed.delta"); - if (firstEvent.value.type !== "turn.proposed.delta") { - return; - } - NodeAssert.equal(firstEvent.value.turnId, "turn-1"); - NodeAssert.equal(firstEvent.value.payload.delta, "## Final plan"); - }), - ); - - it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - const event: ProviderEvent = { - id: asEventId("evt-session-closed"), - kind: "session", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "session/closed", - message: "Session stopped", - }; - - yield* runtime.emit(event); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "session.exited"); - if (firstEvent.value.type !== "session.exited") { - return; - } - NodeAssert.equal(firstEvent.value.threadId, "thread-1"); - NodeAssert.equal(firstEvent.value.payload.reason, "Session stopped"); - }), - ); - - it.effect("maps retryable Codex error notifications to runtime.warning", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - yield* runtime.emit({ - id: asEventId("evt-retryable-error"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "error", - turnId: asTurnId("turn-1"), - payload: { - threadId: "thread-1", - turnId: "turn-1", - error: { - message: "Reconnecting... 2/5", - }, - willRetry: true, - }, - } satisfies ProviderEvent); - - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "runtime.warning"); - if (firstEvent.value.type !== "runtime.warning") { - return; - } - NodeAssert.equal(firstEvent.value.turnId, "turn-1"); - NodeAssert.equal(firstEvent.value.payload.message, "Reconnecting... 2/5"); - }), - ); - - it.effect("maps process stderr notifications to runtime.warning", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - yield* runtime.emit({ - id: asEventId("evt-process-stderr"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "process/stderr", - turnId: asTurnId("turn-1"), - message: "The filename or extension is too long. (os error 206)", - } satisfies ProviderEvent); - - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "runtime.warning"); - if (firstEvent.value.type !== "runtime.warning") { - return; - } - NodeAssert.equal(firstEvent.value.turnId, "turn-1"); - NodeAssert.equal( - firstEvent.value.payload.message, - "The filename or extension is too long. (os error 206)", - ); - }), - ); - - it.effect("maps realtime started notifications with upstream realtime session ids", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - yield* runtime.emit({ - id: asEventId("evt-process-stderr-websocket"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "process/stderr", - turnId: asTurnId("turn-1"), - message: - "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", - } satisfies ProviderEvent); - - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "runtime.error"); - if (firstEvent.value.type !== "runtime.error") { - return; - } - NodeAssert.equal(firstEvent.value.turnId, "turn-1"); - NodeAssert.equal(firstEvent.value.payload.class, "provider_error"); - NodeAssert.equal( - firstEvent.value.payload.message, - "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", - ); - }), - ); - - it.effect("preserves request type when mapping serverRequest/resolved", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - const event: ProviderEvent = { - id: asEventId("evt-request-resolved"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "serverRequest/resolved", - requestKind: "command", - requestId: ApprovalRequestId.make("req-1"), - payload: { - threadId: "thread-1", - requestId: "req-1", - }, - }; - - yield* runtime.emit(event); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "request.resolved"); - if (firstEvent.value.type !== "request.resolved") { - return; - } - NodeAssert.equal(firstEvent.value.payload.requestType, "command_execution_approval"); - }), - ); - - it.effect("preserves file-read request type when mapping serverRequest/resolved", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - const event: ProviderEvent = { - id: asEventId("evt-file-read-request-resolved"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "serverRequest/resolved", - requestKind: "file-read", - requestId: ApprovalRequestId.make("req-file-read-1"), - payload: { - threadId: "thread-1", - requestId: "req-file-read-1", - }, - }; - - yield* runtime.emit(event); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "request.resolved"); - if (firstEvent.value.type !== "request.resolved") { - return; - } - NodeAssert.equal(firstEvent.value.payload.requestType, "file_read_approval"); - }), - ); - - it.effect("preserves explicit empty multi-select user-input answers", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - const event: ProviderEvent = { - id: asEventId("evt-user-input-empty"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/tool/requestUserInput/answered", - payload: { - answers: { - scope: { - answers: [], - }, - }, - }, - }; - - yield* runtime.emit(event); - const firstEvent = yield* Fiber.join(firstEventFiber); - - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "user-input.resolved"); - if (firstEvent.value.type !== "user-input.resolved") { - return; - } - NodeAssert.deepEqual(firstEvent.value.payload.answers, { - scope: [], - }); - }), - ); - - it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe( - Effect.forkChild, - ); - - const event: ProviderEvent = { - id: asEventId("evt-windows-sandbox-failed"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "windowsSandbox/setupCompleted", - message: "Sandbox setup failed", - payload: { - mode: "unelevated", - success: false, - error: "unsupported environment", - }, - }; - - yield* runtime.emit(event); - const events = Array.from(yield* Fiber.join(eventsFiber)); - - NodeAssert.equal(events.length, 2); - - const firstEvent = events[0]; - const secondEvent = events[1]; - - NodeAssert.equal(firstEvent?.type, "session.state.changed"); - if (firstEvent?.type === "session.state.changed") { - NodeAssert.equal(firstEvent.payload.state, "error"); - NodeAssert.equal(firstEvent.payload.reason, "Sandbox setup failed"); - } - - NodeAssert.equal(secondEvent?.type, "runtime.warning"); - if (secondEvent?.type === "runtime.warning") { - NodeAssert.equal(secondEvent.payload.message, "Sandbox setup failed"); - } - }), - ); - - it.effect( - "maps requestUserInput requests and answered notifications to canonical user-input events", - () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe( - Effect.forkChild, - ); - - yield* runtime.emit({ - id: asEventId("evt-user-input-requested"), - kind: "request", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/tool/requestUserInput", - requestId: ApprovalRequestId.make("req-user-input-1"), - payload: { - itemId: "item-user-input-1", - threadId: "thread-1", - turnId: "turn-1", - questions: [ - { - id: "sandbox_mode", - header: "Sandbox", - question: "Which mode should be used?", - options: [ - { - label: "workspace-write", - description: "Allow workspace writes only", - }, - ], - }, - ], - }, - } satisfies ProviderEvent); - yield* runtime.emit({ - id: asEventId("evt-user-input-resolved"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "item/tool/requestUserInput/answered", - requestId: ApprovalRequestId.make("req-user-input-1"), - payload: { - answers: { - sandbox_mode: { - answers: ["workspace-write"], - }, - }, - }, - } satisfies ProviderEvent); - - const events = Array.from(yield* Fiber.join(eventsFiber)); - NodeAssert.equal(events[0]?.type, "user-input.requested"); - if (events[0]?.type === "user-input.requested") { - assert.equal(events[0].requestId, "req-user-input-1"); - assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode"); - assert.equal(events[0].payload.questions[0]?.multiSelect, false); - } - - NodeAssert.equal(events[1]?.type, "user-input.resolved"); - if (events[1]?.type === "user-input.resolved") { - NodeAssert.equal(events[1].requestId, "req-user-input-1"); - NodeAssert.deepEqual(events[1].payload.answers, { - sandbox_mode: "workspace-write", - }); - } - }), - ); - - it.effect("unwraps Codex token usage payloads for context window events", () => - Effect.gen(function* () { - const { adapter, runtime } = yield* startLifecycleRuntime(); - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - yield* runtime.emit({ - id: asEventId("evt-codex-thread-token-usage-updated"), - kind: "notification", - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), - createdAt: "2026-01-01T00:00:00.000Z", - method: "thread/tokenUsage/updated", - payload: { - threadId: "thread-1", - turnId: "turn-1", - tokenUsage: { - total: { - inputTokens: 11_833, - cachedInputTokens: 3456, - outputTokens: 6, - reasoningOutputTokens: 0, - totalTokens: 11_839, - }, - last: { - inputTokens: 120, - cachedInputTokens: 0, - outputTokens: 6, - reasoningOutputTokens: 0, - totalTokens: 126, - }, - modelContextWindow: 258_400, - }, - }, - } satisfies ProviderEvent); - - const firstEvent = yield* Fiber.join(firstEventFiber); - NodeAssert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - NodeAssert.equal(firstEvent.value.type, "thread.token-usage.updated"); - if (firstEvent.value.type !== "thread.token-usage.updated") { - return; - } - - NodeAssert.deepEqual(firstEvent.value.payload.usage, { - usedTokens: 126, - totalProcessedTokens: 11_839, - maxTokens: 258_400, - inputTokens: 120, - cachedInputTokens: 0, - outputTokens: 6, - reasoningOutputTokens: 0, - lastUsedTokens: 126, - lastInputTokens: 120, - lastCachedInputTokens: 0, - lastOutputTokens: 6, - lastReasoningOutputTokens: 0, - compactsAutomatically: true, - }); - }), - ); -}); - -const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory(); -const scopedLifecycleLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ), -); - -scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => { - it.effect("closes the externally owned session scope on stopSession", () => - Effect.gen(function* () { - scopedLifecycleRuntimeFactory.releasedThreadIds.length = 0; - const adapter = yield* CodexAdapter; - - yield* adapter.startSession({ - provider: "codex", - threadId: asThreadId("thread-stop"), - runtimeMode: "full-access", - }); - - const runtime = scopedLifecycleRuntimeFactory.lastRuntime; - assert.ok(runtime); - - yield* adapter.stopSession(asThreadId("thread-stop")); - - assert.equal(runtime.closeImpl.mock.calls.length, 1); - assert.deepStrictEqual(scopedLifecycleRuntimeFactory.releasedThreadIds, [ - asThreadId("thread-stop"), - ]); - assert.equal(yield* adapter.hasSession(asThreadId("thread-stop")), false); - }), - ); -}); - -const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true }); -const scopedFailureLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ), -); - -scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => { - it.effect("closes the externally owned session scope when startSession fails", () => - Effect.gen(function* () { - scopedFailureRuntimeFactory.releasedThreadIds.length = 0; - const adapter = yield* CodexAdapter; - - const result = yield* adapter - .startSession({ - provider: "codex", - threadId: asThreadId("thread-fail"), - runtimeMode: "full-access", - }) - .pipe(Effect.result); - - assert.equal(result._tag, "Failure"); - assert.equal(result.failure._tag, "ProviderAdapterProcessError"); - assert.deepStrictEqual(scopedFailureRuntimeFactory.releasedThreadIds, [ - asThreadId("thread-fail"), - ]); - assert.equal(yield* adapter.hasSession(asThreadId("thread-fail")), false); - }), - ); -}); - -it.effect("flushes managed native logs when the adapter layer shuts down", () => - Effect.gen(function* () { - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-codex-adapter-native-log-")); - const basePath = path.join(tempDir, "provider-native.ndjson"); - const runtimeFactory = makeRuntimeFactory(); - const scope = yield* Scope.make("sequential"); - let scopeClosed = false; - - try { - const layer = makeCodexAdapterLive({ - makeRuntime: runtimeFactory.factory, - nativeEventLogPath: basePath, - }).pipe( - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - const context = yield* Layer.buildWithScope(layer, scope); - const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context)); - - yield* adapter.startSession({ - provider: "codex", - threadId: asThreadId("thread-logger"), - runtimeMode: "full-access", - }); - - const runtime = runtimeFactory.lastRuntime; - assert.ok(runtime); - - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - yield* runtime.emit({ - id: asEventId("evt-native-log"), - kind: "notification", - provider: "codex", - threadId: asThreadId("thread-logger"), - createdAt: new Date().toISOString(), - method: "process/stderr", - message: "native flush test", - } satisfies ProviderEvent); - yield* Fiber.join(firstEventFiber); - - yield* Scope.close(scope, Exit.void); - scopeClosed = true; - - const threadLogPath = path.join(tempDir, "thread-logger.log"); - assert.equal(fs.existsSync(threadLogPath), true); - const contents = fs.readFileSync(threadLogPath, "utf8"); - assert.match(contents, /NTIVE: .*"message":"native flush test"/); - } finally { - if (!scopeClosed) { - yield* Scope.close(scope, Exit.void); - } - fs.rmSync(tempDir, { recursive: true, force: true }); - } - }), -); diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts deleted file mode 100644 index c4d9291c02..0000000000 --- a/apps/server/src/provider/Layers/CursorAdapter.test.ts +++ /dev/null @@ -1,1323 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodePath from "node:path"; -import * as NodeOS from "node:os"; -import * as NodeFSP from "node:fs/promises"; -import * as NodeURL from "node:url"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import * as Context from "effect/Context"; -import * as Deferred from "effect/Deferred"; -import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import { createModelSelection } from "@t3tools/shared/model"; - -import { - ApprovalRequestId, - CursorSettings, - ProviderDriverKind, - type ProviderRuntimeEvent, - ThreadId, - ProviderInstanceId, -} from "@t3tools/contracts"; - -import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import type { CursorAdapterShape } from "../Services/CursorAdapter.ts"; -import { makeCursorAdapter } from "./CursorAdapter.ts"; -const decodeCursorSettings = Schema.decodeSync(CursorSettings); - -// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`. -class CursorAdapter extends Context.Service()( - "t3/provider/Layers/CursorAdapter.test/CursorAdapter", -) {} - -const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); -const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts"); -const mockAgentCommand = "node"; -const mockAgentArgs = [mockAgentPath] as const; - -async function makeMockAgentWrapper( - extraEnv?: Record, - options?: { initialDelaySeconds?: number }, -) { - const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-")); - const wrapperPath = path.join(dir, "fake-agent.sh"); - const envExports = Object.entries(extraEnv ?? {}) - .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`) - .join("\n"); - const script = `#!/bin/sh -${envExports} -${options?.initialDelaySeconds ? `sleep ${JSON.stringify(String(options.initialDelaySeconds))}` : ""} -exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@" -`; - await NodeFSP.writeFile(wrapperPath, script, "utf8"); - await NodeFSP.chmod(wrapperPath, 0o755); - return wrapperPath; -} - -async function makeProbeWrapper( - requestLogPath: string, - argvLogPath: string, - extraEnv?: Record, -) { - const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-probe-")); - const wrapperPath = NodePath.join(dir, "fake-agent.sh"); - const envExports = Object.entries(extraEnv ?? {}) - .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`) - .join("\n"); - const script = `#!/bin/sh -printf '%s\t' "$@" >> ${JSON.stringify(argvLogPath)} -printf '\n' >> ${JSON.stringify(argvLogPath)} -export T3_ACP_REQUEST_LOG_PATH=${JSON.stringify(requestLogPath)} -${envExports} -exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.stringify(arg)).join(" ")} "$@" -`; - await NodeFSP.writeFile(wrapperPath, script, "utf8"); - await NodeFSP.chmod(wrapperPath, 0o755); - return wrapperPath; -} - -async function readArgvLog(filePath: string) { - const raw = await NodeFSP.readFile(filePath, "utf8"); - return raw - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .map((line) => line.split("\t").filter((token) => token.length > 0)); -} - -async function readJsonLines(filePath: string) { - const raw = await NodeFSP.readFile(filePath, "utf8"); - return raw - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record); -} - -async function waitForFileContent(filePath: string, attempts = 40) { - for (let attempt = 0; attempt < attempts; attempt += 1) { - try { - const raw = await readFile(filePath, "utf8"); - if (raw.trim().length > 0) { - return raw; - } - } catch {} - await new Promise((resolve) => setTimeout(resolve, 50)); - } - throw new Error(`Timed out waiting for file content at ${filePath}`); -} - -const cursorAdapterTestLayer = it.layer( - Layer.effect( - CursorAdapter, - Effect.gen(function* () { - const cursorConfig = decodeCursorSettings({}); - const resolveSettings = yield* makeResolveCursorSettings; - return yield* makeCursorAdapter(cursorConfig, { resolveSettings }); - }), - ).pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-cursor-adapter-test-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ), -); - -cursorAdapterTestLayer("CursorAdapterLive", (it) => { - it.effect("starts a session and maps mock ACP prompt flow to runtime events", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const settings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-mock-thread"); - - const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper()); - yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe( - Stream.runCollect, - Effect.forkChild, - ); - - const session = yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - assert.equal(session.provider, "cursor"); - assert.deepStrictEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "mock-session-1", - }); - - yield* adapter.sendTurn({ - threadId, - input: "hello mock", - attachments: [], - }); - - const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); - const types = runtimeEvents.map((e) => e.type); - - for (const t of [ - "session.started", - "session.state.changed", - "thread.started", - "turn.started", - "turn.plan.updated", - "item.started", - "content.delta", - "item.completed", - "turn.completed", - ] as const) { - assert.include(types, t); - } - - const assistantStarted = runtimeEvents.find( - (event) => event.type === "item.started" && event.payload.itemType === "assistant_message", - ); - assert.isDefined(assistantStarted); - - const delta = runtimeEvents.find((e) => e.type === "content.delta"); - assert.isDefined(delta); - if (delta?.type === "content.delta") { - assert.equal(delta.payload.delta, "hello from mock"); - assert.match(String(delta.itemId), /^assistant:mock-session-1:runtime:[^:]+:segment:0$/); - } - - const assistantCompleted = runtimeEvents.find( - (event) => - event.type === "item.completed" && event.payload.itemType === "assistant_message", - ); - assert.isDefined(assistantCompleted); - - const planUpdate = runtimeEvents.find((event) => event.type === "turn.plan.updated"); - assert.isDefined(planUpdate); - if (planUpdate?.type === "turn.plan.updated") { - assert.deepStrictEqual(planUpdate.payload.plan, [ - { step: "Inspect mock ACP state", status: "completed" }, - { step: "Implement the requested change", status: "inProgress" }, - ]); - } - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("closes the ACP child process when a session stops", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const settings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-stop-session-close"); - const tempDir = yield* Effect.promise(() => - mkdtemp(path.join(os.tmpdir(), "cursor-adapter-exit-log-")), - ); - const exitLogPath = path.join(tempDir, "exit.log"); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper({ - T3_ACP_EXIT_LOG_PATH: exitLogPath, - }), - ); - yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* adapter.startSession({ - threadId, - provider: "cursor", - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, - }); - - yield* adapter.stopSession(threadId); - - const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath)); - assert.include(exitLog, "SIGTERM"); - }), - ); - - it.effect( - "serializes concurrent startSession calls for the same thread and closes the replaced ACP session", - () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const settings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-concurrent-start-session"); - const tempDir = yield* Effect.promise(() => - mkdtemp(path.join(os.tmpdir(), "cursor-adapter-concurrent-exit-log-")), - ); - const exitLogPath = path.join(tempDir, "exit.log"); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper( - { - T3_ACP_EXIT_LOG_PATH: exitLogPath, - }, - { initialDelaySeconds: 0.2 }, - ), - ); - yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - const [firstSession, secondSession] = yield* Effect.all( - [ - adapter.startSession({ - threadId, - provider: "cursor", - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, - }), - adapter.startSession({ - threadId, - provider: "cursor", - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, - }), - ], - { concurrency: "unbounded" }, - ); - - assert.equal(firstSession.threadId, threadId); - assert.equal(secondSession.threadId, threadId); - - yield* adapter.stopSession(threadId); - - const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath)); - assert.equal(exitLog.match(/SIGTERM/g)?.length ?? 0, 2); - }), - ); - - it.effect("rejects startSession when provider mismatches", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const result = yield* adapter - .startSession({ - threadId: ThreadId.make("bad-provider"), - provider: ProviderDriverKind.make("codex"), - cwd: process.cwd(), - runtimeMode: "full-access", - }) - .pipe(Effect.result); - - assert.equal(result._tag, "Failure"); - }), - ); - - it.effect("maps app plan mode onto the ACP plan session mode", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-plan-mode-probe"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const argvLogPath = NodePath.join(tempDir, "argv.txt"); - yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "plan this change", - attachments: [], - interactionMode: "plan", - }); - yield* adapter.stopSession(threadId); - - const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const modeRequest = requests - .toReversed() - .find( - (entry) => - entry.method === "session/set_mode" || - (entry.method === "session/set_config_option" && - (entry.params as Record | undefined)?.configId === "mode"), - ); - assert.isDefined(modeRequest); - assert.equal( - (modeRequest?.params as Record | undefined)?.sessionId, - "mock-session-1", - ); - assert.include( - ["architect", "plan"], - String( - (modeRequest?.params as Record | undefined)?.modeId ?? - (modeRequest?.params as Record | undefined)?.value, - ), - ); - }), - ); - - it.effect( - "applies initial model and mode configuration during startSession and skips repeating it on first send", - () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-initial-config-probe"); - const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-"))); - const requestLogPath = path.join(tempDir, "requests.ndjson"); - const argvLogPath = path.join(tempDir, "argv.txt"); - yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath), - ); - yield* serverSettings.updateSettings({ - providers: { cursor: { binaryPath: wrapperPath } }, - }); - - const modelSelection = { - provider: "cursor" as const, - model: "gpt-5.4", - options: { - reasoning: "xhigh" as const, - contextWindow: "1m", - fastMode: true, - }, - }; - - yield* adapter.startSession({ - threadId, - provider: "cursor", - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection, - }); - - yield* Effect.promise(() => waitForFileContent(requestLogPath)); - - const requestsAfterStart = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const configIdsAfterStart = requestsAfterStart.flatMap((entry) => - entry.method === "session/set_config_option" && - typeof (entry.params as Record | undefined)?.configId === "string" - ? [String((entry.params as Record).configId)] - : [], - ); - assert.deepStrictEqual(configIdsAfterStart, [ - "model", - "reasoning", - "context", - "fast", - "mode", - ]); - - yield* adapter.sendTurn({ - threadId, - input: "hello mock", - attachments: [], - modelSelection, - interactionMode: "default", - }); - yield* adapter.stopSession(threadId); - - const finalRequests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const finalConfigIds = finalRequests.flatMap((entry) => - entry.method === "session/set_config_option" && - typeof (entry.params as Record | undefined)?.configId === "string" - ? [String((entry.params as Record).configId)] - : [], - ); - assert.deepStrictEqual(finalConfigIds, ["model", "reasoning", "context", "fast", "mode"]); - assert.equal(finalRequests.filter((entry) => entry.method === "session/prompt").length, 1); - }), - ); - - it.effect( - "streams ACP tool calls and approvals on the active turn in approval-required mode", - () => - Effect.gen(function* () { - const previousEmitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS; - process.env.T3_ACP_EMIT_TOOL_CALLS = "1"; - - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-tool-call-probe"); - const runtimeEvents: Array = []; - const settledEventTypes = new Set(); - const settledEventsReady = yield* Deferred.make(); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper({ T3_ACP_EMIT_TOOL_CALLS: "1" }), - ); - yield* serverSettings.updateSettings({ - providers: { cursor: { binaryPath: wrapperPath } }, - }); - - yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.gen(function* () { - runtimeEvents.push(event); - if (String(event.threadId) !== String(threadId)) { - return; - } - if (event.type === "request.opened" && event.requestId) { - yield* adapter.respondToRequest( - threadId, - ApprovalRequestId.make(String(event.requestId)), - "accept", - ); - } - if ( - event.type === "turn.completed" || - (event.type === "item.completed" && event.payload.itemType === "command_execution") || - event.type === "content.delta" - ) { - settledEventTypes.add(event.type); - if (settledEventTypes.size === 3) { - yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie); - } - } - }), - ).pipe(Effect.forkChild); - - const program = Effect.gen(function* () { - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "approval-required", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - const turn = yield* adapter.sendTurn({ - threadId, - input: "run a tool call", - attachments: [], - }); - yield* Deferred.await(settledEventsReady); - - const threadEvents = runtimeEvents.filter( - (event) => String(event.threadId) === String(threadId), - ); - assert.includeMembers( - threadEvents.map((event) => event.type), - [ - "session.started", - "session.state.changed", - "thread.started", - "turn.started", - "request.opened", - "request.resolved", - "item.updated", - "item.completed", - "content.delta", - "turn.completed", - ], - ); - - const turnEvents = threadEvents.filter( - (event) => String(event.turnId) === String(turn.turnId), - ); - const toolUpdates = turnEvents.filter((event) => event.type === "item.updated"); - // ACP updates can arrive either as distinct pending + in-progress events - // or as a single coalesced in-progress update before approval resolves. - assert.isAtLeast(toolUpdates.length, 1); - for (const toolUpdate of toolUpdates) { - if (toolUpdate.type !== "item.updated") { - continue; - } - assert.equal(toolUpdate.payload.itemType, "command_execution"); - assert.equal(toolUpdate.payload.status, "inProgress"); - assert.equal(toolUpdate.payload.detail, "cat server/package.json"); - assert.equal(String(toolUpdate.itemId), "tool-call-1"); - } - - const requestOpened = turnEvents.find((event) => event.type === "request.opened"); - assert.isDefined(requestOpened); - if (requestOpened?.type === "request.opened") { - assert.equal(String(requestOpened.turnId), String(turn.turnId)); - assert.equal(requestOpened.payload.requestType, "exec_command_approval"); - assert.equal(requestOpened.payload.detail, "cat server/package.json"); - } - - const requestResolved = turnEvents.find((event) => event.type === "request.resolved"); - assert.isDefined(requestResolved); - if (requestResolved?.type === "request.resolved") { - assert.equal(String(requestResolved.turnId), String(turn.turnId)); - assert.equal(requestResolved.payload.requestType, "exec_command_approval"); - assert.equal(requestResolved.payload.decision, "accept"); - } - - const toolCompleted = turnEvents.find( - (event) => - event.type === "item.completed" && event.payload.itemType === "command_execution", - ); - assert.isDefined(toolCompleted); - if (toolCompleted?.type === "item.completed") { - assert.equal(String(toolCompleted.turnId), String(turn.turnId)); - assert.equal(toolCompleted.payload.itemType, "command_execution"); - assert.equal(toolCompleted.payload.status, "completed"); - assert.equal(toolCompleted.payload.detail, "cat server/package.json"); - assert.equal(String(toolCompleted.itemId), "tool-call-1"); - } - - const contentDelta = turnEvents.find((event) => event.type === "content.delta"); - assert.isDefined(contentDelta); - if (contentDelta?.type === "content.delta") { - assert.equal(String(contentDelta.turnId), String(turn.turnId)); - assert.equal(contentDelta.payload.delta, "hello from mock"); - assert.match( - String(contentDelta.itemId), - /^assistant:mock-session-1:runtime:[^:]+:segment:0$/, - ); - } - }); - - yield* program.pipe( - Effect.ensuring( - Effect.sync(() => { - if (previousEmitToolCalls === undefined) { - delete process.env.T3_ACP_EMIT_TOOL_CALLS; - } else { - process.env.T3_ACP_EMIT_TOOL_CALLS = previousEmitToolCalls; - } - }), - ), - ); - }).pipe( - Effect.provide( - Layer.effect( - CursorAdapter, - Effect.gen(function* () { - const cursorConfig = decodeCursorSettings({}); - const resolveSettings = yield* makeResolveCursorSettings; - return yield* makeCursorAdapter(cursorConfig, { resolveSettings }); - }), - ).pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-cursor-adapter-test-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ), - ), - ), - ); - - it.effect( - "auto-approves ACP tool permissions in full-access mode without approval runtime events", - () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-full-access-auto-approve"); - const runtimeEvents: Array = []; - const settledEventTypes = new Set(); - const settledEventsReady = yield* Deferred.make(); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const argvLogPath = NodePath.join(tempDir, "argv.txt"); - yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath, { T3_ACP_EMIT_TOOL_CALLS: "1" }), - ); - yield* serverSettings.updateSettings({ - providers: { cursor: { binaryPath: wrapperPath } }, - }); - - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.gen(function* () { - runtimeEvents.push(event); - if (String(event.threadId) !== String(threadId)) { - return; - } - if ( - event.type === "turn.completed" || - (event.type === "item.completed" && event.payload.itemType === "command_execution") || - event.type === "content.delta" - ) { - settledEventTypes.add(event.type); - if (settledEventTypes.size === 3) { - yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie); - } - } - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - const turn = yield* adapter.sendTurn({ - threadId, - input: "run a tool call", - attachments: [], - }); - - yield* Deferred.await(settledEventsReady); - yield* Fiber.interrupt(runtimeEventsFiber); - - const turnEvents = runtimeEvents.filter( - (event) => - String(event.threadId) === String(threadId) && - String(event.turnId) === String(turn.turnId), - ); - assert.notInclude( - turnEvents.map((event) => event.type), - "request.opened", - ); - assert.notInclude( - turnEvents.map((event) => event.type), - "request.resolved", - ); - assert.includeMembers( - turnEvents.map((event) => event.type), - ["item.updated", "item.completed", "content.delta", "turn.completed"], - ); - - const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const permissionResponse = requests.find( - (entry) => - !("method" in entry) && - typeof entry.result === "object" && - entry.result !== null && - "outcome" in entry.result && - typeof entry.result.outcome === "object" && - entry.result.outcome !== null && - "outcome" in entry.result.outcome && - entry.result.outcome.outcome === "selected" && - "optionId" in entry.result.outcome && - entry.result.outcome.optionId === "allow-always", - ); - assert.isDefined(permissionResponse); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("segments assistant messages around ACP tool activity in full-access mode", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-assistant-tool-segmentation"); - const runtimeEvents: Array = []; - const settledEventTypes = new Set(); - const settledEventsReady = yield* Deferred.make(); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper({ T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1" }), - ); - yield* serverSettings.updateSettings({ - providers: { cursor: { binaryPath: wrapperPath } }, - }); - - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.gen(function* () { - runtimeEvents.push(event); - if (String(event.threadId) !== String(threadId)) { - return; - } - if ( - event.type === "content.delta" || - (event.type === "item.completed" && event.payload.itemType === "command_execution") || - event.type === "turn.completed" - ) { - if (event.type === "content.delta") { - settledEventTypes.add(`delta:${event.payload.delta}`); - } else { - settledEventTypes.add(event.type); - } - if ( - settledEventTypes.has("delta:before tool") && - settledEventTypes.has("delta:after tool") && - settledEventTypes.has("item.completed") && - settledEventTypes.has("turn.completed") - ) { - yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie); - } - } - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - const turn = yield* adapter.sendTurn({ - threadId, - input: "run an interleaved tool call", - attachments: [], - }); - - yield* Deferred.await(settledEventsReady); - yield* Fiber.interrupt(runtimeEventsFiber); - - const turnEvents = runtimeEvents.filter( - (event) => - String(event.threadId) === String(threadId) && - String(event.turnId) === String(turn.turnId), - ); - const firstAssistantStartIndex = turnEvents.findIndex( - (event) => event.type === "item.started" && event.payload.itemType === "assistant_message", - ); - const firstAssistantDeltaIndex = turnEvents.findIndex( - (event) => event.type === "content.delta" && event.payload.delta === "before tool", - ); - const assistantBoundaryIndex = turnEvents.findIndex( - (event) => - event.type === "item.completed" && event.payload.itemType === "assistant_message", - ); - const toolUpdateIndex = turnEvents.findIndex( - (event) => event.type === "item.updated" && event.payload.itemType === "command_execution", - ); - const toolCompletedIndex = turnEvents.findIndex( - (event) => - event.type === "item.completed" && event.payload.itemType === "command_execution", - ); - const secondAssistantStartIndex = turnEvents.findIndex( - (event, index) => - index > toolCompletedIndex && - event.type === "item.started" && - event.payload.itemType === "assistant_message", - ); - const secondAssistantDeltaIndex = turnEvents.findIndex( - (event) => event.type === "content.delta" && event.payload.delta === "after tool", - ); - - assert.isAtLeast(firstAssistantStartIndex, 0); - assert.isAtLeast(firstAssistantDeltaIndex, 0); - assert.isAtLeast(assistantBoundaryIndex, 0); - assert.isAtLeast(toolUpdateIndex, 0); - assert.isAtLeast(toolCompletedIndex, 0); - assert.isAtLeast(secondAssistantStartIndex, 0); - assert.isAtLeast(secondAssistantDeltaIndex, 0); - assert.isBelow(firstAssistantStartIndex, firstAssistantDeltaIndex); - assert.isBelow(firstAssistantDeltaIndex, assistantBoundaryIndex); - assert.isBelow(assistantBoundaryIndex, toolUpdateIndex); - assert.isBelow(toolUpdateIndex, toolCompletedIndex); - assert.isBelow(toolCompletedIndex, secondAssistantStartIndex); - assert.isBelow(secondAssistantStartIndex, secondAssistantDeltaIndex); - - const assistantStarts = turnEvents.filter( - (event) => event.type === "item.started" && event.payload.itemType === "assistant_message", - ); - const assistantDeltas = turnEvents.filter((event) => event.type === "content.delta"); - assert.lengthOf(assistantStarts, 2); - assert.lengthOf(assistantDeltas, 2); - if ( - assistantStarts[0]?.type === "item.started" && - assistantStarts[1]?.type === "item.started" && - assistantDeltas[0]?.type === "content.delta" && - assistantDeltas[1]?.type === "content.delta" - ) { - assert.notEqual(String(assistantStarts[0].itemId), String(assistantStarts[1].itemId)); - assert.equal(String(assistantDeltas[0].itemId), String(assistantStarts[0].itemId)); - assert.equal(String(assistantDeltas[1].itemId), String(assistantStarts[1].itemId)); - } - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("cancels pending ACP approvals and marks the turn cancelled when interrupted", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-cancel-probe"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const argvLogPath = NodePath.join(tempDir, "argv.txt"); - yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath, { T3_ACP_EMIT_TOOL_CALLS: "1" }), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - const requestResolvedReady = yield* Deferred.make(); - const turnCompletedReady = yield* Deferred.make(); - let interrupted = false; - - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.gen(function* () { - if (String(event.threadId) !== String(threadId)) { - return; - } - if (event.type === "request.opened" && event.requestId && !interrupted) { - interrupted = true; - yield* adapter.respondToRequest( - threadId, - ApprovalRequestId.make(String(event.requestId)), - "cancel", - ); - yield* adapter.interruptTurn(threadId); - return; - } - if (event.type === "request.resolved") { - yield* Deferred.succeed(requestResolvedReady, event).pipe(Effect.ignore); - return; - } - if (event.type === "turn.completed") { - yield* Deferred.succeed(turnCompletedReady, event).pipe(Effect.ignore); - } - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "approval-required", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ - threadId, - input: "cancel this turn", - attachments: [], - }) - .pipe(Effect.forkChild); - - const requestResolved = yield* Deferred.await(requestResolvedReady); - const turnCompleted = yield* Deferred.await(turnCompletedReady); - yield* Fiber.join(sendTurnFiber); - yield* Fiber.interrupt(runtimeEventsFiber); - - assert.equal(requestResolved.type, "request.resolved"); - if (requestResolved.type === "request.resolved") { - assert.equal(requestResolved.payload.decision, "cancel"); - } - - assert.equal(turnCompleted.type, "turn.completed"); - if (turnCompleted.type === "turn.completed") { - assert.equal(turnCompleted.payload.state, "cancelled"); - assert.equal(turnCompleted.payload.stopReason, "cancelled"); - } - - const isCancelledApprovalResponse = (entry: Record) => - !("method" in entry) && - typeof entry.result === "object" && - entry.result !== null && - "outcome" in entry.result && - typeof entry.result.outcome === "object" && - entry.result.outcome !== null && - "outcome" in entry.result.outcome && - entry.result.outcome.outcome === "cancelled"; - const approvalResponses = yield* waitForJsonLogMatch( - requestLogPath, - isCancelledApprovalResponse, - ); - assert.isTrue(approvalResponses.some(isCancelledApprovalResponse)); - - yield* adapter.stopSession(threadId); - }), - ); - it.effect("stopping a session settles pending approval waits", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-stop-pending-approval"); - const approvalRequested = yield* Deferred.make(); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper({ T3_ACP_EMIT_TOOL_CALLS: "1" }), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* Stream.runForEach(adapter.streamEvents, (event) => { - if (String(event.threadId) !== String(threadId) || event.type !== "request.opened") { - return Effect.void; - } - return Deferred.succeed(approvalRequested, undefined).pipe(Effect.ignore); - }).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "approval-required", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ - threadId, - input: "run a tool call and then stop", - attachments: [], - }) - .pipe(Effect.forkChild); - - yield* Deferred.await(approvalRequested); - yield* adapter.stopSession(threadId); - yield* Fiber.await(sendTurnFiber); - - assert.equal(yield* adapter.hasSession(threadId), false); - }), - ); - - it.effect("stopping a session settles pending user-input waits", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-stop-pending-user-input"); - const userInputRequested = yield* Deferred.make(); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper({ T3_ACP_EMIT_ASK_QUESTION: "1" }), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* Stream.runForEach(adapter.streamEvents, (event) => { - if (String(event.threadId) !== String(threadId) || event.type !== "user-input.requested") { - return Effect.void; - } - return Deferred.succeed(userInputRequested, undefined).pipe(Effect.ignore); - }).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ - threadId, - input: "ask me a question and then stop", - attachments: [], - }) - .pipe(Effect.forkChild); - - yield* Deferred.await(userInputRequested); - yield* adapter.stopSession(threadId); - yield* Fiber.await(sendTurnFiber); - - assert.equal(yield* adapter.hasSession(threadId), false); - }), - ); - - it.effect("interrupting a session settles pending user-input waits", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-interrupt-pending-user-input"); - const userInputRequested = yield* Deferred.make(); - - const wrapperPath = yield* Effect.promise(() => - makeMockAgentWrapper({ T3_ACP_EMIT_ASK_QUESTION: "1" }), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* Stream.runForEach(adapter.streamEvents, (event) => { - if (String(event.threadId) !== String(threadId) || event.type !== "user-input.requested") { - return Effect.void; - } - return Deferred.succeed(userInputRequested, undefined).pipe(Effect.ignore); - }).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: "cursor", - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ - threadId, - input: "ask me a question and then interrupt", - attachments: [], - }) - .pipe(Effect.forkChild); - - yield* Deferred.await(userInputRequested); - yield* adapter.interruptTurn(threadId); - yield* Fiber.await(sendTurnFiber); - - assert.equal(yield* adapter.hasSession(threadId), true); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("broadcasts runtime events to multiple stream consumers", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const settings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-runtime-event-broadcast"); - - const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper()); - yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - const firstConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe( - Stream.runCollect, - Effect.forkChild, - ); - const secondConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe( - Stream.runCollect, - Effect.forkChild, - ); - - yield* adapter.startSession({ - threadId, - provider: "cursor", - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, - }); - - const firstEvents = Array.from(yield* Fiber.join(firstConsumer)); - const secondEvents = Array.from(yield* Fiber.join(secondConsumer)); - - assert.deepStrictEqual( - firstEvents.map((event) => event.type), - ["session.started", "session.state.changed", "thread.started"], - ); - assert.deepStrictEqual( - secondEvents.map((event) => event.type), - ["session.started", "session.state.changed", "thread.started"], - ); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("switches model in-session via session/set_config_option", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-model-switch"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const argvLogPath = NodePath.join(tempDir, "argv.txt"); - yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "first turn", - attachments: [], - }); - - yield* adapter.sendTurn({ - threadId, - input: "second turn after switching model", - attachments: [], - modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ - { id: "fastMode", value: true }, - ]), - }); - - const argvRuns = yield* Effect.promise(() => readArgvLog(argvLogPath)); - assert.lengthOf(argvRuns, 1, "session should not restart — only one spawn"); - assert.deepStrictEqual(argvRuns[0], ["acp"]); - - const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const setConfigRequests = requests.filter( - (entry) => - entry.method === "session/set_config_option" && - (entry.params as Record | undefined)?.configId === "model", - ); - assert.isAbove(setConfigRequests.length, 0, "should call session/set_config_option"); - assert.equal((setConfigRequests[0]?.params as Record)?.value, "composer-2"); - - const fastConfigRequests = requests.filter( - (entry) => - entry.method === "session/set_config_option" && - (entry.params as Record | undefined)?.configId === "fast", - ); - assert.isAbove(fastConfigRequests.length, 0, "should apply fast mode as a separate config"); - const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1]; - assert.equal((lastFastConfig?.params as Record)?.value, "true"); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("clears prior fast mode in-session when the next turn sets fastMode: false", () => - Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-fast-mode-reset"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const argvLogPath = NodePath.join(tempDir, "argv.txt"); - yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath), - ); - yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "first turn with fast mode", - attachments: [], - modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ - { id: "fastMode", value: true }, - ]), - }); - - yield* adapter.sendTurn({ - threadId, - input: "second turn without fast mode", - attachments: [], - modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ - { id: "fastMode", value: false }, - ]), - }); - - const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const fastConfigRequests = requests.filter( - (entry) => - entry.method === "session/set_config_option" && - (entry.params as Record | undefined)?.configId === "fast", - ); - assert.isAtLeast(fastConfigRequests.length, 2, "should set fast mode on and then off"); - - const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1]; - assert.equal((lastFastConfig?.params as Record)?.value, "false"); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect( - "applies fast mode on the first turn when modelSelection uses a non-default instance id", - () => { - const customInstanceId = ProviderInstanceId.make("cursor_secondary"); - // Custom-instance cases can't share the suite-level `CursorAdapter` - // layer because that one binds `instanceId: "cursor"`. We build a - // fresh layer graph — including a fresh `ServerSettingsService` — so - // mid-test `updateSettings` calls target the same service instance the - // adapter's `resolveSettings` reads from, and so the outer - // `yield* ServerSettingsService` sees the same snapshot as well. - const customAdapterLayer = Layer.effect( - CursorAdapter, - Effect.gen(function* () { - const cursorConfig = decodeCursorSettings({}); - const resolveSettings = yield* makeResolveCursorSettings; - return yield* makeCursorAdapter(cursorConfig, { - instanceId: customInstanceId, - resolveSettings, - }); - }), - ).pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-cursor-adapter-custom-instance-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* CursorAdapter; - const serverSettings = yield* ServerSettingsService; - const threadId = ThreadId.make("cursor-fast-mode-custom-instance"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const argvLogPath = NodePath.join(tempDir, "argv.txt"); - yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8")); - const wrapperPath = yield* Effect.promise(() => - makeProbeWrapper(requestLogPath, argvLogPath), - ); - yield* serverSettings.updateSettings({ - providers: { cursor: { binaryPath: wrapperPath } }, - }); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { - instanceId: customInstanceId, - model: "composer-2", - }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "first turn with fast mode", - attachments: [], - modelSelection: { - ...createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ - { id: "fastMode", value: true }, - ]), - instanceId: customInstanceId, - }, - }); - - const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - const fastConfigRequests = requests.filter( - (entry) => - entry.method === "session/set_config_option" && - (entry.params as Record | undefined)?.configId === "fast", - ); - assert.isAbove( - fastConfigRequests.length, - 0, - "fast mode should apply when instance id matches the adapter binding", - ); - const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1]; - assert.equal((lastFastConfig?.params as Record)?.value, "true"); - - yield* adapter.stopSession(threadId); - }).pipe(Effect.provide(customAdapterLayer)); - }, - ); -}); diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts deleted file mode 100644 index fb24155df5..0000000000 --- a/apps/server/src/provider/Layers/CursorAdapter.ts +++ /dev/null @@ -1,1134 +0,0 @@ -/** - * CursorAdapterLive — Cursor CLI (`agent acp`) via ACP. - * - * @module CursorAdapterLive - */ - -import { - ApprovalRequestId, - type CursorModelOptions, - EventId, - type ProviderApprovalDecision, - type ProviderInteractionMode, - type ProviderRuntimeEvent, - type ProviderSession, - type ProviderUserInputAnswers, - ProviderDriverKind, - ProviderInstanceId, - RuntimeRequestId, - type RuntimeMode, - type ThreadId, - TurnId, -} from "@t3tools/contracts"; -import { - DateTime, - Deferred, - Effect, - Exit, - Fiber, - FileSystem, - Layer, - Option, - PubSub, - Random, - Scope, - Semaphore, - Stream, - SynchronizedRef, -} from "effect"; -import { ChildProcessSpawner } from "effect/unstable/process"; -import type * as EffectAcpSchema from "effect-acp/schema"; - -import { resolveAttachmentPath } from "../../attachmentStore.ts"; -import { ServerConfig } from "../../config.ts"; -import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; -import { - ProviderAdapterProcessError, - ProviderAdapterRequestError, - ProviderAdapterSessionNotFoundError, - ProviderAdapterValidationError, -} from "../Errors.ts"; -import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts"; -import type * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts"; -import { - makeAcpAssistantItemEvent, - makeAcpContentDeltaEvent, - makeAcpPlanUpdatedEvent, - makeAcpRequestOpenedEvent, - makeAcpRequestResolvedEvent, - makeAcpToolCallEvent, -} from "../acp/AcpCoreRuntimeEvents.ts"; -import { - type AcpSessionMode, - type AcpSessionModeState, - parsePermissionRequest, -} from "../acp/AcpRuntimeModel.ts"; -import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts"; -import { applyCursorAcpModelSelection, makeCursorAcpRuntime } from "../acp/CursorAcpSupport.ts"; -import { - CursorAskQuestionRequest, - CursorCreatePlanRequest, - CursorUpdateTodosRequest, - extractAskQuestions, - extractPlanMarkdown, - extractTodosAsPlan, -} from "../acp/CursorAcpExtension.ts"; -import { type CursorAdapterShape } from "../Services/CursorAdapter.ts"; -import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts"; -import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; -const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown)); - -const PROVIDER = ProviderDriverKind.make("cursor"); -const CURSOR_RESUME_VERSION = 1 as const; -const ACP_PLAN_MODE_ALIASES = ["plan", "architect"]; -const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"]; -const ACP_APPROVAL_MODE_ALIASES = ["ask"]; - -function encodeJsonStringForDiagnostics(input: unknown): string | undefined { - const result = encodeUnknownJsonStringExit(input); - return Exit.isSuccess(result) ? result.value : undefined; -} - -export interface CursorAdapterLiveOptions { - readonly environment?: NodeJS.ProcessEnv; - readonly nativeEventLogPath?: string; - readonly nativeEventLogger?: EventNdjsonLogger; - /** - * Selections are honored when `modelSelection.instanceId` matches this value. - * Defaults to the legacy built-in instance id (`cursor`). - */ - readonly instanceId?: ProviderInstanceId; - /** - * Optional per-session settings resolver. When provided the adapter yields - * this effect at the start of every session and uses the result instead of - * the `cursorSettings` captured at construction. - * - * Production instances bind settings to the instance scope (the hydration - * layer rebuilds the adapter on config change) and leave this undefined. - * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to - * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads - * the latest snapshot so the closure isn't stale. - */ - readonly resolveSettings?: Effect.Effect; -} - -interface PendingApproval { - readonly decision: Deferred.Deferred; - readonly kind: string | "unknown"; -} - -interface PendingUserInput { - readonly answers: Deferred.Deferred; -} - -interface CursorSessionContext { - readonly threadId: ThreadId; - session: ProviderSession; - readonly scope: Scope.Closeable; - readonly acp: AcpSessionRuntimeShape; - notificationFiber: Fiber.Fiber | undefined; - readonly pendingApprovals: Map; - readonly pendingUserInputs: Map; - readonly turns: Array<{ id: TurnId; items: Array }>; - lastPlanFingerprint: string | undefined; - activeTurnId: TurnId | undefined; - /** Number of sendTurn prompts currently in flight or being prepared. - * >0 means a turn is actively running, so a new sendTurn is a steer that - * continues it, and only the last remaining prompt settles the turn. */ - promptsInFlight: number; - stopped: boolean; -} - -function settlePendingApprovalsAsCancelled( - pendingApprovals: ReadonlyMap, -): Effect.Effect { - const pendingEntries = Array.from(pendingApprovals.values()); - return Effect.forEach( - pendingEntries, - (pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore), - { - discard: true, - }, - ); -} - -function settlePendingUserInputsAsEmptyAnswers( - pendingUserInputs: ReadonlyMap, -): Effect.Effect { - const pendingEntries = Array.from(pendingUserInputs.values()); - return Effect.forEach( - pendingEntries, - (pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore), - { - discard: true, - }, - ); -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function parseCursorResume(raw: unknown): { sessionId: string } | undefined { - if (!isRecord(raw)) return undefined; - if (raw.schemaVersion !== CURSOR_RESUME_VERSION) return undefined; - if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined; - return { sessionId: raw.sessionId.trim() }; -} - -function normalizeModeSearchText(mode: AcpSessionMode): string { - return [mode.id, mode.name, mode.description] - .filter((value): value is string => typeof value === "string" && value.length > 0) - .join(" ") - .toLowerCase() - .replace(/[^a-z0-9]+/g, " ") - .trim(); -} - -function findModeByAliases( - modes: ReadonlyArray, - aliases: ReadonlyArray, -): AcpSessionMode | undefined { - const normalizedAliases = aliases.map((alias) => alias.toLowerCase()); - for (const alias of normalizedAliases) { - const exact = modes.find((mode) => { - const id = mode.id.toLowerCase(); - const name = mode.name.toLowerCase(); - return id === alias || name === alias; - }); - if (exact) { - return exact; - } - } - for (const alias of normalizedAliases) { - const partial = modes.find((mode) => normalizeModeSearchText(mode).includes(alias)); - if (partial) { - return partial; - } - } - return undefined; -} - -function isPlanMode(mode: AcpSessionMode): boolean { - return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined; -} - -function resolveRequestedModeId(input: { - readonly interactionMode: ProviderInteractionMode | undefined; - readonly runtimeMode: RuntimeMode; - readonly modeState: AcpSessionModeState | undefined; -}): string | undefined { - const modeState = input.modeState; - if (!modeState) { - return undefined; - } - - if (input.interactionMode === "plan") { - return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id; - } - - if (input.runtimeMode === "approval-required") { - return ( - findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ?? - findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ?? - modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ?? - modeState.currentModeId - ); - } - - return ( - findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ?? - findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ?? - modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ?? - modeState.currentModeId - ); -} - -function applyRequestedSessionConfiguration(input: { - readonly runtime: AcpSessionRuntimeShape; - readonly runtimeMode: RuntimeMode; - readonly interactionMode: ProviderInteractionMode | undefined; - readonly modelSelection: - | { - readonly model: string; - readonly options?: CursorModelOptions | null | undefined; - } - | undefined; - readonly mapError: (context: { - readonly cause: import("effect-acp/errors").AcpError; - readonly method: "session/set_config_option" | "session/set_mode"; - }) => E; -}): Effect.Effect { - return Effect.gen(function* () { - if (input.modelSelection) { - yield* applyCursorAcpModelSelection({ - runtime: input.runtime, - model: input.modelSelection.model, - modelOptions: input.modelSelection.options, - mapError: ({ cause }) => - input.mapError({ - cause, - method: "session/set_config_option", - }), - }); - } - - const requestedModeId = resolveRequestedModeId({ - interactionMode: input.interactionMode, - runtimeMode: input.runtimeMode, - modeState: yield* input.runtime.getModeState, - }); - if (!requestedModeId) { - return; - } - - yield* input.runtime.setMode(requestedModeId).pipe( - Effect.mapError((cause) => - input.mapError({ - cause, - method: "session/set_mode", - }), - ), - ); - }); -} - -function selectAutoApprovedPermissionOption( - request: EffectAcpSchema.RequestPermissionRequest, -): string | undefined { - const allowAlwaysOption = request.options.find((option) => option.kind === "allow_always"); - if (typeof allowAlwaysOption?.optionId === "string" && allowAlwaysOption.optionId.trim()) { - return allowAlwaysOption.optionId.trim(); - } - - const allowOnceOption = request.options.find((option) => option.kind === "allow_once"); - if (typeof allowOnceOption?.optionId === "string" && allowOnceOption.optionId.trim()) { - return allowOnceOption.optionId.trim(); - } - - return undefined; -} - -export function makeCursorAdapter( - cursorSettings: CursorSettings, - options?: CursorAdapterLiveOptions, -) { - return Effect.gen(function* () { - const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor"); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const serverConfig = yield* Effect.service(ServerConfig); - const crypto = yield* Crypto.Crypto; - const nativeEventLogger = - options?.nativeEventLogger ?? - (options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { - stream: "native", - }) - : undefined); - const managedNativeEventLogger = - options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; - - const sessions = new Map(); - const threadLocksRef = yield* SynchronizedRef.make(new Map()); - const runtimeEventPubSub = yield* PubSub.unbounded(); - - const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - const randomUUIDv4 = crypto.randomUUIDv4.pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "crypto/randomUUIDv4", - detail: "Failed to generate Cursor runtime identifier.", - cause, - }), - ), - ); - const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id)); - const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); - const mapExtensionFailure = (effect: Effect.Effect) => - effect.pipe( - Effect.mapError( - (cause) => - new EffectAcpErrors.AcpTransportError({ - detail: "Failed to process Cursor ACP extension event.", - cause, - }), - ), - ); - - const offerRuntimeEvent = (event: ProviderRuntimeEvent) => - PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid); - - const getThreadSemaphore = (threadId: string) => - SynchronizedRef.modifyEffect(threadLocksRef, (current) => { - const existing: Option.Option = Option.fromNullishOr( - current.get(threadId), - ); - return Option.match(existing, { - onNone: () => - Semaphore.make(1).pipe( - Effect.map((semaphore) => { - const next = new Map(current); - next.set(threadId, semaphore); - return [semaphore, next] as const; - }), - ), - onSome: (semaphore) => Effect.succeed([semaphore, current] as const), - }); - }); - - const withThreadLock = (threadId: string, effect: Effect.Effect) => - Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); - - const logNative = ( - threadId: ThreadId, - method: string, - payload: unknown, - _source: "acp.jsonrpc" | "acp.cursor.extension", - ) => - Effect.gen(function* () { - if (!nativeEventLogger) return; - const observedAt = yield* nowIso; - yield* nativeEventLogger.write( - { - observedAt, - event: { - id: yield* randomUUIDv4, - kind: "notification", - provider: PROVIDER, - createdAt: observedAt, - method, - threadId, - payload, - }, - }, - threadId, - ); - }); - - const emitPlanUpdate = ( - ctx: CursorSessionContext, - payload: { - readonly explanation?: string | null; - readonly plan: ReadonlyArray<{ - readonly step: string; - readonly status: "pending" | "inProgress" | "completed"; - }>; - }, - rawPayload: unknown, - source: "acp.jsonrpc" | "acp.cursor.extension", - method: string, - ) => - Effect.gen(function* () { - const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`; - if (ctx.lastPlanFingerprint === fingerprint) { - return; - } - ctx.lastPlanFingerprint = fingerprint; - yield* offerRuntimeEvent( - makeAcpPlanUpdatedEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - payload, - source, - method, - rawPayload, - }), - ); - }); - - const requireSession = ( - threadId: ThreadId, - ): Effect.Effect => { - const ctx = sessions.get(threadId); - if (!ctx || ctx.stopped) { - return Effect.fail( - new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }), - ); - } - return Effect.succeed(ctx); - }; - - const stopSessionInternal = (ctx: CursorSessionContext) => - Effect.gen(function* () { - if (ctx.stopped) return; - ctx.stopped = true; - yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); - yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); - if (ctx.notificationFiber) { - yield* Fiber.interrupt(ctx.notificationFiber); - } - yield* Effect.ignore(Scope.close(ctx.scope, Exit.void)); - sessions.delete(ctx.threadId); - yield* offerRuntimeEvent({ - type: "session.exited", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: ctx.threadId, - payload: { exitKind: "graceful" }, - }); - }); - - const startSession: CursorAdapterShape["startSession"] = (input) => - withThreadLock( - input.threadId, - Effect.gen(function* () { - if (input.provider !== undefined && input.provider !== PROVIDER) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, - }); - } - if (!input.cwd?.trim()) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: "cwd is required and must be non-empty.", - }); - } - - const cwd = nodePath.resolve(input.cwd.trim()); - const cursorModelSelection = - input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined; - const existing = sessions.get(input.threadId); - if (existing && !existing.stopped) { - yield* stopSessionInternal(existing); - } - - const cursorSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.cursor), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); - - const pendingApprovals = new Map(); - const pendingUserInputs = new Map(); - const sessionScope = yield* Scope.make("sequential"); - let sessionScopeTransferred = false; - yield* Effect.addFinalizer(() => - sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void), - ); - let ctx!: CursorSessionContext; - - const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId; - const acpNativeLoggers = makeAcpNativeLoggers({ - nativeEventLogger, - provider: PROVIDER, - threadId: input.threadId, - }); - - const acp = yield* makeCursorAcpRuntime({ - cursorSettings, - childProcessSpawner, - cwd, - ...(resumeSessionId ? { resumeSessionId } : {}), - clientInfo: { name: "t3-code", version: "0.0.0" }, - ...acpNativeLoggers, - }).pipe( - Effect.provideService(Scope.Scope, sessionScope), - Effect.mapError( - (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: cause.message, - cause, - }), - ), - ); - const started = yield* Effect.gen(function* () { - yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) => - Effect.gen(function* () { - yield* logNative( - input.threadId, - "cursor/ask_question", - params, - "acp.cursor.extension", - ); - const requestId = ApprovalRequestId.make(crypto.randomUUID()); - const runtimeRequestId = RuntimeRequestId.make(requestId); - const answers = yield* Deferred.make(); - pendingUserInputs.set(requestId, { answers }); - yield* offerRuntimeEvent({ - type: "user-input.requested", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId: ctx?.activeTurnId, - requestId: runtimeRequestId, - payload: { questions: extractAskQuestions(params) }, - raw: { - source: "acp.cursor.extension", - method: "cursor/ask_question", - payload: params, - }, - }); - const resolved = yield* Deferred.await(answers); - pendingUserInputs.delete(requestId); - yield* offerRuntimeEvent({ - type: "user-input.resolved", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId: ctx?.activeTurnId, - requestId: runtimeRequestId, - payload: { answers: resolved }, - }); - return { answers: resolved }; - }), - ); - yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) => - Effect.gen(function* () { - yield* logNative( - input.threadId, - "cursor/create_plan", - params, - "acp.cursor.extension", - ); - yield* offerRuntimeEvent({ - type: "turn.proposed.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId: ctx?.activeTurnId, - payload: { planMarkdown: extractPlanMarkdown(params) }, - raw: { - source: "acp.cursor.extension", - method: "cursor/create_plan", - payload: params, - }, - }); - return { accepted: true } as const; - }), - ); - yield* acp.handleExtNotification( - "cursor/update_todos", - CursorUpdateTodosRequest, - (params) => - Effect.gen(function* () { - yield* logNative( - input.threadId, - "cursor/update_todos", - params, - "acp.cursor.extension", - ); - if (ctx) { - yield* emitPlanUpdate( - ctx, - extractTodosAsPlan(params), - params, - "acp.cursor.extension", - "cursor/update_todos", - ); - } - }), - ); - yield* acp.handleRequestPermission((params) => - Effect.gen(function* () { - yield* logNative( - input.threadId, - "session/request_permission", - params, - "acp.jsonrpc", - ); - if (input.runtimeMode === "full-access") { - const autoApprovedOptionId = selectAutoApprovedPermissionOption(params); - if (autoApprovedOptionId !== undefined) { - return { - outcome: { - outcome: "selected" as const, - optionId: autoApprovedOptionId, - }, - }; - } - } - const permissionRequest = parsePermissionRequest(params); - const requestId = ApprovalRequestId.make(crypto.randomUUID()); - const runtimeRequestId = RuntimeRequestId.make(requestId); - const decision = yield* Deferred.make(); - pendingApprovals.set(requestId, { - decision, - kind: permissionRequest.kind, - }); - yield* offerRuntimeEvent( - makeAcpRequestOpenedEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: input.threadId, - turnId: ctx?.activeTurnId, - requestId: runtimeRequestId, - permissionRequest, - detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000), - args: params, - source: "acp.jsonrpc", - method: "session/request_permission", - rawPayload: params, - }), - ); - const resolved = yield* Deferred.await(decision); - pendingApprovals.delete(requestId); - yield* offerRuntimeEvent( - makeAcpRequestResolvedEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: input.threadId, - turnId: ctx?.activeTurnId, - requestId: runtimeRequestId, - permissionRequest, - decision: resolved, - }), - ); - return { - outcome: - resolved === "cancel" - ? ({ outcome: "cancelled" } as const) - : { - outcome: "selected" as const, - optionId: acpPermissionOutcome(resolved), - }, - }; - }), - ); - return yield* acp.start(); - }).pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error), - ), - ); - - yield* applyRequestedSessionConfiguration({ - runtime: acp, - runtimeMode: input.runtimeMode, - interactionMode: undefined, - modelSelection: cursorModelSelection, - mapError: ({ cause, method }) => - mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), - }); - - const now = yield* nowIso; - const session: ProviderSession = { - provider: PROVIDER, - status: "ready", - runtimeMode: input.runtimeMode, - cwd, - model: cursorModelSelection?.model, - threadId: input.threadId, - resumeCursor: { - schemaVersion: CURSOR_RESUME_VERSION, - sessionId: started.sessionId, - }, - createdAt: now, - updatedAt: now, - }; - - ctx = { - threadId: input.threadId, - session, - scope: sessionScope, - acp, - notificationFiber: undefined, - pendingApprovals, - pendingUserInputs, - turns: [], - lastPlanFingerprint: undefined, - activeTurnId: undefined, - stopped: false, - }; - - const nf = yield* Stream.runDrain( - Stream.mapEffect(acp.getEvents(), (event) => - Effect.gen(function* () { - switch (event._tag) { - case "ModeChanged": - return; - case "AssistantItemStarted": - yield* offerRuntimeEvent( - makeAcpAssistantItemEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - itemId: event.itemId, - lifecycle: "item.started", - }), - ); - return; - case "AssistantItemCompleted": - yield* offerRuntimeEvent( - makeAcpAssistantItemEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - itemId: event.itemId, - lifecycle: "item.completed", - }), - ); - return; - case "PlanUpdated": - yield* logNative( - ctx.threadId, - "session/update", - event.rawPayload, - "acp.jsonrpc", - ); - yield* emitPlanUpdate( - ctx, - event.payload, - event.rawPayload, - "acp.jsonrpc", - "session/update", - ); - return; - case "ToolCallUpdated": - yield* logNative( - ctx.threadId, - "session/update", - event.rawPayload, - "acp.jsonrpc", - ); - yield* offerRuntimeEvent( - makeAcpToolCallEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - toolCall: event.toolCall, - rawPayload: event.rawPayload, - }), - ); - return; - case "ContentDelta": - yield* logNative( - ctx.threadId, - "session/update", - event.rawPayload, - "acp.jsonrpc", - ); - yield* offerRuntimeEvent( - makeAcpContentDeltaEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: ctx.threadId, - turnId: ctx.activeTurnId, - ...(event.itemId ? { itemId: event.itemId } : {}), - text: event.text, - rawPayload: event.rawPayload, - }), - ); - return; - } - }), - ), - ).pipe(Effect.forkChild); - - ctx.notificationFiber = nf; - sessions.set(input.threadId, ctx); - sessionScopeTransferred = true; - - yield* offerRuntimeEvent({ - type: "session.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - payload: { resume: started.initializeResult }, - }); - yield* offerRuntimeEvent({ - type: "session.state.changed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - payload: { state: "ready", reason: "Cursor ACP session ready" }, - }); - yield* offerRuntimeEvent({ - type: "thread.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - payload: { providerThreadId: started.sessionId }, - }); - - return session; - }).pipe(Effect.scoped), - ); - - const sendTurn: CursorAdapterShape["sendTurn"] = (input) => - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - const turnId = TurnId.make(crypto.randomUUID()); - const turnModelSelection = - input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined; - const model = turnModelSelection?.model ?? ctx.session.model; - const resolvedModel = resolveCursorAcpBaseModelId(model); - yield* applyRequestedSessionConfiguration({ - runtime: ctx.acp, - runtimeMode: ctx.session.runtimeMode, - interactionMode: input.interactionMode, - modelSelection: - model === undefined - ? undefined - : { - model, - options: turnModelSelection?.options, - }, - mapError: ({ cause, method }) => - mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), - }); - ctx.activeTurnId = turnId; - ctx.lastPlanFingerprint = undefined; - ctx.session = { - ...ctx.session, - activeTurnId: turnId, - updatedAt: yield* nowIso, - }; - - yield* offerRuntimeEvent({ - type: "turn.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: { model: resolvedModel }, - }); - - if (steeringTurnId === undefined) { - yield* offerRuntimeEvent({ - type: "turn.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: { model: resolvedModel }, - }); - } - - const promptParts: Array = []; - if (input.input?.trim()) { - promptParts.push({ type: "text", text: input.input.trim() }); - } - if (input.attachments && input.attachments.length > 0) { - for (const attachment of input.attachments) { - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!attachmentPath) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: `Invalid attachment id '${attachment.id}'.`, - }); - } - const bytes = yield* fileSystem.readFile(attachmentPath).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: cause.message, - cause, - }), - ), - ); - promptParts.push({ - type: "image", - data: Buffer.from(bytes).toString("base64"), - mimeType: attachment.mimeType, - }); - } - } - - if (promptParts.length === 0) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "Turn requires non-empty text or attachments.", - }); - } - - const result = yield* ctx.acp - .prompt({ - prompt: promptParts, - }) - .pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), - ), - ); - - const turnRecord = ctx.turns.find((turn) => turn.id === turnId); - if (turnRecord) { - turnRecord.items.push({ prompt: promptParts, result }); - } else { - ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); - } - ctx.session = { - ...ctx.session, - activeTurnId: turnId, - updatedAt: yield* nowIso, - model: resolvedModel, - }; - - // Only the last remaining prompt settles the turn — a steer- - // superseded prompt resolving (usually cancelled) while another is - // in flight or pending must leave the merged turn running. - if (ctx.promptsInFlight === 1) { - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: { - state: result.stopReason === "cancelled" ? "cancelled" : "completed", - stopReason: result.stopReason ?? null, - }, - }); - } - - return { - threadId: input.threadId, - turnId, - resumeCursor: ctx.session.resumeCursor, - }; - }).pipe( - Effect.ensuring( - Effect.sync(() => { - ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1); - }), - ), - ); - }); - - const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); - yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); - yield* Effect.ignore( - ctx.acp.cancel.pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error), - ), - ), - ); - }); - - const respondToRequest: CursorAdapterShape["respondToRequest"] = ( - threadId, - requestId, - decision, - ) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - const pending = ctx.pendingApprovals.get(requestId); - if (!pending) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/request_permission", - detail: `Unknown pending approval request: ${requestId}`, - }); - } - yield* Deferred.succeed(pending.decision, decision); - }); - - const respondToUserInput: CursorAdapterShape["respondToUserInput"] = ( - threadId, - requestId, - answers, - ) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - const pending = ctx.pendingUserInputs.get(requestId); - if (!pending) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "cursor/ask_question", - detail: `Unknown pending user-input request: ${requestId}`, - }); - } - yield* Deferred.succeed(pending.answers, answers); - }); - - const readThread: CursorAdapterShape["readThread"] = (threadId) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - return { threadId, turns: ctx.turns }; - }); - - const rollbackThread: CursorAdapterShape["rollbackThread"] = (threadId, numTurns) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - if (!Number.isInteger(numTurns) || numTurns < 1) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "rollbackThread", - issue: "numTurns must be an integer >= 1.", - }); - } - const nextLength = Math.max(0, ctx.turns.length - numTurns); - ctx.turns.splice(nextLength); - return { threadId, turns: ctx.turns }; - }); - - const stopSession: CursorAdapterShape["stopSession"] = (threadId) => - withThreadLock( - threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - yield* stopSessionInternal(ctx); - }), - ); - - const listSessions: CursorAdapterShape["listSessions"] = () => - Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session }))); - - const hasSession: CursorAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => { - const c = sessions.get(threadId); - return c !== undefined && !c.stopped; - }); - - const stopAll: CursorAdapterShape["stopAll"] = () => - Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }); - - yield* Effect.addFinalizer(() => - Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe( - Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)), - Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void), - ), - ); - - const streamEvents = Stream.fromPubSub(runtimeEventPubSub); - - return { - provider: PROVIDER, - capabilities: { sessionModelSwitch: "in-session" }, - startSession, - sendTurn, - interruptTurn, - readThread, - rollbackThread, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - stopAll, - streamEvents, - } satisfies CursorAdapterShape; - }); -} diff --git a/apps/server/src/provider/Layers/GrokAdapter.test.ts b/apps/server/src/provider/Layers/GrokAdapter.test.ts deleted file mode 100644 index 7b6f0972ae..0000000000 --- a/apps/server/src/provider/Layers/GrokAdapter.test.ts +++ /dev/null @@ -1,1200 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodePath from "node:path"; -import * as NodeOS from "node:os"; -import * as NodeFSP from "node:fs/promises"; -import * as NodeURL from "node:url"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import * as Deferred from "effect/Deferred"; -import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; - -import { - ApprovalRequestId, - GrokSettings, - ProviderDriverKind, - ProviderInstanceId, - ThreadId, - TurnId, - type ProviderRuntimeEvent, -} from "@t3tools/contracts"; - -import { ServerConfig } from "../../config.ts"; -import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts"; -const decodeGrokSettings = Schema.decodeSync(GrokSettings); - -const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); -const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts"); -const mockAgentCommand = process.execPath; - -async function makeMockGrokWrapper(extraEnv?: Record) { - const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-mock-")); - const wrapperPath = NodePath.join(dir, "fake-grok.sh"); - const envExports = Object.entries(extraEnv ?? {}) - .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`) - .join("\n"); - const script = `#!/bin/sh -${envExports} -exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@" -`; - await NodeFSP.writeFile(wrapperPath, script, "utf8"); - await NodeFSP.chmod(wrapperPath, 0o755); - return wrapperPath; -} - -function waitForFileContent( - filePath: string, - attempts = 40, - expectedContent?: string, -): Effect.Effect { - const readAttempt = (remainingAttempts: number): Effect.Effect => - Effect.gen(function* () { - if (remainingAttempts <= 0) { - return yield* Effect.die(new Error(`Timed out waiting for file content at ${filePath}`)); - } - const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe( - Effect.orElseSucceed(() => ""), - ); - if ( - raw.trim().length > 0 && - (expectedContent === undefined || raw.includes(expectedContent)) - ) { - return raw; - } - yield* Effect.sleep("25 millis"); - return yield* readAttempt(remainingAttempts - 1); - }); - return readAttempt(attempts); -} - -async function readJsonLines(filePath: string) { - const raw = await NodeFSP.readFile(filePath, "utf8"); - return raw - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record); -} - -const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-grok-adapter-test-", -}).pipe(Layer.provideMerge(NodeServices.layer)); - -const makeTestAdapter = (binaryPath: string, options?: Parameters[1]) => - makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie); - -it("requires a settlement to match the live Grok turn", () => { - const staleTurnId = TurnId.make("stale-turn"); - const replacementTurnId = TurnId.make("replacement-turn"); - - assert.isFalse( - grokPromptSettlementBelongsToContext({ - liveAcpSessionId: "session-1", - expectedAcpSessionId: "session-1", - liveActiveTurnId: replacementTurnId, - liveSessionActiveTurnId: replacementTurnId, - turnId: staleTurnId, - }), - ); - assert.isFalse( - grokPromptSettlementBelongsToContext({ - liveAcpSessionId: "replacement-session", - expectedAcpSessionId: "stale-session", - liveActiveTurnId: staleTurnId, - liveSessionActiveTurnId: staleTurnId, - turnId: staleTurnId, - }), - ); - assert.isTrue( - grokPromptSettlementBelongsToContext({ - liveAcpSessionId: "session-1", - expectedAcpSessionId: "session-1", - liveActiveTurnId: staleTurnId, - liveSessionActiveTurnId: staleTurnId, - turnId: staleTurnId, - }), - ); -}); - -it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => { - it.effect("starts a session and maps mock ACP prompt flow to runtime events", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-mock-thread"); - const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper()); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const turnCompleted = yield* Deferred.make(); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }).pipe( - Effect.andThen( - event.type === "turn.completed" - ? Deferred.succeed(turnCompleted, undefined) - : Effect.void, - ), - ), - ).pipe(Effect.forkChild); - - const session = yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-mock-alt" }, - }); - - assert.equal(session.provider, "grok"); - assert.equal(session.model, "grok-mock-alt"); - assert.deepStrictEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "mock-session-1", - }); - - yield* adapter.sendTurn({ - threadId, - input: "hello grok", - attachments: [], - }); - - yield* Deferred.await(turnCompleted); - yield* Fiber.interrupt(runtimeEventsFiber); - const types = runtimeEvents.map((e) => e.type); - - assert.includeMembers(types, [ - "session.started", - "session.state.changed", - "thread.started", - "turn.started", - "item.started", - "content.delta", - "turn.completed", - ] as const); - - const delta = runtimeEvents.find((e) => e.type === "content.delta"); - assert.isDefined(delta); - if (delta?.type === "content.delta") { - assert.equal(delta.payload.delta, "hello from mock"); - } - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("closes the ACP child process when a session stops", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-stop-session-close"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-adapter-exit-log-")), - ); - const exitLogPath = NodePath.join(tempDir, "exit.log"); - - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EXIT_LOG_PATH: exitLogPath, - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - yield* adapter.stopSession(threadId); - - const exitLog = yield* waitForFileContent(exitLogPath); - assert.include(exitLog, "SIGTERM"); - }), - ); - - it.effect("reports a Grok session running only while the prompt is in flight", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-session-ready-after-prompt"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EMIT_TOOL_CALLS: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - const requestOpened = - yield* Deferred.make>(); - const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - event.type === "request.opened" - ? Deferred.succeed(requestOpened, event).pipe(Effect.ignore) - : Effect.void, - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "approval-required", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ threadId, input: "check lifecycle", attachments: [] }) - .pipe(Effect.forkChild); - const requestOpenedEvent = yield* Deferred.await(requestOpened); - - const runningSessions = yield* adapter.listSessions(); - const runningSession = runningSessions.find((session) => session.threadId === threadId); - assert.equal(runningSession?.status, "running"); - assert.isDefined(runningSession?.activeTurnId); - - yield* adapter.respondToRequest( - threadId, - ApprovalRequestId.make(String(requestOpenedEvent.requestId)), - "accept", - ); - yield* Fiber.join(sendTurnFiber); - - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - yield* Fiber.interrupt(eventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("restores ready without completing an unstarted turn when preparation fails", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-preparation-failure-while-connecting"); - const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper()); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const error = yield* Effect.flip( - adapter.sendTurn({ - threadId, - input: "prepare invalid attachment", - attachments: [ - { - type: "image", - id: "missing-image", - name: "missing.png", - mimeType: "image/png", - sizeBytes: 1, - }, - ], - }), - ); - for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - - const turnCompletedEvent = runtimeEvents.find( - (event): event is Extract => - event.type === "turn.completed", - ); - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - - assert.equal(error._tag, "ProviderAdapterRequestError"); - assert.isUndefined(turnCompletedEvent); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("completes a Grok turn from xAI prompt completion when the prompt RPC hangs", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-xai-prompt-complete-fallback"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1", - T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const turnCompleted = yield* Deferred.make(); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }).pipe( - Effect.andThen( - event.type === "turn.completed" - ? Deferred.succeed(turnCompleted, undefined) - : Effect.void, - ), - ), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const sendTurnResult = yield* adapter.sendTurn({ - threadId, - input: "exercise fallback", - attachments: [], - }); - - yield* Deferred.await(turnCompleted); - for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - const turnCompletedEvent = runtimeEvents.find( - (event): event is Extract => - event.type === "turn.completed", - ); - const eventTypes = runtimeEvents.map((event) => event.type); - const content = runtimeEvents - .filter( - (event): event is Extract => - event.type === "content.delta" && String(event.threadId) === String(threadId), - ) - .map((event) => event.payload.delta) - .join(""); - const terminalIndex = runtimeEvents.findIndex( - (event) => event.type === "turn.completed" && String(event.threadId) === String(threadId), - ); - const turnOutputTypes = new Set([ - "content.delta", - "item.started", - "item.updated", - "item.completed", - "turn.plan.updated", - ]); - const outputAfterTerminal = runtimeEvents - .slice(terminalIndex + 1) - .filter( - (event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type), - ); - const toolTitles = runtimeEvents.flatMap((event) => - event.type === "item.updated" && event.payload.title ? [event.payload.title] : [], - ); - - assert.equal(sendTurnResult.threadId, threadId); - assert.include(eventTypes, "turn.completed"); - assert.equal(content, "hello from mock"); - assert.isAtLeast(terminalIndex, 0); - assert.deepEqual(outputAfterTerminal, []); - assert.notInclude(toolTitles, "Child-only tool"); - assert.equal(turnCompletedEvent?.payload.stopReason, "end_turn"); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - const contentDelta = yield* Deferred.make(); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void, - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ - threadId, - input: "interrupt after prompt", - attachments: [], - }) - .pipe(Effect.forkChild); - - yield* Deferred.await(contentDelta); - for (let yieldAttempt = 0; yieldAttempt < 6; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - yield* Fiber.interrupt(sendTurnFiber); - for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - - const snapshot = yield* adapter.readThread(threadId); - assert.equal(snapshot.turns.length, 1); - assert.equal(snapshot.turns[0]?.items.length, 1); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("does not report a synthetic stop reason when xAI omits one", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-xai-prompt-complete-missing-stop-reason"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1", - T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const turnCompleted = yield* Deferred.make(); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }).pipe( - Effect.andThen( - event.type === "turn.completed" - ? Deferred.succeed(turnCompleted, undefined) - : Effect.void, - ), - ), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "exercise missing stop reason", - attachments: [], - }); - - yield* Deferred.await(turnCompleted); - const turnCompletedEvent = runtimeEvents.find( - (event): event is Extract => - event.type === "turn.completed", - ); - - assert.equal(turnCompletedEvent?.payload.state, "completed"); - assert.isNull(turnCompletedEvent?.payload.stopReason); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("lets Stop unblock a fully silent Grok prompt and accept a follow-up turn", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-stop-after-full-silence"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - yield* Effect.gen(function* () { - yield* Effect.sleep("500 millis"); - yield* adapter.interruptTurn(threadId); - }).pipe(Effect.forkChild({ startImmediately: true })); - - yield* adapter.sendTurn({ - threadId, - input: "hang forever", - attachments: [], - }); - for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - - const cancelledEvents = runtimeEvents.filter( - (event): event is Extract => - event.type === "turn.completed" && String(event.threadId) === String(threadId), - ); - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - - assert.lengthOf(cancelledEvents, 1); - assert.equal(cancelledEvents[0]?.payload.state, "cancelled"); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - const followUpEventsBefore = runtimeEvents.length; - yield* adapter.sendTurn({ - threadId, - input: "continue after stop", - attachments: [], - }); - for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - - const followUpCompletedEvents = runtimeEvents - .slice(followUpEventsBefore) - .filter( - (event): event is Extract => - event.type === "turn.completed" && String(event.threadId) === String(threadId), - ); - assert.lengthOf(followUpCompletedEvents, 1); - assert.equal(followUpCompletedEvents[0]?.payload.state, "completed"); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }).pipe(TestClock.withLive), - ); - - it.effect("does not let a cancelled prompt settlement consume the follow-up prompt slot", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-cancelled-settlement-before-follow-up"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-cancel-race-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1", - T3_ACP_REQUEST_LOG_PATH: requestLogPath, - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const firstTurnStarted = yield* Deferred.make(); - const twoTurnsCompleted = yield* Deferred.make(); - const completedCountRef = yield* Ref.make(0); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.gen(function* () { - runtimeEvents.push(event); - if (String(event.threadId) !== String(threadId)) { - return; - } - if (event.type === "turn.started" && event.turnId !== undefined) { - yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore); - return; - } - if (event.type !== "turn.completed") { - return; - } - const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1); - if (completedCount === 2) { - yield* Deferred.succeed(twoTurnsCompleted, undefined); - } - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - }); - - const firstSendTurnFiber = yield* adapter - .sendTurn({ threadId, input: "cancel this prompt", attachments: [] }) - .pipe(Effect.forkChild); - const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds")); - yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"'); - - yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds")); - const followUp = yield* adapter - .sendTurn({ threadId, input: "complete the follow-up", attachments: [] }) - .pipe(Effect.timeout("2 seconds")); - yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("2 seconds")); - yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds")); - - const turnCompletedEvents = runtimeEvents.filter( - (event): event is Extract => - event.type === "turn.completed" && String(event.threadId) === String(threadId), - ); - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - - assert.notEqual(String(followUp.turnId), String(firstTurnId)); - assert.deepEqual( - turnCompletedEvents.map((event) => [String(event.turnId), event.payload.state]), - [ - [String(firstTurnId), "cancelled"], - [String(followUp.turnId), "completed"], - ], - ); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }).pipe(TestClock.withLive), - ); - - it.effect("drops late ACP notifications after a turn is cancelled", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-drop-late-cancelled-notifications"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_HANG_PROMPT_FOREVER: "1", - T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1", - }), - ); - const lateNativeUpdate = yield* Deferred.make(); - const adapter = yield* makeTestAdapter(wrapperPath, { - nativeEventLogger: { - filePath: "memory://grok-cancelled-native-events", - write: (record: unknown) => - JSON.stringify(record).includes("late after cancel") - ? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid) - : Effect.void, - close: () => Effect.void, - }, - }); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const turnStarted = yield* Deferred.make(); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }).pipe( - Effect.andThen( - event.type === "turn.started" && - event.turnId !== undefined && - String(event.threadId) === String(threadId) - ? Deferred.succeed(turnStarted, event.turnId).pipe(Effect.asVoid) - : Effect.void, - ), - ), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ threadId, input: "cancel before the late update", attachments: [] }) - .pipe(Effect.forkChild); - const turnId = yield* Deferred.await(turnStarted).pipe(Effect.timeout("2 seconds")); - yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds")); - yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds")); - yield* Deferred.await(lateNativeUpdate).pipe(Effect.timeout("2 seconds")); - for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - - const cancelledIndex = runtimeEvents.findIndex( - (event) => - event.type === "turn.completed" && - String(event.threadId) === String(threadId) && - String(event.turnId) === String(turnId) && - event.payload.state === "cancelled", - ); - const turnOutputTypes = new Set([ - "content.delta", - "item.started", - "item.updated", - "item.completed", - "turn.plan.updated", - ]); - const outputAfterCancellation = runtimeEvents - .slice(cancelledIndex + 1) - .filter( - (event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type), - ); - - assert.isAtLeast(cancelledIndex, 0); - assert.deepEqual(outputAfterCancellation, []); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }).pipe(TestClock.withLive), - ); - - it.effect("lets Stop cancel during the xAI completion drain window", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-stop-during-completion-drain"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - - const runtimeEvents: ProviderRuntimeEvent[] = []; - const activeTurnIdRef = yield* Ref.make(undefined); - const trailingChunkTurnId = yield* Deferred.make(); - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.gen(function* () { - runtimeEvents.push(event); - if (String(event.threadId) !== String(threadId)) { - return; - } - if (event.type === "turn.started") { - yield* Ref.set(activeTurnIdRef, event.turnId); - } - if (event.type !== "content.delta" || event.payload.delta !== "mock") { - return; - } - const turnId = event.turnId ?? (yield* Ref.get(activeTurnIdRef)); - if (turnId === undefined) { - return; - } - yield* Deferred.succeed(trailingChunkTurnId, turnId).pipe(Effect.ignore); - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ - threadId, - input: "cancel during completion drain", - attachments: [], - }) - .pipe(Effect.forkChild); - - const turnId = yield* Deferred.await(trailingChunkTurnId).pipe(Effect.timeout("2 seconds")); - yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds")); - yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds")); - - const turnCompletedEvents = runtimeEvents.filter( - (event): event is Extract => - event.type === "turn.completed" && String(event.threadId) === String(threadId), - ); - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - - assert.lengthOf(turnCompletedEvents, 1); - assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled"); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("settles the in-flight prompt before emitting completion", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-completion-before-next-turn"); - const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper()); - const adapter = yield* makeTestAdapter(wrapperPath); - const completedCountRef = yield* Ref.make(0); - const secondTurnCompleted = yield* Deferred.make(); - - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => { - if (event.type !== "turn.completed" || String(event.threadId) !== String(threadId)) { - return Effect.void; - } - - return Ref.modify(completedCountRef, (count) => { - const nextCount = count + 1; - return [nextCount, nextCount] as const; - }).pipe( - Effect.flatMap((count) => { - if (count === 1) { - return adapter - .sendTurn({ - threadId, - input: "second turn after completion", - attachments: [], - }) - .pipe(Effect.forkChild, Effect.asVoid); - } - if (count === 2) { - return Deferred.succeed(secondTurnCompleted, undefined).pipe(Effect.asVoid); - } - return Effect.void; - }), - ); - }).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "first turn", - attachments: [], - }); - yield* Deferred.await(secondTurnCompleted); - - const completedCount = yield* Ref.get(completedCountRef); - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - - assert.equal(completedCount, 2); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("restores a Grok session to ready when the prompt RPC fails", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-prompt-failure-ready"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_FAIL_PROMPT: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - const runtimeEvents: ProviderRuntimeEvent[] = []; - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }), - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const error = yield* Effect.flip( - adapter.sendTurn({ - threadId, - input: "fail prompt", - attachments: [], - }), - ); - const readySessions = yield* adapter.listSessions(); - const readySession = readySessions.find((session) => session.threadId === threadId); - const failedTurnCompleted = runtimeEvents.find( - (event) => event.type === "turn.completed" && event.threadId === threadId, - ); - - assert.equal(error._tag, "ProviderAdapterRequestError"); - assert.equal(readySession?.status, "ready"); - assert.isUndefined(readySession?.activeTurnId); - assert.equal(failedTurnCompleted?.type, "turn.completed"); - if (failedTurnCompleted?.type === "turn.completed") { - assert.equal(failedTurnCompleted.payload.state, "failed"); - assert.isString(failedTurnCompleted.payload.errorMessage); - } - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("ignores replayed session/load updates when resuming a Grok session", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-load-replay-filter"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_EMIT_LOAD_REPLAY: "1", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - const runtimeEvents: ProviderRuntimeEvent[] = []; - const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - Effect.sync(() => { - runtimeEvents.push(event); - }), - ).pipe(Effect.forkChild); - - const session = yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - resumeCursor: { schemaVersion: 1, sessionId: "mock-session-1" }, - }); - - yield* adapter.sendTurn({ - threadId, - input: "after resume", - attachments: [], - }); - - assert.deepStrictEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "mock-session-1", - }); - assert.isFalse( - runtimeEvents.some( - (event) => event.type === "item.completed" && event.payload.title === "Replay tool", - ), - ); - assert.isFalse( - runtimeEvents.some( - (event) => - event.type === "content.delta" && event.payload.delta === "replayed assistant text", - ), - ); - - yield* Fiber.interrupt(runtimeEventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("rejects startSession when provider mismatches", () => - Effect.gen(function* () { - const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper()); - const adapter = yield* makeTestAdapter(wrapperPath); - const threadId = ThreadId.make("grok-provider-mismatch"); - - const error = yield* Effect.flip( - adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("cursor"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }), - ); - - assert.equal(error._tag, "ProviderAdapterValidationError"); - }), - ); - - it.effect("rejects sendTurn with empty input and no attachments", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-empty-turn"); - - const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper()); - const adapter = yield* makeTestAdapter(wrapperPath); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" }, - }); - - const error = yield* Effect.flip( - adapter.sendTurn({ - threadId, - input: " ", - attachments: [], - }), - ); - - assert.equal(error._tag, "ProviderAdapterValidationError"); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("responds to ACP approvals using provider-supplied option ids", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-custom-approval-option-id"); - const tempDir = yield* Effect.promise(() => - NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-")), - ); - const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ - T3_ACP_REQUEST_LOG_PATH: requestLogPath, - T3_ACP_EMIT_TOOL_CALLS: "1", - T3_ACP_ALLOW_ONCE_OPTION_ID: "agent-defined-approval-id", - }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - event.type === "request.opened" - ? adapter.respondToRequest( - threadId, - ApprovalRequestId.make(String(event.requestId)), - "accept", - ) - : Effect.void, - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "approval-required", - }); - yield* adapter.sendTurn({ threadId, input: "approve this", attachments: [] }); - - const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); - assert.isTrue( - requests.some( - (entry) => - !("method" in entry) && - typeof entry.result === "object" && - entry.result !== null && - "outcome" in entry.result && - typeof entry.result.outcome === "object" && - entry.result.outcome !== null && - "optionId" in entry.result.outcome && - entry.result.outcome.optionId === "agent-defined-approval-id", - ), - ); - - yield* Fiber.interrupt(eventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("handles xAI ask_user_question extension requests", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-xai-ask-user-question"); - const wrapperPath = yield* Effect.promise(() => - makeMockGrokWrapper({ T3_ACP_EMIT_XAI_ASK_USER_QUESTION: "1" }), - ); - const adapter = yield* makeTestAdapter(wrapperPath); - const requested = - yield* Deferred.make>(); - const resolved = - yield* Deferred.make>(); - - const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => { - if (String(event.threadId) !== String(threadId)) { - return Effect.void; - } - if (event.type === "user-input.requested") { - return Deferred.succeed(requested, event).pipe(Effect.ignore); - } - if (event.type === "user-input.resolved") { - return Deferred.succeed(resolved, event).pipe(Effect.ignore); - } - return Effect.void; - }).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - }); - - const sendTurnFiber = yield* adapter - .sendTurn({ threadId, input: "ask before continuing", attachments: [] }) - .pipe(Effect.forkChild); - - const requestedEvent = yield* Deferred.await(requested); - assert.equal(requestedEvent.payload.questions.length, 1); - assert.equal(requestedEvent.payload.questions[0]?.id, "Which scope should Grok use?"); - assert.equal(requestedEvent.payload.questions[0]?.question, "Which scope should Grok use?"); - assert.equal(requestedEvent.raw?.method, "_x.ai/ask_user_question"); - - yield* adapter.respondToUserInput( - threadId, - ApprovalRequestId.make(String(requestedEvent.requestId)), - { - "Which scope should Grok use?": "Workspace", - }, - ); - - const resolvedEvent = yield* Deferred.await(resolved); - assert.deepEqual(resolvedEvent.payload.answers, { - "Which scope should Grok use?": "Workspace", - }); - assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId)); - yield* Fiber.join(sendTurnFiber); - - yield* Fiber.interrupt(eventsFiber); - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("continues streaming events when native notification logging fails", () => - Effect.gen(function* () { - const threadId = ThreadId.make("grok-native-log-failure"); - const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper()); - const adapter = yield* makeTestAdapter(wrapperPath, { - nativeEventLogger: { - filePath: "memory://grok-native-events", - write: (record: unknown) => - typeof record === "object" && - record !== null && - "event" in record && - typeof record.event === "object" && - record.event !== null && - "kind" in record.event && - record.event.kind === "notification" - ? Effect.die(new Error("native log write failed")) - : Effect.void, - close: () => Effect.void, - }, - }); - const contentDelta = yield* Deferred.make(); - const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => - event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void, - ).pipe(Effect.forkChild); - - yield* adapter.startSession({ - threadId, - provider: ProviderDriverKind.make("grok"), - cwd: process.cwd(), - runtimeMode: "full-access", - }); - yield* adapter.sendTurn({ threadId, input: "keep streaming", attachments: [] }); - yield* Deferred.await(contentDelta); - - yield* Fiber.interrupt(eventsFiber); - yield* adapter.stopSession(threadId); - }), - ); -}); diff --git a/apps/server/src/provider/Layers/GrokAdapter.ts b/apps/server/src/provider/Layers/GrokAdapter.ts deleted file mode 100644 index 977cc8caad..0000000000 --- a/apps/server/src/provider/Layers/GrokAdapter.ts +++ /dev/null @@ -1,1464 +0,0 @@ -import { - ApprovalRequestId, - type GrokSettings, - EventId, - type ProviderApprovalDecision, - type ProviderRuntimeEvent, - type ProviderSession, - type ProviderUserInputAnswers, - ProviderDriverKind, - ProviderInstanceId, - RuntimeRequestId, - type ThreadId, - TurnId, -} from "@t3tools/contracts"; -import * as Crypto from "effect/Crypto"; -import * as DateTime from "effect/DateTime"; -import * as Deferred from "effect/Deferred"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as FileSystem from "effect/FileSystem"; -import * as Option from "effect/Option"; -import * as Path from "effect/Path"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; -import * as Semaphore from "effect/Semaphore"; -import * as Stream from "effect/Stream"; -import * as SynchronizedRef from "effect/SynchronizedRef"; -import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; -import * as EffectAcpErrors from "effect-acp/errors"; -import type * as EffectAcpSchema from "effect-acp/schema"; - -import { resolveAttachmentPath } from "../../attachmentStore.ts"; -import { ServerConfig } from "../../config.ts"; -import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; -import { - ProviderAdapterProcessError, - ProviderAdapterRequestError, - ProviderAdapterSessionNotFoundError, - ProviderAdapterValidationError, -} from "../Errors.ts"; -import { mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts"; -import type * as AcpSessionRuntime from "../acp/AcpSessionRuntime.ts"; -import { - makeAcpAssistantItemEvent, - makeAcpContentDeltaEvent, - makeAcpPlanUpdatedEvent, - makeAcpRequestOpenedEvent, - makeAcpRequestResolvedEvent, - makeAcpToolCallEvent, -} from "../acp/AcpCoreRuntimeEvents.ts"; -import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts"; -import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts"; -import { - applyGrokAcpModelSelection, - currentGrokModelIdFromSessionSetup, - makeGrokAcpRuntime, - resolveGrokAcpBaseModelId, -} from "../acp/GrokAcpSupport.ts"; -import { - extractXAiAskUserQuestions, - makeXAiAskUserQuestionCancelledResponse, - makeXAiAskUserQuestionResponse, - promptResponseHasMissingXAiStopReason, - XAiAskUserQuestionRequest, -} from "../acp/XAiAcpExtension.ts"; -import { type GrokAdapterShape } from "../Services/GrokAdapter.ts"; -import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; - -const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown)); - -const PROVIDER = ProviderDriverKind.make("grok"); -const GROK_RESUME_VERSION = 1 as const; - -function encodeJsonStringForDiagnostics(input: unknown): string | undefined { - const result = encodeUnknownJsonStringExit(input); - return Exit.isSuccess(result) ? result.value : undefined; -} - -export interface GrokAdapterLiveOptions { - readonly environment?: NodeJS.ProcessEnv; - readonly nativeEventLogPath?: string; - readonly nativeEventLogger?: EventNdjsonLogger; - readonly instanceId?: ProviderInstanceId; -} - -interface PendingApproval { - readonly decision: Deferred.Deferred; -} - -type PendingUserInputResolution = - | { readonly _tag: "answered"; readonly answers: ProviderUserInputAnswers } - | { readonly _tag: "cancelled" }; - -interface PendingUserInput { - readonly resolution: Deferred.Deferred; -} - -interface GrokSessionContext { - readonly threadId: ThreadId; - readonly acpSessionId: string; - session: ProviderSession; - readonly scope: Scope.Closeable; - readonly acp: AcpSessionRuntime.AcpSessionRuntime["Service"]; - notificationFiber: Fiber.Fiber | undefined; - readonly pendingApprovals: Map; - readonly pendingUserInputs: Map; - turns: Array<{ id: TurnId; items: Array }>; - lastPlanFingerprint: string | undefined; - activeTurnId: TurnId | undefined; - /** Turns already interrupted; late prompt RPCs must not resurrect them. */ - interruptedTurnIds: Set; - /** Number of sendTurn prompts currently in flight or being prepared. - * >0 means a turn is actively running, so a new sendTurn is a steer that - * continues it, and only the last remaining prompt settles the turn. */ - promptsInFlight: number; - currentModelId: string | undefined; - stopped: boolean; -} - -function settlePendingApprovalsAsCancelled( - pendingApprovals: ReadonlyMap, -): Effect.Effect { - return Effect.forEach( - Array.from(pendingApprovals.values()), - (pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore), - { discard: true }, - ); -} - -function settlePendingUserInputsAsCancelled( - pendingUserInputs: ReadonlyMap, -): Effect.Effect { - return Effect.forEach( - Array.from(pendingUserInputs.values()), - (pending) => Deferred.succeed(pending.resolution, { _tag: "cancelled" }).pipe(Effect.ignore), - { discard: true }, - ); -} - -function appendPromptResultToTurn( - ctx: GrokSessionContext, - turnId: TurnId, - promptParts: ReadonlyArray, - result: EffectAcpSchema.PromptResponse, -): void { - const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId); - ctx.turns = existingTurnRecord - ? ctx.turns.map((turn) => - turn.id === turnId - ? { ...turn, items: [...turn.items, { prompt: promptParts, result }] } - : turn, - ) - : [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }]; -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId; - -const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId; - -const resolveSessionCallbackTurnId = ( - sessions: ReadonlyMap, - threadId: ThreadId, -): TurnId | undefined => { - const ctx = sessions.get(threadId); - return ctx ? resolveCallbackTurnId(ctx) : undefined; -}; - -function parseGrokResume(raw: unknown): { sessionId: string } | undefined { - if (!isRecord(raw)) return undefined; - if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined; - if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined; - return { sessionId: raw.sessionId.trim() }; -} - -function selectPermissionOptionId( - request: EffectAcpSchema.RequestPermissionRequest, - decision: Exclude, -): string | undefined { - const kind = - decision === "acceptForSession" - ? "allow_always" - : decision === "accept" - ? "allow_once" - : "reject_once"; - const option = request.options.find((entry) => entry.kind === kind); - return option?.optionId.trim() || undefined; -} - -function selectAutoApprovedPermissionOption( - request: EffectAcpSchema.RequestPermissionRequest, -): string | undefined { - return ( - selectPermissionOptionId(request, "acceptForSession") ?? - selectPermissionOptionId(request, "accept") - ); -} - -function completedStopReasonFromPromptResponse( - response: EffectAcpSchema.PromptResponse | undefined, -): EffectAcpSchema.StopReason | null { - if (response === undefined || promptResponseHasMissingXAiStopReason(response)) { - return null; - } - return response.stopReason; -} - -export function grokPromptSettlementBelongsToContext(input: { - readonly liveAcpSessionId: string; - readonly expectedAcpSessionId: string; - readonly liveActiveTurnId: TurnId | undefined; - readonly liveSessionActiveTurnId: TurnId | undefined; - readonly turnId: TurnId; -}): boolean { - return ( - input.liveAcpSessionId === input.expectedAcpSessionId && - (input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId) - ); -} - -export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) { - return Effect.gen(function* () { - const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok"); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const serverConfig = yield* Effect.service(ServerConfig); - const crypto = yield* Crypto.Crypto; - const nativeEventLogger = - options?.nativeEventLogger ?? - (options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" }) - : undefined); - const managedNativeEventLogger = - options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; - const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory(); - - const sessions = new Map(); - const threadLocksRef = yield* SynchronizedRef.make(new Map()); - const runtimeEventPubSub = yield* PubSub.unbounded(); - - const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - const randomUUIDv4 = crypto.randomUUIDv4.pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "crypto/randomUUIDv4", - detail: "Failed to generate Grok runtime identifier.", - cause, - }), - ), - ); - const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id)); - const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); - const mapAcpCallbackFailure = (effect: Effect.Effect) => - effect.pipe( - Effect.mapError( - (cause) => - new EffectAcpErrors.AcpTransportError({ - detail: "Failed to process Grok ACP callback.", - cause, - }), - ), - ); - - const offerRuntimeEvent = (event: ProviderRuntimeEvent) => - PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid); - - const getThreadSemaphore = (threadId: string) => - SynchronizedRef.modifyEffect(threadLocksRef, (current) => { - const existing: Option.Option = Option.fromNullishOr( - current.get(threadId), - ); - return Option.match(existing, { - onNone: () => - Semaphore.make(1).pipe( - Effect.map((semaphore) => { - const next = new Map(current); - next.set(threadId, semaphore); - return [semaphore, next] as const; - }), - ), - onSome: (semaphore) => Effect.succeed([semaphore, current] as const), - }); - }); - - const withThreadLock = (threadId: string, effect: Effect.Effect) => - Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); - - const settlePromptInFlight = ( - threadId: ThreadId, - turnId: TurnId, - expectedAcpSessionId: string, - options?: { - readonly errorMessage?: string; - readonly completedStopReason?: EffectAcpSchema.StopReason | null; - readonly emitTurnCompletion?: boolean; - /** Interrupt/cancel: drop every outstanding prompt slot and settle once. */ - readonly settleAllPrompts?: boolean; - }, - ) => - Effect.gen(function* () { - const liveCtx = sessions.get(threadId); - if (!liveCtx) { - return; - } - const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({ - liveAcpSessionId: liveCtx.acpSessionId, - expectedAcpSessionId, - liveActiveTurnId: liveCtx.activeTurnId, - liveSessionActiveTurnId: liveCtx.session.activeTurnId, - turnId, - }); - if (!settlementBelongsToLiveContext) { - // interruptTurn already consumed every prompt slot for this turn. A - // late prompt result must neither emit a second terminal event nor - // consume a slot belonging to a newer turn on the same ACP session. - if ( - liveCtx.acpSessionId !== expectedAcpSessionId || - liveCtx.interruptedTurnIds.has(turnId) - ) { - return; - } - if (options?.emitTurnCompletion !== false) { - if (options?.errorMessage !== undefined) { - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId, - payload: { - state: "failed", - errorMessage: options.errorMessage, - }, - }); - } else if (options?.completedStopReason !== undefined) { - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId, - payload: { - state: options.completedStopReason === "cancelled" ? "cancelled" : "completed", - stopReason: options.completedStopReason ?? null, - }, - }); - } - } - return; - } - let settleTurnId = turnId; - if (options?.settleAllPrompts) { - liveCtx.promptsInFlight = 0; - if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) { - const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId; - if (!fallbackTurnId) { - if (liveCtx.session.status === "running" || liveCtx.session.status === "connecting") { - const updatedAt = yield* nowIso; - const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session; - liveCtx.activeTurnId = undefined; - liveCtx.session = { - ...readySession, - status: "ready", - updatedAt, - }; - } - return; - } - settleTurnId = fallbackTurnId; - } - } else { - const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1); - if ( - remainingPrompts > 0 || - liveCtx.activeTurnId !== settleTurnId || - liveCtx.session.activeTurnId !== settleTurnId - ) { - liveCtx.promptsInFlight = remainingPrompts; - return; - } - liveCtx.promptsInFlight = remainingPrompts; - } - const updatedAt = yield* nowIso; - const canEmitTurnCompletion = - liveCtx.session.status === "running" || liveCtx.session.status === "connecting"; - const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion; - const shouldEmitCompletedTurn = - options?.completedStopReason !== undefined && canEmitTurnCompletion; - const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session; - liveCtx.activeTurnId = undefined; - liveCtx.session = { - ...readySession, - status: "ready", - updatedAt, - }; - if (options?.emitTurnCompletion === false) { - return; - } - if (shouldEmitFailedTurn) { - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId: settleTurnId, - payload: { - state: "failed", - errorMessage: options.errorMessage, - }, - }); - } else if (shouldEmitCompletedTurn) { - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId, - turnId: settleTurnId, - payload: { - state: options.completedStopReason === "cancelled" ? "cancelled" : "completed", - stopReason: options.completedStopReason ?? null, - }, - }); - } - }); - - const logNative = (threadId: ThreadId, method: string, payload: unknown) => - Effect.gen(function* () { - if (!nativeEventLogger) return; - const observedAt = yield* nowIso; - yield* nativeEventLogger.write( - { - observedAt, - event: { - id: yield* randomUUIDv4, - kind: "notification", - provider: PROVIDER, - createdAt: observedAt, - method, - threadId, - payload, - }, - }, - threadId, - ); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Failed to write native Grok notification log.", { - cause, - threadId, - method, - }), - ), - ); - - const emitPlanUpdate = ( - ctx: GrokSessionContext, - turnId: TurnId | undefined, - stamp: { readonly eventId: EventId; readonly createdAt: string }, - payload: { - readonly explanation?: string | null; - readonly plan: ReadonlyArray<{ - readonly step: string; - readonly status: "pending" | "inProgress" | "completed"; - }>; - }, - rawPayload: unknown, - method: string, - ) => - Effect.gen(function* () { - const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`; - if (ctx.lastPlanFingerprint === fingerprint) { - return; - } - ctx.lastPlanFingerprint = fingerprint; - yield* offerRuntimeEvent( - makeAcpPlanUpdatedEvent({ - stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId, - payload, - source: "acp.jsonrpc", - method, - rawPayload, - }), - ); - }); - - const requireSession = ( - threadId: ThreadId, - ): Effect.Effect => { - const ctx = sessions.get(threadId); - if (!ctx || ctx.stopped) { - return Effect.fail( - new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }), - ); - } - return Effect.succeed(ctx); - }; - - const stopSessionInternal = (ctx: GrokSessionContext) => - Effect.gen(function* () { - if (ctx.stopped) return; - ctx.stopped = true; - yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); - yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs); - if (ctx.notificationFiber) { - yield* Fiber.interrupt(ctx.notificationFiber); - } - yield* Effect.ignore(Scope.close(ctx.scope, Exit.void)); - sessions.delete(ctx.threadId); - yield* offerRuntimeEvent({ - type: "session.exited", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: ctx.threadId, - payload: { exitKind: "graceful" }, - }); - }); - - const startSession: GrokAdapterShape["startSession"] = (input) => - withThreadLock( - input.threadId, - Effect.gen(function* () { - if (input.provider !== undefined && input.provider !== PROVIDER) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, - }); - } - if (!input.cwd?.trim()) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: "cwd is required and must be non-empty.", - }); - } - - const cwd = path.resolve(input.cwd.trim()); - const grokModelSelection = - input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; - const existing = sessions.get(input.threadId); - if (existing && !existing.stopped) { - yield* stopSessionInternal(existing); - } - - const pendingApprovals = new Map(); - const pendingUserInputs = new Map(); - const sessionScope = yield* Scope.make("sequential"); - let sessionScopeTransferred = false; - yield* Effect.addFinalizer(() => - sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void), - ); - - const resumeSessionId = parseGrokResume(input.resumeCursor)?.sessionId; - const acpNativeLoggers = makeAcpNativeLoggers({ - nativeEventLogger, - provider: PROVIDER, - threadId: input.threadId, - }); - - const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId); - const acp = yield* makeGrokAcpRuntime({ - grokSettings, - ...(options?.environment ? { environment: options.environment } : {}), - childProcessSpawner, - cwd, - ...(resumeSessionId ? { resumeSessionId } : {}), - clientInfo: { name: "t3-code", version: "0.0.0" }, - ...(mcpSession - ? { - mcpServers: [ - { - type: "http" as const, - name: "t3-code", - url: mcpSession.endpoint, - headers: [ - { - name: "Authorization", - value: mcpSession.authorizationHeader, - }, - ], - }, - ], - } - : {}), - ...acpNativeLoggers, - }).pipe( - Effect.provideService(Crypto.Crypto, crypto), - Effect.provideService(Scope.Scope, sessionScope), - Effect.mapError( - (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: cause.message, - cause, - }), - ), - ); - const started = yield* Effect.gen(function* () { - yield* Effect.forEach( - ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const, - (method) => - acp.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => - mapAcpCallbackFailure( - Effect.gen(function* () { - yield* logNative(input.threadId, method, params); - const requestId = ApprovalRequestId.make(yield* randomUUIDv4); - const runtimeRequestId = RuntimeRequestId.make(requestId); - const resolution = yield* Deferred.make(); - const turnId = resolveSessionCallbackTurnId(sessions, input.threadId); - pendingUserInputs.set(requestId, { resolution }); - yield* offerRuntimeEvent({ - type: "user-input.requested", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - requestId: runtimeRequestId, - payload: { questions: extractXAiAskUserQuestions(params) }, - raw: { - source: "acp.grok.extension", - method, - payload: params, - }, - }); - const resolved = yield* Deferred.await(resolution); - pendingUserInputs.delete(requestId); - const resolvedAnswers = resolved._tag === "answered" ? resolved.answers : {}; - yield* offerRuntimeEvent({ - type: "user-input.resolved", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - requestId: runtimeRequestId, - payload: { answers: resolvedAnswers }, - raw: { - source: "acp.grok.extension", - method, - payload: params, - }, - }); - switch (resolved._tag) { - case "answered": - return makeXAiAskUserQuestionResponse(params, resolved.answers); - case "cancelled": - return makeXAiAskUserQuestionCancelledResponse(); - } - }), - ), - ), - { discard: true }, - ); - yield* acp.handleRequestPermission((params) => - mapAcpCallbackFailure( - Effect.gen(function* () { - yield* logNative(input.threadId, "session/request_permission", params); - if (input.runtimeMode === "full-access") { - const autoApprovedOptionId = selectAutoApprovedPermissionOption(params); - if (autoApprovedOptionId !== undefined) { - return { - outcome: { - outcome: "selected" as const, - optionId: autoApprovedOptionId, - }, - }; - } - } - const permissionRequest = parsePermissionRequest(params); - const requestId = ApprovalRequestId.make(yield* randomUUIDv4); - const runtimeRequestId = RuntimeRequestId.make(requestId); - const decision = yield* Deferred.make(); - const turnId = resolveSessionCallbackTurnId(sessions, input.threadId); - pendingApprovals.set(requestId, { decision }); - yield* offerRuntimeEvent( - makeAcpRequestOpenedEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: input.threadId, - turnId, - requestId: runtimeRequestId, - permissionRequest, - detail: - permissionRequest.detail ?? - encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ?? - "[unserializable params]", - args: params, - source: "acp.jsonrpc", - method: "session/request_permission", - rawPayload: params, - }), - ); - const resolved = yield* Deferred.await(decision); - pendingApprovals.delete(requestId); - yield* offerRuntimeEvent( - makeAcpRequestResolvedEvent({ - stamp: yield* makeEventStamp(), - provider: PROVIDER, - threadId: input.threadId, - turnId, - requestId: runtimeRequestId, - permissionRequest, - decision: resolved, - }), - ); - const selectedOptionId = - resolved === "cancel" ? undefined : selectPermissionOptionId(params, resolved); - return { - outcome: selectedOptionId - ? { - outcome: "selected" as const, - optionId: selectedOptionId, - } - : ({ outcome: "cancelled" } as const), - }; - }), - ), - ); - return yield* acp.start(); - }).pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error), - ), - ); - - const requestedStartModelId = grokModelSelection?.model - ? resolveGrokAcpBaseModelId(grokModelSelection.model) - : undefined; - const boundModelId = yield* applyGrokAcpModelSelection({ - runtime: acp, - currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult), - requestedModelId: requestedStartModelId, - mapError: (cause) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause), - }); - - const now = yield* nowIso; - const session: ProviderSession = { - provider: PROVIDER, - providerInstanceId: boundInstanceId, - status: "ready", - runtimeMode: input.runtimeMode, - cwd, - ...(boundModelId ? { model: resolveGrokAcpBaseModelId(boundModelId) } : {}), - threadId: input.threadId, - resumeCursor: { - schemaVersion: GROK_RESUME_VERSION, - sessionId: started.sessionId, - }, - createdAt: now, - updatedAt: now, - }; - - const ctx: GrokSessionContext = { - threadId: input.threadId, - acpSessionId: started.sessionId, - session, - scope: sessionScope, - acp, - notificationFiber: undefined, - pendingApprovals, - pendingUserInputs, - turns: [], - lastPlanFingerprint: undefined, - activeTurnId: undefined, - interruptedTurnIds: new Set(), - promptsInFlight: 0, - currentModelId: boundModelId, - stopped: false, - }; - - const nf = yield* Stream.runDrain( - Stream.mapEffect(acp.getEvents(), (event) => - Effect.gen(function* () { - if (event._tag === "EventStreamBarrier") { - yield* Deferred.succeed(event.acknowledge, undefined); - return; - } - if ( - event._tag === "PlanUpdated" || - event._tag === "ToolCallUpdated" || - event._tag === "ContentDelta" - ) { - yield* logNative(ctx.threadId, "session/update", event.rawPayload); - } - - if (event._tag === "ModeChanged") { - return; - } - - const notificationTurnId = resolveNotificationTurnId(ctx); - if ( - notificationTurnId === undefined || - ctx.interruptedTurnIds.has(notificationTurnId) - ) { - return; - } - const stamp = yield* makeEventStamp(); - - switch (event._tag) { - case "AssistantItemStarted": - yield* offerRuntimeEvent( - makeAcpAssistantItemEvent({ - stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: notificationTurnId, - itemId: event.itemId, - lifecycle: "item.started", - }), - ); - return; - case "AssistantItemCompleted": - yield* offerRuntimeEvent( - makeAcpAssistantItemEvent({ - stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: notificationTurnId, - itemId: event.itemId, - lifecycle: "item.completed", - }), - ); - return; - case "PlanUpdated": - yield* emitPlanUpdate( - ctx, - notificationTurnId, - stamp, - event.payload, - event.rawPayload, - "session/update", - ); - return; - case "ToolCallUpdated": - yield* offerRuntimeEvent( - makeAcpToolCallEvent({ - stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: notificationTurnId, - toolCall: event.toolCall, - rawPayload: event.rawPayload, - }), - ); - return; - case "ContentDelta": - yield* offerRuntimeEvent( - makeAcpContentDeltaEvent({ - stamp, - provider: PROVIDER, - threadId: ctx.threadId, - turnId: notificationTurnId, - ...(event.itemId ? { itemId: event.itemId } : {}), - text: event.text, - rawPayload: event.rawPayload, - }), - ); - return; - } - }), - ), - ).pipe( - Effect.catch((cause) => - Effect.logError("Failed to process Grok runtime notification.", { cause }), - ), - Effect.forkChild, - ); - - ctx.notificationFiber = nf; - sessions.set(input.threadId, ctx); - sessionScopeTransferred = true; - - yield* offerRuntimeEvent({ - type: "session.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - payload: { resume: started.initializeResult }, - }); - yield* offerRuntimeEvent({ - type: "session.state.changed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - payload: { state: "ready", reason: "Grok ACP session ready" }, - }); - yield* offerRuntimeEvent({ - type: "thread.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - payload: { providerThreadId: started.sessionId }, - }); - - return session; - }).pipe(Effect.scoped), - ); - - const sendTurn: GrokAdapterShape["sendTurn"] = (input) => - Effect.gen(function* () { - const prepared = yield* withThreadLock( - input.threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - // A sendTurn while a prompt is in flight is a steer: the agent - // folds the new prompt into the ongoing work, so the active turn - // id is reused instead of opening a new turn. - const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined; - const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4); - // Count this prompt immediately so a superseded in-flight prompt - // resolving from here on does not settle the turn; decremented on - // preparation failure here, and after the prompt below otherwise. - ctx.promptsInFlight += 1; - // Bind the turn id before cooperative yields so interruptTurn can - // settle this prompt even if stop arrives during preparation. - ctx.activeTurnId = turnId; - ctx.session = { - ...ctx.session, - status: steeringTurnId === undefined ? "connecting" : "running", - activeTurnId: turnId, - updatedAt: yield* nowIso, - }; - - return yield* Effect.gen(function* () { - const turnModelSelection = - input.modelSelection?.instanceId === boundInstanceId - ? input.modelSelection - : undefined; - const requestedTurnModelId = turnModelSelection?.model - ? resolveGrokAcpBaseModelId(turnModelSelection.model) - : undefined; - const currentModelId = yield* applyGrokAcpModelSelection({ - runtime: ctx.acp, - currentModelId: ctx.currentModelId, - requestedModelId: requestedTurnModelId, - mapError: (cause) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause), - }); - - const text = input.input?.trim(); - const imagePromptParts = yield* Effect.forEach( - input.attachments ?? [], - (attachment) => - Effect.gen(function* () { - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!attachmentPath) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: `Invalid attachment id '${attachment.id}'.`, - }); - } - const bytes = yield* fileSystem.readFile(attachmentPath).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: cause.message, - cause, - }), - ), - ); - return { - type: "image", - data: Buffer.from(bytes).toString("base64"), - mimeType: attachment.mimeType, - } satisfies EffectAcpSchema.ContentBlock; - }), - ); - const promptParts: Array = [ - ...(text ? [{ type: "text" as const, text }] : []), - ...imagePromptParts, - ]; - - if (promptParts.length === 0) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "Turn requires non-empty text or attachments.", - }); - } - - ctx.currentModelId = currentModelId; - const displayModel = currentModelId - ? resolveGrokAcpBaseModelId(currentModelId) - : undefined; - for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - if (ctx.interruptedTurnIds.has(turnId)) { - yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, { - completedStopReason: "cancelled", - emitTurnCompletion: false, - settleAllPrompts: true, - }); - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: "Grok prompt was interrupted during preparation.", - }); - } - if (steeringTurnId === undefined) { - ctx.lastPlanFingerprint = undefined; - } - ctx.session = { - ...ctx.session, - status: "running", - activeTurnId: turnId, - updatedAt: yield* nowIso, - ...(displayModel ? { model: displayModel } : {}), - }; - - if (steeringTurnId === undefined) { - yield* offerRuntimeEvent({ - type: "turn.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: displayModel ? { model: displayModel } : {}, - }); - } - - return { - acp: ctx.acp, - acpSessionId: ctx.acpSessionId, - displayModel, - promptParts, - turnId, - }; - }).pipe( - Effect.tapCause(() => - Effect.gen(function* () { - const liveCtx = sessions.get(input.threadId); - if (!liveCtx) { - return; - } - yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, { - errorMessage: "Grok prompt preparation failed.", - emitTurnCompletion: false, - }); - }), - ), - ); - }), - ); - const promptSettled = yield* Ref.make(false); - const promptRpcSucceeded = yield* Ref.make(false); - const promptResultRef = yield* Ref.make( - undefined, - ); - - const promptFailureMessageRef = yield* Ref.make(undefined); - - return yield* Effect.gen(function* () { - const result = yield* prepared.acp - .prompt({ - prompt: prepared.promptParts, - }) - .pipe( - Effect.tap((promptResult) => - Effect.all([ - Ref.set(promptRpcSucceeded, true), - Ref.set(promptResultRef, promptResult), - ]), - ), - Effect.tapError((error) => - Ref.set( - promptFailureMessageRef, - mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message, - ).pipe(Effect.andThen(prepared.acp.drainEvents)), - ), - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), - ), - ); - - return yield* withThreadLock( - input.threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - if (ctx.acpSessionId !== prepared.acpSessionId) { - yield* settlePromptInFlight( - input.threadId, - prepared.turnId, - prepared.acpSessionId, - { - errorMessage: "Grok session changed before the turn completed.", - settleAllPrompts: true, - }, - ); - yield* Ref.set(promptSettled, true); - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: "Grok session changed before the turn completed.", - }); - } - // Keep prompt settlement atomic with respect to Stop and steering. - // interruptTurn marks its target before waiting for this lock, so - // cancellation can still win while queued ACP events are drained. - for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) { - yield* Effect.yieldNow; - } - yield* prepared.acp.drainEvents; - if (ctx.interruptedTurnIds.has(prepared.turnId)) { - yield* Ref.set(promptSettled, true); - return { - threadId: input.threadId, - turnId: prepared.turnId, - resumeCursor: ctx.session.resumeCursor, - }; - } - - if ( - ctx.promptsInFlight <= 0 || - ctx.activeTurnId !== prepared.turnId || - ctx.session.activeTurnId !== prepared.turnId - ) { - yield* Ref.set(promptSettled, true); - return { - threadId: input.threadId, - turnId: prepared.turnId, - resumeCursor: ctx.session.resumeCursor, - }; - } - - appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result); - ctx.session = { - ...ctx.session, - status: "running", - activeTurnId: prepared.turnId, - updatedAt: yield* nowIso, - ...(prepared.displayModel ? { model: prepared.displayModel } : {}), - }; - const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1); - ctx.promptsInFlight = remainingPrompts; - - // Only the last remaining prompt settles the turn. A steer- - // superseded prompt resolving while another is in flight or - // pending must leave the merged turn running. - if ( - remainingPrompts === 0 && - ctx.activeTurnId === prepared.turnId && - ctx.session.activeTurnId === prepared.turnId - ) { - if (ctx.interruptedTurnIds.has(prepared.turnId)) { - yield* Ref.set(promptSettled, true); - return { - threadId: input.threadId, - turnId: prepared.turnId, - resumeCursor: ctx.session.resumeCursor, - }; - } - const completedAt = yield* nowIso; - const { activeTurnId: _completedTurnId, ...readySession } = ctx.session; - ctx.activeTurnId = undefined; - ctx.session = { - ...readySession, - status: "ready", - updatedAt: completedAt, - ...(prepared.displayModel ? { model: prepared.displayModel } : {}), - }; - const completedStopReason = completedStopReasonFromPromptResponse(result); - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId: prepared.turnId, - payload: { - state: result.stopReason === "cancelled" ? "cancelled" : "completed", - stopReason: completedStopReason, - }, - }); - ctx.interruptedTurnIds.delete(prepared.turnId); - yield* Ref.set(promptSettled, true); - } else if (remainingPrompts > 0) { - yield* Ref.set(promptSettled, true); - } - - return { - threadId: input.threadId, - turnId: prepared.turnId, - resumeCursor: ctx.session.resumeCursor, - }; - }), - ); - }).pipe( - Effect.ensuring( - Effect.gen(function* () { - if (yield* Ref.get(promptSettled)) { - return; - } - - if (yield* Ref.get(promptRpcSucceeded)) { - const promptResult = yield* Ref.get(promptResultRef); - if (promptResult === undefined) { - return; - } - yield* withThreadLock( - input.threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - if (ctx.acpSessionId !== prepared.acpSessionId) { - yield* settlePromptInFlight( - input.threadId, - prepared.turnId, - prepared.acpSessionId, - { - errorMessage: "Grok session changed before the turn completed.", - settleAllPrompts: true, - }, - ); - return; - } - if (ctx.interruptedTurnIds.has(prepared.turnId)) { - return; - } - if ( - ctx.promptsInFlight <= 0 || - ctx.activeTurnId !== prepared.turnId || - ctx.session.activeTurnId !== prepared.turnId - ) { - return; - } - appendPromptResultToTurn( - ctx, - prepared.turnId, - prepared.promptParts, - promptResult, - ); - yield* settlePromptInFlight( - input.threadId, - prepared.turnId, - prepared.acpSessionId, - { - completedStopReason: completedStopReasonFromPromptResponse(promptResult), - }, - ); - }), - ); - return; - } - - const errorMessage = yield* Ref.get(promptFailureMessageRef); - yield* withThreadLock( - input.threadId, - settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, { - errorMessage: errorMessage ?? "Grok prompt request failed.", - }), - ); - }).pipe(Effect.catch(() => Effect.void)), - ), - ); - }); - - const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) => - Effect.gen(function* () { - const observed = yield* Effect.sync(() => { - const ctx = sessions.get(threadId); - if (!ctx || ctx.stopped) { - return { - _tag: "Proceed" as const, - acpSessionId: undefined, - interruptedTurnId: turnId, - }; - } - const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId; - if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) { - return { _tag: "Ignore" as const }; - } - const interruptedTurnId = turnId ?? activeTurnId; - if (interruptedTurnId !== undefined) { - ctx.interruptedTurnIds.add(interruptedTurnId); - } - return { - _tag: "Proceed" as const, - acpSessionId: ctx.acpSessionId, - interruptedTurnId, - }; - }); - if (observed._tag === "Ignore") { - return; - } - - yield* withThreadLock( - threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) { - return; - } - const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId; - if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) { - return; - } - if ( - observed.interruptedTurnId !== undefined && - activeTurnId !== undefined && - activeTurnId !== observed.interruptedTurnId - ) { - return; - } - const interruptedTurnId = - observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId; - yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); - yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs); - yield* Effect.ignore( - ctx.acp.cancel.pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error), - ), - ), - ); - if (interruptedTurnId) { - ctx.interruptedTurnIds.add(interruptedTurnId); - yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, { - completedStopReason: "cancelled", - settleAllPrompts: true, - }); - } else if ( - ctx.promptsInFlight > 0 || - ctx.session.status === "running" || - ctx.session.status === "connecting" - ) { - const updatedAt = yield* nowIso; - ctx.promptsInFlight = 0; - ctx.activeTurnId = undefined; - const { activeTurnId: _activeTurnId, ...readySession } = ctx.session; - ctx.session = { - ...readySession, - status: "ready", - updatedAt, - }; - } - }), - ); - }); - - const respondToRequest: GrokAdapterShape["respondToRequest"] = ( - threadId, - requestId, - decision, - ) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - const pending = ctx.pendingApprovals.get(requestId); - if (!pending) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/request_permission", - detail: `Unknown pending approval request: ${requestId}`, - }); - } - yield* Deferred.succeed(pending.decision, decision); - }); - - const respondToUserInput: GrokAdapterShape["respondToUserInput"] = ( - threadId, - requestId, - answers, - ) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - const pending = ctx.pendingUserInputs.get(requestId); - if (!pending) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "_x.ai/ask_user_question", - detail: `Unknown pending user-input request: ${requestId}`, - }); - } - yield* Deferred.succeed(pending.resolution, { _tag: "answered", answers }); - }); - - const readThread: GrokAdapterShape["readThread"] = (threadId) => - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - return { threadId, turns: ctx.turns }; - }); - - const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) => - Effect.gen(function* () { - yield* requireSession(threadId); - if (!Number.isInteger(numTurns) || numTurns < 1) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "rollbackThread", - issue: "numTurns must be an integer >= 1.", - }); - } - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "thread/rollback", - detail: "Grok ACP sessions do not support provider-side rollback yet.", - }); - }); - - const stopSession: GrokAdapterShape["stopSession"] = (threadId) => - withThreadLock( - threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(threadId); - yield* stopSessionInternal(ctx); - }), - ); - - const listSessions: GrokAdapterShape["listSessions"] = () => - Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session }))); - - const hasSession: GrokAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => { - const c = sessions.get(threadId); - return c !== undefined && !c.stopped; - }); - - const stopAll: GrokAdapterShape["stopAll"] = () => - Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true }); - - yield* Effect.addFinalizer(() => - Effect.ignore(stopAll()).pipe( - Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)), - Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void), - ), - ); - - const streamEvents = Stream.fromPubSub(runtimeEventPubSub); - - return { - provider: PROVIDER, - capabilities: { sessionModelSwitch: "in-session" }, - startSession, - sendTurn, - interruptTurn, - readThread, - rollbackThread, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - stopAll, - streamEvents, - } satisfies GrokAdapterShape; - }); -} diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts deleted file mode 100644 index 1385ccbaab..0000000000 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts +++ /dev/null @@ -1,1377 +0,0 @@ -import * as NodeAssert from "node:assert/strict"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it } from "@effect/vitest"; -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Path from "effect/Path"; -import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import { beforeEach } from "vite-plus/test"; - -import { - OpenCodeSettings, - ProviderDriverKind, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; -import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; -import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; -import { - OpenCodeRuntime, - OpenCodeRuntimeError, - type OpenCodeRuntimeShape, -} from "../opencodeRuntime.ts"; -import { - appendOpenCodeAssistantTextDelta, - isOpenCodeNotFound, - isSameOpenCodeDirectory, - makeOpenCodeAdapter, - mergeOpenCodeAssistantText, -} from "./OpenCodeAdapter.ts"; - -// Test-local service tag so the rest of the file can keep using `yield* OpenCodeAdapter`. -class OpenCodeAdapter extends Context.Service()( - "t3/provider/Layers/OpenCodeAdapter.test/OpenCodeAdapter", -) {} - -const asThreadId = (value: string): ThreadId => ThreadId.make(value); - -type MessageEntry = { - info: { - id: string; - role: "user" | "assistant"; - }; - parts: Array; -}; - -const runtimeMock = { - state: { - startCalls: [] as string[], - sessionCreateUrls: [] as string[], - sessionCreateInputs: [] as Array>, - authHeaders: [] as Array, - abortCalls: [] as string[], - closeCalls: [] as string[], - revertCalls: [] as Array<{ sessionID: string; messageID?: string }>, - promptCalls: [] as Array, - promptAsyncError: null as Error | null, - closeError: null as Error | null, - messages: [] as MessageEntry[], - subscribedEvents: [] as unknown[], - sessionGetIds: [] as string[], - missingSessionIds: new Set(), - transientErrorSessionIds: new Set(), - sessionDirectoryById: new Map(), - sessionUpdateCalls: [] as Array<{ sessionID: string; permission: unknown }>, - forkCalls: [] as Array<{ sessionID: string; directory?: string }>, - }, - reset() { - this.state.startCalls.length = 0; - this.state.sessionCreateUrls.length = 0; - this.state.sessionCreateInputs.length = 0; - this.state.authHeaders.length = 0; - this.state.abortCalls.length = 0; - this.state.closeCalls.length = 0; - this.state.revertCalls.length = 0; - this.state.promptCalls.length = 0; - this.state.promptAsyncError = null; - this.state.closeError = null; - this.state.messages = []; - this.state.subscribedEvents = []; - this.state.sessionGetIds.length = 0; - this.state.missingSessionIds.clear(); - this.state.transientErrorSessionIds.clear(); - this.state.sessionDirectoryById.clear(); - this.state.sessionUpdateCalls.length = 0; - this.state.forkCalls.length = 0; - }, -}; - -const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { - startOpenCodeServerProcess: ({ binaryPath }) => - Effect.gen(function* () { - runtimeMock.state.startCalls.push(binaryPath); - const url = "http://127.0.0.1:4301"; - yield* Effect.addFinalizer(() => - Effect.sync(() => { - runtimeMock.state.closeCalls.push(url); - if (runtimeMock.state.closeError) { - throw runtimeMock.state.closeError; - } - }), - ); - return { - url, - exitCode: Effect.never, - }; - }), - connectToOpenCodeServer: ({ serverUrl }) => - Effect.gen(function* () { - const url = serverUrl ?? "http://127.0.0.1:4301"; - // Always register a finalizer so the closeCalls/closeError probes fire; - // production attaches none for external servers. - yield* Effect.addFinalizer(() => - Effect.sync(() => { - runtimeMock.state.closeCalls.push(url); - if (runtimeMock.state.closeError) { - throw runtimeMock.state.closeError; - } - }), - ); - return { - url, - exitCode: null, - external: Boolean(serverUrl), - }; - }), - runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }), - createOpenCodeSdkClient: ({ baseUrl, serverPassword }) => - ({ - session: { - create: async (input: Record) => { - runtimeMock.state.sessionCreateUrls.push(baseUrl); - runtimeMock.state.sessionCreateInputs.push(input); - runtimeMock.state.authHeaders.push( - serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, - ); - return { data: { id: `${baseUrl}/session` } }; - }, - get: async ({ sessionID }: { sessionID: string }) => { - runtimeMock.state.sessionGetIds.push(sessionID); - // The real client is `throwOnError: true`: non-2xx rejects rather - // than resolving, so missing → 404 throw, transient → 500 throw. - if (runtimeMock.state.transientErrorSessionIds.has(sessionID)) { - throw new Error("opencode server error", { cause: { status: 500 } }); - } - if (runtimeMock.state.missingSessionIds.has(sessionID)) { - throw new Error(`Session not found: ${sessionID}`, { - cause: { status: 404, body: { name: "NotFoundError" } }, - }); - } - const directory = runtimeMock.state.sessionDirectoryById.get(sessionID); - return { data: { id: sessionID, ...(directory ? { directory } : {}) } }; - }, - update: async ({ sessionID, permission }: { sessionID: string; permission: unknown }) => { - runtimeMock.state.sessionUpdateCalls.push({ sessionID, permission }); - return { data: { id: sessionID } }; - }, - fork: async ({ sessionID, directory }: { sessionID: string; directory?: string }) => { - // Fork clones history into a new session bound to the directory. - const forkedId = `${sessionID}_fork`; - runtimeMock.state.forkCalls.push({ sessionID, ...(directory ? { directory } : {}) }); - if (directory) { - runtimeMock.state.sessionDirectoryById.set(forkedId, directory); - } - return { data: { id: forkedId, ...(directory ? { directory } : {}) } }; - }, - abort: async ({ sessionID }: { sessionID: string }) => { - runtimeMock.state.abortCalls.push(sessionID); - }, - promptAsync: async (input: unknown) => { - runtimeMock.state.promptCalls.push(input); - if (runtimeMock.state.promptAsyncError) { - throw runtimeMock.state.promptAsyncError; - } - }, - messages: async () => ({ data: runtimeMock.state.messages }), - revert: async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => { - runtimeMock.state.revertCalls.push({ - sessionID, - ...(messageID ? { messageID } : {}), - }); - if (!messageID) { - runtimeMock.state.messages = []; - return; - } - - const targetIndex = runtimeMock.state.messages.findIndex( - (entry) => entry.info.id === messageID, - ); - runtimeMock.state.messages = - targetIndex >= 0 - ? runtimeMock.state.messages.slice(0, targetIndex + 1) - : runtimeMock.state.messages; - }, - }, - event: { - subscribe: async () => ({ - stream: (async function* () { - for (const event of runtimeMock.state.subscribedEvents) { - yield event; - } - })(), - }), - }, - }) as unknown as ReturnType, - loadOpenCodeInventory: () => - Effect.fail( - new OpenCodeRuntimeError({ - operation: "loadOpenCodeInventory", - detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test", - cause: null, - }), - ), - loadInventoryFromCli: () => - Effect.fail( - new OpenCodeRuntimeError({ - operation: "loadInventoryFromCli", - detail: "OpenCodeRuntimeTestDouble.loadInventoryFromCli not used in this test", - cause: null, - }), - ), -}; - -const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, { - upsert: () => Effect.void, - getProvider: () => - Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")), - getBinding: () => Effect.succeed(Option.none()), - listThreadIds: () => Effect.succeed([]), - listBindings: () => Effect.succeed([]), -}); - -// The adapter now receives its settings as a plain argument (the old design -// read from `ServerSettingsService` internally). The test-only -// `ServerSettingsService` below is still kept because other dependencies in -// the layer graph reach for it — but the routing values the assertions -// probe (serverUrl, serverPassword) must be threaded directly through the -// decoded `OpenCodeSettings`. -const openCodeAdapterTestSettings = Schema.decodeSync(OpenCodeSettings)({ - binaryPath: "fake-opencode", - serverUrl: "http://127.0.0.1:9999", - serverPassword: "secret-password", -}); - -const OpenCodeAdapterTestLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings), -).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge( - ServerSettingsService.layerTest({ - providers: { - opencode: { - binaryPath: "fake-opencode", - serverUrl: "http://127.0.0.1:9999", - serverPassword: "secret-password", - }, - }, - }), - ), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), -); - -beforeEach(() => { - runtimeMock.reset(); -}); - -const advanceTestClock = (ms: number) => - TestClock.adjust(`${ms} millis`).pipe(Effect.andThen(Effect.yieldNow)); - -it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { - it.effect("reuses a configured OpenCode server URL instead of spawning a local server", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-opencode"), - runtimeMode: "full-access", - }); - - NodeAssert.equal(session.provider, "opencode"); - NodeAssert.equal(session.threadId, "thread-opencode"); - NodeAssert.deepEqual(runtimeMock.state.startCalls, []); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]); - NodeAssert.deepEqual(runtimeMock.state.authHeaders, [ - `Basic ${btoa("opencode:secret-password")}`, - ]); - }), - ); - - it.effect("returns a durable resume cursor for a freshly created session", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-cursor"); - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - // Without a persisted cursor, a session is created and its id is - // surfaced as a resume cursor so the upper layer can persist it. - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, []); - NodeAssert.deepEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "http://127.0.0.1:9999/session", - }); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("resumes the persisted OpenCode session instead of creating a new one", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-resume"); - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 1, sessionId: "ses_persisted" }, - }); - - // The adapter validates the persisted id with session.get and re-adopts - // it — no new session is minted (issue #3604). - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_persisted"]); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []); - NodeAssert.deepEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "ses_persisted", - }); - // Resume re-asserts the permission ruleset for the current runtimeMode. - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1); - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_persisted"); - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.permission != null, true); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("sends follow-up turns to the resumed session id", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-resume-turn"); - - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 1, sessionId: "ses_persisted" }, - }); - - const result = yield* adapter.sendTurn({ - threadId, - input: "continue where we left off", - modelSelection: createModelSelection( - ProviderInstanceId.make("opencode"), - "anthropic/sonnet", - ), - }); - - // The prompt targets the resumed id, and the turn re-surfaces the cursor. - NodeAssert.deepEqual( - (runtimeMock.state.promptCalls[0] as { sessionID: string }).sessionID, - "ses_persisted", - ); - NodeAssert.deepEqual(result.resumeCursor, { - schemaVersion: 1, - sessionId: "ses_persisted", - }); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("falls back to a fresh session when the persisted session is gone", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-stale"); - runtimeMock.state.missingSessionIds.add("ses_stale"); - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 1, sessionId: "ses_stale" }, - }); - - // get probed the stale id, found nothing, then created a new session and - // emitted a fresh cursor rather than wedging the thread. - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_stale"]); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]); - NodeAssert.deepEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "http://127.0.0.1:9999/session", - }); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("ignores a malformed or wrong-version resume cursor", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-badcursor"); - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 99, sessionId: "ses_persisted" }, - }); - - // A foreign/stale-shaped cursor is treated as "no resume": never probed, - // a fresh session is created. - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, []); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]); - NodeAssert.deepEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "http://127.0.0.1:9999/session", - }); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("surfaces a non-not-found resume probe error instead of silently starting fresh", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-transient"); - // session.get returns a 500 (not a 404) for this id. - runtimeMock.state.transientErrorSessionIds.add("ses_transient"); - - const exit = yield* Effect.exit( - adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 1, sessionId: "ses_transient" }, - }), - ); - - // A transient/transport/auth failure must propagate — NOT be masked as a - // brand-new empty session (the #3604 class of silent context loss). - NodeAssert.equal(Exit.isFailure(exit), true); - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_transient"]); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []); - }), - ); - - it.effect("re-applies the current runtimeMode permissions when resuming", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-perms"); - - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - // A different runtimeMode than the original create — resume must not - // leave the upstream session on stale permissions. - runtimeMode: "approval-required", - threadId, - resumeCursor: { schemaVersion: 1, sessionId: "ses_perms" }, - }); - - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_perms"]); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []); - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1); - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_perms"); - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.permission != null, true); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect( - "forks the resumed session into the requested directory instead of losing context", - () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-cwd"); - // The persisted session still exists but was created in another working dir - // (e.g. the thread moved from the project root into a git worktree). - runtimeMock.state.sessionDirectoryById.set("ses_otherdir", "/some/other/worktree"); - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 1, sessionId: "ses_otherdir" }, - }); - - // A cwd change must not mint an empty session: the adapter forks the - // persisted session into the requested cwd, carrying history forward. - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_otherdir"]); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []); - NodeAssert.equal(runtimeMock.state.forkCalls.length, 1); - NodeAssert.equal(runtimeMock.state.forkCalls[0]?.sessionID, "ses_otherdir"); - NodeAssert.equal(typeof runtimeMock.state.forkCalls[0]?.directory, "string"); - // Permission ruleset re-asserted on the fork for the current runtimeMode. - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1); - NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_otherdir_fork"); - // Durable cursor now points at the history-complete fork in the new directory. - NodeAssert.deepEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "ses_otherdir_fork", - }); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("reuses the resumed session when the stored directory differs only lexically", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-samedir"); - // Same working tree, different spelling (trailing slash) — must reuse, - // not fork. - runtimeMock.state.sessionDirectoryById.set("ses_samedir", `${process.cwd()}/`); - - const session = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - resumeCursor: { schemaVersion: 1, sessionId: "ses_samedir" }, - }); - - NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_samedir"]); - NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []); - NodeAssert.deepEqual(runtimeMock.state.forkCalls, []); - NodeAssert.deepEqual(session.resumeCursor, { - schemaVersion: 1, - sessionId: "ses_samedir", - }); - - yield* adapter.stopSession(threadId); - }), - ); - - it.effect("fails sendTurn for missing sessions through the typed error channel", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const result = yield* adapter - .sendTurn({ - threadId: asThreadId("thread-opencode-missing-send"), - input: "hello", - attachments: [], - }) - .pipe(Effect.result); - - NodeAssert.equal(result._tag, "Failure"); - NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError"); - NodeAssert.equal(result.failure.provider, "opencode"); - NodeAssert.equal(result.failure.threadId, "thread-opencode-missing-send"); - }), - ); - - it.effect("fails stopSession for missing sessions through the typed error channel", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const result = yield* adapter - .stopSession(asThreadId("thread-opencode-missing-stop")) - .pipe(Effect.result); - - NodeAssert.equal(result._tag, "Failure"); - NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError"); - NodeAssert.equal(result.failure.provider, "opencode"); - NodeAssert.equal(result.failure.threadId, "thread-opencode-missing-stop"); - }), - ); - - it.effect("stops a configured-server session without trying to own server lifecycle", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-opencode"), - runtimeMode: "full-access", - }); - - yield* adapter.stopSession(asThreadId("thread-opencode")); - - NodeAssert.deepEqual(runtimeMock.state.startCalls, []); - NodeAssert.deepEqual( - runtimeMock.state.abortCalls.includes("http://127.0.0.1:9999/session"), - true, - ); - }), - ); - - it.effect("emits one session.exited event when stopping a session", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-stop-event"); - const eventsFiber = yield* adapter.streamEvents.pipe( - Stream.filter((event) => event.threadId === threadId), - Stream.take(3), - Stream.runCollect, - Effect.forkChild, - ); - - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - yield* adapter.stopSession(threadId); - - const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second"))); - NodeAssert.deepEqual( - events.map((event) => event.type), - ["session.started", "thread.started", "session.exited"], - ); - }), - ); - - it.effect("clears session state even when cleanup finalizers throw", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-stop-all-a"), - runtimeMode: "full-access", - }); - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-stop-all-b"), - runtimeMode: "full-access", - }); - - runtimeMock.state.closeError = new Error("close failed"); - // `stopAll` relies on `stopOpenCodeContext`, which is typed as - // never-failing. A throwing finalizer surfaces as a defect — `Effect.exit` - // captures it so the assertions can still run. The key invariant we're - // validating is "the sessions map and close-call probes reflect cleanup - // attempts regardless of finalizer outcome". - yield* Effect.exit(adapter.stopAll()); - const sessions = yield* adapter.listSessions(); - - NodeAssert.deepEqual(runtimeMock.state.closeCalls, [ - "http://127.0.0.1:9999", - "http://127.0.0.1:9999", - ]); - NodeAssert.deepEqual(sessions, []); - }), - ); - - it.effect("completes streamEvents when the adapter scope closes", () => - Effect.gen(function* () { - const scope = yield* Scope.make("sequential"); - let scopeClosed = false; - - try { - const adapterLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings), - ).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - const context = yield* Layer.buildWithScope(adapterLayer, scope); - const adapter = yield* Effect.service(OpenCodeAdapter).pipe(Effect.provide(context)); - const eventsFiber = yield* adapter.streamEvents.pipe(Stream.runCollect, Effect.forkChild); - - yield* Scope.close(scope, Exit.void); - scopeClosed = true; - - const exit = yield* Fiber.await(eventsFiber).pipe(Effect.timeout("1 second")); - NodeAssert.equal(Exit.hasInterrupts(exit), true); - } finally { - if (!scopeClosed) { - yield* Scope.close(scope, Exit.void).pipe(Effect.ignore); - } - } - }), - ); - - it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-send-turn-failure"), - runtimeMode: "full-access", - }); - - runtimeMock.state.promptAsyncError = new Error("prompt failed"); - const error = yield* adapter - .sendTurn({ - threadId: asThreadId("thread-send-turn-failure"), - input: "Fix it", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "openai/gpt-5", - }, - }) - .pipe(Effect.flip); - const sessions = yield* adapter.listSessions(); - - NodeAssert.equal(error._tag, "ProviderAdapterRequestError"); - if (error._tag !== "ProviderAdapterRequestError") { - throw new Error("Unexpected error type"); - } - NodeAssert.equal(error.detail, "prompt failed"); - NodeAssert.equal( - error.message, - "Provider adapter request failed (opencode) for session.promptAsync: prompt failed", - ); - NodeAssert.equal(sessions.length, 1); - NodeAssert.equal(sessions[0]?.status, "ready"); - NodeAssert.equal(sessions[0]?.activeTurnId, undefined); - NodeAssert.equal(sessions[0]?.lastError, "prompt failed"); - }), - ); - - it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-steer"); - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - const turn = yield* adapter.sendTurn({ - threadId, - input: "run 5 commands", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "openai/gpt-5", - }, - }); - - // Steer: OpenCode queues the prompt into the busy session, so the - // active turn id is reused instead of opening a new turn. - const steeredTurn = yield* adapter.sendTurn({ - threadId, - input: "actually run 15", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "openai/gpt-5", - }, - }); - NodeAssert.equal(String(steeredTurn.turnId), String(turn.turnId)); - - const sessions = yield* adapter.listSessions(); - const session = sessions.find((entry) => entry.threadId === threadId); - NodeAssert.equal(session?.status, "running"); - NodeAssert.equal(String(session?.activeTurnId), String(turn.turnId)); - NodeAssert.equal(runtimeMock.state.promptCalls.length, 2); - }), - ); - - it.effect("keeps the running turn when a steer prompt fails", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-steer-failure"); - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - const turn = yield* adapter.sendTurn({ - threadId, - input: "run 5 commands", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "openai/gpt-5", - }, - }); - - runtimeMock.state.promptAsyncError = new Error("steer failed"); - const error = yield* adapter - .sendTurn({ - threadId, - input: "actually run 15", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "openai/gpt-5", - }, - }) - .pipe(Effect.flip); - - // The original turn keeps running — only the steer prompt failed. - NodeAssert.equal(error._tag, "ProviderAdapterRequestError"); - const sessions = yield* adapter.listSessions(); - const session = sessions.find((entry) => entry.threadId === threadId); - NodeAssert.equal(session?.status, "running"); - NodeAssert.equal(String(session?.activeTurnId), String(turn.turnId)); - }), - ); - - it.effect("passes agent and variant options for the adapter's bound custom instance id", () => { - const instanceId = ProviderInstanceId.make("opencode_zen"); - const adapterLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }), - ).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-custom-instance"), - runtimeMode: "full-access", - }); - - yield* adapter.sendTurn({ - threadId: asThreadId("thread-custom-instance"), - input: "Fix it", - modelSelection: createModelSelection( - ProviderInstanceId.make("opencode_zen"), - "anthropic/claude-sonnet-4-5", - [ - { id: "agent", value: "github-copilot" }, - { id: "variant", value: "high" }, - ], - ), - }); - - NodeAssert.deepEqual(runtimeMock.state.promptCalls.at(-1), { - sessionID: "http://127.0.0.1:9999/session", - model: { - providerID: "anthropic", - modelID: "claude-sonnet-4-5", - }, - agent: "github-copilot", - variant: "high", - parts: [{ type: "text", text: "Fix it" }], - }); - }).pipe(Effect.provide(adapterLayer)); - }); - - it.effect("uses the bound custom instance id for fallback sendTurn model selection", () => { - const instanceId = ProviderInstanceId.make("opencode_zen"); - const adapterLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }), - ).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-custom-instance-fallback-model"); - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - modelSelection: createModelSelection( - ProviderInstanceId.make("opencode_zen"), - "anthropic/claude-sonnet-4-5", - ), - }); - - yield* adapter.sendTurn({ - threadId, - input: "Fix it", - }); - - NodeAssert.deepEqual(runtimeMock.state.promptCalls.at(-1), { - sessionID: "http://127.0.0.1:9999/session", - model: { - providerID: "anthropic", - modelID: "claude-sonnet-4-5", - }, - parts: [{ type: "text", text: "Fix it" }], - }); - }).pipe(Effect.provide(adapterLayer)); - }); - - it.effect("rejects sendTurn model selections for another instance id", () => { - const instanceId = ProviderInstanceId.make("opencode_zen"); - const adapterLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }), - ).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-custom-instance-wrong-selection"); - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - const error = yield* adapter - .sendTurn({ - threadId, - input: "Fix it", - modelSelection: createModelSelection( - ProviderInstanceId.make("opencode"), - "anthropic/claude-sonnet-4-5", - ), - }) - .pipe(Effect.flip); - - NodeAssert.equal(error._tag, "ProviderAdapterValidationError"); - if (error._tag !== "ProviderAdapterValidationError") { - throw new Error("Unexpected error type"); - } - NodeAssert.equal( - error.issue, - "OpenCode model selection is bound to instance 'opencode', expected 'opencode_zen'.", - ); - NodeAssert.deepEqual(runtimeMock.state.promptCalls, []); - }).pipe(Effect.provide(adapterLayer)); - }); - - it.effect("reverts the full thread when rollback removes every assistant turn", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-rollback-all"); - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - runtimeMock.state.messages = [ - { - info: { id: "assistant-1", role: "assistant" }, - parts: [], - }, - { - info: { id: "assistant-2", role: "assistant" }, - parts: [], - }, - ]; - - const snapshot = yield* adapter.rollbackThread(threadId, 2); - - NodeAssert.deepEqual(runtimeMock.state.revertCalls, [ - { sessionID: "http://127.0.0.1:9999/session" }, - ]); - NodeAssert.deepEqual(snapshot.turns, []); - }), - ); - - it.effect("classifies a confirmed not-found across the shapes the SDK/runtime can produce", () => - Effect.sync(() => { - // The real production shape: runOpenCodeSdk wraps the thrown Error - // (cause = { body, status }) under OpenCodeRuntimeError. - const wrappedError = new Error("Session not found: ses_x", { - cause: { body: { name: "NotFoundError" }, status: 404 }, - }); - NodeAssert.equal( - isOpenCodeNotFound({ - _tag: "OpenCodeRuntimeError", - operation: "session.get", - detail: "Session not found: ses_x", - cause: wrappedError, - }), - true, - ); - - // 404 expressed only via response.status (the bot's flagged shape). - NodeAssert.equal(isOpenCodeNotFound({ cause: { response: { status: 404 } } }), true); - // 404 via a bare numeric status / statusCode. - NodeAssert.equal(isOpenCodeNotFound(new Error("x", { cause: { status: 404 } })), true); - NodeAssert.equal(isOpenCodeNotFound({ statusCode: 404 }), true); - // OpenCode NotFoundError body name with no status. - NodeAssert.equal(isOpenCodeNotFound({ body: { name: "NotFoundError" } }), true); - - // NOT a miss: only structured signals count, never free text. A non-404 - // error whose message/detail merely contains "not found" must propagate, - // not be misread as a missing session and silently start fresh. - NodeAssert.equal( - isOpenCodeNotFound(new Error("upstream provider not found", { cause: { status: 500 } })), - false, - ); - NodeAssert.equal(isOpenCodeNotFound({ detail: "status=500 body={...not found...}" }), false); - // An explicit non-404 status seals its subtree: a 500 whose serialized - // body echoes a NotFoundError name — or that is itself named - // *NotFound* — is a real failure, never a miss. - NodeAssert.equal(isOpenCodeNotFound({ status: 500, body: { name: "NotFoundError" } }), false); - NodeAssert.equal(isOpenCodeNotFound({ name: "UpstreamNotFoundError", status: 500 }), false); - // A "NotFound"-flavored name that isn't OpenCode's exact `NotFoundError` - // is not a confirmed miss even without a sealing status. - NodeAssert.equal(isOpenCodeNotFound({ name: "UpstreamNotFoundError" }), false); - NodeAssert.equal(isOpenCodeNotFound({ cause: { name: "ProviderNotFoundError" } }), false); - NodeAssert.equal( - isOpenCodeNotFound( - new Error("x", { cause: { status: 502, body: { name: "NotFoundError" } } }), - ), - false, - ); - // Other transient/auth/network failures must propagate too. - NodeAssert.equal(isOpenCodeNotFound(new Error("boom", { cause: { status: 500 } })), false); - NodeAssert.equal(isOpenCodeNotFound({ cause: { response: { status: 401 } } }), false); - NodeAssert.equal(isOpenCodeNotFound(new Error("network error (no response)")), false); - NodeAssert.equal(isOpenCodeNotFound(undefined), false); - }), - ); - - it.effect("treats lexically or physically identical directories as the same", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const sameDirectory = (left: string, right: string) => - isSameOpenCodeDirectory(fileSystem, path, left, right); - - // Lexical-only differences (trailing slash, dot segments) short-circuit - // without touching the filesystem — the paths need not exist. - NodeAssert.equal(yield* sameDirectory("/repo/project/", "/repo/project"), true); - NodeAssert.equal(yield* sameDirectory("/repo/nested/../project", "/repo/project"), true); - // Nonexistent paths degrade to the lexical comparison instead of failing. - NodeAssert.equal(yield* sameDirectory("/repo/project", "/repo/other"), false); - - // A symlinked cwd (the macOS `/tmp` → `/private/tmp` shape) resolves to - // the directory it points at, so the two spellings compare equal. - const base = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-opencode-dir-" }); - const real = path.join(base, "real"); - const link = path.join(base, "link"); - yield* fileSystem.makeDirectory(real); - yield* fileSystem.symlink(real, link); - NodeAssert.equal(yield* sameDirectory(link, real), true); - NodeAssert.equal(yield* sameDirectory(link, path.join(base, "other")), false); - }).pipe(Effect.scoped), - ); - - it.effect("appends raw assistant text deltas and reconciles part update snapshots", () => - Effect.sync(() => { - const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello"); - const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world"); - const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hellolo world"); - - NodeAssert.deepEqual( - [firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit], - ["Hello", "lo world", ""], - ); - NodeAssert.equal(secondUpdate.latestText, "Hellolo world"); - }), - ); - - it.effect("does not strip coincidental prefix overlap from OpenCode part deltas", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-raw-delta"); - const part = { - id: "part-raw-delta", - sessionID: "http://127.0.0.1:9999/session", - messageID: "msg-raw-delta", - type: "text", - text: "A B", - time: { start: 1 }, - }; - runtimeMock.state.subscribedEvents = [ - { - type: "message.updated", - properties: { - sessionID: "http://127.0.0.1:9999/session", - info: { - id: "msg-raw-delta", - role: "assistant", - }, - }, - }, - { - type: "message.part.updated", - properties: { - sessionID: "http://127.0.0.1:9999/session", - part, - time: 1, - }, - }, - { - type: "message.part.delta", - properties: { - sessionID: "http://127.0.0.1:9999/session", - messageID: "msg-raw-delta", - partID: "part-raw-delta", - field: "text", - delta: "Bonus", - }, - }, - { - type: "message.part.updated", - properties: { - sessionID: "http://127.0.0.1:9999/session", - part: { - ...part, - text: "A BBonus", - time: { start: 1, end: 2 }, - }, - time: 2, - }, - }, - ]; - const eventsFiber = yield* adapter.streamEvents.pipe( - Stream.filter((event) => event.threadId === threadId), - Stream.take(5), - Stream.runCollect, - Effect.forkChild, - ); - - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second"))); - const deltas = events.filter((event) => event.type === "content.delta"); - NodeAssert.deepEqual( - deltas.map((event) => (event.type === "content.delta" ? event.payload.delta : "")), - ["A B", "Bonus"], - ); - NodeAssert.equal(events.at(-1)?.type, "item.completed"); - const completed = events.at(-1); - if (completed?.type === "item.completed") { - NodeAssert.equal(completed.payload.detail, "A BBonus"); - } - }), - ); - - it.effect("lets OpenCode own session title generation and emits title metadata updates", () => - Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const threadId = asThreadId("thread-opencode-title-sync"); - runtimeMock.state.subscribedEvents = [ - { - type: "session.updated", - properties: { - info: { - id: "http://127.0.0.1:9999/session", - title: "Investigate OpenCode title sync", - }, - }, - }, - ]; - - const eventsFiber = yield* adapter.streamEvents.pipe( - Stream.filter((event) => event.threadId === threadId), - Stream.take(3), - Stream.runCollect, - Effect.forkChild, - ); - - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId, - runtimeMode: "full-access", - }); - - const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second"))); - NodeAssert.equal(runtimeMock.state.sessionCreateInputs.length, 1); - NodeAssert.equal("title" in (runtimeMock.state.sessionCreateInputs[0] ?? {}), false); - - const metadataUpdated = events.find((event) => event.type === "thread.metadata.updated"); - NodeAssert.ok(metadataUpdated); - if (metadataUpdated.type === "thread.metadata.updated") { - NodeAssert.equal(metadataUpdated.payload.name, "Investigate OpenCode title sync"); - } - }), - ); - - it.effect("writes provider-native observability records using the session thread id", () => - Effect.gen(function* () { - const nativeEvents: Array<{ - readonly event?: { - readonly provider?: string; - readonly threadId?: string; - readonly providerThreadId?: string; - readonly type?: string; - }; - }> = []; - const nativeThreadIds: Array = []; - runtimeMock.state.subscribedEvents = [ - { - type: "message.updated", - properties: { - info: { - id: "msg-missing-session", - role: "assistant", - }, - }, - }, - { - type: "message.updated", - properties: { - sessionID: "http://127.0.0.1:9999/other-session", - info: { - id: "msg-other-session", - role: "assistant", - }, - }, - }, - { - type: "message.updated", - properties: { - sessionID: "http://127.0.0.1:9999/session", - info: { - id: "msg-native-log", - role: "assistant", - }, - }, - }, - ]; - - const nativeEventLogger = { - filePath: "memory://opencode-native-events", - write: (event: unknown, threadId: ThreadId | null) => { - nativeEvents.push(event as (typeof nativeEvents)[number]); - nativeThreadIds.push(threadId ?? null); - return Effect.void; - }, - close: () => Effect.void, - }; - - const adapterLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings, { - nativeEventLogger, - }), - ).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge( - ServerSettingsService.layerTest({ - providers: { - opencode: { - binaryPath: "fake-opencode", - serverUrl: "http://127.0.0.1:9999", - serverPassword: "secret-password", - }, - }, - }), - ), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - const session = yield* Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - const started = yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-native-log"), - runtimeMode: "full-access", - }); - yield* advanceTestClock(10); - return started; - }).pipe(Effect.provide(adapterLayer)); - - NodeAssert.equal(session.threadId, "thread-native-log"); - NodeAssert.equal(nativeEvents.length, 1); - NodeAssert.equal( - nativeEvents.some((record) => record.event?.provider === "opencode"), - true, - ); - NodeAssert.equal( - nativeEvents.some( - (record) => record.event?.providerThreadId === "http://127.0.0.1:9999/session", - ), - true, - ); - NodeAssert.equal( - nativeEvents.some((record) => record.event?.threadId === "thread-native-log"), - true, - ); - NodeAssert.equal( - nativeEvents.some((record) => record.event?.type === "message.updated"), - true, - ); - NodeAssert.equal( - nativeThreadIds.every((threadId) => threadId === "thread-native-log"), - true, - ); - }), - ); - - it.effect("keeps the event pump alive when native event logging fails", () => - Effect.gen(function* () { - runtimeMock.state.subscribedEvents = [ - { - type: "message.updated", - properties: { - sessionID: "http://127.0.0.1:9999/session", - info: { - id: "msg-native-log-failure", - role: "assistant", - }, - }, - }, - ]; - - const nativeEventLogger = { - filePath: "memory://opencode-native-events", - write: () => Effect.die(new Error("native log write failed")), - close: () => Effect.void, - }; - - const adapterLayer = Layer.effect( - OpenCodeAdapter, - makeOpenCodeAdapter(openCodeAdapterTestSettings, { - nativeEventLogger, - }), - ).pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge( - ServerSettingsService.layerTest({ - providers: { - opencode: { - binaryPath: "fake-opencode", - serverUrl: "http://127.0.0.1:9999", - serverPassword: "secret-password", - }, - }, - }), - ), - Layer.provideMerge(providerSessionDirectoryTestLayer), - Layer.provideMerge(NodeServices.layer), - ); - - // Capture closeCalls *inside* the provided layer scope: the adapter's - // layer finalizer now tears down any live sessions when the layer - // closes (which is exactly what we want for leak prevention), so - // inspecting closeCalls after `Effect.provide` completes would observe - // the teardown — not the behavior under test. We care that the event - // pump kept the session alive while logging was failing. - const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () { - const adapter = yield* OpenCodeAdapter; - yield* adapter.startSession({ - provider: ProviderDriverKind.make("opencode"), - threadId: asThreadId("thread-native-log-failure"), - runtimeMode: "full-access", - }); - yield* advanceTestClock(10); - return { - sessions: yield* adapter.listSessions(), - closeCallsDuringRun: [...runtimeMock.state.closeCalls], - }; - }).pipe(Effect.provide(adapterLayer)); - - NodeAssert.equal(sessions.length, 1); - NodeAssert.equal(sessions[0]?.threadId, "thread-native-log-failure"); - NodeAssert.deepEqual(closeCallsDuringRun, []); - }), - ); -}); diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts deleted file mode 100644 index 1308672aeb..0000000000 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ /dev/null @@ -1,1742 +0,0 @@ -import { - EventId, - type OpenCodeSettings, - ProviderDriverKind, - ProviderInstanceId, - type ProviderRuntimeEvent, - type ProviderSession, - RuntimeItemId, - RuntimeRequestId, - ThreadId, - type ToolLifecycleItemType, - TurnId, - type UserInputQuestion, -} from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; -import * as Queue from "effect/Queue"; -import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2"; -import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; - -import { resolveAttachmentPath } from "../../attachmentStore.ts"; -import { ServerConfig } from "../../config.ts"; -import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; -import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; -import { - ProviderAdapterProcessError, - ProviderAdapterRequestError, - ProviderAdapterSessionClosedError, - ProviderAdapterSessionNotFoundError, - ProviderAdapterValidationError, -} from "../Errors.ts"; -import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; -import { - buildOpenCodePermissionRules, - OpenCodeRuntime, - OpenCodeRuntimeError, - openCodeQuestionId, - openCodeRuntimeErrorDetail, - parseOpenCodeModelSlug, - runOpenCodeSdk, - toOpenCodeFileParts, - toOpenCodePermissionReply, - toOpenCodeQuestionAnswers, - type OpenCodeServerConnection, -} from "../opencodeRuntime.ts"; -import * as Option from "effect/Option"; - -const PROVIDER = ProviderDriverKind.make("opencode"); - -/** - * Version tag stamped into the OpenCode resume cursor. Bump if the cursor - * shape changes so stale-shaped cursors written by older builds are ignored - * rather than misread (mirrors GROK_RESUME_VERSION / CURSOR_RESUME_VERSION). - */ -const OPENCODE_RESUME_VERSION = 1 as const; - -/** - * Decode a persisted resume cursor into the upstream `ses_…` id. Anything - * that isn't a current-version cursor with a non-empty id means "no resume" - * rather than an error. Re-adopting the session id IS the resume mechanism — - * OpenCode scopes a conversation's history by session id. - */ -function parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | undefined { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { - return undefined; - } - const record = raw as Record; - if (record.schemaVersion !== OPENCODE_RESUME_VERSION) { - return undefined; - } - if (typeof record.sessionId !== "string" || record.sessionId.trim().length === 0) { - return undefined; - } - return { sessionId: record.sessionId.trim() }; -} - -/** - * Whether an error definitively reports a missing session. Only a confirmed - * miss may silently start a fresh session; any other failure (the SDK client - * is `throwOnError: true`, so `session.get` rejects on every non-2xx) must - * propagate, or a transient blip resets a live thread to an empty one — the - * #3604 silent context loss. Decides on structured signals only, never free - * text: a numeric 404 or the exact `NotFoundError` name, found via a bounded walk - * over `cause`/`body`/`error`/`data`. An explicit non-404 status seals its - * subtree so a wrapped "NotFound" name can't reclassify a real failure. - * Exported for unit testing. - */ -export function isOpenCodeNotFound(cause: unknown): boolean { - const seen = new Set(); - const queue: Array = [cause]; - for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) { - const node = queue.shift(); - if (node === null || typeof node !== "object" || seen.has(node)) { - continue; - } - seen.add(node); - const record = node as Record; - - const response = record.response; - const statuses = [ - record.status, - record.statusCode, - response !== null && typeof response === "object" - ? (response as { readonly status?: unknown }).status - : undefined, - ].filter((status): status is number => typeof status === "number"); - if (statuses.includes(404)) { - return true; - } - if (statuses.length > 0) { - continue; - } - - const name = record.name; - if (typeof name === "string" && name.toLowerCase() === "notfounderror") { - return true; - } - - for (const key of ["cause", "body", "error", "data"] as const) { - if (record[key] !== undefined) { - queue.push(record[key]); - } - } - } - return false; -} - -/** - * Whether two directory spellings name the same location. Raw string - * equality misreads a trailing slash, `.`/`..` segment, or symlinked cwd - * (macOS `/tmp` → `/private/tmp`) as a cwd change, needlessly forking the - * session on every resume. Lexically equal paths short-circuit; otherwise - * both sides go through `realPath`, each falling back to its lexical form - * on failure (deleted directory, external-server path) — so the probe can - * only widen matches, never split them. Takes the services as arguments so - * adapter methods stay service-free. Exported for unit testing. - */ -export function isSameOpenCodeDirectory( - fileSystem: FileSystem.FileSystem, - path: Path.Path, - left: string, - right: string, -): Effect.Effect { - const lexicalLeft = path.resolve(left); - const lexicalRight = path.resolve(right); - if (lexicalLeft === lexicalRight) { - return Effect.succeed(true); - } - const canonicalize = (lexical: string) => - fileSystem.realPath(lexical).pipe(Effect.orElseSucceed(() => lexical)); - return Effect.zipWith( - canonicalize(lexicalLeft), - canonicalize(lexicalRight), - (canonicalLeft, canonicalRight) => canonicalLeft === canonicalRight, - ); -} - -interface OpenCodeTurnSnapshot { - readonly id: TurnId; - readonly items: Array; -} - -type OpenCodeSubscribedEvent = - Awaited> extends { - readonly stream: AsyncIterable; - } - ? TEvent - : never; - -function trimText(value: string | undefined | null): string | undefined { - const trimmed = value?.trim(); - return trimmed && trimmed.length > 0 ? trimmed : undefined; -} - -function openCodeEventSessionId(event: OpenCodeSubscribedEvent): string | undefined { - const properties = "properties" in event ? event.properties : undefined; - if (!properties || typeof properties !== "object") { - return undefined; - } - - const sessionID = (properties as { readonly sessionID?: unknown }).sessionID; - const sessionIDFromProperties = typeof sessionID === "string" ? sessionID : undefined; - if (sessionIDFromProperties) { - return sessionIDFromProperties; - } - - const info = (properties as { readonly info?: { readonly id?: unknown } }).info; - return info && typeof info.id === "string" ? info.id : undefined; -} - -function openCodeEventSessionTitle(event: OpenCodeSubscribedEvent): string | undefined { - if (event.type !== "session.updated") { - return undefined; - } - - return trimText(event.properties.info.title); -} - -interface OpenCodeSessionContext { - session: ProviderSession; - readonly client: OpencodeClient; - readonly server: OpenCodeServerConnection; - readonly directory: string; - readonly openCodeSessionId: string; - readonly pendingPermissions: Map; - readonly pendingQuestions: Map; - readonly messageRoleById: Map; - readonly partById: Map; - readonly emittedTextByPartId: Map; - readonly completedAssistantPartIds: Set; - readonly turns: Array; - activeTurnId: TurnId | undefined; - activeAgent: string | undefined; - activeVariant: string | undefined; - /** - * One-shot guard flipped by `stopOpenCodeContext` / `emitUnexpectedExit`. - * The session lifecycle is owned by `sessionScope`; this Ref exists only - * so concurrent callers can race the transition safely via `getAndSet`. - */ - readonly stopped: Ref.Ref; - /** - * Sole lifecycle handle for the session. Closing this scope: - * - aborts the `AbortController` registered as a finalizer - * (cancels the in-flight `event.subscribe` fetch), - * - interrupts the event-pump and server-exit fibers forked - * via `Effect.forkIn(sessionScope)`, - * - tears down the OpenCode server process for scope-owned servers. - */ - readonly sessionScope: Scope.Closeable; -} - -export interface OpenCodeAdapterLiveOptions { - readonly instanceId?: ProviderInstanceId; - readonly environment?: NodeJS.ProcessEnv; - readonly nativeEventLogPath?: string; - readonly nativeEventLogger?: EventNdjsonLogger; -} - -const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - -/** - * Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into - * the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call - * sites pipe through this in `Effect.mapError` so they never build the error - * shape by hand. - */ -const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: cause.operation, - detail: cause.detail, - cause: cause.cause, - }); - -/** - * Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The - * typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}), - * in which case we preserve its `detail`; otherwise we fall back to - * {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.). - */ -const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId, - detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause), - cause, - }); - -type EventBaseInput = { - readonly threadId: ThreadId; - readonly turnId?: TurnId | undefined; - readonly itemId?: string | undefined; - readonly requestId?: string | undefined; - readonly createdAt?: string | undefined; - readonly raw?: unknown; -}): Pick< - ProviderRuntimeEvent, - "eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw" -> { - return { - eventId: EventId.make(randomUUID()), - provider: PROVIDER, - threadId: input.threadId, - createdAt: input.createdAt ?? nowIso(), - ...(input.turnId ? { turnId: input.turnId } : {}), - ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}), - ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}), - ...(input.raw !== undefined - ? { - raw: { - source: "opencode.sdk.event", - payload: input.raw, - }, - } - : {}), - }; -} - -function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType { - const normalized = toolName.toLowerCase(); - if (normalized.includes("bash") || normalized.includes("command")) { - return "command_execution"; - } - if ( - normalized.includes("edit") || - normalized.includes("write") || - normalized.includes("patch") || - normalized.includes("multiedit") - ) { - return "file_change"; - } - if (normalized.includes("web")) { - return "web_search"; - } - if (normalized.includes("mcp")) { - return "mcp_tool_call"; - } - if (normalized.includes("image")) { - return "image_view"; - } - if ( - normalized.includes("task") || - normalized.includes("agent") || - normalized.includes("subtask") - ) { - return "collab_agent_tool_call"; - } - return "dynamic_tool_call"; -} - -function mapPermissionToRequestType( - permission: string, -): "command_execution_approval" | "file_read_approval" | "file_change_approval" | "unknown" { - switch (permission) { - case "bash": - return "command_execution_approval"; - case "read": - return "file_read_approval"; - case "edit": - return "file_change_approval"; - default: - return "unknown"; - } -} - -function mapPermissionDecision(reply: "once" | "always" | "reject"): string { - switch (reply) { - case "once": - return "accept"; - case "always": - return "acceptForSession"; - case "reject": - default: - return "decline"; - } -} - -function resolveTurnSnapshot( - context: OpenCodeSessionContext, - turnId: TurnId, -): OpenCodeTurnSnapshot { - const existing = context.turns.find((turn) => turn.id === turnId); - if (existing) { - return existing; - } - - const created: OpenCodeTurnSnapshot = { id: turnId, items: [] }; - context.turns.push(created); - return created; -} - -function appendTurnItem( - context: OpenCodeSessionContext, - turnId: TurnId | undefined, - item: unknown, -): void { - if (!turnId) { - return; - } - resolveTurnSnapshot(context, turnId).items.push(item); -} - -const ensureSessionContext = Effect.fn("ensureSessionContext")(function* ( - sessions: ReadonlyMap, - threadId: ThreadId, -) { - const session = sessions.get(threadId); - if (!session) { - return yield* new ProviderAdapterSessionNotFoundError({ - provider: PROVIDER, - threadId, - }); - } - if (yield* Ref.get(session.stopped)) { - return yield* new ProviderAdapterSessionClosedError({ - provider: PROVIDER, - threadId, - }); - } - return session; -}); - -function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray { - return request.questions.map((question, index) => ({ - id: openCodeQuestionId(index, question), - header: question.header, - question: question.question, - options: question.options.map((option) => ({ - label: option.label, - description: option.description, - })), - ...(question.multiple ? { multiSelect: true } : {}), - })); -} - -function resolveTextStreamKind(part: Part | undefined): "assistant_text" | "reasoning_text" { - return part?.type === "reasoning" ? "reasoning_text" : "assistant_text"; -} - -function textFromPart(part: Part): string | undefined { - switch (part.type) { - case "text": - case "reasoning": - return part.text; - default: - return undefined; - } -} - -function commonPrefixLength(left: string, right: string): number { - let index = 0; - while (index < left.length && index < right.length && left[index] === right[index]) { - index += 1; - } - return index; -} - -function resolveLatestAssistantText(previousText: string | undefined, nextText: string): string { - if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) { - return previousText; - } - return nextText; -} - -export function mergeOpenCodeAssistantText( - previousText: string | undefined, - nextText: string, -): { - readonly latestText: string; - readonly deltaToEmit: string; -} { - const latestText = resolveLatestAssistantText(previousText, nextText); - return { - latestText, - deltaToEmit: latestText.slice(commonPrefixLength(previousText ?? "", latestText)), - }; -} - -export function appendOpenCodeAssistantTextDelta( - previousText: string, - delta: string, -): { - readonly nextText: string; - readonly deltaToEmit: string; -} { - return { - nextText: previousText + delta, - deltaToEmit: delta, - }; -} - -const isoFromEpochMs = (value: number) => - DateTime.make(value).pipe( - Option.match({ - onNone: () => undefined, - onSome: DateTime.formatIso, - }), - ); - -function messageRoleForPart( - context: OpenCodeSessionContext, - part: Pick, -): "assistant" | "user" | undefined { - const known = context.messageRoleById.get(part.messageID); - if (known) { - return known; - } - return part.type === "tool" ? "assistant" : undefined; -} - -function detailFromToolPart(part: Extract): string | undefined { - switch (part.state.status) { - case "completed": - return part.state.output; - case "error": - return part.state.error; - case "running": - return part.state.title; - default: - return undefined; - } -} - -function toolStateCreatedAt(part: Extract): string | undefined { - switch (part.state.status) { - case "running": - return isoFromEpochMs(part.state.time.start); - case "completed": - case "error": - return isoFromEpochMs(part.state.time.end); - default: - return undefined; - } -} - -function sessionErrorMessage(error: unknown): string { - if (!error || typeof error !== "object") { - return "OpenCode session failed."; - } - const data = "data" in error && error.data && typeof error.data === "object" ? error.data : null; - const message = data && "message" in data ? data.message : null; - return typeof message === "string" && message.trim().length > 0 - ? message - : "OpenCode session failed."; -} - -function updateProviderSession( - context: OpenCodeSessionContext, - patch: Partial, - options?: { - readonly clearActiveTurnId?: boolean; - readonly clearLastError?: boolean; - }, -): Effect.Effect { - return Effect.gen(function* () { - const updatedAt = yield* nowIso; - const nextSession = { - ...context.session, - ...patch, - updatedAt, - } as ProviderSession & Record; - const mutableSession = nextSession as Record; - if (options?.clearActiveTurnId) { - delete mutableSession.activeTurnId; - } - if (options?.clearLastError) { - delete mutableSession.lastError; - } - context.session = nextSession; - return nextSession; - }); -} - -const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* ( - context: OpenCodeSessionContext, -) { - // Race-safe one-shot: first caller flips the flag, everyone else no-ops. - if (yield* Ref.getAndSet(context.stopped, true)) { - return false; - } - - // Best-effort remote abort. The scope close below tears down the local - // handles (event-pump fiber, server-exit fiber, event-subscribe fetch), - // but we still want to tell OpenCode that this session is done. - yield* runOpenCodeSdk("session.abort", () => - context.client.session.abort({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.ignore({ log: true })); - - // Closing the session scope interrupts every fiber forked into it and - // runs each finalizer we registered — the `AbortController.abort()` call, - // the child-process termination, etc. - yield* Scope.close(context.sessionScope, Exit.void); - return true; -}); - -export function makeOpenCodeAdapter( - openCodeSettings: OpenCodeSettings, - options?: OpenCodeAdapterLiveOptions, -) { - return Effect.gen(function* () { - const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode"); - const serverConfig = yield* ServerConfig; - const openCodeRuntime = yield* OpenCodeRuntime; - const crypto = yield* Crypto.Crypto; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const sameDirectory = (left: string, right: string) => - isSameOpenCodeDirectory(fileSystem, path, left, right); - const nativeEventLogger = - options?.nativeEventLogger ?? - (options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { - stream: "native", - }) - : undefined); - // Only close loggers we created. If the caller passed one in via - // `options.nativeEventLogger`, they own its lifecycle. - const managedNativeEventLogger = - options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; - const runtimeEvents = yield* Queue.unbounded(); - const sessions = new Map(); - const randomUUIDv4 = crypto.randomUUIDv4.pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "crypto/randomUUIDv4", - detail: "Failed to generate OpenCode runtime identifier.", - cause, - }), - ), - ); - const buildEventBase = (input: EventBaseInput) => - Effect.all({ - eventId: randomUUIDv4.pipe(Effect.map(EventId.make)), - createdAt: input.createdAt === undefined ? nowIso : Effect.succeed(input.createdAt), - }).pipe( - Effect.map(({ eventId, createdAt }) => ({ - eventId, - provider: PROVIDER, - threadId: input.threadId, - createdAt, - ...(input.turnId ? { turnId: input.turnId } : {}), - ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}), - ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}), - ...(input.raw !== undefined - ? { - raw: { - source: "opencode.sdk.event" as const, - payload: input.raw, - }, - } - : {}), - })), - ); - - // Layer-level finalizer: when the adapter layer shuts down, stop every - // session. Each session's `Scope.close` tears down its spawned OpenCode - // server (via the `ChildProcessSpawner` finalizer installed in - // `startOpenCodeServerProcess`) and interrupts the forked event/exit - // fibers. Consumers that can't reason about Effect scopes therefore - // cannot leak OpenCode child processes by forgetting to call `stopAll`. - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - const contexts = [...sessions.values()]; - sessions.clear(); - // `ignoreCause` swallows both typed failures (none here) and defects - // from throwing scope finalizers so a sibling's death can't interrupt - // the remaining cleanups. - yield* Effect.forEach( - contexts, - (context) => Effect.ignoreCause(stopOpenCodeContext(context)), - { concurrency: "unbounded", discard: true }, - ); - // Close the logger AFTER session teardown so any final lifecycle - // events emitted during shutdown still get written. `close` flushes - // the `Logger.batched` window and closes each per-thread - // `RotatingFileSink` handle owned by the logger's internal scope. - if (managedNativeEventLogger !== undefined) { - yield* managedNativeEventLogger.close(); - } - }).pipe(Effect.ensuring(Queue.shutdown(runtimeEvents))), - ); - - const emit = (event: ProviderRuntimeEvent) => - Queue.offer(runtimeEvents, event).pipe(Effect.asVoid); - const writeNativeEvent = ( - threadId: ThreadId, - event: { - readonly observedAt: string; - readonly event: Record; - }, - ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void); - const writeNativeEventBestEffort = ( - threadId: ThreadId, - event: { - readonly observedAt: string; - readonly event: Record; - }, - ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void)); - - const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* ( - context: OpenCodeSessionContext, - message: string, - ) { - // Atomic one-shot: two fibers can race here (the event-pump on stream - // failure and the server-exit watcher). `getAndSet` flips the flag in - // a single step so the loser observes `true` and returns; a plain - // `Ref.get` would let both racers slip past and emit duplicates. - if (yield* Ref.getAndSet(context.stopped, true)) { - return; - } - const turnId = context.activeTurnId; - sessions.delete(context.session.threadId); - // Emit lifecycle events BEFORE tearing down the scope. Both call sites - // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`; - // closing that scope triggers the fiber-interrupt finalizer, so any - // subsequent yield point would unwind and silently drop these emits. - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - })), - type: "runtime.error", - payload: { - message, - class: "transport_error", - }, - }).pipe(Effect.ignore); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - })), - type: "session.exited", - payload: { - reason: message, - recoverable: false, - exitKind: "error", - }, - }).pipe(Effect.ignore); - // Inline the teardown that `stopOpenCodeContext` would do; we can't - // delegate to it because our `getAndSet` above already flipped the - // one-shot guard, so the call would no-op. - yield* runOpenCodeSdk("session.abort", () => - context.client.session.abort({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.ignore({ log: true })); - yield* Scope.close(context.sessionScope, Exit.void); - }); - - /** Emit content.delta and item.completed events for an assistant text part. */ - const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* ( - context: OpenCodeSessionContext, - part: Part, - turnId: TurnId | undefined, - raw: unknown, - ) { - const text = textFromPart(part); - if (text === undefined) { - return; - } - const previousText = context.emittedTextByPartId.get(part.id); - const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text); - context.emittedTextByPartId.set(part.id, latestText); - if (latestText !== text) { - context.partById.set( - part.id, - (part.type === "text" || part.type === "reasoning" - ? { ...part, text: latestText } - : part) satisfies Part, - ); - } - if (deltaToEmit.length > 0) { - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: part.id, - createdAt: - (part.type === "text" || part.type === "reasoning") && part.time !== undefined - ? isoFromEpochMs(part.time.start) - : undefined, - raw, - })), - type: "content.delta", - payload: { - streamKind: resolveTextStreamKind(part), - delta: deltaToEmit, - }, - }); - } - - if ( - part.type === "text" && - part.time?.end !== undefined && - !context.completedAssistantPartIds.has(part.id) - ) { - context.completedAssistantPartIds.add(part.id); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: part.id, - createdAt: isoFromEpochMs(part.time.end), - raw, - })), - type: "item.completed", - payload: { - itemType: "assistant_message", - status: "completed", - title: "Assistant message", - ...(latestText.length > 0 ? { detail: latestText } : {}), - }, - }); - } - }); - - const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* ( - context: OpenCodeSessionContext, - event: OpenCodeSubscribedEvent, - ) { - const payloadSessionId = openCodeEventSessionId(event); - if (payloadSessionId !== context.openCodeSessionId) { - return; - } - - const turnId = context.activeTurnId; - yield* writeNativeEventBestEffort(context.session.threadId, { - observedAt: yield* nowIso, - event: { - provider: PROVIDER, - threadId: context.session.threadId, - providerThreadId: context.openCodeSessionId, - type: event.type, - ...(turnId ? { turnId } : {}), - payload: event, - }, - }); - - switch (event.type) { - case "session.updated": { - const title = openCodeEventSessionTitle(event); - if (title) { - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - raw: event, - })), - type: "thread.metadata.updated", - payload: { - name: title, - metadata: { - sessionID: context.openCodeSessionId, - }, - }, - }); - } - break; - } - - case "message.updated": { - context.messageRoleById.set(event.properties.info.id, event.properties.info.role); - if (event.properties.info.role === "assistant") { - for (const part of context.partById.values()) { - if (part.messageID !== event.properties.info.id) { - continue; - } - yield* emitAssistantTextDelta(context, part, turnId, event); - } - } - break; - } - - case "message.removed": { - context.messageRoleById.delete(event.properties.messageID); - break; - } - - case "message.part.delta": { - const existingPart = context.partById.get(event.properties.partID); - if (!existingPart) { - break; - } - const role = messageRoleForPart(context, existingPart); - if (role !== "assistant") { - break; - } - const streamKind = resolveTextStreamKind(existingPart); - const delta = event.properties.delta; - if (delta.length === 0) { - break; - } - const previousText = - context.emittedTextByPartId.get(event.properties.partID) ?? - textFromPart(existingPart) ?? - ""; - const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta); - if (deltaToEmit.length === 0) { - break; - } - context.emittedTextByPartId.set(event.properties.partID, nextText); - if (existingPart.type === "text" || existingPart.type === "reasoning") { - context.partById.set(event.properties.partID, { - ...existingPart, - text: nextText, - }); - } - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: event.properties.partID, - raw: event, - })), - type: "content.delta", - payload: { - streamKind, - delta: deltaToEmit, - }, - }); - break; - } - - case "message.part.updated": { - const part = event.properties.part; - context.partById.set(part.id, part); - const messageRole = messageRoleForPart(context, part); - - if (messageRole === "assistant") { - yield* emitAssistantTextDelta(context, part, turnId, event); - } - - if (part.type === "tool") { - const itemType = toToolLifecycleItemType(part.tool); - const title = - part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool; - const detail = detailFromToolPart(part); - const payload = { - itemType, - ...(part.state.status === "error" - ? { status: "failed" as const } - : part.state.status === "completed" - ? { status: "completed" as const } - : { status: "inProgress" as const }), - ...(title ? { title } : {}), - ...(detail ? { detail } : {}), - data: { - tool: part.tool, - state: part.state, - }, - }; - const runtimeEvent: ProviderRuntimeEvent = { - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: part.callID, - createdAt: toolStateCreatedAt(part), - raw: event, - })), - type: - part.state.status === "pending" - ? "item.started" - : part.state.status === "completed" || part.state.status === "error" - ? "item.completed" - : "item.updated", - payload, - }; - appendTurnItem(context, turnId, part); - yield* emit(runtimeEvent); - } - break; - } - - case "permission.asked": { - context.pendingPermissions.set(event.properties.id, event.properties); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.id, - raw: event, - })), - type: "request.opened", - payload: { - requestType: mapPermissionToRequestType(event.properties.permission), - detail: - event.properties.patterns.length > 0 - ? event.properties.patterns.join("\n") - : event.properties.permission, - args: event.properties.metadata, - }, - }); - break; - } - - case "permission.replied": { - context.pendingPermissions.delete(event.properties.requestID); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - })), - type: "request.resolved", - payload: { - requestType: "unknown", - decision: mapPermissionDecision(event.properties.reply), - }, - }); - break; - } - - case "question.asked": { - context.pendingQuestions.set(event.properties.id, event.properties); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.id, - raw: event, - })), - type: "user-input.requested", - payload: { - questions: normalizeQuestionRequest(event.properties), - }, - }); - break; - } - - case "question.replied": { - const request = context.pendingQuestions.get(event.properties.requestID); - context.pendingQuestions.delete(event.properties.requestID); - const answers = Object.fromEntries( - (request?.questions ?? []).map((question, index) => [ - openCodeQuestionId(index, question), - event.properties.answers[index]?.join(", ") ?? "", - ]), - ); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - })), - type: "user-input.resolved", - payload: { answers }, - }); - break; - } - - case "question.rejected": { - context.pendingQuestions.delete(event.properties.requestID); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - })), - type: "user-input.resolved", - payload: { answers: {} }, - }); - break; - } - - case "session.status": { - if (event.properties.status.type === "busy") { - yield* updateProviderSession(context, { - status: "running", - activeTurnId: turnId, - }); - } - - if (event.properties.status.type === "retry") { - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - raw: event, - })), - type: "runtime.warning", - payload: { - message: event.properties.status.message, - detail: event.properties.status, - }, - }); - break; - } - - if (event.properties.status.type === "idle" && turnId) { - context.activeTurnId = undefined; - yield* updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true }); - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId, - raw: event, - })), - type: "turn.completed", - payload: { - state: "completed", - }, - }); - } - break; - } - - case "session.error": { - const message = sessionErrorMessage(event.properties.error); - const activeTurnId = context.activeTurnId; - context.activeTurnId = undefined; - yield* updateProviderSession( - context, - { - status: "error", - lastError: message, - }, - { clearActiveTurnId: true }, - ); - if (activeTurnId) { - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - turnId: activeTurnId, - raw: event, - })), - type: "turn.completed", - payload: { - state: "failed", - errorMessage: message, - }, - }); - } - yield* emit({ - ...(yield* buildEventBase({ - threadId: context.session.threadId, - raw: event, - })), - type: "runtime.error", - payload: { - message, - class: "provider_error", - detail: event.properties.error, - }, - }); - break; - } - - default: - break; - } - }); - - const startEventPump = Effect.fn("startEventPump")(function* (context: OpenCodeSessionContext) { - // One AbortController per session scope. The finalizer fires when - // the scope closes (explicit stop, unexpected exit, or layer - // shutdown) and cancels the in-flight `event.subscribe` fetch so - // the async iterable unwinds cleanly. - const eventsAbortController = new AbortController(); - yield* Scope.addFinalizer( - context.sessionScope, - Effect.sync(() => eventsAbortController.abort()), - ); - - // Fibers forked into `context.sessionScope` are interrupted - // automatically when the scope closes — no bookkeeping required. - yield* Effect.flatMap( - runOpenCodeSdk("event.subscribe", () => - context.client.event.subscribe(undefined, { - signal: eventsAbortController.signal, - }), - ), - (subscription) => - Stream.fromAsyncIterable( - subscription.stream, - (cause) => - new OpenCodeRuntimeError({ - operation: "event.subscribe", - detail: openCodeRuntimeErrorDetail(cause), - cause, - }), - ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))), - ).pipe( - Effect.exit, - Effect.flatMap((exit) => - Effect.gen(function* () { - // Expected paths: caller aborted the fetch or the session - // has already been marked stopped. Treat as a clean exit. - if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) { - return; - } - if (Exit.isFailure(exit)) { - yield* emitUnexpectedExit( - context, - openCodeRuntimeErrorDetail(Cause.squash(exit.cause)), - ); - } - }), - ), - Effect.forkIn(context.sessionScope), - ); - - if (!context.server.external && context.server.exitCode !== null) { - yield* context.server.exitCode.pipe( - Effect.flatMap((code) => - Effect.gen(function* () { - if (yield* Ref.get(context.stopped)) { - return; - } - yield* emitUnexpectedExit(context, `OpenCode server exited unexpectedly (${code}).`); - }), - ), - Effect.forkIn(context.sessionScope), - ); - } - }); - - const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")( - function* (input) { - const binaryPath = openCodeSettings.binaryPath; - const serverUrl = openCodeSettings.serverUrl; - const serverPassword = openCodeSettings.serverPassword; - const directory = input.cwd ?? serverConfig.cwd; - const resumeSessionId = parseOpenCodeResume(input.resumeCursor)?.sessionId; - const existing = sessions.get(input.threadId); - if (existing) { - yield* stopOpenCodeContext(existing); - sessions.delete(input.threadId); - } - - const started = yield* Effect.gen(function* () { - const sessionScope = yield* Scope.make(); - const startedExit = yield* Effect.exit( - Effect.gen(function* () { - // The runtime binds the server's lifetime to the Scope.Scope - // we provide below — closing `sessionScope` kills the child - // process automatically. No manual `server.close()` needed. - const server = yield* openCodeRuntime.connectToOpenCodeServer({ - binaryPath, - serverUrl, - ...(options?.environment ? { environment: options.environment } : {}), - }); - const client = openCodeRuntime.createOpenCodeSdkClient({ - baseUrl: server.url, - directory, - ...(server.external && serverPassword ? { serverPassword } : {}), - }); - const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId); - if (mcpSession && !server.external) { - yield* runOpenCodeSdk("mcp.add", () => - client.mcp.add({ - name: "t3-code", - config: { - type: "remote", - url: mcpSession.endpoint, - headers: { - Authorization: mcpSession.authorizationHeader, - }, - oauth: false, - }, - }), - ); - } - // Resume: re-adopt the session named by the durable cursor — - // OpenCode scopes history by session id. The probe recovers only - // a confirmed not-found (start fresh); transport/auth/server - // errors propagate instead of masking as a new empty session. - const resolved = yield* Effect.gen(function* () { - const adopted = resumeSessionId - ? yield* runOpenCodeSdk("session.get", () => - client.session.get({ sessionID: resumeSessionId }), - ).pipe( - Effect.map((response) => response.data), - Effect.catchIf( - (cause) => isOpenCodeNotFound(cause), - () => Effect.void, - ), - ) - : undefined; - - // Reuse in place only when the session still matches the - // requested cwd; on a cwd change it is forked below instead. - const reusable = - adopted && - (!adopted.directory || (yield* sameDirectory(adopted.directory, directory))) - ? adopted - : undefined; - - if (reusable) { - // Resume skips `session.create`, so re-assert the ruleset — - // a runtime-mode change would otherwise leave the session on - // its original permissions. - yield* runOpenCodeSdk("session.update", () => - client.session.update({ - sessionID: reusable.id, - permission: buildOpenCodePermissionRules(input.runtimeMode), - }), - ); - return { openCodeSession: reusable, created: false }; - } - - // The session lives under a different cwd (e.g. the thread - // moved into a git worktree). Fork it into the requested - // directory instead of minting an empty one — the fork carries - // the full history, so the follow-up keeps its context (#3604). - if (adopted) { - yield* Effect.logInfo( - `OpenCode session '${adopted.id}' was created under a different working directory; forking into '${directory}' to preserve conversation history.`, - ); - const forkedSession = yield* runOpenCodeSdk("session.fork", () => - client.session.fork({ sessionID: adopted.id, directory }), - ); - const forked = forkedSession.data; - if (!forked) { - return yield* new OpenCodeRuntimeError({ - operation: "session.fork", - detail: "OpenCode session.fork returned no session payload.", - }); - } - yield* runOpenCodeSdk("session.update", () => - client.session.update({ - sessionID: forked.id, - permission: buildOpenCodePermissionRules(input.runtimeMode), - }), - ); - return { openCodeSession: forked, created: true }; - } - - if (resumeSessionId) { - yield* Effect.logWarning( - `OpenCode session '${resumeSessionId}' no longer exists; starting a fresh session.`, - ); - } - const createdSession = yield* runOpenCodeSdk("session.create", () => - client.session.create({ - permission: buildOpenCodePermissionRules(input.runtimeMode), - }), - ); - if (!createdSession.data) { - return yield* new OpenCodeRuntimeError({ - operation: "session.create", - detail: "OpenCode session.create returned no session payload.", - }); - } - return { openCodeSession: createdSession.data, created: true }; - }); - - return { - sessionScope, - server, - client, - openCodeSession: resolved.openCodeSession, - created: resolved.created, - }; - }).pipe(Effect.provideService(Scope.Scope, sessionScope)), - ); - if (Exit.isFailure(startedExit)) { - yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore); - return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause)); - } - return startedExit.value; - }); - - // Guard against a concurrent startSession call that may have raced - // and already inserted a session while we were awaiting async work. - const raceWinner = sessions.get(input.threadId); - if (raceWinner) { - // Another call won the race — clean up. Only abort the remote - // session if we created it here; a resumed one is shared upstream - // state the winner is now using. - if (started.created) { - yield* runOpenCodeSdk("session.abort", () => - started.client.session.abort({ - sessionID: started.openCodeSession.id, - }), - ).pipe(Effect.ignore); - } - yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore); - return raceWinner.session; - } - - const createdAt = yield* nowIso; - const session: ProviderSession = { - provider: PROVIDER, - providerInstanceId: boundInstanceId, - status: "ready", - runtimeMode: input.runtimeMode, - cwd: directory, - ...(input.modelSelection ? { model: input.modelSelection.model } : {}), - threadId: input.threadId, - // ProviderService persists this cursor and feeds it back into - // `startSession` after the in-memory session is lost (reaper / - // restart), so follow-ups continue the same conversation (#3604). - resumeCursor: { - schemaVersion: OPENCODE_RESUME_VERSION, - sessionId: started.openCodeSession.id, - }, - createdAt, - updatedAt: createdAt, - }; - - const context: OpenCodeSessionContext = { - session, - client: started.client, - server: started.server, - directory, - openCodeSessionId: started.openCodeSession.id, - pendingPermissions: new Map(), - pendingQuestions: new Map(), - partById: new Map(), - emittedTextByPartId: new Map(), - messageRoleById: new Map(), - completedAssistantPartIds: new Set(), - turns: [], - activeTurnId: undefined, - activeAgent: undefined, - activeVariant: undefined, - stopped: yield* Ref.make(false), - sessionScope: started.sessionScope, - }; - sessions.set(input.threadId, context); - yield* startEventPump(context); - - yield* emit({ - ...(yield* buildEventBase({ threadId: input.threadId })), - type: "session.started", - payload: { - message: "OpenCode session started", - }, - }); - yield* emit({ - ...(yield* buildEventBase({ threadId: input.threadId })), - type: "thread.started", - payload: { - providerThreadId: started.openCodeSession.id, - }, - }); - - return session; - }, - ); - - const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { - const context = yield* ensureSessionContext(sessions, input.threadId); - // A sendTurn while a turn is active is a steer: OpenCode queues the - // prompt into the busy session and the work continues as one turn, so - // the active turn id is reused instead of opening a new turn. - const steeringTurnId = context.activeTurnId; - const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`); - const modelSelection = - input.modelSelection ?? - (context.session.model - ? { instanceId: boundInstanceId, model: context.session.model } - : undefined); - if (modelSelection !== undefined && modelSelection.instanceId !== boundInstanceId) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`, - }); - } - const parsedModel = parseOpenCodeModelSlug(modelSelection?.model); - if (!parsedModel) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "OpenCode model selection must use the 'provider/model' format.", - }); - } - - const text = input.input?.trim(); - const fileParts = toOpenCodeFileParts({ - attachments: input.attachments, - resolveAttachmentPath: (attachment) => - resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }), - }); - if ((!text || text.length === 0) && fileParts.length === 0) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "OpenCode turns require text input or at least one attachment.", - }); - } - - const agent = getModelSelectionStringOptionValue(modelSelection, "agent"); - const variant = getModelSelectionStringOptionValue(modelSelection, "variant"); - - context.activeTurnId = turnId; - context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined); - context.activeVariant = variant; - yield* updateProviderSession( - context, - { - status: "running", - activeTurnId: turnId, - model: modelSelection?.model ?? context.session.model, - }, - { clearLastError: true }, - ); - - if (steeringTurnId === undefined) { - yield* emit({ - ...(yield* buildEventBase({ threadId: input.threadId, turnId })), - type: "turn.started", - payload: { - model: modelSelection?.model ?? context.session.model, - ...(variant ? { effort: variant } : {}), - }, - }); - } - - yield* runOpenCodeSdk("session.promptAsync", () => - context.client.session.promptAsync({ - sessionID: context.openCodeSessionId, - model: parsedModel, - ...(context.activeAgent ? { agent: context.activeAgent } : {}), - ...(context.activeVariant ? { variant: context.activeVariant } : {}), - parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts], - }), - ).pipe( - Effect.mapError(toRequestError), - // On failure of a fresh turn: clear active-turn state, flip the - // session back to ready with lastError set, emit turn.aborted, then - // let the typed error propagate. We don't need to rebuild the error - // here — `toRequestError` already produced the right shape. A failed - // steer leaves the still-running original turn untouched. - Effect.tapError((requestError) => - steeringTurnId !== undefined - ? Effect.void - : Effect.gen(function* () { - context.activeTurnId = undefined; - context.activeAgent = undefined; - context.activeVariant = undefined; - yield* updateProviderSession( - context, - { - status: "ready", - model: modelSelection?.model ?? context.session.model, - lastError: requestError.detail, - }, - { clearActiveTurnId: true }, - ); - yield* emit({ - ...(yield* buildEventBase({ - threadId: input.threadId, - turnId, - })), - type: "turn.aborted", - payload: { - reason: requestError.detail, - }, - }); - }), - ), - ); - - return { - threadId: input.threadId, - turnId, - // Re-surface the durable cursor on every turn so the persisted binding - // is refreshed alongside last-seen/runtime state (mirrors Grok/Codex). - ...(context.session.resumeCursor !== undefined - ? { resumeCursor: context.session.resumeCursor } - : {}), - }; - }); - - const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")( - function* (threadId, turnId) { - const context = yield* ensureSessionContext(sessions, threadId); - yield* runOpenCodeSdk("session.abort", () => - context.client.session.abort({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.mapError(toRequestError)); - if (turnId ?? context.activeTurnId) { - yield* emit({ - ...(yield* buildEventBase({ - threadId, - turnId: turnId ?? context.activeTurnId, - })), - type: "turn.aborted", - payload: { - reason: "Interrupted by user.", - }, - }); - } - }, - ); - - const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn( - "respondToRequest", - )(function* (threadId, requestId, decision) { - const context = yield* ensureSessionContext(sessions, threadId); - if (!context.pendingPermissions.has(requestId)) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "permission.reply", - detail: `Unknown pending permission request: ${requestId}`, - }); - } - - yield* runOpenCodeSdk("permission.reply", () => - context.client.permission.reply({ - requestID: requestId, - reply: toOpenCodePermissionReply(decision), - }), - ).pipe(Effect.mapError(toRequestError)); - }); - - const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn( - "respondToUserInput", - )(function* (threadId, requestId, answers) { - const context = yield* ensureSessionContext(sessions, threadId); - const request = context.pendingQuestions.get(requestId); - if (!request) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "question.reply", - detail: `Unknown pending user-input request: ${requestId}`, - }); - } - - yield* runOpenCodeSdk("question.reply", () => - context.client.question.reply({ - requestID: requestId, - answers: toOpenCodeQuestionAnswers(request, answers), - }), - ).pipe(Effect.mapError(toRequestError)); - }); - - const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")( - function* (threadId) { - const context = sessions.get(threadId); - if (!context) { - return yield* new ProviderAdapterSessionNotFoundError({ - provider: PROVIDER, - threadId, - }); - } - const stopped = yield* stopOpenCodeContext(context); - sessions.delete(threadId); - if (!stopped) { - return; - } - yield* emit({ - ...(yield* buildEventBase({ threadId })), - type: "session.exited", - payload: { - reason: "Session stopped.", - recoverable: false, - exitKind: "graceful", - }, - }); - }, - ); - - const listSessions: OpenCodeAdapterShape["listSessions"] = () => - Effect.sync(() => [...sessions.values()].map((context) => context.session)); - - const hasSession: OpenCodeAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => sessions.has(threadId)); - - const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")( - function* (threadId) { - const context = yield* ensureSessionContext(sessions, threadId); - const messages = yield* runOpenCodeSdk("session.messages", () => - context.client.session.messages({ - sessionID: context.openCodeSessionId, - }), - ).pipe(Effect.mapError(toRequestError)); - - const turns: Array = []; - for (const entry of messages.data ?? []) { - if (entry.info.role === "assistant") { - turns.push({ - id: TurnId.make(entry.info.id), - items: [entry.info, ...entry.parts], - }); - } - } - - return { - threadId, - turns, - }; - }, - ); - - const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")( - function* (threadId, numTurns) { - const context = yield* ensureSessionContext(sessions, threadId); - const messages = yield* runOpenCodeSdk("session.messages", () => - context.client.session.messages({ - sessionID: context.openCodeSessionId, - }), - ).pipe(Effect.mapError(toRequestError)); - - const assistantMessages = (messages.data ?? []).filter( - (entry) => entry.info.role === "assistant", - ); - const targetIndex = assistantMessages.length - numTurns - 1; - const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null; - yield* runOpenCodeSdk("session.revert", () => - context.client.session.revert({ - sessionID: context.openCodeSessionId, - ...(target ? { messageID: target.info.id } : {}), - }), - ).pipe(Effect.mapError(toRequestError)); - - return yield* readThread(threadId); - }, - ); - - const stopAll: OpenCodeAdapterShape["stopAll"] = () => - Effect.gen(function* () { - const contexts = [...sessions.values()]; - sessions.clear(); - // `stopOpenCodeContext` is typed as never-failing — SDK aborts are - // already `Effect.ignore`'d inside it. `ignoreCause` here also - // swallows defects from throwing finalizers so one bad close can't - // interrupt the sibling fibers. Same pattern as the layer finalizer. - yield* Effect.forEach( - contexts, - (context) => Effect.ignoreCause(stopOpenCodeContext(context)), - { concurrency: "unbounded", discard: true }, - ); - }); - - return { - provider: PROVIDER, - capabilities: { - sessionModelSwitch: "in-session", - }, - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - readThread, - rollbackThread, - stopAll, - get streamEvents() { - return Stream.fromQueue(runtimeEvents); - }, - } satisfies OpenCodeAdapterShape; - }); -} diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts deleted file mode 100644 index e36ed52d4a..0000000000 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { - defaultInstanceIdForDriver, - ProviderDriverKind, - type ServerProvider, -} from "@t3tools/contracts"; -import { it, assert, vi } from "@effect/vitest"; - -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as PubSub from "effect/PubSub"; -import * as Stream from "effect/Stream"; - -import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; -import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; -import { CodexAdapter } from "../Services/CodexAdapter.ts"; -import type { CodexAdapterShape } from "../Services/CodexAdapter.ts"; -import { CursorAdapter } from "../Services/CursorAdapter.ts"; -import type { CursorAdapterShape } from "../Services/CursorAdapter.ts"; -import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; -import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; -import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; -import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts"; -import { ProviderUnsupportedError } from "../Errors.ts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; - -const CODEX_DRIVER = ProviderDriverKind.make("codex"); -const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); -const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); -const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); - -const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = { - provider: CODEX_DRIVER, - capabilities: { sessionModelSwitch: "in-session" }, - startSession: vi.fn(), - sendTurn: vi.fn(), - interruptTurn: vi.fn(), - respondToRequest: vi.fn(), - respondToUserInput: vi.fn(), - stopSession: vi.fn(), - listSessions: vi.fn(), - hasSession: vi.fn(), - readThread: vi.fn(), - rollbackThread: vi.fn(), - stopAll: vi.fn(), - streamEvents: Stream.empty, -}; - -const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = { - provider: CLAUDE_AGENT_DRIVER, - capabilities: { sessionModelSwitch: "in-session" }, - startSession: vi.fn(), - sendTurn: vi.fn(), - interruptTurn: vi.fn(), - respondToRequest: vi.fn(), - respondToUserInput: vi.fn(), - stopSession: vi.fn(), - listSessions: vi.fn(), - hasSession: vi.fn(), - readThread: vi.fn(), - rollbackThread: vi.fn(), - stopAll: vi.fn(), - streamEvents: Stream.empty, -}; - -const fakeOpenCodeAdapter: OpenCodeAdapterShape = { - provider: "opencode", - capabilities: { sessionModelSwitch: "in-session" }, - startSession: vi.fn(), - sendTurn: vi.fn(), - interruptTurn: vi.fn(), - respondToRequest: vi.fn(), - respondToUserInput: vi.fn(), - stopSession: vi.fn(), - listSessions: vi.fn(), - hasSession: vi.fn(), - readThread: vi.fn(), - rollbackThread: vi.fn(), - stopAll: vi.fn(), - streamEvents: Stream.empty, -}; - -const fakeCursorAdapter: CursorAdapterShape = { - provider: "cursor", - capabilities: { sessionModelSwitch: "in-session" }, - startSession: vi.fn(), - sendTurn: vi.fn(), - interruptTurn: vi.fn(), - respondToRequest: vi.fn(), - respondToUserInput: vi.fn(), - stopSession: vi.fn(), - listSessions: vi.fn(), - hasSession: vi.fn(), - readThread: vi.fn(), - rollbackThread: vi.fn(), - stopAll: vi.fn(), - streamEvents: Stream.empty, -}; - -// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry — -// it walks `listInstances` once at boot and surfaces the default-instance -// adapter keyed by its driver kind. To test the facade we supply four fake -// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so -// they pass the default-instance filter. -const makeFakeInstance = ( - driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode", - adapter: ProviderInstance["adapter"], -): ProviderInstance => { - const driverKind = ProviderDriverKind.make(driverKindString); - return { - instanceId: defaultInstanceIdForDriver(driverKind), - driverKind, - continuationIdentity: { - driverKind, - continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`, - }, - displayName: undefined, - enabled: true, - snapshot: { - maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ - provider: driverKind, - packageName: null, - }), - getSnapshot: Effect.succeed({} as unknown as ServerProvider), - refresh: Effect.succeed({} as unknown as ServerProvider), - streamChanges: Stream.empty, - }, - adapter, - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration: {} as unknown as TextGenerationShape, - }; -}; - -const fakeInstances: ReadonlyArray = [ - makeFakeInstance("codex", fakeCodexAdapter), - makeFakeInstance("claudeAgent", fakeClaudeAdapter), - makeFakeInstance("opencode", fakeOpenCodeAdapter), - makeFakeInstance("cursor", fakeCursorAdapter), -]; - -const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { - getInstance: (instanceId) => - Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)), - listInstances: Effect.succeed(fakeInstances), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.empty, - // Tests never drive changes through this fake; acquire a throwaway - // subscription on an unused PubSub so the shape is satisfied. - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => PubSub.subscribe(pubsub)), -}); - -const layer = Layer.mergeAll( - Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer), - NodeServices.layer, -); - -it.layer(layer)("ProviderAdapterRegistryLive", (it) => { - it("resolves adapters and routing metadata from provider instances", () => - Effect.gen(function* () { - const registry = yield* ProviderAdapterRegistry; - const codex = yield* registry.getByProvider("codex"); - const claude = yield* registry.getByProvider("claudeAgent"); - const openCode = yield* registry.getByProvider("opencode"); - const cursor = yield* registry.getByProvider("cursor"); - assert.equal(codex, fakeCodexAdapter); - assert.equal(claude, fakeClaudeAdapter); - assert.equal(openCode, fakeOpenCodeAdapter); - assert.equal(cursor, fakeCursorAdapter); - - const providers = yield* registry.listProviders(); - assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]); - }), - ); - - it.effect("fails with ProviderUnsupportedError for unknown providers", () => - Effect.gen(function* () { - const registry = yield* ProviderAdapterRegistry; - const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result); - assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" })); - }), - ); -}); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts deleted file mode 100644 index 3394af5d2b..0000000000 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`. - * - * `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one - * adapter via the four `AdapterLive` singleton Layers. The per-instance - * refactor moved adapter construction inside each `ProviderDriver.create()`: - * adapters are now bundled on the `ProviderInstance` that the - * `ProviderInstanceRegistry` owns. - * - * This facade fulfills the `ProviderAdapterRegistryShape` contract by doing - * dynamic look-ups against `ProviderInstanceRegistry` on every call. That - * means settings-driven hot-reload shows up here automatically — adding a - * new instance via settings makes `getByInstance` resolve immediately - * without rebuilding the facade. - * - * @module ProviderAdapterRegistryLive - */ -import { - defaultInstanceIdForDriver, - ProviderInstanceId, - type ProviderDriverKind, -} from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { ProviderUnsupportedError } from "../Errors.ts"; -import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; -import { - ProviderAdapterRegistry, - type ProviderAdapterRegistryShape, -} from "../Services/ProviderAdapterRegistry.ts"; -import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; -import { CodexAdapter } from "../Services/CodexAdapter.ts"; -import { CursorAdapter } from "../Services/CursorAdapter.ts"; -import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; - -const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () { - const registry = yield* ProviderInstanceRegistry; - -const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* ( - options?: ProviderAdapterRegistryLiveOptions, -) { - const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter); - const adapters = - options?.adapters !== undefined - ? options.adapters - : [ - yield* CodexAdapter, - yield* ClaudeAdapter, - yield* OpenCodeAdapter, - ...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []), - ]; - const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); - - const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) => - registry.getInstance(instanceId).pipe( - Effect.flatMap((instance) => - instance === undefined - ? Effect.fail( - new ProviderUnsupportedError({ - provider: instanceId, - }), - ) - : Effect.succeed({ - instanceId: instance.instanceId, - driverKind: instance.driverKind, - displayName: instance.displayName, - accentColor: instance.accentColor, - enabled: instance.enabled, - continuationIdentity: instance.continuationIdentity, - }), - ), - ); - - const listInstances: ProviderAdapterRegistryShape["listInstances"] = () => - registry.listInstances.pipe( - Effect.map((instances) => instances.map((instance) => instance.instanceId)), - ); - - const listProviders: ProviderAdapterRegistryShape["listProviders"] = () => - registry.listInstances.pipe( - Effect.map((instances) => { - const kinds = new Set(); - for (const instance of instances) { - const defaultId = defaultInstanceIdForDriver(instance.driverKind); - if (instance.instanceId === defaultId) { - // Only the default-instance rows show up through the legacy - // shim — custom instances like `codex_personal` have no - // `ProviderDriverKind` equivalent. - kinds.add(instance.driverKind); - } - } - return Array.from(kinds); - }), - ); - - return { - getByInstance, - getInstanceInfo, - listInstances, - listProviders, - // Proxy directly — the facade has no state of its own; the instance - // registry already coalesces adds/removes/rebuilds into one emission. - streamChanges: registry.streamChanges, - subscribeChanges: registry.subscribeChanges, - } satisfies ProviderAdapterRegistryShape; -}); - -export const ProviderAdapterRegistryLive = Layer.effect( - ProviderAdapterRegistry, - makeProviderAdapterRegistry(), -); - -// Exposed for tests that want to build a facade over a pre-assembled -// `ProviderInstanceRegistry` without pulling in the whole boot graph. -export { makeProviderAdapterRegistry }; - -// Re-export for consumers that need the accessor shape. The service tag -// itself lives in `Services/ProviderAdapterRegistry.ts`. -export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; -// Re-export for consumers (including tests) that construct a -// `ProviderInstanceId` before calling `getByInstance`. -export { ProviderInstanceId }; diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts index f0b8fd46dc..4cb9856581 100644 --- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts @@ -203,7 +203,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => { const work = yield* registry.getInstance(workId); expect(personal).toBeDefined(); expect(work).toBeDefined(); - expect(personal!.adapter).not.toBe(work!.adapter); + expect(personal!.orchestrationAdapter).not.toBe(work!.orchestrationAdapter); expect(personal!.textGeneration).not.toBe(work!.textGeneration); expect(personal!.snapshot).not.toBe(work!.snapshot); @@ -384,16 +384,16 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => { expect(openCode?.displayName).toBe("OpenCode"); // Every instance owns its own set of closures — no sharing across - // drivers. `adapter` / `textGeneration` / `snapshot` are all + // drivers. `orchestrationAdapter` / `textGeneration` / `snapshot` are all // distinct references even when two instances happen to share a // trait (e.g. Cursor + others all use a stub-or-real // `textGeneration`; they must still be different object values). const adapters = [ - codex!.adapter, - claude!.adapter, - cursor!.adapter, - grok!.adapter, - openCode!.adapter, + codex!.orchestrationAdapter, + claude!.orchestrationAdapter, + cursor!.orchestrationAdapter, + grok!.orchestrationAdapter, + openCode!.orchestrationAdapter, ]; expect(new Set(adapters).size).toBe(adapters.length); const textGenerations = [ diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 6d1196446e..101475558d 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -658,7 +658,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), streamChanges: Stream.empty, }, - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; @@ -701,7 +700,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( refresh: Effect.succeed(refreshedProvider), streamChanges: Stream.fromPubSub(changes), }, - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; @@ -800,7 +798,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( refresh: Effect.die(new Error("simulated refresh failure")), streamChanges: Stream.empty, }, - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; @@ -890,7 +887,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( refresh: Effect.succeed(provider), streamChanges: Stream.empty, }, - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], }); diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts deleted file mode 100644 index ccbbce1759..0000000000 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ /dev/null @@ -1,1894 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - -import type { - ProviderApprovalDecision, - ProviderRuntimeEvent, - ProviderSendTurnInput, - ProviderSession, - ProviderTurnStartResult, -} from "@t3tools/contracts"; -import { - ApprovalRequestId, - EventId, - ProviderDriverKind, - ProviderInstanceId, - ProviderSessionStartInput, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; -import { it, assert, vi } from "@effect/vitest"; - -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Metric from "effect/Metric"; -import * as Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -import { - ProviderAdapterRequestError, - ProviderAdapterSessionNotFoundError, - ProviderUnsupportedError, - ProviderValidationError, - type ProviderAdapterError, -} from "../Errors.ts"; -import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; -import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts"; -import * as ProviderService from "../Services/ProviderService.ts"; -import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts"; -import { makeProviderServiceLive } from "./ProviderService.ts"; -import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; -import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts"; -import { - makeSqlitePersistenceLive, - SqlitePersistenceMemory, -} from "../../persistence/Layers/Sqlite.ts"; -import * as ServerSettings from "../../serverSettings.ts"; -import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; -import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts"; - -const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest(); - -const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asThreadId = (value: string): ThreadId => ThreadId.make(value); -const asTurnId = (value: string): TurnId => TurnId.make(value); -const codexInstanceId = ProviderInstanceId.make("codex"); -const claudeAgentInstanceId = ProviderInstanceId.make("claudeAgent"); -const CODEX_DRIVER = ProviderDriverKind.make("codex"); -const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); -const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); - -type LegacyProviderRuntimeEvent = { - readonly type: string; - readonly eventId: EventId; - readonly provider: ProviderDriverKind; - readonly createdAt: string; - readonly threadId: ThreadId; - readonly turnId?: string | undefined; - readonly itemId?: string | undefined; - readonly requestId?: string | undefined; - readonly payload?: unknown | undefined; - readonly [key: string]: unknown; -}; - -function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) { - const sessions = new Map(); - const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); - - const startSession = vi.fn((input: ProviderSessionStartInput) => - Effect.sync(() => { - const now = "2026-01-01T00:00:00.000Z"; - const session: ProviderSession = { - provider, - ...(input.providerInstanceId !== undefined - ? { providerInstanceId: input.providerInstanceId } - : {}), - status: "ready", - runtimeMode: input.runtimeMode, - threadId: input.threadId, - resumeCursor: input.resumeCursor ?? { - opaque: `resume-${String(input.threadId)}`, - }, - cwd: input.cwd ?? process.cwd(), - createdAt: now, - updatedAt: now, - }; - sessions.set(session.threadId, session); - return session; - }), - ); - - const sendTurn = vi.fn( - ( - input: ProviderSendTurnInput, - ): Effect.Effect => { - if (!sessions.has(input.threadId)) { - return Effect.fail( - new ProviderAdapterSessionNotFoundError({ - provider, - threadId: input.threadId, - }), - ); - } - - return Effect.succeed({ - threadId: input.threadId, - turnId: TurnId.make(`turn-${String(input.threadId)}`), - }); - }, - ); - - const interruptTurn = vi.fn( - (_threadId: ThreadId, _turnId?: TurnId): Effect.Effect => - Effect.void, - ); - - const respondToRequest = vi.fn( - ( - _threadId: ThreadId, - _requestId: string, - _decision: ProviderApprovalDecision, - ): Effect.Effect => Effect.void, - ); - - const respondToUserInput = vi.fn( - ( - _threadId: ThreadId, - _requestId: string, - _answers: Record, - ): Effect.Effect => Effect.void, - ); - - const stopSession = vi.fn( - (threadId: ThreadId): Effect.Effect => - Effect.sync(() => { - sessions.delete(threadId); - }), - ); - - const listSessions = vi.fn( - (): Effect.Effect> => - Effect.sync(() => Array.from(sessions.values())), - ); - - const hasSession = vi.fn( - (threadId: ThreadId): Effect.Effect => Effect.succeed(sessions.has(threadId)), - ); - - const readThread = vi.fn( - ( - threadId: ThreadId, - ): Effect.Effect< - { - threadId: ThreadId; - turns: ReadonlyArray<{ id: TurnId; items: readonly [] }>; - }, - ProviderAdapterError - > => - Effect.succeed({ - threadId, - turns: [{ id: asTurnId("turn-1"), items: [] }], - }), - ); - - const rollbackThread = vi.fn( - ( - threadId: ThreadId, - _numTurns: number, - ): Effect.Effect<{ threadId: ThreadId; turns: readonly [] }, ProviderAdapterError> => - Effect.succeed({ threadId, turns: [] }), - ); - - const stopAll = vi.fn( - (): Effect.Effect => - Effect.sync(() => { - sessions.clear(); - }), - ); - - const adapter: ProviderAdapterShape = { - provider, - capabilities: { - sessionModelSwitch: "in-session", - }, - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - readThread, - rollbackThread, - stopAll, - get streamEvents() { - return Stream.fromPubSub(runtimeEventPubSub); - }, - }; - - const emit = (event: LegacyProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent)); - }; - - const updateSession = ( - threadId: ThreadId, - update: (session: ProviderSession) => ProviderSession, - ): void => { - const existing = sessions.get(threadId); - if (!existing) { - return; - } - sessions.set(threadId, update(existing)); - }; - - return { - adapter, - emit, - updateSession, - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - readThread, - rollbackThread, - stopAll, - }; -} - -const advanceTestClock = (ms: number) => - TestClock.adjust(`${ms} millis`).pipe(Effect.andThen(Effect.yieldNow)); - -const hasMetricSnapshot = ( - snapshots: ReadonlyArray, - id: string, - attributes: Readonly>, -) => - snapshots.some( - (snapshot) => - snapshot.id === id && - Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), - ); - -function makeProviderServiceLayer() { - const codex = makeFakeCodexAdapter(); - const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const cursor = makeFakeCodexAdapter(CURSOR_DRIVER); - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: codex.adapter, - [ProviderDriverKind.make("claudeAgent")]: claude.adapter, - [ProviderDriverKind.make("cursor")]: cursor.adapter, - }); - - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - - const layer = it.layer( - Layer.mergeAll( - makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provideMerge(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ), - directoryLayer, - - runtimeRepositoryLayer, - NodeServices.layer, - ), - ); - - return { - codex, - claude, - cursor, - layer, - }; -} - -it.effect("ProviderServiceLive catches stopAll failures during shutdown", () => - Effect.gen(function* () { - const codex = makeFakeCodexAdapter(); - codex.stopAll.mockImplementation(() => - Effect.fail( - new ProviderAdapterRequestError({ - provider: String(CODEX_DRIVER), - method: "stopAll", - detail: "simulated stopAll failure", - }), - ), - ); - const registry = makeAdapterRegistryMock({ - [CODEX_DRIVER]: codex.adapter, - }); - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = Layer.mergeAll( - makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provideMerge(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ), - directoryLayer, - runtimeRepositoryLayer, - NodeServices.layer, - ); - const scope = yield* Scope.make(); - const runtimeServices = yield* Layer.build(providerLayer).pipe(Scope.provide(scope)); - - yield* ProviderService.ProviderService.pipe(Effect.provide(runtimeServices)); - const closeExit = yield* Scope.close(scope, Exit.void).pipe(Effect.exit); - - assert.equal(Exit.isSuccess(closeExit), true); - assert.equal(codex.stopAll.mock.calls.length, 1); - }), -); - -it.effect("ProviderServiceLive rejects new sessions for disabled providers", () => - Effect.gen(function* () { - const codex = makeFakeCodexAdapter(); - const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const registryBase = makeAdapterRegistryMock({ - [CODEX_DRIVER]: codex.adapter, - [CLAUDE_AGENT_DRIVER]: claude.adapter, - }); - const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = { - ...registryBase, - getInstanceInfo: (instanceId) => - instanceId === claudeAgentInstanceId - ? Effect.succeed({ - instanceId, - driverKind: CLAUDE_AGENT_DRIVER, - displayName: undefined, - enabled: false, - continuationIdentity: { - driverKind: CLAUDE_AGENT_DRIVER, - continuationKey: "claudeAgent:instance:claudeAgent", - }, - }) - : registryBase.getInstanceInfo(instanceId), - }; - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const failure = yield* Effect.flip( - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-disabled"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-disabled"), - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(providerLayer)), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider instance 'claudeAgent' is disabled"); - assert.equal(claude.startSession.mock.calls.length, 0); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect( - "ProviderServiceLive allows enabled custom instances when legacy driver is disabled", - () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex_personal"); - const driverKind = CODEX_DRIVER; - const codex = makeFakeCodexAdapter(); - const unsupported = () => - new ProviderUnsupportedError({ - provider: driverKind, - }); - const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = { - getByInstance: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed(codex.adapter) - : Effect.fail(unsupported()), - getInstanceInfo: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed({ - instanceId, - driverKind, - displayName: "Codex Personal", - enabled: true, - continuationIdentity: { - driverKind, - continuationKey: "codex:/Users/example/.codex", - }, - }) - : Effect.fail(unsupported()), - listInstances: () => Effect.succeed([instanceId]), - listProviders: () => Effect.succeed([driverKind] as const), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }; - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest({ - providers: { - codex: { - enabled: false, - }, - }, - }); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(serverSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const session = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-enabled-custom"), { - provider: driverKind, - providerInstanceId: instanceId, - threadId: asThreadId("thread-enabled-custom"), - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(providerLayer)); - - assert.equal(session.providerInstanceId, instanceId); - assert.equal(codex.startSession.mock.calls.length, 1); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect("ProviderServiceLive rejects new sessions for disabled custom instances", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex_personal"); - const driverKind = ProviderDriverKind.make("codex"); - const codex = makeFakeCodexAdapter(); - const unsupported = () => - new ProviderUnsupportedError({ - provider: ProviderDriverKind.make("codex"), - }); - const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = { - getByInstance: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed(codex.adapter) - : Effect.fail(unsupported()), - getInstanceInfo: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed({ - instanceId, - driverKind, - displayName: "Codex Personal", - enabled: false, - continuationIdentity: { - driverKind, - continuationKey: "codex:/Users/example/.codex", - }, - }) - : Effect.fail(unsupported()), - listInstances: () => Effect.succeed([instanceId]), - listProviders: () => Effect.succeed([CODEX_DRIVER] as const), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }; - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const failure = yield* Effect.flip( - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-disabled-instance"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: instanceId, - threadId: asThreadId("thread-disabled-instance"), - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(providerLayer)), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider instance 'codex_personal' is disabled"); - assert.equal(codex.startSession.mock.calls.length, 0); - }).pipe(Effect.provide(NodeServices.layer)), -); - -const routing = makeProviderServiceLayer(); - -it.effect("ProviderServiceLive writes canonical events to the emitting thread segment", () => - Effect.gen(function* () { - const codex = makeFakeCodexAdapter(); - const canonicalEvents: ProviderRuntimeEvent[] = []; - const canonicalThreadIds: Array = []; - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: codex.adapter, - }); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive({ - canonicalEventLogger: { - filePath: "memory://provider-canonical-events", - write: (event, threadId) => { - canonicalEvents.push(event as ProviderRuntimeEvent); - canonicalThreadIds.push(threadId ?? null); - return Effect.void; - }, - close: () => Effect.void, - }, - }).pipe( - Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - yield* Effect.gen(function* () { - yield* ProviderService.ProviderService; - yield* advanceTestClock(10); - codex.emit({ - eventId: asEventId("evt-canonical-thread-segment"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-canonical-thread-segment"), - createdAt: "2026-01-01T00:00:00.000Z", - type: "turn.completed", - payload: { - state: "completed", - }, - }); - yield* advanceTestClock(20); - }).pipe(Effect.provide(providerLayer)); - - assert.equal(canonicalEvents.length, 1); - assert.equal(canonicalEvents[0]?.threadId, "thread-canonical-thread-segment"); - assert.deepEqual(canonicalThreadIds, ["thread-canonical-thread-segment"]); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-service-")); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - - const codex = makeFakeCodexAdapter(); - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: codex.adapter, - }); - - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - - yield* Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: ThreadId.make("thread-stale"), - }); - }).pipe(Effect.provide(directoryLayer)); - - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - yield* ProviderService.ProviderService.pipe(Effect.provide(providerLayer)); - - const persistedProvider = yield* Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - return yield* directory.getProvider(asThreadId("thread-stale")); - }).pipe(Effect.provide(directoryLayer)); - assert.equal(persistedProvider, "codex"); - - const runtime = yield* Effect.gen(function* () { - const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - return yield* repository.getByThreadId({ - threadId: asThreadId("thread-stale"), - }); - }).pipe(Effect.provide(runtimeRepositoryLayer)); - assert.equal(Option.isSome(runtime), true); - - const legacyTableRows = yield* Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - return yield* sql<{ readonly name: string }>` - SELECT name - FROM sqlite_master - WHERE type = 'table' AND name = 'provider_sessions' - `; - }).pipe(Effect.provide(persistenceLayer)); - assert.equal(legacyTableRows.length, 0); - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect( - "ProviderServiceLive restores rollback routing after restart using persisted thread mapping", - () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-provider-service-restart-"), - ); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - - const firstCodex = makeFakeCodexAdapter(); - const firstRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: firstCodex.adapter, - }); - - const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const firstProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), - ), - Layer.provide(firstDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - const updatedResumeCursor = { - threadId: asThreadId("thread-1"), - resume: "resume-session-1", - resumeSessionAt: "assistant-message-1", - turnCount: 1, - }; - - const startedSession = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const threadId = asThreadId("thread-1"); - const session = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: "/tmp/project", - runtimeMode: "full-access", - threadId, - }); - firstCodex.updateSession(threadId, (existing) => ({ - ...existing, - status: "ready", - resumeCursor: updatedResumeCursor, - updatedAt: "2026-01-01T00:00:01.000Z", - })); - return session; - }).pipe(Effect.provide(firstProviderLayer)); - - const persistedAfterStopAll = yield* Effect.gen(function* () { - const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - return yield* repository.getByThreadId({ - threadId: startedSession.threadId, - }); - }).pipe(Effect.provide(runtimeRepositoryLayer)); - assert.equal(Option.isSome(persistedAfterStopAll), true); - if (Option.isSome(persistedAfterStopAll)) { - assert.equal(persistedAfterStopAll.value.status, "stopped"); - assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor); - } - - const secondCodex = makeFakeCodexAdapter(); - const secondRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: secondCodex.adapter, - }); - const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const secondProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), - ), - Layer.provide(secondDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - secondCodex.startSession.mockClear(); - secondCodex.rollbackThread.mockClear(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.rollbackConversation({ - threadId: startedSession.threadId, - numTurns: 1, - }); - }).pipe(Effect.provide(secondProviderLayer)); - - assert.equal(secondCodex.startSession.mock.calls.length, 1); - const resumedStartInput = secondCodex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project"); - assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor); - assert.equal(startPayload.threadId, startedSession.threadId); - } - assert.equal(secondCodex.rollbackThread.mock.calls.length, 1); - const rollbackCall = secondCodex.rollbackThread.mock.calls[0]; - assert.equal(typeof rollbackCall?.[0], "string"); - assert.equal(rollbackCall?.[1], 1); - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), -); - -routing.layer("ProviderServiceLive routing", (it) => { - it.effect("routes provider operations and rollback conversation", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - assert.equal(session.provider, "codex"); - - const sessions = yield* provider.listSessions(); - assert.equal(sessions.length, 1); - - yield* provider.sendTurn({ - threadId: session.threadId, - input: "hello", - attachments: [], - }); - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - - yield* provider.interruptTurn({ threadId: session.threadId }); - assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.threadId, undefined]]); - - yield* provider.respondToRequest({ - threadId: session.threadId, - requestId: asRequestId("req-1"), - decision: "accept", - }); - assert.deepEqual(routing.codex.respondToRequest.mock.calls, [ - [session.threadId, asRequestId("req-1"), "accept"], - ]); - - yield* provider.respondToUserInput({ - threadId: session.threadId, - requestId: asRequestId("req-user-input-1"), - answers: { - sandbox_mode: "workspace-write", - }, - }); - assert.deepEqual(routing.codex.respondToUserInput.mock.calls, [ - [ - session.threadId, - asRequestId("req-user-input-1"), - { - sandbox_mode: "workspace-write", - }, - ], - ]); - - yield* provider.rollbackConversation({ - threadId: session.threadId, - numTurns: 0, - }); - - yield* provider.stopSession({ threadId: session.threadId }); - routing.codex.startSession.mockClear(); - routing.codex.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: session.threadId, - input: "after-stop", - attachments: [], - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project"); - assert.deepEqual(startPayload.resumeCursor, session.resumeCursor); - assert.equal(startPayload.threadId, session.threadId); - } - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const initial = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - yield* routing.codex.stopSession(initial.threadId); - routing.codex.startSession.mockClear(); - routing.codex.rollbackThread.mockClear(); - - yield* provider.rollbackConversation({ - threadId: initial.threadId, - numTurns: 1, - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.codex.rollbackThread.mock.calls.length, 1); - const rollbackCall = routing.codex.rollbackThread.mock.calls[0]; - assert.equal(rollbackCall?.[1], 1); - }), - ); - - it.effect("preserves the persisted binding when stopping a session", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const initial = yield* provider.startSession(asThreadId("thread-reap-preserve"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-reap-preserve"), - cwd: "/tmp/project-reap-preserve", - runtimeMode: "full-access", - }); - - yield* provider.stopSession({ threadId: initial.threadId }); - - const persistedAfterStop = yield* runtimeRepository.getByThreadId({ - threadId: initial.threadId, - }); - assert.equal(Option.isSome(persistedAfterStop), true); - if (Option.isSome(persistedAfterStop)) { - assert.equal(persistedAfterStop.value.status, "stopped"); - assert.deepEqual(persistedAfterStop.value.resumeCursor, initial.resumeCursor); - } - - routing.codex.startSession.mockClear(); - routing.codex.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: initial.threadId, - input: "resume after reap", - attachments: [], - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project-reap-preserve"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-claude"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude"), - cwd: "/tmp/project-claude", - runtimeMode: "full-access", - }); - - assert.equal(session.provider, "claudeAgent"); - assert.equal(routing.claude.startSession.mock.calls.length, 1); - const startInput = routing.claude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof startInput === "object" && startInput !== null, true); - if (startInput && typeof startInput === "object") { - const startPayload = startInput as { - provider?: string; - providerInstanceId?: ProviderInstanceId; - cwd?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.providerInstanceId, claudeAgentInstanceId); - assert.equal(startPayload.cwd, "/tmp/project-claude"); - } - }), - ); - - it.effect("dies when an active session conflicts with its persisted binding", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - const threadId = asThreadId("thread-binding-mismatch"); - - yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId, - cwd: "/tmp/project-binding-mismatch", - runtimeMode: "full-access", - }); - yield* directory.upsert({ - threadId, - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - runtimeMode: "full-access", - }); - - const exit = yield* Effect.exit(provider.listSessions()); - assert.equal(Exit.hasDies(exit), true); - yield* directory.upsert({ - threadId, - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - runtimeMode: "full-access", - }); - }), - ); - - it.effect("stops stale sessions in other providers after a successful replacement start", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const threadId = asThreadId("thread-provider-replacement"); - - const codexSession = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId, - cwd: "/tmp/project-provider-replacement", - runtimeMode: "full-access", - }); - - routing.codex.stopSession.mockClear(); - routing.claude.stopSession.mockClear(); - - const claudeSession = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId, - cwd: "/tmp/project-provider-replacement", - runtimeMode: "full-access", - }); - - assert.equal(codexSession.provider, "codex"); - assert.equal(claudeSession.provider, "claudeAgent"); - assert.deepEqual(routing.codex.stopSession.mock.calls, [[threadId]]); - assert.equal(routing.claude.stopSession.mock.calls.length, 0); - - const sessions = yield* provider.listSessions(); - assert.deepEqual( - sessions - .filter((session) => session.threadId === threadId) - .map((session) => session.provider), - ["claudeAgent"], - ); - }), - ); - - it.effect("recovers stale sessions for sendTurn using persisted cwd", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const initial = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - cwd: "/tmp/project-send-turn", - runtimeMode: "full-access", - }); - - yield* routing.codex.stopAll(); - routing.codex.startSession.mockClear(); - routing.codex.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: initial.threadId, - input: "resume", - attachments: [], - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project-send-turn"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude-send-turn"), - cwd: "/tmp/project-claude-send-turn", - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - [{ id: "effort", value: "max" }], - ), - runtimeMode: "full-access", - }); - - yield* routing.claude.stopAll(); - routing.claude.startSession.mockClear(); - routing.claude.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: initial.threadId, - input: "resume with claude", - attachments: [], - }); - - assert.equal(routing.claude.startSession.mock.calls.length, 1); - const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - modelSelection?: unknown; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn"); - assert.deepEqual( - startPayload.modelSelection, - createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [ - { id: "effort", value: "max" }, - ]), - ); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.claude.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("lists no sessions after adapter runtime clears", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - yield* provider.startSession(asThreadId("thread-2"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-2"), - runtimeMode: "full-access", - }); - - yield* routing.codex.stopAll(); - yield* routing.claude.stopAll(); - - const remaining = yield* provider.listSessions(); - assert.equal(remaining.length, 0); - }), - ); - - it.effect("persists runtime status transitions in provider_session_runtime", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const threadId = asThreadId("thread-runtime-status"); - const session = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId, - runtimeMode: "full-access", - }); - yield* provider.sendTurn({ - threadId: session.threadId, - input: "hello", - attachments: [], - }); - - const runningRuntime = yield* runtimeRepository.getByThreadId({ - threadId: session.threadId, - }); - assert.equal(Option.isSome(runningRuntime), true); - if (Option.isSome(runningRuntime)) { - assert.equal(runningRuntime.value.status, "running"); - assert.deepEqual(runningRuntime.value.resumeCursor, session.resumeCursor); - const payload = runningRuntime.value.runtimePayload; - assert.equal(payload !== null && typeof payload === "object", true); - if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) { - const runtimePayload = payload as { - cwd: string; - model: string | null; - activeTurnId: string | null; - lastError: string | null; - lastRuntimeEvent: string | null; - }; - assert.equal(runtimePayload.cwd, session.cwd); - assert.equal(runtimePayload.model, null); - assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`); - assert.equal(runtimePayload.lastError, null); - assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn"); - } - } - }), - ); - - it.effect("reuses persisted resume cursor when startSession is called after a restart", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-provider-service-start-"), - ); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - - const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const firstRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter, - }); - const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const firstProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), - ), - Layer.provide(firstDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const initial = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-claude-start"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude-start"), - cwd: "/tmp/project-claude-start", - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(firstProviderLayer)); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.listSessions(); - }).pipe(Effect.provide(firstProviderLayer)); - - const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const secondRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter, - }); - const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const secondProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), - ), - Layer.provide(secondDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - secondClaude.startSession.mockClear(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.startSession(initial.threadId, { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: initial.threadId, - cwd: "/tmp/project-claude-start", - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(secondProviderLayer)); - - assert.equal(secondClaude.startSession.mock.calls.length, 1); - const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.cwd, "/tmp/project-claude-start"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect( - "reuses persisted cwd when startSession resumes a claude session without cwd input", - () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-provider-service-cwd-"), - ); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - - const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const firstRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter, - }); - const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const firstProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), - ), - Layer.provide(firstDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const initial = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-claude-cwd"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude-cwd"), - cwd: "/tmp/project-claude-cwd", - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(firstProviderLayer)); - - const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const secondRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter, - }); - const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const secondProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), - ), - Layer.provide(secondDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - secondClaude.startSession.mockClear(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.startSession(initial.threadId, { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: initial.threadId, - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(secondProviderLayer)); - - assert.equal(secondClaude.startSession.mock.calls.length, 1); - const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.cwd, "/tmp/project-claude-cwd"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), - ); -}); - -const fanout = makeProviderServiceLayer(); -fanout.layer("ProviderServiceLive fanout", (it) => { - it.effect("fans out adapter turn completion events", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - - const eventsRef = yield* Ref.make>([]); - const consumer = yield* Stream.runForEach(provider.streamEvents, (event) => - Ref.update(eventsRef, (current) => [...current, event]), - ).pipe(Effect.forkChild); - yield* advanceTestClock(50); - - const completedEvent: LegacyProviderRuntimeEvent = { - type: "turn.completed", - eventId: asEventId("evt-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - status: "completed", - }; - - fanout.codex.emit(completedEvent); - yield* advanceTestClock(50); - - const events = yield* Ref.get(eventsRef); - yield* Fiber.interrupt(consumer); - - assert.equal( - events.some((entry) => entry.type === "turn.completed"), - true, - ); - assert.equal( - events.some( - (entry) => - entry.type === "turn.completed" && entry.providerInstanceId === codexInstanceId, - ), - true, - ); - }), - ); - - it.effect("fans out canonical runtime events in emission order", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const session = yield* provider.startSession(asThreadId("thread-seq"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-seq"), - runtimeMode: "full-access", - }); - - const receivedRef = yield* Ref.make>([]); - const consumer = yield* Stream.take(provider.streamEvents, 3).pipe( - Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])), - Effect.forkChild, - ); - yield* advanceTestClock(50); - - fanout.codex.emit({ - type: "tool.started", - eventId: asEventId("evt-seq-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Ran command", - }); - fanout.codex.emit({ - type: "tool.completed", - eventId: asEventId("evt-seq-2"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Ran command", - }); - fanout.codex.emit({ - type: "turn.completed", - eventId: asEventId("evt-seq-3"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - status: "completed", - }); - - yield* Fiber.join(consumer); - const received = yield* Ref.get(receivedRef); - assert.deepEqual( - received.map((event) => event.eventId), - [asEventId("evt-seq-1"), asEventId("evt-seq-2"), asEventId("evt-seq-3")], - ); - }), - ); - - it.effect("keeps subscriber delivery ordered and isolates failing subscribers", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - - const receivedByHealthy: string[] = []; - const expectedEventIds = new Set(["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"]); - const healthyFiber = yield* Stream.take(provider.streamEvents, 3).pipe( - Stream.runForEach((event) => - Effect.sync(() => { - receivedByHealthy.push(event.eventId); - }), - ), - Effect.forkChild, - ); - const failingFiber = yield* Stream.take(provider.streamEvents, 1).pipe( - Stream.runForEach(() => Effect.fail("listener crash")), - Effect.forkChild, - ); - yield* advanceTestClock(50); - - const events: ReadonlyArray = [ - { - type: "tool.completed", - eventId: asEventId("evt-ordered-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Ran command", - detail: "echo one", - }, - { - type: "message.delta", - eventId: asEventId("evt-ordered-2"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - delta: "hello", - }, - { - type: "turn.completed", - eventId: asEventId("evt-ordered-3"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - status: "completed", - }, - ]; - - for (const event of events) { - fanout.codex.emit(event); - } - const failingResult = yield* Effect.result(Fiber.join(failingFiber)); - assert.equal(failingResult._tag, "Failure"); - yield* Fiber.join(healthyFiber); - - assert.deepEqual( - receivedByHealthy.filter((eventId) => expectedEventIds.has(eventId)).slice(0, 3), - ["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"], - ); - }), - ); - - it.effect("records provider metrics with the routed provider label", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-metrics"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-metrics"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - - yield* provider.interruptTurn({ threadId: session.threadId }); - yield* provider.respondToRequest({ - threadId: session.threadId, - requestId: asRequestId("req-metrics-1"), - decision: "accept", - }); - yield* provider.respondToUserInput({ - threadId: session.threadId, - requestId: asRequestId("req-metrics-2"), - answers: { - sandbox_mode: "workspace-write", - }, - }); - yield* provider.rollbackConversation({ - threadId: session.threadId, - numTurns: 1, - }); - yield* provider.stopSession({ threadId: session.threadId }); - - const snapshots = yield* Metric.snapshot; - - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "interrupt", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "approval-response", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "user-input-response", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "rollback", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_sessions_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "stop", - outcome: "success", - }), - true, - ); - }), - ); - - it.effect( - "records sendTurn metrics with the resolved provider when modelSelection is omitted", - () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-send-metrics"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-send-metrics"), - cwd: "/tmp/project-send-metrics", - runtimeMode: "full-access", - }); - - yield* provider.sendTurn({ - threadId: session.threadId, - input: "hello", - attachments: [], - }); - - const snapshots = yield* Metric.snapshot; - - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "send", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turn_duration", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "send", - }), - true, - ); - }), - ); -}); - -const validation = makeProviderServiceLayer(); -validation.layer("ProviderServiceLive validation", (it) => { - it.effect("rejects session starts without an explicit provider instance id", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - validation.codex.startSession.mockClear(); - const failure = yield* Effect.flip( - provider.startSession(asThreadId("thread-missing-instance-id"), { - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-missing-instance-id"), - runtimeMode: "full-access", - }), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider instance id is required for provider 'codex'."); - assert.equal(validation.codex.startSession.mock.calls.length, 0); - }), - ); - - it.effect("rejects mismatched provider kind and provider instance id", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - validation.codex.startSession.mockClear(); - validation.claude.startSession.mockClear(); - const failure = yield* Effect.flip( - provider.startSession(asThreadId("thread-instance-mismatch"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-instance-mismatch"), - runtimeMode: "full-access", - }), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include( - failure.issue, - "Provider instance 'claudeAgent' belongs to driver 'claudeAgent', not 'codex'.", - ); - assert.equal(validation.codex.startSession.mock.calls.length, 0); - assert.equal(validation.claude.startSession.mock.calls.length, 0); - }), - ); - - it.effect("returns ProviderValidationError for invalid input payloads", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const failure = yield* Effect.result( - provider.startSession(asThreadId("thread-validation"), { - threadId: asThreadId("thread-validation"), - provider: "invalid-provider", - runtimeMode: "full-access", - } as never), - ); - - assert.equal(failure._tag, "Failure"); - if (failure._tag !== "Failure") { - return; - } - assert.equal(failure.failure._tag, "ProviderValidationError"); - if (failure.failure._tag !== "ProviderValidationError") { - return; - } - assert.equal(failure.failure.operation, "ProviderService.startSession"); - assert.equal(failure.failure.issue.includes("invalid-provider"), true); - }), - ); - - it.effect("accepts startSession when adapter has not emitted provider thread id yet", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - validation.codex.startSession.mockImplementationOnce((input: ProviderSessionStartInput) => - Effect.sync(() => { - const now = "2026-01-01T00:00:00.000Z"; - return { - provider: ProviderDriverKind.make("codex"), - status: "ready", - threadId: input.threadId, - runtimeMode: input.runtimeMode, - cwd: input.cwd ?? process.cwd(), - createdAt: now, - updatedAt: now, - } satisfies ProviderSession; - }), - ); - - const session = yield* provider.startSession(asThreadId("thread-missing"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-missing"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - - assert.equal(session.threadId, asThreadId("thread-missing")); - - const runtime = yield* runtimeRepository.getByThreadId({ - threadId: session.threadId, - }); - assert.equal(Option.isSome(runtime), true); - if (Option.isSome(runtime)) { - assert.equal(runtime.value.threadId, session.threadId); - } - }), - ); -}); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts deleted file mode 100644 index d0acc1039c..0000000000 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ /dev/null @@ -1,1124 +0,0 @@ -/** - * ProviderServiceLive - Cross-provider orchestration layer. - * - * Routes validated transport/API calls to provider adapters through - * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a - * unified provider event stream for subscribers. - * - * It does not implement provider protocol details (adapter concern). - * - * @module ProviderServiceLive - */ -import { - ModelSelection, - NonNegativeInt, - ThreadId, - ProviderInterruptTurnInput, - ProviderRespondToRequestInput, - ProviderRespondToUserInputInput, - ProviderSendTurnInput, - ProviderSessionStartInput, - ProviderStopSessionInput, - type ProviderInstanceId, - type ProviderDriverKind, - type ProviderRuntimeEvent, - type ProviderSession, -} from "@t3tools/contracts"; -import { causeErrorTag } from "@t3tools/shared/observability"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as SchemaIssue from "effect/SchemaIssue"; -import * as Stream from "effect/Stream"; - -import { - increment, - providerMetricAttributes, - providerRuntimeEventsTotal, - providerSessionsTotal, - providerTurnDuration, - providerTurnsTotal, - providerTurnMetricAttributes, - withMetrics, -} from "../../observability/Metrics.ts"; -import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; -import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts"; -import * as ProviderService from "../Services/ProviderService.ts"; -import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts"; -import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts"; -import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; -import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; -import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; -import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts"; -const isModelSelection = Schema.is(ModelSelection); - -/** - * Hook for tests that want to override the canonical event logger pulled - * from `ProviderEventLoggers`. Production wiring leaves this undefined and - * reads the logger off the tag. - */ -export interface ProviderServiceLiveOptions { - readonly canonicalEventLogger?: EventNdjsonLogger; -} - -type ProviderServiceMethod = - ProviderService.ProviderService["Service"][Name]; - -const ProviderRollbackConversationInput = Schema.Struct({ - threadId: ThreadId, - numTurns: NonNegativeInt, -}); - -function toValidationError( - operation: string, - issue: string, - cause?: unknown, -): ProviderValidationError { - return new ProviderValidationError({ - operation, - issue, - ...(cause !== undefined ? { cause } : {}), - }); -} - -const decodeInputOrValidationError = (input: { - readonly operation: string; - readonly schema: S; - readonly payload: unknown; -}) => { - const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema); - return decodeProviderRequestInput(input.payload).pipe( - Effect.mapError( - (schemaError) => - new ProviderValidationError({ - operation: input.operation, - issue: SchemaIssue.makeFormatterDefault()(schemaError.issue), - cause: schemaError, - }), - ), - ); -}; - -function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" { - switch (session.status) { - case "connecting": - return "starting"; - case "error": - return "error"; - case "closed": - return "stopped"; - case "ready": - case "running": - default: - return "running"; - } -} - -function toRuntimePayloadFromSession( - session: ProviderSession, - extra?: { - readonly modelSelection?: unknown; - readonly lastRuntimeEvent?: string; - readonly lastRuntimeEventAt?: string; - }, -): Record { - return { - cwd: session.cwd ?? null, - model: session.model ?? null, - activeTurnId: session.activeTurnId ?? null, - lastError: session.lastError ?? null, - ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}), - ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}), - ...(extra?.lastRuntimeEventAt !== undefined - ? { lastRuntimeEventAt: extra.lastRuntimeEventAt } - : {}), - }; -} - -function readPersistedModelSelection( - runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"], -): ModelSelection | undefined { - if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) { - return undefined; - } - const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined; - return isModelSelection(raw) ? raw : undefined; -} - -function readPersistedCwd( - runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"], -): string | undefined { - if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) { - return undefined; - } - const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined; - if (typeof rawCwd !== "string") return undefined; - const trimmed = rawCwd.trim(); - return trimmed.length > 0 ? trimmed : undefined; -} - -const dieOnMissingBindingInstanceId = ( - operation: string, - payload: { - readonly providerInstanceId?: ProviderInstanceId | undefined; - readonly provider?: ProviderDriverKind | undefined; - }, -): ProviderInstanceId => { - if (payload.providerInstanceId !== undefined) { - return payload.providerInstanceId; - } - throw new Error( - payload.provider - ? `${operation}: provider instance id is required for provider '${payload.provider}'.` - : `${operation}: provider instance id is required.`, - ); -}; - -const correlateRuntimeEventWithInstance = ( - source: { - readonly instanceId: ProviderInstanceId; - readonly provider: ProviderDriverKind; - }, - event: ProviderRuntimeEvent, -): ProviderRuntimeEvent => { - if (event.provider !== source.provider) { - throw new Error( - `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`, - ); - } - if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) { - throw new Error( - `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`, - ); - } - return { ...event, providerInstanceId: source.instanceId }; -}; - -const makeProviderService = Effect.fn("makeProviderService")(function* ( - options?: ProviderServiceLiveOptions, -) { - const analytics = yield* Effect.service(AnalyticsService.AnalyticsService); - const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers; - // Options-provided logger wins (test overrides); otherwise we take whatever - // the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical - // log writer is attached", which downstream code already handles as a - // no-op. - const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical; - - const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry; - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - const runtimeEventPubSub = yield* PubSub.unbounded(); - const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => - McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe( - Effect.tap((credential) => - credential - ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)) - : Effect.void, - ), - ); - const clearMcpSession = (threadId: ThreadId) => - McpSessionRegistry.revokeActiveMcpThread(threadId).pipe( - Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))), - ); - - const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - Effect.succeed(event).pipe( - Effect.tap((canonicalEvent) => - canonicalEventLogger - ? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId) - : Effect.void, - ), - Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)), - Effect.asVoid, - ); - - const requireBindingInstanceId = ( - operation: string, - payload: { - readonly providerInstanceId?: ProviderInstanceId | undefined; - readonly provider?: ProviderDriverKind | undefined; - }, - ): Effect.Effect => - payload.providerInstanceId !== undefined - ? Effect.succeed(payload.providerInstanceId) - : Effect.fail( - toValidationError( - operation, - payload.provider - ? `Provider instance id is required for provider '${payload.provider}'.` - : "Provider instance id is required.", - ), - ); - - const upsertSessionBinding = ( - session: ProviderSession, - threadId: ThreadId, - extra?: { - readonly modelSelection?: unknown; - readonly lastRuntimeEvent?: string; - readonly lastRuntimeEventAt?: string; - }, - ) => - Effect.gen(function* () { - const providerInstanceId = yield* requireBindingInstanceId( - "ProviderService.upsertSessionBinding", - session, - ); - yield* directory.upsert({ - threadId, - provider: session.provider, - providerInstanceId, - runtimeMode: session.runtimeMode, - status: toRuntimeStatus(session), - ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), - runtimePayload: toRuntimePayloadFromSession(session, extra), - }); - }); - - const processRuntimeEvent = ( - source: { - readonly instanceId: ProviderInstanceId; - readonly provider: ProviderDriverKind; - }, - event: ProviderRuntimeEvent, - ): Effect.Effect => - Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe( - Effect.flatMap((canonicalEvent) => - increment(providerRuntimeEventsTotal, { - provider: canonicalEvent.provider, - eventType: canonicalEvent.type, - }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))), - ), - ); - - // `subscribedAdapters` is our source-of-truth for "which instance adapters - // are currently wired into the runtime event bus". It both tracks the set - // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and - // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter - // list consumed by `stopStaleSessionsForThread`, `listSessions`, and - // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added - // instances become visible to those call sites as soon as settings edits - // land. - const subscribedAdapters = yield* Ref.make( - new Map>(), - ); - - const getAdapterEntries = Ref.get(subscribedAdapters).pipe( - Effect.map((map) => Array.from(map.entries())), - ); - - // Rebuild the map of id → adapter from the registry and fork a new event - // subscription for every instance that is either brand new or whose adapter - // identity changed (indicating the underlying `ProviderInstance` was torn - // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned - // fibers for removed/replaced instances exit on their own because their - // adapter's `streamEvents` source terminates when the old scope closes. - const reconcileInstanceSubscriptions = Effect.gen(function* () { - const previous = yield* Ref.get(subscribedAdapters); - const currentIds = yield* registry.listInstances(); - const next = new Map>(); - for (const id of currentIds) { - const adapterOption = yield* registry - .getByInstance(id) - .pipe(Effect.tapError(Effect.logWarning), Effect.option); - if (Option.isNone(adapterOption)) continue; - const adapter = adapterOption.value; - next.set(id, adapter); - if (previous.get(id) !== adapter) { - yield* Stream.runForEach(adapter.streamEvents, (event) => - processRuntimeEvent( - { - instanceId: id, - provider: adapter.provider, - }, - event, - ), - ).pipe(Effect.forkScoped); - } - } - yield* Ref.set(subscribedAdapters, next); - }); - - const instanceChanges = yield* registry.subscribeChanges; - yield* reconcileInstanceSubscriptions; - yield* Stream.runForEach( - Stream.fromSubscription(instanceChanges), - () => reconcileInstanceSubscriptions, - ).pipe(Effect.forkScoped); - - const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: { - readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding; - readonly operation: string; - }) { - const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding); - yield* Effect.annotateCurrentSpan({ - "provider.operation": "recover-session", - "provider.kind": input.binding.provider, - "provider.instance_id": bindingInstanceId, - "provider.thread_id": input.binding.threadId, - }); - return yield* Effect.gen(function* () { - const adapter = yield* registry.getByInstance(bindingInstanceId); - 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, providerInstanceId: bindingInstanceId }, - 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); - - yield* prepareMcpSession(input.binding.threadId, bindingInstanceId); - const resumed = yield* adapter - .startSession({ - threadId: input.binding.threadId, - provider: input.binding.provider, - providerInstanceId: bindingInstanceId, - ...(persistedCwd ? { cwd: persistedCwd } : {}), - ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), - ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), - runtimeMode: input.binding.runtimeMode ?? "full-access", - }) - .pipe(Effect.onError(() => clearMcpSession(input.binding.threadId))); - if (resumed.provider !== adapter.provider) { - yield* clearMcpSession(input.binding.threadId); - return yield* toValidationError( - input.operation, - `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, - ); - } - - yield* upsertSessionBinding( - { ...resumed, providerInstanceId: bindingInstanceId }, - 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; - }).pipe( - withMetrics({ - counter: providerSessionsTotal, - attributes: providerMetricAttributes(input.binding.provider, { - operation: "recover", - }), - }), - ); - }); - - 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 instanceId = yield* requireBindingInstanceId(input.operation, binding); - const adapter = yield* registry.getByInstance(instanceId); - - const hasRequestedSession = yield* adapter.hasSession(input.threadId); - if (hasRequestedSession) { - return { - adapter, - instanceId, - threadId: input.threadId, - runtimeMode: binding.runtimeMode, - isActive: true, - } as const; - } - - if (!input.allowRecovery) { - return { - adapter, - instanceId, - threadId: input.threadId, - runtimeMode: binding.runtimeMode, - isActive: false, - } as const; - } - - const recovered = yield* recoverSessionForThread({ - binding, - operation: input.operation, - }); - return { - adapter: recovered.adapter, - instanceId, - threadId: input.threadId, - runtimeMode: recovered.session.runtimeMode, - isActive: true, - } as const; - }); - - const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: { - readonly threadId: ThreadId; - readonly currentInstanceId: ProviderInstanceId; - }) { - const currentAdapters = yield* getAdapterEntries; - yield* Effect.forEach( - currentAdapters, - ([instanceId, adapter]) => - instanceId === input.currentInstanceId - ? Effect.void - : Effect.gen(function* () { - const hasSession = yield* adapter.hasSession(input.threadId); - if (!hasSession) { - return; - } - - yield* adapter.stopSession(input.threadId).pipe( - Effect.tap(() => - analytics.record("provider.session.stopped", { - provider: adapter.provider, - }), - ), - Effect.catchCause((cause) => - Effect.logWarning("provider.session.stop-stale-failed", { - threadId: input.threadId, - provider: adapter.provider, - cause, - }), - ), - ); - }), - { discard: true }, - ); - }); - - const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")( - function* (threadId, rawInput) { - const parsed = yield* decodeInputOrValidationError({ - operation: "ProviderService.startSession", - schema: ProviderSessionStartInput, - payload: rawInput, - }); - - const resolvedInstanceId = yield* requireBindingInstanceId( - "ProviderService.startSession", - parsed, - ); - let metricProvider = parsed.provider ?? String(resolvedInstanceId); - yield* Effect.annotateCurrentSpan({ - "provider.operation": "start-session", - "provider.instance_id": resolvedInstanceId, - "provider.thread_id": threadId, - "provider.runtime_mode": parsed.runtimeMode, - }); - return yield* Effect.gen(function* () { - const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId); - const resolvedProvider = instanceInfo.driverKind; - metricProvider = resolvedProvider; - if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) { - return yield* toValidationError( - "ProviderService.startSession", - `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`, - ); - } - const input = { - ...parsed, - threadId, - provider: resolvedProvider, - }; - if (!instanceInfo.enabled) { - return yield* toValidationError( - "ProviderService.startSession", - `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`, - ); - } - const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId)); - const effectiveResumeCursor = - input.resumeCursor ?? - (persistedBinding?.providerInstanceId === resolvedInstanceId - ? persistedBinding.resumeCursor - : undefined); - const effectiveCwd = - input.cwd ?? - (persistedBinding?.providerInstanceId === resolvedInstanceId - ? readPersistedCwd(persistedBinding.runtimePayload) - : undefined); - yield* Effect.annotateCurrentSpan({ - "provider.kind": resolvedProvider, - "provider.resume_cursor.source": - input.resumeCursor !== undefined - ? "request" - : effectiveResumeCursor !== undefined && - persistedBinding?.providerInstanceId === resolvedInstanceId - ? "persisted" - : "none", - "provider.resume_cursor.present": effectiveResumeCursor !== undefined, - "provider.cwd.source": - input.cwd !== undefined - ? "request" - : effectiveCwd !== undefined && - persistedBinding?.providerInstanceId === resolvedInstanceId - ? "persisted" - : "none", - "provider.cwd.effective": effectiveCwd ?? "", - }); - const adapter = yield* registry.getByInstance(resolvedInstanceId); - yield* prepareMcpSession(threadId, resolvedInstanceId); - const session = yield* adapter - .startSession({ - ...input, - providerInstanceId: resolvedInstanceId, - ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), - ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), - }) - .pipe(Effect.onError(() => clearMcpSession(threadId))); - - if (session.provider !== adapter.provider) { - yield* clearMcpSession(threadId); - return yield* toValidationError( - "ProviderService.startSession", - `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, - ); - } - const sessionWithInstance = { - ...session, - providerInstanceId: resolvedInstanceId, - }; - - yield* stopStaleSessionsForThread({ - threadId, - currentInstanceId: resolvedInstanceId, - }); - yield* upsertSessionBinding(sessionWithInstance, threadId, { - modelSelection: input.modelSelection, - }); - yield* analytics.record("provider.session.started", { - provider: sessionWithInstance.provider, - runtimeMode: input.runtimeMode, - hasResumeCursor: sessionWithInstance.resumeCursor !== undefined, - hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0, - hasModel: - typeof input.modelSelection?.model === "string" && - input.modelSelection.model.trim().length > 0, - }); - - // Changing runtime mode restarts the session, so the transition is only - // observable here, by diffing against the mode the previous session for - // this thread was bound to. Recording it separately is what makes the - // "started supervised, switched to full access" funnel answerable. - const previousRuntimeMode = persistedBinding?.runtimeMode; - if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) { - yield* analytics.record("provider.runtime_mode.changed", { - provider: sessionWithInstance.provider, - from: previousRuntimeMode, - to: input.runtimeMode, - }); - } - - return sessionWithInstance; - }).pipe( - withMetrics({ - counter: providerSessionsTotal, - attributes: () => - providerMetricAttributes(metricProvider, { - operation: "start", - }), - }), - ); - }, - ); - - const sendTurn: ProviderServiceMethod<"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", - ); - } - yield* Effect.annotateCurrentSpan({ - "provider.operation": "send-turn", - "provider.thread_id": input.threadId, - "provider.interaction_mode": input.interactionMode, - "provider.attachment_count": input.attachments.length, - }); - let metricProvider = "unknown"; - let metricModel = input.modelSelection?.model; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.sendTurn", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - metricModel = input.modelSelection?.model; - yield* Effect.annotateCurrentSpan({ - "provider.kind": routed.adapter.provider, - ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}), - }); - // A turn is the clearest sign a session is still alive. The MCP - // credential is minted once at session start and cannot be rotated into - // an already-spawned agent process, so we keep the existing token valid - // rather than issuing a new one: sessions that go a long time between - // browser tool calls used to lose the toolkit outright. - yield* McpSessionRegistry.touchActiveMcpThread(input.threadId); - const turn = yield* routed.adapter.sendTurn(input); - yield* directory.upsert({ - threadId: input.threadId, - provider: routed.adapter.provider, - providerInstanceId: routed.instanceId, - status: "running", - ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), - runtimePayload: { - ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), - activeTurnId: turn.turnId, - lastRuntimeEvent: "provider.sendTurn", - lastRuntimeEventAt: yield* nowIso, - }, - }); - yield* analytics.record("provider.turn.sent", { - provider: routed.adapter.provider, - model: input.modelSelection?.model, - interactionMode: input.interactionMode, - // Session-start events alone skew runtime mode toward users who toggle - // often, since every toggle restarts the session. Recording it per turn - // gives a usage-weighted view and lets it cross with interactionMode. - runtimeMode: routed.runtimeMode, - attachmentCount: input.attachments.length, - hasInput: typeof input.input === "string" && input.input.trim().length > 0, - }); - return turn; - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - timer: providerTurnDuration, - attributes: () => - providerTurnMetricAttributes({ - provider: metricProvider, - model: metricModel, - extra: { - operation: "send", - }, - }), - }), - ); - }); - - const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")( - function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.interruptTurn", - schema: ProviderInterruptTurnInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.interruptTurn", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "interrupt-turn", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.turn_id": input.turnId, - }); - yield* routed.adapter.interruptTurn(routed.threadId, input.turnId); - yield* analytics.record("provider.turn.interrupted", { - provider: routed.adapter.provider, - }); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "interrupt", - }), - }), - ); - }, - ); - - const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")( - function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.respondToRequest", - schema: ProviderRespondToRequestInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToRequest", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "respond-to-request", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.request_id": input.requestId, - }); - yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); - yield* analytics.record("provider.request.responded", { - provider: routed.adapter.provider, - decision: input.decision, - }); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "approval-response", - }), - }), - ); - }, - ); - - const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn( - "respondToUserInput", - )(function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.respondToUserInput", - schema: ProviderRespondToUserInputInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToUserInput", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "respond-to-user-input", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.request_id": input.requestId, - }); - yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "user-input-response", - }), - }), - ); - }); - - const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")( - function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.stopSession", - schema: ProviderStopSessionInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.stopSession", - allowRecovery: false, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "stop-session", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - }); - if (routed.isActive) { - yield* routed.adapter.stopSession(routed.threadId); - } - yield* clearMcpSession(input.threadId); - yield* directory.upsert({ - threadId: input.threadId, - provider: routed.adapter.provider, - providerInstanceId: routed.instanceId, - status: "stopped", - runtimePayload: { - activeTurnId: null, - }, - }); - yield* analytics.record("provider.session.stopped", { - provider: routed.adapter.provider, - }); - }).pipe( - withMetrics({ - counter: providerSessionsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "stop", - }), - }), - ); - }, - ); - - const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")( - function* () { - const currentAdapters = yield* getAdapterEntries; - const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => - adapter.listSessions().pipe( - Effect.map((sessions) => - sessions.map((session) => ({ - ...session, - providerInstanceId: instanceId, - })), - ), - ), - ); - 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(), - ), - ), - { concurrency: "unbounded" }, - ), - ), - Effect.orElseSucceed( - () => [] as Array>, - ), - ); - const bindingsByThreadId = new Map< - ThreadId, - ProviderSessionDirectory.ProviderRuntimeBinding - >(); - for (const bindingOption of persistedBindings) { - const binding = Option.getOrUndefined(bindingOption); - if (binding) { - bindingsByThreadId.set(binding.threadId, binding); - } - } - - const sessions: ProviderSession[] = []; - for (const session of activeSessions) { - const binding = bindingsByThreadId.get(session.threadId); - if (!binding) { - sessions.push(session); - continue; - } - - const overrides: { - resumeCursor?: ProviderSession["resumeCursor"]; - runtimeMode?: ProviderSession["runtimeMode"]; - providerInstanceId?: ProviderSession["providerInstanceId"]; - } = {}; - overrides.providerInstanceId = dieOnMissingBindingInstanceId( - "ProviderService.listSessions", - binding, - ); - if (binding.provider !== session.provider) { - return yield* Effect.die( - new Error( - `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`, - ), - ); - } - if (overrides.providerInstanceId !== session.providerInstanceId) { - return yield* Effect.die( - new Error( - `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`, - ), - ); - } - if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) { - overrides.resumeCursor = binding.resumeCursor; - } - if (binding.runtimeMode !== undefined) { - overrides.runtimeMode = binding.runtimeMode; - } - sessions.push(Object.assign({}, session, overrides)); - } - return sessions; - }, - ); - - const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) => - registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities)); - - const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) => - registry.getInstanceInfo(instanceId); - - const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn( - "rollbackConversation", - )(function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.rollbackConversation", - schema: ProviderRollbackConversationInput, - payload: rawInput, - }); - if (input.numTurns === 0) { - return; - } - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.rollbackConversation", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "rollback-conversation", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.rollback_turns": input.numTurns, - }); - yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); - yield* analytics.record("provider.conversation.rolled_back", { - provider: routed.adapter.provider, - turns: input.numTurns, - }); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "rollback", - }), - }), - ); - }); - - const runStopAll = Effect.fn("runStopAll")(function* () { - const threadIds = yield* directory.listThreadIds(); - const currentAdapters = yield* getAdapterEntries; - const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => - adapter.listSessions().pipe( - Effect.map((sessions) => - sessions.map((session) => ({ - ...session, - providerInstanceId: instanceId, - })), - ), - ), - ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions))); - yield* Effect.forEach(activeSessions, (session) => - Effect.flatMap(nowIso, (lastRuntimeEventAt) => - upsertSessionBinding(session, session.threadId, { - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt, - }), - ), - ).pipe(Effect.asVoid); - yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid); - yield* McpSessionRegistry.revokeAllActiveMcpCredentials(); - McpProviderSession.clearAllMcpProviderSessions(); - const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => [])); - yield* Effect.forEach(bindings, (binding) => - Effect.gen(function* () { - const providerInstanceId = dieOnMissingBindingInstanceId( - "ProviderService.stopAll", - binding, - ); - return yield* directory.upsert({ - threadId: binding.threadId, - provider: binding.provider, - providerInstanceId, - status: "stopped", - runtimePayload: { - activeTurnId: null, - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt: yield* nowIso, - }, - }); - }), - ).pipe(Effect.asVoid); - yield* analytics.record("provider.sessions.stopped_all", { - sessionCount: threadIds.length, - }); - yield* analytics.flush; - }); - - yield* Effect.addFinalizer(() => - runStopAll().pipe( - Effect.catchCause((cause) => - Effect.logWarning("failed to stop provider service", { - errorTag: causeErrorTag(cause), - }), - ), - ), - ); - - return { - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - getCapabilities, - getInstanceInfo, - rollbackConversation, - // Each access creates a fresh PubSub subscription so that multiple - // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each - // independently receive all runtime events. - get streamEvents(): ProviderServiceMethod<"streamEvents"> { - return Stream.fromPubSub(runtimeEventPubSub); - }, - } satisfies ProviderService.ProviderService["Service"]; -}); - -export const ProviderServiceLive = Layer.effect( - ProviderService.ProviderService, - makeProviderService(), -); - -export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) { - return Layer.effect(ProviderService.ProviderService, makeProviderService(options)); -} diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts deleted file mode 100644 index 079b7f10eb..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ProviderDriverKind, ThreadId } from "@t3tools/contracts"; -import { it, assert } from "@effect/vitest"; -import { assertSome } from "@effect/vitest/utils"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -import { - makeSqlitePersistenceLive, - SqlitePersistenceMemory, -} from "../../persistence/Layers/Sqlite.ts"; -import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts"; -import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; -import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; - -function makeDirectoryLayer(persistenceLayer: Layer.Layer) { - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer)); - return Layer.mergeAll( - runtimeRepositoryLayer, - ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)), - NodeServices.layer, - ); -} - -it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => { - it("upserts and reads thread bindings", () => - Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const initialThreadId = ThreadId.make("thread-1"); - - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - threadId: initialThreadId, - }); - - const provider = yield* directory.getProvider(initialThreadId); - assert.equal(provider, "codex"); - const resolvedBinding = yield* directory.getBinding(initialThreadId); - assertSome(resolvedBinding, { - threadId: initialThreadId, - provider: ProviderDriverKind.make("codex"), - }); - if (Option.isSome(resolvedBinding)) { - assert.equal(resolvedBinding.value.threadId, initialThreadId); - } - - const nextThreadId = ThreadId.make("thread-2"); - - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - threadId: nextThreadId, - }); - const updatedBinding = yield* directory.getBinding(nextThreadId); - assert.equal(Option.isSome(updatedBinding), true); - if (Option.isSome(updatedBinding)) { - assert.equal(updatedBinding.value.threadId, nextThreadId); - } - - const runtime = yield* runtimeRepository.getByThreadId({ threadId: nextThreadId }); - assert.equal(Option.isSome(runtime), true); - if (Option.isSome(runtime)) { - assert.equal(runtime.value.threadId, nextThreadId); - assert.equal(runtime.value.status, "running"); - assert.equal(runtime.value.providerName, "codex"); - } - - const threadIds = yield* directory.listThreadIds(); - assert.deepEqual(threadIds, [nextThreadId]); - })); - - it("persists runtime fields and merges payload updates", () => - Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const threadId = ThreadId.make("thread-runtime"); - - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - threadId, - status: "starting", - resumeCursor: { - threadId: "provider-thread-runtime", - }, - runtimePayload: { - cwd: "/tmp/project", - model: "gpt-5-codex", - }, - }); - - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - threadId, - status: "running", - runtimePayload: { - activeTurnId: "turn-1", - }, - }); - - const runtime = yield* runtimeRepository.getByThreadId({ threadId }); - assert.equal(Option.isSome(runtime), true); - if (Option.isSome(runtime)) { - assert.equal(runtime.value.threadId, threadId); - assert.equal(runtime.value.status, "running"); - assert.deepEqual(runtime.value.resumeCursor, { - threadId: "provider-thread-runtime", - }); - assert.deepEqual(runtime.value.runtimePayload, { - cwd: "/tmp/project", - model: "gpt-5-codex", - activeTurnId: "turn-1", - }); - } - })); - - it("lists persisted bindings with metadata in oldest-first order", () => - Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const olderThreadId = ThreadId.make("thread-runtime-older"); - const newerThreadId = ThreadId.make("thread-runtime-newer"); - - yield* runtimeRepository.upsert({ - threadId: newerThreadId, - providerName: "codex", - providerInstanceId: null, - adapterKey: "codex", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T12:05:00.000Z", - resumeCursor: { - opaque: "resume-newer", - }, - runtimePayload: { - cwd: "/tmp/newer", - }, - }); - - yield* runtimeRepository.upsert({ - threadId: olderThreadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "approval-required", - status: "starting", - lastSeenAt: "2026-04-14T12:00:00.000Z", - resumeCursor: { - opaque: "resume-older", - }, - runtimePayload: { - cwd: "/tmp/older", - }, - }); - - const bindings = yield* directory.listBindings(); - - assert.deepEqual(bindings, [ - { - threadId: olderThreadId, - provider: ProviderDriverKind.make("claudeAgent"), - adapterKey: "claudeAgent", - runtimeMode: "approval-required", - status: "starting", - lastSeenAt: "2026-04-14T12:00:00.000Z", - resumeCursor: { - opaque: "resume-older", - }, - runtimePayload: { - cwd: "/tmp/older", - }, - }, - { - threadId: newerThreadId, - provider: ProviderDriverKind.make("codex"), - adapterKey: "codex", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T12:05:00.000Z", - resumeCursor: { - opaque: "resume-newer", - }, - runtimePayload: { - cwd: "/tmp/newer", - }, - }, - ]); - })); - - it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () => - Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - const threadId = ThreadId.make("thread-provider-change"); - - yield* runtimeRepository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-01-01T00:00:00.000Z", - resumeCursor: null, - runtimePayload: null, - }); - - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - threadId, - }); - - const runtime = yield* runtimeRepository.getByThreadId({ threadId }); - assert.equal(Option.isSome(runtime), true); - if (Option.isSome(runtime)) { - assert.equal(runtime.value.providerName, "codex"); - assert.equal(runtime.value.adapterKey, "codex"); - } - })); - - it("rehydrates persisted mappings across layer restart", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-directory-")); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const directoryLayer = makeDirectoryLayer(makeSqlitePersistenceLive(dbPath)); - - const threadId = ThreadId.make("thread-restart"); - - yield* Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory; - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - threadId, - }); - }).pipe(Effect.provide(directoryLayer)); - - yield* Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory; - const sql = yield* SqlClient.SqlClient; - const provider = yield* directory.getProvider(threadId); - assert.equal(provider, "codex"); - - const resolvedBinding = yield* directory.getBinding(threadId); - assertSome(resolvedBinding, { - threadId, - provider: ProviderDriverKind.make("codex"), - }); - if (Option.isSome(resolvedBinding)) { - assert.equal(resolvedBinding.value.threadId, threadId); - } - - const legacyTableRows = yield* sql<{ readonly name: string }>` - SELECT name - FROM sqlite_master - WHERE type = 'table' AND name = 'provider_sessions' - `; - assert.equal(legacyTableRows.length, 0); - }).pipe(Effect.provide(directoryLayer)); - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - })); -}); diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts deleted file mode 100644 index 23075bd9a0..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts"; -import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts"; -import { - ProviderSessionDirectory, - type ProviderRuntimeBinding, - type ProviderRuntimeBindingWithMetadata, - type ProviderSessionDirectoryShape, -} from "../Services/ProviderSessionDirectory.ts"; -const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind); - -function toPersistenceError(operation: string) { - return (cause: unknown) => - new ProviderSessionDirectoryPersistenceError({ - operation, - detail: `Failed to execute ${operation}.`, - cause, - }); -} - -function decodeProviderDriverKind( - providerName: string, - operation: string, -): Effect.Effect { - return decodeProviderDriverKindValue(providerName).pipe( - Effect.mapError( - (cause) => - new ProviderSessionDirectoryPersistenceError({ - operation, - detail: `Unknown persisted provider '${providerName}'.`, - cause, - }), - ), - ); -} - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -function mergeRuntimePayload( - existing: unknown | null, - next: unknown | null | undefined, -): unknown | null { - if (next === undefined) { - return existing ?? null; - } - if (isRecord(existing) && isRecord(next)) { - return { ...existing, ...next }; - } - return next; -} - -function toRuntimeBinding( - runtime: ProviderSessionRuntime.ProviderSessionRuntime, - operation: string, -): Effect.Effect { - return decodeProviderDriverKind(runtime.providerName, operation).pipe( - Effect.map( - (provider) => - ({ - threadId: runtime.threadId, - provider, - // Migration boundary only: rows written before the instance split - // have a null provider_instance_id. Promote them as they leave - // persistence so hot routing code never has to infer an instance - // from a driver kind. - providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider), - adapterKey: runtime.adapterKey, - runtimeMode: runtime.runtimeMode, - status: runtime.status, - resumeCursor: runtime.resumeCursor, - runtimePayload: runtime.runtimePayload, - lastSeenAt: runtime.lastSeenAt, - }) satisfies ProviderRuntimeBindingWithMetadata, - ), - ); -} - -const makeProviderSessionDirectory = Effect.gen(function* () { - const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const getBinding = (threadId: ThreadId) => - repository.getByThreadId({ threadId }).pipe( - Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")), - Effect.flatMap((runtime) => - Option.match(runtime, { - onNone: () => Effect.succeed(Option.none()), - onSome: (value) => - toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe( - Effect.map((binding) => Option.some(binding)), - ), - }), - ), - ); - - const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) { - const existing = yield* repository - .getByThreadId({ threadId: binding.threadId }) - .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId"))); - - const existingRuntime = Option.getOrUndefined(existing); - const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId; - if (!resolvedThreadId) { - return yield* new ProviderValidationError({ - operation: "ProviderSessionDirectory.upsert", - issue: "threadId must be a non-empty string.", - }); - } - - const now = DateTime.formatIso(yield* DateTime.now); - const providerChanged = - existingRuntime !== undefined && existingRuntime.providerName !== binding.provider; - const providerInstanceId = - binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null); - if (providerInstanceId === null || providerInstanceId === undefined) { - return yield* new ProviderValidationError({ - operation: "ProviderSessionDirectory.upsert", - issue: "providerInstanceId is required for provider session runtime bindings.", - }); - } - yield* repository - .upsert({ - threadId: resolvedThreadId, - providerName: binding.provider, - providerInstanceId, - adapterKey: - binding.adapterKey ?? - (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)), - runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access", - status: binding.status ?? existingRuntime?.status ?? "running", - lastSeenAt: now, - resumeCursor: - binding.resumeCursor !== undefined - ? binding.resumeCursor - : (existingRuntime?.resumeCursor ?? null), - runtimePayload: mergeRuntimePayload( - existingRuntime?.runtimePayload ?? null, - binding.runtimePayload, - ), - }) - .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert"))); - }); - - const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) => - getBinding(threadId).pipe( - Effect.flatMap((binding) => - Option.match(binding, { - onSome: (value) => Effect.succeed(value.provider), - onNone: () => - Effect.fail( - new ProviderSessionDirectoryPersistenceError({ - operation: "ProviderSessionDirectory.getProvider", - detail: `No persisted provider binding found for thread '${threadId}'.`, - }), - ), - }), - ), - ); - - const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () => - repository.list().pipe( - Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")), - Effect.map((rows) => rows.map((row) => row.threadId)), - ); - - const listBindings: ProviderSessionDirectoryShape["listBindings"] = () => - repository.list().pipe( - Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")), - Effect.flatMap((rows) => - Effect.forEach( - rows, - (row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"), - { concurrency: "unbounded" }, - ), - ), - ); - - return { - upsert, - getProvider, - getBinding, - listThreadIds, - listBindings, - } satisfies ProviderSessionDirectoryShape; -}); - -export const ProviderSessionDirectoryLive = Layer.effect( - ProviderSessionDirectory, - makeProviderSessionDirectory, -); - -export function makeProviderSessionDirectoryLive() { - return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory); -} diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts deleted file mode 100644 index f3f4ca39d4..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ /dev/null @@ -1,592 +0,0 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { - ProjectId, - ThreadId, - TurnId, - ProviderDriverKind, - ProviderInstanceId, -} from "@t3tools/contracts"; -import * as Clock from "effect/Clock"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Layer from "effect/Layer"; -import * as ManagedRuntime from "effect/ManagedRuntime"; -import * as Option from "effect/Option"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; - -import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; -import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts"; -import { ProviderValidationError } from "../Errors.ts"; -import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts"; -import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; -import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; -import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts"; - -const defaultModelSelection = { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", -} as const; - -async function waitFor( - predicate: () => boolean | Promise, - timeoutMs = 2_000, -): Promise { - const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs; - const poll = async (): Promise => { - if (await predicate()) { - return; - } - if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) { - throw new Error("Timed out waiting for expectation."); - } - await Effect.runPromise(Effect.yieldNow); - return poll(); - }; - - return poll(); -} - -const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, { - discard: true, -}); - -const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - -function makeReadModel( - threads: ReadonlyArray<{ - readonly id: ThreadId; - readonly session: { - readonly threadId: ThreadId; - readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"; - readonly providerName: "codex" | "claudeAgent"; - readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits"; - readonly activeTurnId: TurnId | null; - readonly lastError: string | null; - readonly updatedAt: string; - } | null; - }>, -) { - const now = "2026-01-01T00:00:00.000Z"; - const projectId = ProjectId.make("project-provider-session-reaper"); - - return { - snapshotSequence: 0, - updatedAt: now, - projects: [ - { - id: projectId, - title: "Provider Reaper Project", - workspaceRoot: "/tmp/provider-reaper-project", - defaultModelSelection, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: threads.map((thread) => ({ - id: thread.id, - projectId, - title: `Thread ${thread.id}`, - modelSelection: defaultModelSelection, - interactionMode: "default" as const, - runtimeMode: "full-access" as const, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - latestTurn: null, - messages: [], - session: thread.session, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - })), - }; -} - -describe("ProviderSessionReaper", () => { - let runtime: ManagedRuntime.ManagedRuntime< - ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository, - unknown - > | null = null; - let scope: Scope.Closeable | null = null; - - afterEach(async () => { - if (scope) { - await Effect.runPromise(Scope.close(scope, Exit.void)); - } - scope = null; - if (runtime) { - await runtime.dispose(); - } - runtime = null; - }); - - async function createHarness(input: { - readonly readModel: ReturnType; - readonly stopSessionImplementation?: (input: { - readonly threadId: ThreadId; - }) => ReturnType; - }) { - const stoppedThreadIds = new Set(); - const stopSession = vi.fn( - (request) => - (input.stopSessionImplementation - ? input.stopSessionImplementation(request) - : Effect.sync(() => { - stoppedThreadIds.add(request.threadId); - })) as ReturnType, - ); - - const providerService: ProviderServiceShape = { - startSession: () => unsupported(), - sendTurn: () => unsupported(), - interruptTurn: () => unsupported(), - respondToRequest: () => unsupported(), - respondToUserInput: () => unsupported(), - stopSession, - listSessions: () => Effect.succeed([]), - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), - getInstanceInfo: (instanceId) => { - const driverKind = ProviderDriverKind.make(String(instanceId)); - return Effect.succeed({ - instanceId, - driverKind, - displayName: undefined, - enabled: true, - continuationIdentity: { - driverKind, - continuationKey: `${driverKind}:instance:${instanceId}`, - }, - }); - }, - rollbackConversation: () => unsupported(), - streamEvents: Stream.empty, - }; - - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const layer = makeProviderSessionReaperLive({ - inactivityThresholdMs: 1_000, - sweepIntervalMs: 60_000, - }).pipe( - Layer.provideMerge(providerSessionDirectoryLayer), - Layer.provideMerge(runtimeRepositoryLayer), - Layer.provideMerge(Layer.succeed(ProviderService, providerService)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => - Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }), - getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: () => Effect.die("unused"), - getProjectShellById: () => Effect.die("unused"), - getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), - getThreadCheckpointContext: () => Effect.die("unused"), - getFullThreadDiffContext: () => Effect.die("unused"), - getThreadShellById: (threadId) => - Effect.succeed( - input.readModel.threads.find((thread) => thread.id === threadId) - ? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!) - : Option.none(), - ), - getThreadDetailById: () => Effect.die("unused"), - getThreadDetailSnapshot: () => Effect.die("unused"), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - Layer.provideMerge(NodeServices.layer), - ); - - runtime = ManagedRuntime.make(layer); - return { stopSession, stoppedThreadIds }; - } - - it("reaps stale persisted sessions without active turns", async () => { - const threadId = ThreadId.make("thread-reaper-stale"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-stale", - }, - runtimePayload: null, - }), - ); - - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - - await waitFor(() => harness.stopSession.mock.calls.length === 1); - - expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId }); - expect(harness.stoppedThreadIds.has(threadId)).toBe(true); - }); - - it("skips stale sessions when the thread still has an active turn", async () => { - const threadId = ThreadId.make("thread-reaper-active-turn"); - const turnId = TurnId.make("turn-reaper-active"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "running", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: turnId, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-active-turn", - }, - runtimePayload: null, - }), - ); - - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("does not reap sessions that are still within the inactivity threshold", async () => { - const threadId = ThreadId.make("thread-reaper-fresh"); - const now = DateTime.formatIso(await Effect.runPromise(DateTime.now)); - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: now, - resumeCursor: { - opaque: "resume-fresh", - }, - runtimePayload: null, - }), - ); - - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("skips persisted sessions that are already marked stopped", async () => { - const threadId = ThreadId.make("thread-reaper-stopped"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "stopped", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "stopped", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-stopped", - }, - runtimePayload: null, - }), - ); - - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("continues reaping other sessions when one stop attempt fails", async () => { - const failedThreadId = ThreadId.make("thread-reaper-stop-failure"); - const reapedThreadId = ThreadId.make("thread-reaper-stop-success"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: failedThreadId, - session: { - threadId: failedThreadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - { - id: reapedThreadId, - session: { - threadId: reapedThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - stopSessionImplementation: (request) => - request.threadId === failedThreadId - ? Effect.fail( - new ProviderValidationError({ - operation: "ProviderSessionReaper.test", - issue: "simulated stop failure", - }), - ) - : Effect.void, - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId: failedThreadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-failure", - }, - runtimePayload: null, - }), - ); - await runtime!.runPromise( - repository.upsert({ - threadId: reapedThreadId, - providerName: "codex", - providerInstanceId: null, - adapterKey: "codex", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:01:00.000Z", - resumeCursor: { - opaque: "resume-success", - }, - runtimePayload: null, - }), - ); - - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - - await waitFor(() => harness.stopSession.mock.calls.length === 2); - - expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([ - failedThreadId, - reapedThreadId, - ]); - }); - - it("continues reaping other sessions when one stop attempt defects", async () => { - const defectThreadId = ThreadId.make("thread-reaper-stop-defect"); - const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: defectThreadId, - session: { - threadId: defectThreadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - { - id: reapedThreadId, - session: { - threadId: reapedThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - stopSessionImplementation: (request) => - request.threadId === defectThreadId - ? Effect.die(new Error("simulated stop defect")) - : Effect.void, - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId: defectThreadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-defect", - }, - runtimePayload: null, - }), - ); - await runtime!.runPromise( - repository.upsert({ - threadId: reapedThreadId, - providerName: "codex", - providerInstanceId: null, - adapterKey: "codex", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:01:00.000Z", - resumeCursor: { - opaque: "resume-after-defect", - }, - runtimePayload: null, - }), - ); - - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - - await waitFor(() => harness.stopSession.mock.calls.length === 2); - - expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([ - defectThreadId, - reapedThreadId, - ]); - }); -}); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts deleted file mode 100644 index 8eccd52fb2..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ /dev/null @@ -1,139 +0,0 @@ -import * as Clock from "effect/Clock"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schedule from "effect/Schedule"; - -import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; -import { - ProviderSessionReaper, - type ProviderSessionReaperShape, -} from "../Services/ProviderSessionReaper.ts"; -import { forkParked } from "../../serverActivation.ts"; -import { ProviderService } from "../Services/ProviderService.ts"; - -const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; -const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000; - -export interface ProviderSessionReaperLiveOptions { - readonly inactivityThresholdMs?: number; - readonly sweepIntervalMs?: number; -} - -const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) => - Effect.gen(function* () { - const providerService = yield* ProviderService; - const directory = yield* ProviderSessionDirectory; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - - const inactivityThresholdMs = Math.max( - 1, - options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS, - ); - const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS); - - const sweep = Effect.gen(function* () { - const bindings = yield* directory.listBindings(); - const now = yield* Clock.currentTimeMillis; - let reapedCount = 0; - - for (const binding of bindings) { - if (binding.status === "stopped") { - continue; - } - - const lastSeenMs = Date.parse(binding.lastSeenAt); - if (Number.isNaN(lastSeenMs)) { - yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", { - threadId: binding.threadId, - provider: binding.provider, - lastSeenAt: binding.lastSeenAt, - }); - continue; - } - - const idleDurationMs = now - lastSeenMs; - if (idleDurationMs < inactivityThresholdMs) { - continue; - } - - const thread = yield* projectionSnapshotQuery - .getThreadShellById(binding.threadId) - .pipe(Effect.map(Option.getOrUndefined)); - if (thread?.session?.activeTurnId != null) { - yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", { - threadId: binding.threadId, - activeTurnId: thread.session.activeTurnId, - idleDurationMs, - }); - continue; - } - - const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe( - Effect.tap(() => - Effect.logInfo("provider.session.reaped", { - threadId: binding.threadId, - provider: binding.provider, - idleDurationMs, - reason: "inactivity_threshold", - }), - ), - Effect.as(true), - Effect.catchCause((cause) => - Effect.logWarning("provider.session.reaper.stop-failed", { - threadId: binding.threadId, - provider: binding.provider, - idleDurationMs, - cause, - }).pipe(Effect.as(false)), - ), - ); - - if (reaped) { - reapedCount += 1; - } - } - - if (reapedCount > 0) { - yield* Effect.logInfo("provider.session.reaper.sweep-complete", { - reapedCount, - totalBindings: bindings.length, - }); - } - }); - - const start: ProviderSessionReaperShape["start"] = () => - Effect.gen(function* () { - yield* forkParked( - sweep.pipe( - Effect.catch((error: unknown) => - Effect.logWarning("provider.session.reaper.sweep-failed", { - error, - }), - ), - Effect.catchDefect((defect: unknown) => - Effect.logWarning("provider.session.reaper.sweep-defect", { - defect, - }), - ), - Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))), - ), - ); - - yield* Effect.logInfo("provider.session.reaper.started", { - inactivityThresholdMs, - sweepIntervalMs, - }); - }); - - return { - start, - } satisfies ProviderSessionReaperShape; - }); - -export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) => - Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options)); - -export const ProviderSessionReaperLive = makeProviderSessionReaperLive(); diff --git a/apps/server/src/provider/ProviderDriver.ts b/apps/server/src/provider/ProviderDriver.ts index 359da392f8..50205103e3 100644 --- a/apps/server/src/provider/ProviderDriver.ts +++ b/apps/server/src/provider/ProviderDriver.ts @@ -2,8 +2,8 @@ * ProviderDriver / ProviderInstance — driver SPI as plain values. * * `ProviderDriver` is a record, not a Context.Service. The thing it produces - * (`ProviderInstance`) is also a record — three captured closures - * (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There + * (`ProviderInstance`) is also a record of captured closures + * (`snapshot`, `orchestrationAdapter`, `textGeneration`), an id, and a driver kind. There * are intentionally no per-driver Context tags because tags are * singleton-per-runtime and we need many instances of the same driver. * @@ -32,8 +32,7 @@ import type * as Scope from "effect/Scope"; import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts"; import type { ProviderAdapterV2Shape } from "../orchestration-v2/ProviderAdapter.ts"; -import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts"; -import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts"; +import type { ProviderDriverError } from "./Errors.ts"; import type { ServerProviderShape } from "./Services/ServerProvider.ts"; /** @@ -70,7 +69,6 @@ export interface ProviderInstance { readonly accentColor?: string | undefined; readonly enabled: boolean; readonly snapshot: ServerProviderShape; - readonly adapter: ProviderAdapterShape; readonly orchestrationAdapter: ProviderAdapterV2Shape; readonly textGeneration: TextGenerationShape; } diff --git a/apps/server/src/provider/Services/ClaudeAdapter.ts b/apps/server/src/provider/Services/ClaudeAdapter.ts deleted file mode 100644 index ed9bd7081b..0000000000 --- a/apps/server/src/provider/Services/ClaudeAdapter.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * ClaudeAdapter — shape type for the Claude provider adapter. - * - * Historically this module exposed a `Context.Service` tag so consumers - * could inject the adapter through the Effect layer graph. The driver - * model ({@link ../Drivers/ClaudeDriver}) bundles one adapter per - * instance as a captured closure instead, so the tag is gone — we only - * retain the shape interface as a naming anchor for the driver bundle. - * - * @module ClaudeAdapter - */ -import type { ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; - -/** - * ClaudeAdapterShape — per-instance Claude adapter contract. Carries - * a branded driver kind as the nominal discriminant. - */ -export interface ClaudeAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/CodexAdapter.ts b/apps/server/src/provider/Services/CodexAdapter.ts deleted file mode 100644 index 33fe0fa12b..0000000000 --- a/apps/server/src/provider/Services/CodexAdapter.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * CodexAdapter — shape type for the Codex provider adapter. - * - * Historically this module exposed a `Context.Service` tag so consumers - * could inject the adapter through the Effect layer graph. The driver - * model ({@link ../Drivers/CodexDriver}) bundles one adapter per - * instance as a captured closure instead, so the tag is gone — we only - * retain the shape interface as a naming anchor for the driver bundle. - * - * @module CodexAdapter - */ -import type { ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; - -/** - * CodexAdapterShape — per-instance Codex adapter contract. Carries - * a branded driver kind as the nominal discriminant. - */ -export interface CodexAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/CursorAdapter.ts b/apps/server/src/provider/Services/CursorAdapter.ts deleted file mode 100644 index 83581f0a45..0000000000 --- a/apps/server/src/provider/Services/CursorAdapter.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * CursorAdapter — shape type for the Cursor provider adapter. - * - * Historically this module exposed a `Context.Service` tag so consumers - * could inject the adapter through the Effect layer graph. The driver - * model ({@link ../Drivers/CursorDriver}) bundles one adapter per - * instance as a captured closure instead, so the tag is gone — we only - * retain the shape interface as a naming anchor for the driver bundle. - * - * @module CursorAdapter - */ -import type { ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; - -/** - * CursorAdapterShape — per-instance Cursor adapter contract. Carries - * a branded driver kind as the nominal discriminant. - */ -export interface CursorAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/GrokAdapter.ts b/apps/server/src/provider/Services/GrokAdapter.ts deleted file mode 100644 index 73254cefe3..0000000000 --- a/apps/server/src/provider/Services/GrokAdapter.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * GrokAdapter — shape type for the Grok provider adapter. - * - * The driver model ({@link ../Drivers/GrokDriver}) bundles one adapter per - * instance as a captured closure, so this module only retains the shape - * interface as a naming anchor for the driver bundle. - * - * @module GrokAdapter - */ -import type { ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; - -/** - * GrokAdapterShape — per-instance Grok adapter contract. - */ -export interface GrokAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/OpenCodeAdapter.ts b/apps/server/src/provider/Services/OpenCodeAdapter.ts deleted file mode 100644 index e3ad97904d..0000000000 --- a/apps/server/src/provider/Services/OpenCodeAdapter.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * OpenCodeAdapter — shape type for the OpenCode provider adapter. - * - * Historically this module exposed a `Context.Service` tag so consumers - * could inject the adapter through the Effect layer graph. The driver - * model ({@link ../Drivers/OpenCodeDriver}) bundles one adapter per - * instance as a captured closure instead, so the tag is gone — we only - * retain the shape interface as a naming anchor for the driver bundle. - * - * @module OpenCodeAdapter - */ -import type { ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; - -/** - * OpenCodeAdapterShape — per-instance OpenCode adapter contract. Carries - * a branded driver kind as the nominal discriminant. - */ -export interface OpenCodeAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts deleted file mode 100644 index 01eeae7b7b..0000000000 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ /dev/null @@ -1,126 +0,0 @@ -/** - * ProviderAdapter - Provider-specific runtime adapter contract. - * - * Defines the provider-native session/protocol operations that `ProviderService` - * routes to after resolving the target provider. Implementations should focus - * on provider behavior only and avoid cross-provider orchestration concerns. - * - * @module ProviderAdapter - */ -import type { - ApprovalRequestId, - ProviderApprovalDecision, - ProviderDriverKind, - ProviderUserInputAnswers, - ProviderRuntimeEvent, - ProviderSendTurnInput, - ProviderSession, - ProviderSessionStartInput, - ThreadId, - ProviderTurnStartResult, - TurnId, -} from "@t3tools/contracts"; -import type * as Effect from "effect/Effect"; -import type * as Stream from "effect/Stream"; - -export type ProviderSessionModelSwitchMode = "in-session" | "unsupported"; - -export interface ProviderAdapterCapabilities { - /** - * Declares whether changing the model on an existing session is supported. - */ - readonly sessionModelSwitch: ProviderSessionModelSwitchMode; -} - -export interface ProviderThreadTurnSnapshot { - readonly id: TurnId; - readonly items: ReadonlyArray; -} - -export interface ProviderThreadSnapshot { - readonly threadId: ThreadId; - readonly turns: ReadonlyArray; -} - -export interface ProviderAdapterShape { - /** - * Provider kind implemented by this adapter. - */ - readonly provider: ProviderDriverKind; - readonly capabilities: ProviderAdapterCapabilities; - - /** - * Start a provider-backed session. - */ - readonly startSession: ( - input: ProviderSessionStartInput, - ) => Effect.Effect; - - /** - * Send a turn to an active provider session. - */ - readonly sendTurn: ( - input: ProviderSendTurnInput, - ) => Effect.Effect; - - /** - * Interrupt an active turn. - */ - readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect; - - /** - * Respond to an interactive approval request. - */ - readonly respondToRequest: ( - threadId: ThreadId, - requestId: ApprovalRequestId, - decision: ProviderApprovalDecision, - ) => Effect.Effect; - - /** - * Respond to a structured user-input request. - */ - readonly respondToUserInput: ( - threadId: ThreadId, - requestId: ApprovalRequestId, - answers: ProviderUserInputAnswers, - ) => Effect.Effect; - - /** - * Stop one provider session. - */ - readonly stopSession: (threadId: ThreadId) => Effect.Effect; - - /** - * List currently active provider sessions for this adapter. - */ - readonly listSessions: () => Effect.Effect>; - - /** - * Check whether this adapter owns an active session id. - */ - readonly hasSession: (threadId: ThreadId) => Effect.Effect; - - /** - * Read a provider thread snapshot. - */ - readonly readThread: (threadId: ThreadId) => Effect.Effect; - - /** - * Roll back a provider thread by N turns. - */ - readonly rollbackThread: ( - threadId: ThreadId, - numTurns: number, - ) => Effect.Effect; - - /** - * Stop all sessions owned by this adapter. - */ - readonly stopAll: () => Effect.Effect; - - /** - * Canonical runtime event stream emitted by this adapter. - */ - readonly streamEvents: Stream.Stream; -} diff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts deleted file mode 100644 index 5b755c42ee..0000000000 --- a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts +++ /dev/null @@ -1,100 +0,0 @@ -/** - * ProviderAdapterRegistry - Lookup boundary for provider adapter implementations. - * - * Maps a `ProviderInstanceId` (the new per-instance routing key) or a - * `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete - * adapter service (Codex, Claude, etc). It does not own session lifecycle - * or routing rules; `ProviderService` uses this registry together with - * `ProviderSessionDirectory`. - * - * During the driver/instance migration this tag exposes both flavours: - * - * - `getByInstance` / `listInstances` — new per-instance routing. Callers - * that already know an `instanceId` (threads, sessions, events) - * should prefer these. - * (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D - * behaviour. New code should not grow additional callers of the kind-keyed - * methods; they exist so the settings UI, WS refresh RPC, and a handful - * of legacy persisted rows can still be routed during the rollout. - * - * @module ProviderAdapterRegistry - */ -import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as PubSub from "effect/PubSub"; -import type * as Scope from "effect/Scope"; -import type * as Stream from "effect/Stream"; - -import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; -import type { ProviderContinuationIdentity } from "../ProviderDriver.ts"; - -export interface ProviderInstanceRoutingInfo { - readonly instanceId: ProviderInstanceId; - readonly driverKind: ProviderDriverKind; - readonly displayName: string | undefined; - readonly accentColor?: string | undefined; - readonly enabled: boolean; - readonly continuationIdentity: ProviderContinuationIdentity; -} - -/** - * ProviderAdapterRegistryShape - Service API for adapter lookup. - */ -export interface ProviderAdapterRegistryShape { - /** - * Resolve the adapter for a specific instance id. Returns - * `ProviderUnsupportedError` if no such instance is currently registered - * (which covers "never configured" *and* "configured but the driver is - * unavailable in this build" — both surface the same failure to callers - * that expect a working adapter). - */ - readonly getByInstance: ( - instanceId: ProviderInstanceId, - ) => Effect.Effect, ProviderUnsupportedError>; - - readonly getInstanceInfo: ( - instanceId: ProviderInstanceId, - ) => Effect.Effect; - - /** - * List all live instance ids. Excludes unavailable/shadow instances — - * callers of this method want something they can pass to `getByInstance`. - */ - readonly listInstances: () => Effect.Effect>; - - /** - * Legacy: list provider kinds whose default instance is currently - * registered. - * - * @deprecated Prefer `listInstances`. Retained for migration-era call - * sites that iterate providers to build UI/metrics. - */ - readonly listProviders: () => Effect.Effect>; - - /** - * Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`. - * Emits one `void` tick whenever the set of live instances changes - * (instance added, removed, or rebuilt after a settings edit). Consumers - * that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s - * runtime event bus — re-pull `listInstances` on each tick and fork new - * subscriptions for instances they haven't seen yet. - */ - readonly streamChanges: Stream.Stream; - - /** - * Acquire a change subscription synchronously in the caller's current fiber. - * Consumers that must avoid missing a publish between initial reconciliation - * and watcher startup should use this, then fork `Stream.fromSubscription`. - */ - readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; -} - -/** - * ProviderAdapterRegistry - Service tag for provider adapter lookup. - */ -export class ProviderAdapterRegistry extends Context.Service< - ProviderAdapterRegistry, - ProviderAdapterRegistryShape ->()("t3/provider/Services/ProviderAdapterRegistry") {} diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts deleted file mode 100644 index 4d4cb4fa01..0000000000 --- a/apps/server/src/provider/Services/ProviderService.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** - * ProviderService - Service interface for provider sessions, turns, and checkpoints. - * - * Acts as the cross-provider facade used by transports (WebSocket/RPC). It - * resolves provider adapters through `ProviderAdapterRegistry`, routes - * session-scoped calls via `ProviderSessionDirectory`, and exposes one unified - * provider event stream to callers. - * - * Uses Effect `Context.Service` for dependency injection and returns typed - * domain errors for validation, session, codex, and checkpoint workflows. - * - * @module ProviderService - */ -import type { - ProviderInterruptTurnInput, - ProviderInstanceId, - ProviderRespondToRequestInput, - ProviderRespondToUserInputInput, - ProviderRuntimeEvent, - ProviderSendTurnInput, - ProviderSession, - ProviderSessionStartInput, - ProviderStopSessionInput, - ThreadId, - ProviderTurnStartResult, -} from "@t3tools/contracts"; -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Stream from "effect/Stream"; - -import type { ProviderServiceError } from "../Errors.ts"; -import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts"; -import type { ProviderInstanceRoutingInfo } from "./ProviderAdapterRegistry.ts"; - -/** - * ProviderServiceShape - Service API for provider session and turn orchestration. - */ -export interface ProviderServiceShape { - /** - * Start a provider session. - */ - readonly startSession: ( - threadId: ThreadId, - input: ProviderSessionStartInput, - ) => Effect.Effect; - - /** - * Send a provider turn. - */ - readonly sendTurn: ( - input: ProviderSendTurnInput, - ) => Effect.Effect; - - /** - * Interrupt a running provider turn. - */ - readonly interruptTurn: ( - input: ProviderInterruptTurnInput, - ) => Effect.Effect; - - /** - * Respond to a provider approval request. - */ - readonly respondToRequest: ( - input: ProviderRespondToRequestInput, - ) => Effect.Effect; - - /** - * Respond to a provider structured user-input request. - */ - readonly respondToUserInput: ( - input: ProviderRespondToUserInputInput, - ) => Effect.Effect; - - /** - * Stop a provider session. - */ - readonly stopSession: ( - input: ProviderStopSessionInput, - ) => Effect.Effect; - - /** - * List active provider sessions. - * - * Aggregates runtime session lists from all registered adapters. - */ - readonly listSessions: () => Effect.Effect>; - - /** - * Read capabilities for the adapter bound to a configured provider instance. - */ - readonly getCapabilities: ( - instanceId: ProviderInstanceId, - ) => Effect.Effect; - - readonly getInstanceInfo: ( - instanceId: ProviderInstanceId, - ) => Effect.Effect; - - /** - * Roll back provider conversation state by a number of turns. - */ - readonly rollbackConversation: (input: { - readonly threadId: ThreadId; - readonly numTurns: number; - }) => Effect.Effect; - - /** - * Canonical provider runtime event stream. - * - * Fan-out is owned by ProviderService (not by a standalone event-bus service). - */ - readonly streamEvents: Stream.Stream; -} - -/** - * ProviderService - Service tag for provider orchestration. - */ -export class ProviderService extends Context.Service()( - "t3/provider/Services/ProviderService", -) {} diff --git a/apps/server/src/provider/Services/ProviderSessionDirectory.ts b/apps/server/src/provider/Services/ProviderSessionDirectory.ts deleted file mode 100644 index f2dd4323f7..0000000000 --- a/apps/server/src/provider/Services/ProviderSessionDirectory.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type { - ProviderInstanceId, - ProviderDriverKind, - ProviderSessionRuntimeStatus, - RuntimeMode, - ThreadId, -} from "@t3tools/contracts"; -import * as Option from "effect/Option"; -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; - -import type { - ProviderSessionDirectoryPersistenceError, - ProviderValidationError, -} from "../Errors.ts"; - -export interface ProviderRuntimeBinding { - readonly threadId: ThreadId; - readonly provider: ProviderDriverKind; - /** - * Routing key for the configured provider instance that owns this - * session. The persistence layer promotes legacy null rows before - * exposing bindings; runtime callers must not infer this from `provider`. - */ - readonly providerInstanceId?: ProviderInstanceId; - readonly adapterKey?: string; - readonly status?: ProviderSessionRuntimeStatus; - readonly resumeCursor?: unknown | null; - readonly runtimePayload?: unknown | null; - readonly runtimeMode?: RuntimeMode; -} - -export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding { - readonly lastSeenAt: string; -} - -export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError; - -export type ProviderSessionDirectoryWriteError = - | ProviderValidationError - | ProviderSessionDirectoryPersistenceError; - -export interface ProviderSessionDirectoryShape { - readonly upsert: ( - binding: ProviderRuntimeBinding, - ) => Effect.Effect; - - readonly getProvider: ( - threadId: ThreadId, - ) => Effect.Effect; - - readonly getBinding: ( - threadId: ThreadId, - ) => Effect.Effect, ProviderSessionDirectoryReadError>; - - readonly listThreadIds: () => Effect.Effect< - ReadonlyArray, - ProviderSessionDirectoryPersistenceError - >; - - readonly listBindings: () => Effect.Effect< - ReadonlyArray, - ProviderSessionDirectoryPersistenceError - >; -} - -export class ProviderSessionDirectory extends Context.Service< - ProviderSessionDirectory, - ProviderSessionDirectoryShape ->()("t3/provider/Services/ProviderSessionDirectory") {} diff --git a/apps/server/src/provider/Services/ProviderSessionReaper.ts b/apps/server/src/provider/Services/ProviderSessionReaper.ts deleted file mode 100644 index 7c4627eca8..0000000000 --- a/apps/server/src/provider/Services/ProviderSessionReaper.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import type * as Scope from "effect/Scope"; - -export interface ProviderSessionReaperShape { - /** - * Start the background provider session reaper within the provided scope. - */ - readonly start: () => Effect.Effect; -} - -export class ProviderSessionReaper extends Context.Service< - ProviderSessionReaper, - ProviderSessionReaperShape ->()("t3/provider/Services/ProviderSessionReaper") {} diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts deleted file mode 100644 index 0aebe0ca6d..0000000000 --- a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import * as EffectAcpErrors from "effect-acp/errors"; -import { ProviderDriverKind } from "@t3tools/contracts"; - -import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts"; - -describe("AcpAdapterSupport", () => { - it("maps ACP approval decisions to permission outcomes", () => { - expect(acpPermissionOutcome("accept")).toBe("allow-once"); - expect(acpPermissionOutcome("acceptForSession")).toBe("allow-always"); - expect(acpPermissionOutcome("decline")).toBe("reject-once"); - }); - - it("maps ACP request errors to provider adapter request errors", () => { - const error = mapAcpToAdapterError( - ProviderDriverKind.make("cursor"), - "thread-1" as never, - "session/prompt", - new EffectAcpErrors.AcpRequestError({ - code: -32602, - errorMessage: "Invalid params", - }), - ); - - expect(error._tag).toBe("ProviderAdapterRequestError"); - expect(error.message).toContain("Invalid params"); - }); -}); diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.ts b/apps/server/src/provider/acp/AcpAdapterSupport.ts deleted file mode 100644 index cde110e6dd..0000000000 --- a/apps/server/src/provider/acp/AcpAdapterSupport.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { - type ProviderApprovalDecision, - type ProviderDriverKind, - type ThreadId, -} from "@t3tools/contracts"; -import * as Schema from "effect/Schema"; -import * as EffectAcpErrors from "effect-acp/errors"; - -import { - ProviderAdapterRequestError, - ProviderAdapterSessionClosedError, - type ProviderAdapterError, -} from "../Errors.ts"; -const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError); -const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError); - -export function mapAcpToAdapterError( - provider: ProviderDriverKind, - threadId: ThreadId, - method: string, - error: EffectAcpErrors.AcpError, -): ProviderAdapterError { - if (isAcpProcessExitedError(error)) { - return new ProviderAdapterSessionClosedError({ - provider, - threadId, - cause: error, - }); - } - if (isAcpRequestError(error)) { - return new ProviderAdapterRequestError({ - provider, - method, - detail: error.message, - cause: error, - }); - } - return new ProviderAdapterRequestError({ - provider, - method, - detail: error.message, - cause: error, - }); -} - -export function acpPermissionOutcome(decision: ProviderApprovalDecision): string { - switch (decision) { - case "acceptForSession": - return "allow-always"; - case "accept": - return "allow-once"; - case "decline": - default: - return "reject-once"; - } -} diff --git a/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts deleted file mode 100644 index c696a51c37..0000000000 --- a/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Test helpers for constructing a `ProviderAdapterRegistryShape` mock from a - * kind-keyed adapter map. - * - * Tests historically assembled a `registry` object with only `getByProvider` - * + `listProviders` populated. Slice D grew the shape with `getByInstance` - * and `listInstances`; this helper fills both in from a single kind-keyed - * input so individual fixtures can stay concise. - * - * Non-default instance ids (e.g. `codex_personal`) are not addressable via - * the shim returned here — the legacy test fixtures only ever had - * single-instance-per-driver data anyway. - * - * @module provider/testUtils/providerAdapterRegistryMock - */ -import { - defaultInstanceIdForDriver, - ProviderDriverKind, - type ProviderInstanceId, -} from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as PubSub from "effect/PubSub"; -import * as Record from "effect/Record"; -import * as Result from "effect/Result"; -import * as Stream from "effect/Stream"; - -import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; -import type { ProviderAdapterRegistryShape } from "../Services/ProviderAdapterRegistry.ts"; - -export type KindAdapterMap = Partial< - Record> ->; - -/** - * Build a `ProviderAdapterRegistryShape` from a kind-keyed adapter map. - * Every adapter present in the map is addressable via both the legacy - * `getByProvider(kind)` path and the new `getByInstance(id)` path (where - * `id = defaultInstanceIdForDriver(kind)`). - */ -export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapterRegistryShape => { - const byInstanceId = new Map>(); - for (const [kind, adapter] of Object.entries(adapters)) { - if (!adapter) continue; - const driverKind = ProviderDriverKind.make(kind); - byInstanceId.set(defaultInstanceIdForDriver(driverKind), adapter); - } - - const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) => { - const adapter = byInstanceId.get(instanceId); - return adapter - ? Effect.succeed(adapter) - : Effect.fail( - new ProviderUnsupportedError({ - provider: ProviderDriverKind.make(instanceId), - }), - ); - }; - - return { - getByInstance, - getInstanceInfo: (instanceId) => { - const adapter = byInstanceId.get(instanceId); - if (!adapter) { - return Effect.fail( - new ProviderUnsupportedError({ - provider: ProviderDriverKind.make(instanceId), - }), - ); - } - return Effect.succeed({ - instanceId, - driverKind: ProviderDriverKind.make(adapter.provider), - displayName: undefined, - enabled: true, - continuationIdentity: { - driverKind: ProviderDriverKind.make(adapter.provider), - continuationKey: `${adapter.provider}:instance:${instanceId}`, - }, - }); - }, - listInstances: () => Effect.succeed(Array.from(byInstanceId.keys())), - listProviders: () => - Effect.succeed( - Record.keys( - Record.filterMap(adapters, (adapter, kind) => - adapter !== undefined ? Result.succeed(kind) : Result.failVoid, - ), - ), - ), - // Static test fixtures don't reload; an empty stream is enough to - // satisfy the shape. Tests exercising hot-reload build their own - // stream via the real `ProviderInstanceRegistry`. - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }; -}; diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts deleted file mode 100644 index 74a4de594a..0000000000 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ /dev/null @@ -1,725 +0,0 @@ -import * as NodeCrypto from "node:crypto"; -import * as NodeServices from "@effect/platform-node/NodeServices"; - -import type { - EnvironmentId, - ExecutionEnvironmentDescriptor, - OrchestrationEvent, - OrchestrationProjectShell, - OrchestrationShellSnapshot, - OrchestrationThreadShell, - ProjectId, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import type { - RelayAgentActivityPublishProofPayload, - RelayAgentActivityState, -} from "@t3tools/contracts/relay"; -import { CommandId, ProviderInstanceId } from "@t3tools/contracts"; -import { RelayClientTracer } from "@t3tools/shared/relayTracing"; -import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt"; -import { describe, expect, it } from "@effect/vitest"; -import * as Deferred from "effect/Deferred"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Queue from "effect/Queue"; -import * as Stream from "effect/Stream"; -import * as Tracer from "effect/Tracer"; - -import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; -import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; -import { - OrchestrationEngineService, - type OrchestrationEngineShape, -} from "../orchestration/Services/OrchestrationEngine.ts"; -import { - ProjectionSnapshotQuery, - type ProjectionSnapshotQueryShape, -} from "../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { - RELAY_ENVIRONMENT_CREDENTIAL_SECRET, - RELAY_ISSUER_SECRET, - RELAY_URL_SECRET, - PUBLISH_AGENT_ACTIVITY_SECRET, -} from "../cloud/config.ts"; -import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts"; - -const state: RelayAgentActivityState = { - environmentId: "env" as RelayAgentActivityState["environmentId"], - threadId: "thread" as RelayAgentActivityState["threadId"], - projectTitle: "Project", - threadTitle: "Thread", - modelTitle: "gpt-5.4", - phase: "running", - headline: "Running", - updatedAt: "2026-05-25T00:00:00.000Z", - deepLink: "/threads/env/thread", -}; - -const encodeSecret = (value: string): Uint8Array => new TextEncoder().encode(value); - -function makeMemorySecretStore() { - const values = new Map(); - const store = { - get: ((name) => - Effect.sync(() => { - const value = values.get(name); - return value === undefined ? Option.none() : Option.some(Uint8Array.from(value)); - })) satisfies ServerSecretStore.ServerSecretStore["Service"]["get"], - set: ((name, value) => - Effect.sync(() => { - values.set(name, Uint8Array.from(value)); - })) satisfies ServerSecretStore.ServerSecretStore["Service"]["set"], - create: ((name, value) => - Effect.sync(() => { - values.set(name, Uint8Array.from(value)); - })) satisfies ServerSecretStore.ServerSecretStore["Service"]["create"], - getOrCreateRandom: ((name, bytes) => - Effect.sync(() => { - const existing = values.get(name); - if (existing) { - return existing; - } - const generated = new Uint8Array(bytes); - values.set(name, generated); - return generated; - })) satisfies ServerSecretStore.ServerSecretStore["Service"]["getOrCreateRandom"], - remove: ((name) => - Effect.sync(() => { - values.delete(name); - })) satisfies ServerSecretStore.ServerSecretStore["Service"]["remove"], - } satisfies ServerSecretStore.ServerSecretStore["Service"]; - return { - store, - setString: (name: string, value: string) => store.set(name, encodeSecret(value)), - }; -} - -describe.sequential("signRelayAgentActivityPublishProof", () => { - it("distinguishes pending link credentials from disabled publication", () => { - expect( - AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({ - relayConfigured: false, - publishEnabled: false, - }), - ).toBe("waiting-for-link"); - expect( - AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({ - relayConfigured: true, - publishEnabled: false, - }), - ).toBe("disabled"); - expect( - AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({ - relayConfigured: true, - publishEnabled: true, - }), - ).toBe("enabled"); - }); - - it("derives the thread id from the aggregate id for thread events without payload thread ids", () => { - const threadId = "thread-aggregate-1" as ThreadId; - const now = "2026-05-25T00:00:00.000Z"; - const event = { - type: "thread.activity-appended", - sequence: 1, - eventId: "evt-aggregate-1", - commandId: CommandId.make("cmd-1"), - aggregateKind: "thread", - aggregateId: threadId, - actor: { kind: "server" }, - payload: {}, - occurredAt: now, - } as unknown as OrchestrationEvent; - - expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId); - }); - - it("does not publish start intents, streaming content, or non-awareness activity events", () => { - const now = "2026-05-25T00:00:00.000Z"; - const base = { - sequence: 1, - eventId: "evt-1", - commandId: CommandId.make("cmd-1"), - aggregateKind: "thread", - aggregateId: "thread-1" as ThreadId, - occurredAt: now, - }; - - expect( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ - ...base, - type: "thread.message-sent", - payload: { - threadId: "thread-1" as ThreadId, - streaming: true, - }, - } as unknown as OrchestrationEvent), - ).toBe(false); - expect( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ - ...base, - type: "thread.activity-appended", - payload: { - threadId: "thread-1" as ThreadId, - activity: { - kind: "task.progress", - }, - }, - } as unknown as OrchestrationEvent), - ).toBe(false); - expect( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ - ...base, - type: "thread.activity-appended", - payload: { - threadId: "thread-1" as ThreadId, - activity: { - kind: "approval.requested", - }, - }, - } as unknown as OrchestrationEvent), - ).toBe(true); - expect( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ - ...base, - type: "thread.message-sent", - payload: { - threadId: "thread-1" as ThreadId, - streaming: false, - }, - } as unknown as OrchestrationEvent), - ).toBe(false); - expect( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ - ...base, - type: "thread.turn-start-requested", - payload: { - threadId: "thread-1" as ThreadId, - }, - } as unknown as OrchestrationEvent), - ).toBe(false); - }); - - it("deduplicates awareness state updates whose only change is their event timestamp", () => { - expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).toBe( - AgentAwarenessRelay.agentAwarenessPublishIdentity({ - ...state, - updatedAt: "2026-05-25T00:10:00.000Z", - }), - ); - expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).not.toBe( - AgentAwarenessRelay.agentAwarenessPublishIdentity({ - ...state, - phase: "completed", - headline: "Agent finished", - }), - ); - }); - - it("requires an explicit opt-in before publishing agent activity", () => { - expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled(null)).toBe(false); - expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled("false")).toBe(false); - expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled("true")).toBe(true); - }); - - it("redacts failed activity details and caps other relay detail", () => { - expect( - AgentAwarenessRelay.sanitizeRelayAgentActivityState({ - ...state, - phase: "failed", - detail: "Provider process exited with secret token.", - }), - ).toMatchObject({ - phase: "failed", - detail: "The agent run failed.", - }); - expect( - AgentAwarenessRelay.sanitizeRelayAgentActivityState({ - ...state, - detail: "x".repeat(200), - })?.detail, - ).toHaveLength(160); - }); - - it("resolves a null publish state when a thread or project snapshot disappeared", () => { - const environmentId = "env-1" as EnvironmentId; - const threadId = "thread-1" as ThreadId; - const thread = { - id: threadId, - projectId: "project-1" as ProjectId, - title: "Deleted thread", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - session: null, - latestTurn: null, - updatedAt: "2026-05-25T00:00:00.000Z", - hasPendingApprovals: false, - hasPendingUserInput: false, - } as OrchestrationThreadShell; - - expect( - AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({ - environmentId, - threadId, - thread: Option.none(), - project: Option.none(), - }), - ).toEqual({ - projectId: null, - state: null, - reason: "thread-not-found", - }); - - expect( - AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({ - environmentId, - threadId, - thread: Option.some(thread), - project: Option.none(), - }), - ).toEqual({ - projectId: "project-1", - state: null, - reason: "project-not-found", - }); - }); - - it("selects only active shell snapshot threads for startup catch-up", () => { - const now = "2026-05-25T00:00:00.000Z"; - const environmentId = "env-1" as EnvironmentId; - const projectId = "project-1" as ProjectId; - const activeThreadId = "thread-active" as ThreadId; - const idleThreadId = "thread-idle" as ThreadId; - - const baseThread = { - projectId, - title: "Run remote agent", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - session: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - } satisfies Omit; - - expect( - AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({ - environmentId, - projects: [ - { - id: projectId, - title: "T3 Code", - }, - ], - threads: [ - { - ...baseThread, - id: activeThreadId, - latestTurn: { - turnId: "turn-1" as TurnId, - state: "running", - requestedAt: now, - startedAt: now, - completedAt: null, - assistantMessageId: null, - }, - }, - { - ...baseThread, - id: idleThreadId, - }, - { - ...baseThread, - id: "thread-missing-project" as ThreadId, - projectId: "missing-project" as ProjectId, - latestTurn: { - turnId: "turn-2" as TurnId, - state: "running", - requestedAt: now, - startedAt: now, - completedAt: null, - assistantMessageId: null, - }, - }, - ], - }), - ).toEqual([activeThreadId]); - }); - - it("signs the activity publish JWT and rejects tampering", async () => { - const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const payload = { - iss: "t3-env:env", - aud: "https://relay.example.test", - sub: "env", - jti: "nonce-1", - iat: 100, - exp: 200, - environmentId: state.environmentId, - threadId: state.threadId, - state, - } satisfies RelayAgentActivityPublishProofPayload; - const proof = await Effect.runPromise( - AgentAwarenessRelay.signRelayAgentActivityPublishProof({ - privateKey: keyPair.privateKey, - payload, - }), - ); - - await expect( - Effect.runPromise( - verifyRelayJwt({ - publicKey: keyPair.publicKey, - token: proof, - typ: RELAY_ACTIVITY_PUBLISH_TYP, - issuer: "t3-env:env", - audience: "https://relay.example.test", - nowEpochSeconds: 150, - }), - ), - ).resolves.toMatchObject({ jti: "nonce-1", state }); - await expect( - Effect.runPromise( - verifyRelayJwt({ - publicKey: keyPair.publicKey, - token: (() => { - const [header, body, signature = ""] = proof.split("."); - const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`; - return `${header}.${body}.${corruptedSignature}`; - })(), - typ: RELAY_ACTIVITY_PUBLISH_TYP, - issuer: "t3-env:env", - audience: "https://relay.example.test", - nowEpochSeconds: 150, - }), - ), - ).rejects.toBeDefined(); - }); - - it.effect("keeps the orchestration listener armed until relay config is installed", () => - Effect.scoped( - Effect.gen(function* () { - const events = yield* Queue.unbounded(); - const threadShellRequested = yield* Deferred.make(); - const secrets = makeMemorySecretStore(); - const now = "2026-05-25T00:00:00.000Z"; - const projectId = "project-1" as ProjectId; - const threadId = "thread-1" as ThreadId; - const environmentId = "env-1" as EnvironmentId; - - const project = { - id: projectId, - title: "T3 Code", - workspaceRoot: "/workspace", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - } satisfies OrchestrationProjectShell; - - const thread = { - id: threadId, - projectId, - title: "Run remote agent", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: { - turnId: "turn-1" as TurnId, - state: "running", - requestedAt: now, - startedAt: now, - completedAt: null, - assistantMessageId: null, - }, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - session: { - threadId, - status: "running", - providerName: "Codex", - runtimeMode: "full-access", - activeTurnId: "turn-1" as TurnId, - lastError: null, - updatedAt: now, - }, - latestUserMessageAt: now, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - } satisfies OrchestrationThreadShell; - - const orchestrationEngine = { - readEvents: () => Stream.empty, - dispatch: () => Effect.succeed({ sequence: 1 }), - streamDomainEvents: Stream.fromQueue(events), - latestSequence: Effect.succeed(0), - } satisfies OrchestrationEngineShape; - - const snapshotQuery = { - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 1, - projects: [project], - threads: [thread], - updatedAt: now, - } satisfies OrchestrationShellSnapshot), - getThreadShellById: () => - Deferred.succeed(threadShellRequested, undefined).pipe( - Effect.ignore, - Effect.as(Option.some(thread)), - ), - getProjectShellById: () => Effect.succeed(Option.some(project)), - } as unknown as ProjectionSnapshotQueryShape; - - const descriptor = { - environmentId, - label: "Test Desktop", - platform: { - os: "darwin", - arch: "arm64", - }, - serverVersion: "0.0.0-test", - capabilities: { - repositoryIdentity: true, - }, - } satisfies ExecutionEnvironmentDescriptor; - - const layer = Layer.mergeAll( - Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store), - Layer.succeed(ServerEnvironment.ServerEnvironment, { - getEnvironmentId: Effect.succeed(environmentId), - getDescriptor: Effect.succeed(descriptor), - }), - Layer.succeed(OrchestrationEngineService, orchestrationEngine), - Layer.succeed(ProjectionSnapshotQuery, snapshotQuery), - ); - - yield* Effect.gen(function* () { - const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay; - yield* relay.start(); - yield* secrets.setString(RELAY_URL_SECRET, "http://127.0.0.1:1"); - yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential"); - yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true"); - yield* Queue.offer(events, { - type: "thread.activity-appended", - sequence: 1, - eventId: "evt-1", - commandId: CommandId.make("cmd-1"), - aggregateKind: "thread", - aggregateId: threadId, - actor: { kind: "server" }, - payload: { - threadId, - activity: { - kind: "approval.requested", - }, - }, - occurredAt: now, - } as unknown as OrchestrationEvent); - - yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds")); - }).pipe( - Effect.provide( - AgentAwarenessRelay.layer.pipe( - Layer.provide(layer), - Layer.provideMerge(NodeServices.layer), - ), - ), - ); - }), - ), - ); - - it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () => - Effect.scoped( - Effect.gen(function* () { - const originalFetch = globalThis.fetch; - const context = yield* Effect.context(); - const runFork = Effect.runForkWith(context); - const events = yield* Queue.unbounded(); - const fetchSeen = yield* Deferred.make(); - const userSpans: Array = []; - const productSpans: Array = []; - const collectingTracer = (spans: Array) => - Tracer.make({ - span: (options) => { - const span = new Tracer.NativeSpan(options); - const end = span.end.bind(span); - span.end = (endTime, exit) => { - end(endTime, exit); - spans.push(span.name); - }; - return span; - }, - }); - const secrets = makeMemorySecretStore(); - const now = "2026-05-25T00:00:00.000Z"; - const projectId = "project-1" as ProjectId; - const threadId = "thread-1" as ThreadId; - const environmentId = "env-1" as EnvironmentId; - - const project = { - id: projectId, - title: "T3 Code", - workspaceRoot: "/workspace", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - } satisfies OrchestrationProjectShell; - - const thread = { - id: threadId, - projectId, - title: "Run remote agent", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: { - turnId: "turn-1" as TurnId, - state: "running", - requestedAt: now, - startedAt: now, - completedAt: null, - assistantMessageId: null, - }, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - session: { - threadId, - status: "running", - providerName: "Codex", - runtimeMode: "full-access", - activeTurnId: "turn-1" as TurnId, - lastError: null, - updatedAt: now, - }, - latestUserMessageAt: now, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - } satisfies OrchestrationThreadShell; - - const descriptor = { - environmentId, - label: "Test Desktop", - platform: { - os: "darwin", - arch: "arm64", - }, - serverVersion: "0.0.0-test", - capabilities: { - repositoryIdentity: true, - }, - } satisfies ExecutionEnvironmentDescriptor; - - globalThis.fetch = ((input: Parameters[0]) => { - const url = new URL( - typeof input === "string" || input instanceof URL - ? input - : (input as unknown as { readonly url: string }).url, - ); - runFork(Deferred.succeed(fetchSeen, url)); - return Promise.resolve(Response.json({ ok: true, deliveries: [] })); - }) as unknown as typeof fetch; - yield* Effect.addFinalizer(() => - Effect.sync(() => { - globalThis.fetch = originalFetch; - }), - ); - - const layer = Layer.mergeAll( - Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store), - Layer.succeed(ServerEnvironment.ServerEnvironment, { - getEnvironmentId: Effect.succeed(environmentId), - getDescriptor: Effect.succeed(descriptor), - }), - Layer.succeed(OrchestrationEngineService, { - readEvents: () => Stream.empty, - dispatch: () => Effect.succeed({ sequence: 1 }), - streamDomainEvents: Stream.fromQueue(events), - latestSequence: Effect.succeed(0), - } satisfies OrchestrationEngineShape), - Layer.succeed(ProjectionSnapshotQuery, { - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 1, - projects: [project], - threads: [thread], - updatedAt: now, - } satisfies OrchestrationShellSnapshot), - getThreadShellById: () => Effect.succeed(Option.some(thread)), - getProjectShellById: () => Effect.succeed(Option.some(project)), - } as unknown as ProjectionSnapshotQueryShape), - ); - - yield* Effect.gen(function* () { - const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay; - yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test"); - yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test"); - yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential"); - yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true"); - yield* relay.start(); - yield* Queue.offer(events, { - type: "thread.activity-appended", - sequence: 1, - eventId: "evt-1", - commandId: CommandId.make("cmd-1"), - aggregateKind: "thread", - aggregateId: threadId, - actor: { kind: "server" }, - payload: { - threadId, - activity: { - kind: "approval.requested", - }, - }, - occurredAt: now, - } as unknown as OrchestrationEvent); - - const url = yield* Deferred.await(fetchSeen).pipe(Effect.timeout("2 seconds")); - expect(url.origin).toBe("https://transport.example.test"); - expect(productSpans).toContain("makePublishProof"); - expect(userSpans).not.toContain("makePublishProof"); - }).pipe( - Effect.provide( - AgentAwarenessRelay.layer.pipe( - Layer.provide(layer), - Layer.provideMerge(NodeServices.layer), - ), - ), - Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))), - Effect.withTracer(collectingTracer(userSpans)), - ); - }), - ), - ); -}); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 2a4de7eda9..af10bf631d 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -1,8 +1,8 @@ import type { EnvironmentId, - OrchestrationEvent, - OrchestrationProjectShell, - OrchestrationThreadShell, + OrchestrationV2DomainEvent, + OrchestrationV2ThreadShell, + Project, ThreadId, } from "@t3tools/contracts"; import { @@ -10,7 +10,7 @@ import { type RelayAgentActivityPublishProofPayload, type RelayAgentActivityState, } from "@t3tools/contracts/relay"; -import { projectThreadAwareness } from "@t3tools/shared/agentAwareness"; +import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import { @@ -42,9 +42,8 @@ import { } from "../cloud/config.ts"; import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; -import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts"; -import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { forkParked } from "../serverActivation.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; export class AgentAwarenessRelay extends Context.Service< AgentAwarenessRelay, @@ -54,43 +53,15 @@ export class AgentAwarenessRelay extends Context.Service< } >()("t3/relay/AgentAwarenessRelay") {} -export function eventThreadId(event: OrchestrationEvent): ThreadId | null { - const payload = event.payload as { readonly threadId?: unknown }; - if (typeof payload.threadId === "string") { - return payload.threadId as ThreadId; - } - if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") { - return event.aggregateId as ThreadId; - } - return null; +export function eventThreadId(event: OrchestrationV2DomainEvent): ThreadId { + return event.threadId; } -export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean { - switch (event.type) { - case "thread.message-sent": - case "thread.turn-start-requested": - // These events express intent to start work, but the shell still contains - // the previous turn's terminal state until the provider acknowledges the - // new turn. Publishing that snapshot can queue a fresh "Done" alert just - // before the real running state arrives. Provider lifecycle events publish - // the authoritative starting/running state instead. - return false; - case "thread.proposed-plan-upserted": - case "thread.runtime-mode-set": - case "thread.interaction-mode-set": - return false; - case "thread.activity-appended": - return ( - event.payload.activity.kind === "approval.requested" || - event.payload.activity.kind === "approval.resolved" || - event.payload.activity.kind === "provider.approval.respond.failed" || - event.payload.activity.kind === "user-input.requested" || - event.payload.activity.kind === "user-input.resolved" || - event.payload.activity.kind === "runtime.error" - ); - default: - return true; - } +export function shouldPublishAgentAwarenessEvent(_event: OrchestrationV2DomainEvent): boolean { + // Publishing is identity-deduplicated below. Watching every V2 event keeps + // this consumer correct as the shell projection evolves without duplicating + // projection-specific relevance rules here. + return true; } export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string { @@ -233,8 +204,8 @@ export function describeThreadShellForAwareness( export function resolveAgentAwarenessRelayPublishSnapshot(input: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; - readonly thread: Option.Option; - readonly project: Option.Option; + readonly thread: Option.Option; + readonly project: Option.Option; }): { readonly projectId: string | null; readonly state: RelayAgentActivityState | null; @@ -257,7 +228,7 @@ export function resolveAgentAwarenessRelayPublishSnapshot(input: { return { projectId: input.thread.value.projectId, state: sanitizeRelayAgentActivityState( - projectThreadAwareness({ + projectThreadAwarenessV2({ environmentId: input.environmentId, project: input.project.value, thread: input.thread.value, @@ -269,8 +240,8 @@ export function resolveAgentAwarenessRelayPublishSnapshot(input: { export function resolveAgentAwarenessRelayActiveThreadIds(input: { readonly environmentId: EnvironmentId; - readonly projects: ReadonlyArray>; - readonly threads: ReadonlyArray; + readonly projects: ReadonlyArray>; + readonly threads: ReadonlyArray; }): ReadonlyArray { const projectById = new Map(input.projects.map((project) => [project.id, project])); return input.threads @@ -280,7 +251,7 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: { return false; } return ( - projectThreadAwareness({ + projectThreadAwarenessV2({ environmentId: input.environmentId, project, thread, @@ -293,8 +264,8 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: { export const make = Effect.gen(function* () { const secrets = yield* ServerSecretStore.ServerSecretStore; const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; - const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; - const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService; + const threads = yield* ThreadManagement.ThreadManagementService; + const projects = yield* ProjectService.ProjectService; const crypto = yield* Crypto.Crypto; const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets); const activeSnapshotPublishedRef = yield* Ref.make(false); @@ -404,10 +375,12 @@ export const make = Effect.gen(function* () { }); }); - const thread = yield* snapshotQuery.getThreadShellById(threadId); + const shell = yield* threads.getShellSnapshot(); + const threadValue = shell.threads.find((candidate) => candidate.id === threadId); + const thread = threadValue === undefined ? Option.none() : Option.some(threadValue); const project = Option.isSome(thread) - ? yield* snapshotQuery.getProjectShellById(thread.value.projectId) - : Option.none(); + ? yield* projects.getById(thread.value.projectId) + : Option.none(); const snapshot = resolveAgentAwarenessRelayPublishSnapshot({ environmentId, threadId, @@ -525,11 +498,14 @@ export const make = Effect.gen(function* () { return false; } const environmentId = yield* serverEnvironment.getEnvironmentId; - const snapshot = yield* snapshotQuery.getShellSnapshot(); + const [projectSnapshot, shellSnapshot] = yield* Effect.all([ + projects.snapshot, + threads.getShellSnapshot(), + ]); const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({ environmentId, - projects: snapshot.projects, - threads: snapshot.threads, + projects: projectSnapshot.projects, + threads: shellSnapshot.threads, }); if (activeThreadIds.length === 0) { yield* Effect.logDebug("agent activity snapshot has no publishable threads"); @@ -605,14 +581,9 @@ export const make = Effect.gen(function* () { Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")), ), ); - yield* forkParked( - Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { + yield* Effect.forkScoped( + Stream.runForEach(threads.streamDomainEvents, (event) => { const threadId = eventThreadId(event); - if (threadId === null) { - return Effect.logDebug("agent activity publishing ignored event without thread id", { - eventType: event.type, - }); - } if (!shouldPublishAgentAwarenessEvent(event)) { return Effect.logDebug( "agent activity publishing ignored event without activity changes", diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts deleted file mode 100644 index d0bf0cb3c1..0000000000 --- a/apps/server/src/server.test.ts +++ /dev/null @@ -1,7949 +0,0 @@ -import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; -import * as NodeSocket from "@effect/platform-node/NodeSocket"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeCrypto from "node:crypto"; -import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; - -import { - AuthAccessTokenType, - AuthEnvironmentBootstrapTokenType, - AuthTokenExchangeGrantType, - CommandId, - DEFAULT_SERVER_SETTINGS, - EnvironmentId, - EventId, - GitCommandError, - KeybindingRule, - MessageId, - OpenError, - ORCHESTRATION_V2_WS_METHODS, - type OrchestrationThreadShell, - TerminalNotRunningError, - type OrchestrationCommand, - type OrchestrationEvent, - type OrchestrationV2ShellStreamItem, - type OrchestrationV2ThreadStreamItem, - ORCHESTRATION_WS_METHODS, - type ProviderKind, - ProjectId, - ProviderDriverKind, - ProviderInstanceId, - ResolvedKeybindingRule, - ThreadId, - WS_METHODS, - WsRpcGroup, - EditorId, -} from "@t3tools/contracts"; -import { - computeDpopAccessTokenHash, - computeDpopJwkThumbprint, - type DpopPublicJwk, -} from "@t3tools/shared/dpop"; -import { RELAY_HEALTH_REQUEST_TYP, RELAY_MINT_REQUEST_TYP } from "@t3tools/shared/relayJwt"; -import * as RelayClient from "@t3tools/shared/relayClient"; -import { assert, it } from "@effect/vitest"; -import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; -import { - Deferred, - Duration, - Effect, - FileSystem, - Fiber, - Layer, - ManagedRuntime, - Option, - Path, - Queue, - Schema, - Stream, -} from "effect"; -import { - FetchHttpClient, - HttpBody, - HttpClient, - HttpClientRequest, - HttpClientResponse, - HttpRouter, - HttpServer, -} from "effect/unstable/http"; -import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; -import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; -import * as Socket from "effect/unstable/socket/Socket"; -import { vi } from "vitest"; -import { readFile } from "node:fs/promises"; - -const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); - -import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; -import * as ServerConfig from "./config.ts"; -import { makeRoutesLayer } from "./server.ts"; -import { resolveAttachmentRelativePath } from "./attachmentPaths.ts"; -import { - CheckpointDiffQuery, - type CheckpointDiffQueryShape, -} from "./checkpointing/Services/CheckpointDiffQuery.ts"; -import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts"; -import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; -import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts"; -import { - GitStatusBroadcaster, - type GitStatusBroadcasterShape, -} from "./git/Services/GitStatusBroadcaster.ts"; -import { Keybindings, type KeybindingsShape } from "./keybindings.ts"; -import { Open, type OpenShape } from "./open.ts"; -import { - OrchestrationEngineService, - type OrchestrationEngineShape, -} from "./orchestration/Services/OrchestrationEngine.ts"; -import { layerUnavailable as OrchestratorV2UnavailableLayer } from "./orchestration-v2/Orchestrator.ts"; -import { layer as ThreadManagementServiceLayer } from "./orchestration-v2/ThreadManagementService.ts"; -import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; -import { - OrchestratorV2, - layerUnavailable as OrchestratorV2Unavailable, -} from "./orchestration-v2/Orchestrator.ts"; -import { CodexOrchestratorReplayHarness } from "./orchestration-v2/Adapters/CodexAdapterV2.testkit.ts"; -import { layer as idAllocatorV2Layer } from "./orchestration-v2/IdAllocator.ts"; -import { provideDeterministicTestRuntime } from "./orchestration-v2/testkit/DeterministicRuntime.ts"; -import { ORCHESTRATOR_REPLAY_FIXTURES } from "./orchestration-v2/testkit/fixtures/index.ts"; -import { materializeFixtureInput } from "./orchestration-v2/testkit/fixtures/shared.ts"; -import { makeOrchestratorV2ProviderReplayLayer } from "./orchestration-v2/testkit/ProviderReplayHarness.ts"; -import { decodeProviderReplayNdjson } from "./orchestration-v2/testkit/ReplayTranscriptNdjson.ts"; -import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; -import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; -import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts"; -import { PersistenceSqlError } from "./persistence/Errors.ts"; -import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts"; -import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts"; -import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; -import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; -import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; -import * as ServerSettings from "./serverSettings.ts"; -import * as TerminalManager from "./terminal/Manager.ts"; -import * as PreviewManager from "./preview/Manager.ts"; -import * as PortScanner from "./preview/PortScanner.ts"; -import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts"; -import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; -import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; -import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; -import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; -import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; -import { layer as mcpSessionRegistryTestLayer } from "./mcp/McpSessionRegistry.testkit.ts"; -import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; -import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; -import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; -import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; -import * as VcsDriver from "./vcs/VcsDriver.ts"; -import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; -import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; -import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; -import * as GitWorkflowService from "./git/GitWorkflowService.ts"; -import * as ReviewService from "./review/ReviewService.ts"; -import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; -import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; -import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"; -import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts"; -import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; -import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; -import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; -import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts"; -import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; -import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; -import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; -import * as Data from "effect/Data"; - -const OrchestrationV2UnavailableTestLayer = Layer.merge( - OrchestratorV2UnavailableLayer, - ThreadManagementServiceLayer.pipe(Layer.provide(OrchestratorV2UnavailableLayer)), -); - -const defaultProjectId = ProjectId.make("project-default"); -const defaultThreadId = ThreadId.make("thread-default"); -const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token"; -const defaultModelSelection = { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", -} as const; -const testEnvironmentDescriptor = { - environmentId: EnvironmentId.make("environment-test"), - label: "Test environment", - platform: { - os: "darwin" as const, - arch: "arm64" as const, - }, - serverVersion: "0.0.0-test", - capabilities: { - repositoryIdentity: true, - }, -}; -const makeDefaultOrchestrationReadModel = () => { - const now = "2026-01-01T00:00:00.000Z"; - return { - snapshotSequence: 0, - updatedAt: now, - projects: [ - { - id: defaultProjectId, - title: "Default Project", - workspaceRoot: "/tmp/default-project", - defaultModelSelection, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: [ - { - id: defaultThreadId, - projectId: defaultProjectId, - title: "Default Thread", - modelSelection: defaultModelSelection, - interactionMode: "default" as const, - runtimeMode: "full-access" as const, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestTurn: null, - messages: [], - session: null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - }, - ], - }; -}; - -const makeDefaultOrchestrationThreadShell = ( - overrides: Partial = {}, -): OrchestrationThreadShell => { - const now = "2026-01-01T00:00:00.000Z"; - return { - id: defaultThreadId, - projectId: defaultProjectId, - title: "Default Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - session: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - ...overrides, - }; -}; - -const browserOtlpTracingLayer = Layer.mergeAll( - FetchHttpClient.layer, - OtlpSerialization.layerJson, - Layer.succeed(HttpClient.TracerDisabledWhen, () => true), -); - -const makeAuthTestLayer = () => - EnvironmentAuth.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - Layer.provide(ServerSecretStore.layer), - ); - -const makeBrowserOtlpPayload = (spanName: string) => - Effect.gen(function* () { - const collector = yield* Effect.acquireRelease( - Effect.promise(async () => { - const NodeHttp = await import("node:http"); - - return await new Promise<{ - readonly close: () => Promise; - readonly firstRequest: Promise<{ - readonly body: string; - readonly contentType: string | null; - }>; - readonly url: string; - }>((resolve, reject) => { - let resolveFirstRequest: - | ((request: { readonly body: string; readonly contentType: string | null }) => void) - | undefined; - const firstRequest = new Promise<{ - readonly body: string; - readonly contentType: string | null; - }>((resolveRequest) => { - resolveFirstRequest = resolveRequest; - }); - - const server = NodeHttp.createServer((request, response) => { - const chunks: Buffer[] = []; - request.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - request.on("end", () => { - resolveFirstRequest?.({ - body: Buffer.concat(chunks).toString("utf8"), - contentType: request.headers["content-type"] ?? null, - }); - resolveFirstRequest = undefined; - response.statusCode = 204; - response.end(); - }); - }); - - server.on("error", reject); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - if (!address || typeof address === "string") { - reject(new Error("Expected TCP collector address")); - return; - } - - resolve({ - url: `http://127.0.0.1:${address.port}/v1/traces`, - firstRequest, - close: () => - new Promise((resolveClose, rejectClose) => { - server.close((error) => { - if (error) { - rejectClose(error); - return; - } - resolveClose(); - }); - }), - }); - }); - }); - }), - ({ close }) => Effect.promise(close), - ); - - const runtime = ManagedRuntime.make( - OtlpTracer.layer({ - url: collector.url, - exportInterval: "10 millis", - resource: { - serviceName: "t3-web", - attributes: { - "service.runtime": "t3-web", - "service.mode": "browser", - "service.version": "test", - }, - }, - }).pipe(Layer.provide(browserOtlpTracingLayer)), - ); - - try { - yield* Effect.promise(() => runtime.runPromise(Effect.void.pipe(Effect.withSpan(spanName)))); - } finally { - yield* Effect.promise(() => runtime.dispose()); - } - - const request = yield* Effect.raceFirst( - Effect.promise(() => collector.firstRequest).pipe(Effect.orDie), - Effect.sleep(Duration.seconds(1)).pipe( - Effect.andThen(Effect.die(new Error("Timed out waiting for OTLP trace export"))), - ), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - return JSON.parse(request.body) as OtlpTracer.TraceData; - }); - -const buildAppUnderTest = (options?: { - config?: Partial; - layers?: { - keybindings?: Partial; - providerRegistry?: Partial; - serverSettings?: Partial; - open?: Partial; - gitCore?: Partial; - gitManager?: Partial; - gitStatusBroadcaster?: Partial; - projectSetupScriptRunner?: Partial; - terminalManager?: Partial; - orchestrationEngine?: Partial; - projectionSnapshotQuery?: Partial; - checkpointDiffQuery?: Partial; - browserTraceCollector?: Partial; - serverLifecycleEvents?: Partial; - serverRuntimeStartup?: Partial; - serverEnvironment?: Partial; - repositoryIdentityResolver?: Partial; - orchestratorV2?: Layer.Layer; - }; -}) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const tempBaseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-test-" }); - const baseDir = options?.config?.baseDir ?? tempBaseDir; - const devUrl = options?.config?.devUrl; - const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl); - const config: ServerConfig.ServerConfig["Service"] = { - logLevel: "Info", - traceMinLevel: "Info", - traceTimingEnabled: true, - traceBatchWindowMs: 200, - traceMaxBytes: 10 * 1024 * 1024, - traceMaxFiles: 10, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpExportIntervalMs: 10_000, - otlpServiceName: "t3-server", - mode: "desktop", - port: 0, - host: "127.0.0.1", - cwd: process.cwd(), - baseDir, - ...derivedPaths, - staticDir: undefined, - devUrl, - devAllowedOrigins: [], - noBrowser: true, - startupPresentation: "browser", - desktopBootstrapToken: defaultDesktopBootstrapToken, - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - ...options?.config, - }; - const layerConfig = ServerConfig.layer(config); - const defaultVcsDriver: VcsDriver.VcsDriver["Service"] = { - capabilities: { - kind: "git", - supportsWorktrees: true, - supportsBookmarks: false, - supportsAtomicSnapshot: false, - supportsPushDefaultRemote: true, - ignoreClassifier: "native", - }, - execute: () => - Effect.succeed({ - exitCode: ChildProcessSpawner.ExitCode(0), - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }), - detectRepository: () => Effect.succeed(null), - isInsideWorkTree: () => Effect.succeed(false), - listWorkspaceFiles: () => - Effect.succeed({ - paths: [], - truncated: false, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - listRemotes: () => - Effect.succeed({ - remotes: [], - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths), - initRepository: () => Effect.void, - ...options?.layers?.vcsDriver, - }; - const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ - get: () => Effect.succeed(defaultVcsDriver), - detect: (input) => - defaultVcsDriver.detectRepository(input.cwd).pipe( - Effect.flatMap((repository) => - repository - ? Effect.succeed(repository) - : defaultVcsDriver.isInsideWorkTree(input.cwd).pipe( - Effect.map((isInsideWorkTree) => - isInsideWorkTree - ? { - kind: "git" as const, - rootPath: input.cwd, - metadataPath: null, - freshness: { - source: "live-local" as const, - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - } - : null, - ), - ), - ), - Effect.map((repository) => - repository - ? ({ - kind: repository.kind, - repository, - driver: defaultVcsDriver, - } satisfies VcsDriverRegistry.VcsDriverHandle) - : null, - ), - ), - resolve: (input) => - Effect.succeed({ - kind: - input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind, - repository: { - kind: - input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind, - rootPath: input.cwd, - metadataPath: null, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }, - driver: defaultVcsDriver, - }), - ...options?.layers?.vcsDriverRegistry, - }); - const gitVcsDriverLayer = Layer.mock(GitVcsDriver.GitVcsDriver)({ - ...options?.layers?.gitVcsDriver, - }); - const gitManagerLayer = Layer.mock(GitManager.GitManager)({ - ...options?.layers?.gitManager, - }); - const workspaceEntriesLayer = WorkspaceEntries.layer.pipe( - Layer.provide(WorkspacePaths.layer), - Layer.provideMerge(vcsDriverRegistryLayer), - ); - const workspaceAndProjectServicesLayer = Layer.mergeAll( - WorkspacePaths.layer, - workspaceEntriesLayer, - WorkspaceFileSystem.layer.pipe( - Layer.provide(WorkspacePaths.layer), - Layer.provide(workspaceEntriesLayer), - ), - ProjectFaviconResolver.layer.pipe( - Layer.provide(WorkspacePaths.layer), - Layer.provide(T3ProjectFileLoader.layer), - ), - ); - const gitWorkflowLayer = GitWorkflowService.layer.pipe( - Layer.provideMerge(vcsDriverRegistryLayer), - Layer.provideMerge(gitVcsDriverLayer), - Layer.provideMerge(gitManagerLayer), - ); - const vcsProvisioningLayer = VcsProvisioningService.layer.pipe( - Layer.provide(vcsDriverRegistryLayer), - ); - const reviewLayer = options?.layers?.reviewService - ? Layer.mock(ReviewService.ReviewService)({ - ...options.layers.reviewService, - }) - : ReviewService.layer.pipe( - Layer.provideMerge(gitVcsDriverLayer), - Layer.provide(vcsDriverRegistryLayer), - ); - const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster - ? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ - ...options.layers.vcsStatusBroadcaster, - }) - : VcsStatusBroadcaster.layer.pipe(Layer.provide(gitWorkflowLayer)); - const resourceTelemetryLayer = ResourceTelemetry.layer.pipe( - Layer.provide( - Layer.mergeAll( - NativeTelemetryClient.layerTest(options?.layers?.nativeTelemetryClient), - DesktopTelemetryReceiver.layerTest(options?.layers?.desktopTelemetryReceiver), - ResourceAttribution.layer, - ), - ), - ); - - const servedRoutesBaseLayer = HttpRouter.serve(makeRoutesLayer, { - disableListenLog: true, - disableLogger: true, - }).pipe( - Layer.provide( - Layer.merge( - mcpSessionRegistryTestLayer, - Layer.mock(Keybindings.Keybindings)({ - loadConfigState: Effect.succeed({ - keybindings: [], - issues: [], - }), - streamChanges: Stream.empty, - ...options?.layers?.keybindings, - }), - ), - ), - Layer.provide( - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([]), - refresh: () => Effect.succeed([]), - refreshInstance: () => Effect.succeed([]), - getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }), - ), - setProviderMaintenanceActionState: () => Effect.succeed([]), - streamChanges: Stream.empty, - ...options?.layers?.providerRegistry, - }), - ), - Layer.provide( - Layer.mock(ServerSettings.ServerSettingsService)({ - start: Effect.void, - ready: Effect.void, - getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), - updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS), - streamChanges: Stream.empty, - ...options?.layers?.serverSettings, - }), - ), - Layer.provide( - Layer.mock(ExternalLauncher.ExternalLauncher)({ - resolveAvailableEditors: () => Effect.succeed([]), - ...options?.layers?.externalLauncher, - }), - ), - Layer.provide( - Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({ - read: Effect.succeed({ - serverPid: process.pid, - readAt: TEST_EPOCH, - processCount: 0, - totalRssBytes: 0, - totalCpuPercent: 0, - processes: [], - error: Option.none(), - }), - signal: (input) => - Effect.succeed({ - pid: input.pid, - signal: input.signal, - signaled: true, - message: Option.none(), - }), - }), - ), - Layer.provide( - Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({ - readHistory: (input) => - Effect.succeed({ - readAt: TEST_EPOCH, - windowMs: input.windowMs, - bucketMs: input.bucketMs, - sampleIntervalMs: 5_000, - retainedSampleCount: 0, - totalCpuSecondsApprox: 0, - buckets: [], - topProcesses: [], - error: Option.none(), - }), - }), - ), - Layer.provide( - Layer.mock(TraceDiagnostics.TraceDiagnostics)({ - read: () => - Effect.succeed({ - traceFilePath: "", - scannedFilePaths: [], - readAt: TEST_EPOCH, - recordCount: 0, - parseErrorCount: 0, - firstSpanAt: Option.none(), - lastSpanAt: Option.none(), - failureCount: 0, - interruptionCount: 0, - slowSpanThresholdMs: 1_000, - slowSpanCount: 0, - logLevelCounts: {}, - topSpansByCount: [], - slowestSpans: [], - commonFailures: [], - latestFailures: [], - latestWarningAndErrorLogs: [], - partialFailure: Option.none(), - error: Option.none(), - }), - }), - ), - Layer.provide(gitManagerLayer), - Layer.provide(gitVcsDriverLayer), - Layer.provide(gitWorkflowLayer), - Layer.provide(reviewLayer), - Layer.provide(vcsProvisioningLayer), - Layer.provide( - Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({ - ...options?.layers?.sourceControlRepositoryService, - }), - ), - Layer.provideMerge(vcsStatusBroadcasterLayer), - Layer.provide( - Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ - runForThread: () => Effect.succeed({ status: "no-script" as const }), - ...options?.layers?.projectSetupScriptRunner, - }), - ), - Layer.provide( - Layer.mergeAll( - Layer.mock(TerminalManager)({ - ...options?.layers?.terminalManager, - }), - Layer.mock(PreviewManager.PreviewManager)({ - open: () => Effect.die("PreviewManager not stubbed in this test"), - navigate: () => Effect.die("PreviewManager not stubbed in this test"), - resize: () => Effect.die("PreviewManager not stubbed in this test"), - reportStatus: () => Effect.void, - refresh: () => Effect.void, - close: () => Effect.void, - list: () => Effect.succeed({ sessions: [], serverEpoch: "test-server", revision: 0 }), - events: Stream.empty, - subscribeEvents: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }), - Layer.mock(PortScanner.PortDiscovery)({ - scan: () => Effect.succeed([]), - subscribe: () => Effect.void, - retain: Effect.void, - registerTerminalProcesses: () => Effect.void, - unregisterTerminal: () => Effect.void, - }), - ), - ), - Layer.provide( - Layer.mock(OrchestrationEngine.OrchestrationEngineService)({ - readEvents: () => Stream.empty, - dispatch: () => Effect.succeed({ sequence: 0 }), - streamDomainEvents: Stream.empty, - latestSequence: Effect.succeed(0), - ...options?.layers?.orchestrationEngine, - }), - ), - Layer.provide( - Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({ - getCommandReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()), - getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()), - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 0, - projects: [], - threads: [], - updatedAt: "1970-01-01T00:00:00.000Z", - }), - getArchivedShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 0, - projects: [], - threads: [], - updatedAt: "1970-01-01T00:00:00.000Z", - }), - searchThreads: () => Effect.succeed({ matches: [] }), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getProjectShellById: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - ...options?.layers?.projectionSnapshotQuery, - }), - ), - Layer.provide(options?.layers?.orchestratorV2 ?? OrchestratorV2Unavailable), - Layer.provide( - Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({ - getTurnDiff: () => - Effect.succeed({ - threadId: defaultThreadId, - fromTurnCount: 0, - toTurnCount: 0, - diff: "", - }), - getFullThreadDiff: () => - Effect.succeed({ - threadId: defaultThreadId, - fromTurnCount: 0, - toTurnCount: 0, - diff: "", - }), - ...options?.layers?.checkpointDiffQuery, - }), - ), - ); - - const servedRoutesLayer = servedRoutesBaseLayer.pipe( - Layer.provide(OrchestrationV2UnavailableTestLayer), - ); - - const appLayer = servedRoutesLayer.pipe( - Layer.provide(resourceTelemetryLayer), - Layer.provide( - Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({ - record: () => Effect.void, - ...options?.layers?.browserTraceCollector, - }), - ), - Layer.provide( - Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ - publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }), - snapshot: Effect.succeed({ sequence: 0, events: [] }), - stream: Stream.empty, - ...options?.layers?.serverLifecycleEvents, - }), - ), - Layer.provide( - Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({ - awaitCommandReady: Effect.void, - markHttpListening: Effect.void, - enqueueCommand: (effect) => effect, - ...options?.layers?.serverRuntimeStartup, - }), - ), - Layer.provide( - Layer.mock(BackgroundPolicy.BackgroundPolicy)({ - reportClientActivity: () => Effect.void, - removeRpcClient: () => Effect.void, - reportHostPowerState: () => Effect.void, - snapshot: Effect.succeed({ - hostPower: { - source: "unknown", - idle: "unknown", - idleSeconds: null, - locked: "unknown", - suspended: false, - onBattery: "unknown", - lowPowerMode: "unknown", - thermalState: "unknown", - stale: true, - updatedAt: TEST_EPOCH, - }, - leases: [], - activeForegroundLeaseCount: 0, - activeScopeKeys: [], - shouldRunOpportunisticWork: false, - updatedAt: TEST_EPOCH, - }), - streamChanges: Stream.empty, - subscribe: Effect.succeed({ - latest: { - hostPower: { - source: "unknown", - idle: "unknown", - idleSeconds: null, - locked: "unknown", - suspended: false, - onBattery: "unknown", - lowPowerMode: "unknown", - thermalState: "unknown", - stale: true, - updatedAt: TEST_EPOCH, - }, - leases: [], - activeForegroundLeaseCount: 0, - activeScopeKeys: [], - shouldRunOpportunisticWork: false, - updatedAt: TEST_EPOCH, - }, - changes: Stream.empty, - }), - hasDemand: () => Effect.succeed(false), - shouldRunScopeWork: () => Effect.succeed(false), - shouldRunOpportunisticWork: Effect.succeed(false), - }), - ), - Layer.provide( - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId), - getDescriptor: Effect.succeed(testEnvironmentDescriptor), - ...options?.layers?.serverEnvironment, - }), - ), - Layer.provide( - Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ - resolve: () => Effect.succeed(null), - ...options?.layers?.repositoryIdentityResolver, - }), - ), - Layer.provide( - Layer.succeed( - CloudManagedEndpointRuntime.CloudManagedEndpointRuntime, - CloudManagedEndpointRuntime.CloudManagedEndpointRuntime.of({ - applyConfig: () => Effect.succeed({ status: "disabled" }), - ...options?.layers?.cloudManagedEndpointRuntime, - }), - ), - ), - Layer.provide( - Layer.succeed( - RelayClient.RelayClient, - RelayClient.RelayClient.of({ - resolve: Effect.succeed({ - status: "missing", - version: RelayClient.CLOUDFLARED_VERSION, - }), - install: Effect.die("unused relay-client install"), - installWithProgress: () => Effect.die("unused relay-client install"), - ...options?.layers?.relayClient, - }), - ), - ), - Layer.provide( - Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({ - get: Effect.die(new Error("Unexpected T3 Connect CLI authorization request.")), - getExisting: Effect.succeed(Option.none()), - hasCredential: Effect.succeed(false), - clear: Effect.void, - ...options?.layers?.cloudCliTokenManager, - }), - ), - Layer.provideMerge(makeAuthTestLayer()), - Layer.provideMerge(ServerSecretStore.layer), - Layer.provide(workspaceAndProjectServicesLayer), - Layer.provideMerge(FetchHttpClient.layer), - Layer.provide(layerConfig), - ); - - yield* Layer.build(appLayer); - return config; - }); - -const parseSessionCookieFromWsUrl = ( - wsUrl: string, -): { readonly cookie: string | null; readonly url: string } => { - const next = new URL(wsUrl); - const cookie = next.hash.startsWith("#cookie=") - ? decodeURIComponent(next.hash.slice("#cookie=".length)) - : null; - next.hash = ""; - return { - cookie, - url: next.toString(), - }; -}; - -const wsRpcProtocolLayer = (wsUrl: string) => { - const { cookie, url } = parseSessionCookieFromWsUrl(wsUrl); - const webSocketConstructorLayer = Layer.succeed( - Socket.WebSocketConstructor, - (socketUrl, protocols) => - new NodeSocket.NodeWS.WebSocket( - socketUrl, - protocols, - cookie ? { headers: { cookie } } : undefined, - ) as unknown as globalThis.WebSocket, - ); - - return RpcClient.layerProtocolSocket().pipe( - Layer.provide(Socket.layerWebSocket(url).pipe(Layer.provide(webSocketConstructorLayer))), - Layer.provide(RpcSerialization.layerJson), - ); -}; - -const makeWsRpcClient = RpcClient.make(WsRpcGroup); -type WsRpcClient = - typeof makeWsRpcClient extends Effect.Effect ? Client : never; - -class WsRpcTestTimeoutError extends Schema.TaggedErrorClass()( - "WsRpcTestTimeoutError", - { - label: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return `Timed out waiting for ${this.label}.`; - } -} - -const withWsRpcClient = ( - wsUrl: string, - f: (client: WsRpcClient) => Effect.Effect, -) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl))); - -const ORCHESTRATION_V2_REPLAY_HARNESSES = [CodexOrchestratorReplayHarness] as const; - -function orchestrationV2ReplayHarnessFor(provider: ProviderKind) { - const harness = ORCHESTRATION_V2_REPLAY_HARNESSES.find( - (candidate) => candidate.provider === provider, - ); - if (!harness) { - throw new Error(`No orchestration V2 replay harness registered for ${provider}.`); - } - return harness; -} - -const readProviderReplayTranscript = (file: URL) => - Effect.promise(() => readFile(file, "utf8")).pipe(Effect.flatMap(decodeProviderReplayNdjson)); - -const takeWsItem = (queue: Queue.Queue, label: string) => - Queue.take(queue).pipe( - Effect.raceFirst( - Effect.tryPromise({ - try: () => - new Promise((_resolve, reject) => { - setTimeout(() => reject(new WsRpcTestTimeoutError({ label })), 5_000); - }), - catch: (cause) => - Schema.is(WsRpcTestTimeoutError)(cause) - ? cause - : new WsRpcTestTimeoutError({ label, cause }), - }), - ), - ); - -const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => { - const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url); - const next = new URL(url, "http://localhost"); - next.hash = `cookie=${encodeURIComponent(sessionCookieHeader)}`; - return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`; -}; - -const getHttpServerUrl = (pathname = "") => - Effect.gen(function* () { - const server = yield* HttpServer.HttpServer; - const address = server.address as HttpServer.TcpAddress; - return `http://127.0.0.1:${address.port}${pathname}`; - }); - -const bootstrapBrowserSession = ( - credential = defaultDesktopBootstrapToken, - options?: { - readonly headers?: Record; - }, -) => - Effect.gen(function* () { - const bootstrapUrl = yield* getHttpServerUrl("/api/auth/browser-session"); - const response = yield* fetchEffect(bootstrapUrl, { - method: "POST", - headers: { - "content-type": "application/json", - ...options?.headers, - }, - body: jsonRequestBody({ - credential, - }), - }); - const body = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod: string; - readonly expiresAt: string; - }>(response); - return { - response, - body, - cookie: response.headers["set-cookie"], - }; - }); - -const exchangeAccessToken = ( - credential = defaultDesktopBootstrapToken, - options?: { - readonly headers?: Record; - readonly scope?: string; - readonly clientMetadata?: { - readonly label?: string; - readonly deviceType?: string; - readonly os?: string; - }; - }, -) => - Effect.gen(function* () { - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const response = yield* fetchEffect(tokenUrl, { - method: "POST", - headers: { - "content-type": "application/x-www-form-urlencoded", - ...options?.headers, - }, - body: new URLSearchParams({ - grant_type: AuthTokenExchangeGrantType, - subject_token: credential, - subject_token_type: AuthEnvironmentBootstrapTokenType, - requested_token_type: AuthAccessTokenType, - scope: - options?.scope ?? - "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", - ...(options?.clientMetadata?.label ? { client_label: options.clientMetadata.label } : {}), - ...(options?.clientMetadata?.deviceType - ? { client_device_type: options.clientMetadata.deviceType } - : {}), - ...(options?.clientMetadata?.os ? { client_os: options.clientMetadata.os } : {}), - }).toString(), - }); - const body = yield* responseJsonEffect<{ - readonly access_token?: string; - readonly issued_token_type?: string; - readonly token_type?: string; - readonly expires_in?: number; - readonly scope?: string; - readonly _tag?: string; - readonly code?: string; - readonly reason?: string; - readonly traceId?: string; - }>(response); - return { - response, - body, - }; - }); - -const makeDpopProof = (input: { - readonly method: string; - readonly url: string; - readonly iat: number; - readonly accessToken?: string; - readonly jti?: string; - readonly privateKey?: NodeCrypto.KeyObject; - readonly publicJwk?: DpopPublicJwk; -}) => { - const keyPair = - input.privateKey && input.publicJwk - ? { privateKey: input.privateKey, publicJwk: input.publicJwk } - : (() => { - const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { - namedCurve: "P-256", - }); - return { privateKey, publicJwk: publicKey.export({ format: "jwk" }) as DpopPublicJwk }; - })(); - const header = Buffer.from( - JSON.stringify({ - typ: "dpop+jwt", - alg: "ES256", - jwk: keyPair.publicJwk, - }), - ).toString("base64url"); - const payload = Buffer.from( - JSON.stringify({ - htm: input.method, - htu: input.url, - jti: input.jti ?? "proof-1", - iat: input.iat, - ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}), - }), - ).toString("base64url"); - const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), { - key: keyPair.privateKey, - dsaEncoding: "ieee-p1363", - }).toString("base64url"); - return { - proof: `${header}.${payload}.${signature}`, - thumbprint: computeDpopJwkThumbprint(keyPair.publicJwk), - privateKey: keyPair.privateKey, - publicJwk: keyPair.publicJwk, - }; -}; - -const makeCloudMintCredentialRequest = (input: { - readonly privateKey: string; - readonly environmentId: EnvironmentId; - readonly clientProofKeyThumbprint: string; - readonly issuer?: string; - readonly audience?: string; - readonly subject?: string; - readonly jti?: string; - readonly nonce: string; - readonly issuedAt: string; - readonly expiresAt: string; - readonly scope?: ReadonlyArray<"environment:connect">; -}) => { - const payload = { - iss: input.issuer ?? "https://relay.example.test", - aud: input.audience ?? `t3-env:${input.environmentId}`, - sub: input.subject ?? "user_123", - jti: input.jti ?? "cloud-mint-jti-1", - environmentId: input.environmentId, - clientProofKeyThumbprint: input.clientProofKeyThumbprint, - cnf: { - jkt: input.clientProofKeyThumbprint, - }, - nonce: input.nonce, - iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000), - exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000), - scope: input.scope ?? ["environment:connect"], - } as const; - const header = Buffer.from( - JSON.stringify({ alg: "EdDSA", typ: RELAY_MINT_REQUEST_TYP }), - ).toString("base64url"); - const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); - const signingInput = `${header}.${encodedPayload}`; - return { - proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`, - }; -}; - -const makeCloudEnvironmentHealthRequest = (input: { - readonly privateKey: string; - readonly environmentId: EnvironmentId; - readonly issuer?: string; - readonly audience?: string; - readonly subject?: string; - readonly jti?: string; - readonly nonce: string; - readonly issuedAt: string; - readonly expiresAt: string; - readonly scope?: ReadonlyArray<"environment:status">; -}) => { - const payload = { - iss: input.issuer ?? "https://relay.example.test", - aud: input.audience ?? `t3-env:${input.environmentId}`, - sub: input.subject ?? "user_123", - jti: input.jti ?? "cloud-health-jti-1", - environmentId: input.environmentId, - nonce: input.nonce, - iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000), - exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000), - scope: input.scope ?? ["environment:status"], - } as const; - const header = Buffer.from( - JSON.stringify({ alg: "EdDSA", typ: RELAY_HEALTH_REQUEST_TYP }), - ).toString("base64url"); - const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); - const signingInput = `${header}.${encodedPayload}`; - return { - proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`, - }; -}; - -const decodeCompactJwtPayload = (token: string): A => { - const encodedPayload = token.split(".")[1]; - if (!encodedPayload) { - throw new Error("JWT does not contain a payload."); - } - return JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8")) as A; -}; - -class AuthenticationGetterError extends Data.TaggedError("AuthenticationGetterError")<{ - readonly message: string; -}> {} - -class TestHttpRequestError extends Data.TaggedError("TestHttpRequestError")<{ - readonly cause: unknown; -}> {} - -const testRequestUrl = (input: Parameters[0]): string => { - const value = input.toString(); - if (!/^https?:\/\//i.test(value)) { - return value; - } - const url = new URL(value); - return `${url.pathname}${url.search}`; -}; - -const fetchEffect = (input: Parameters[0], init?: RequestInit) => { - const request = HttpClientRequest.make((init?.method ?? "GET") as "GET" | "POST")( - testRequestUrl(input), - { - headers: init?.headers as Record | undefined, - }, - ).pipe( - typeof init?.body === "string" - ? HttpClientRequest.bodyText( - init.body, - (init.headers as Record | undefined)?.["content-type"] ?? - "application/json", - ) - : (request) => request, - ); - const effect = HttpClient.execute(request); - return ( - init?.redirect === "manual" - ? effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })) - : effect - ).pipe(Effect.mapError((cause) => new TestHttpRequestError({ cause }))); -}; - -const jsonRequestBody = (value: unknown): string => { - return JSON.stringify(value); -}; - -const responseJsonEffect = (response: HttpClientResponse.HttpClientResponse) => - response.json.pipe( - Effect.map((json) => json as A), - Effect.mapError((cause) => new TestHttpRequestError({ cause })), - ); - -const responseOk = (response: HttpClientResponse.HttpClientResponse) => - response.status >= 200 && response.status < 300; - -const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) => - Effect.gen(function* () { - const { response, cookie } = yield* bootstrapBrowserSession(credential); - if (!responseOk(response)) { - return yield* new AuthenticationGetterError({ - message: `Expected bootstrap session response to succeed, got ${response.status}`, - }); - } - - if (!cookie) { - return yield* new AuthenticationGetterError({ - message: "Expected bootstrap session response to set a cookie.", - }); - } - - return cookie.split(";")[0] ?? cookie; - }); - -const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) => - Effect.gen(function* () { - const { response, body } = yield* exchangeAccessToken(credential); - if (!responseOk(response)) { - return yield* new AuthenticationGetterError({ - message: `Expected bearer bootstrap response to succeed, got ${response.status}`, - }); - } - - if (!body.access_token) { - return yield* new AuthenticationGetterError({ - message: "Expected token exchange response to include an access token.", - }); - } - - return body.access_token; - }); - -const extractSessionTokenFromSetCookie = (cookieHeader: string): string => { - const [nameValue] = cookieHeader.split(";", 1); - const token = nameValue?.split("=", 2)[1]; - if (!token) { - throw new Error("Expected session cookie header to contain a token value."); - } - return token; -}; - -const splitHeaderTokens = (value: string | null | undefined) => - (value ?? "") - .split(",") - .map((token) => token.trim()) - .filter((token) => token.length > 0) - .toSorted(); - -const assertBrowserApiCorsResponseHeaders = ( - headers: Readonly>, - options?: { - readonly origin?: string; - readonly credentials?: boolean; - }, -) => { - assert.equal(headers["access-control-allow-origin"], options?.origin ?? "*"); - assert.equal( - headers["access-control-allow-credentials"], - options?.credentials ? "true" : undefined, - ); -}; - -const assertBrowserApiCorsPreflightHeaders = ( - headers: Readonly>, - options?: { - readonly origin?: string; - readonly credentials?: boolean; - }, -) => { - assertBrowserApiCorsResponseHeaders(headers, options); - assert.deepEqual(splitHeaderTokens(headers["access-control-allow-methods"] ?? null), [ - "GET", - "OPTIONS", - "POST", - ]); - assert.deepEqual(splitHeaderTokens(headers["access-control-allow-headers"]), [ - "authorization", - "b3", - "content-type", - "dpop", - "traceparent", - ]); -}; -const crossOriginClientOrigin = "http://remote-client.test:3773"; - -const getWsServerUrl = ( - pathname = "", - options?: { authenticated?: boolean; credential?: string }, -) => - Effect.gen(function* () { - const server = yield* HttpServer.HttpServer; - const address = server.address as HttpServer.TcpAddress; - const baseUrl = `ws://127.0.0.1:${address.port}${pathname}`; - if (options?.authenticated === false) { - return baseUrl; - } - return appendSessionCookieToWsUrl( - baseUrl, - yield* getAuthenticatedSessionCookieHeader(options?.credential), - ); - }); - -it.layer(NodeServices.layer)("server router seam", (it) => { - it.effect("parks HTTP ingress until command readiness", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-gate-" }); - yield* fileSystem.writeFileString(path.join(staticDir, "index.html"), "ready"); - const entered = yield* Deferred.make(); - const ready = yield* Deferred.make(); - const completed = yield* Deferred.make(); - - yield* buildAppUnderTest({ - config: { staticDir }, - layers: { - serverRuntimeStartup: { - awaitCommandReady: Deferred.succeed(entered, undefined).pipe( - Effect.andThen(Deferred.await(ready)), - ), - }, - }, - }); - const request = yield* HttpClient.get("/").pipe( - Effect.tap(() => Deferred.succeed(completed, undefined)), - Effect.forkChild, - ); - yield* Deferred.await(entered); - assert.isFalse(yield* Deferred.isDone(completed)); - - yield* Deferred.succeed(ready, undefined); - assert.equal((yield* Fiber.join(request)).status, 200); - assert.isTrue(yield* Deferred.isDone(completed)); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves static index content for GET / when staticDir is configured", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-static-" }); - const indexPath = path.join(staticDir, "index.html"); - yield* fileSystem.writeFileString(indexPath, "router-static-ok"); - - yield* buildAppUnderTest({ config: { staticDir } }); - - const response = yield* HttpClient.get("/"); - assert.equal(response.status, 200); - assert.include(yield* response.text, "router-static-ok"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("redirects to dev URL when configured", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { devUrl: new URL("http://127.0.0.1:5173") }, - }); - - const url = yield* getHttpServerUrl("/foo/bar?token=test-token"); - const response = yield* fetchEffect(url, { redirect: "manual" }); - - assert.equal(response.status, 302); - assert.equal(response.headers.location, "http://127.0.0.1:5173/foo/bar?token=test-token"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves the public environment descriptor without requiring auth", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const url = yield* getHttpServerUrl("/.well-known/t3/environment"); - const response = yield* fetchEffect(url); - const body = yield* responseJsonEffect(response); - - assert.equal(response.status, 200); - assert.deepEqual(body, testEnvironmentDescriptor); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("compresses large JSON responses through the composed routes", () => - Effect.gen(function* () { - const descriptor = { - ...testEnvironmentDescriptor, - label: "Test environment".repeat(100), - }; - yield* buildAppUnderTest({ - layers: { - serverEnvironment: { - getDescriptor: Effect.succeed(descriptor), - }, - }, - }); - - const url = yield* getHttpServerUrl("/.well-known/t3/environment"); - const response = yield* fetchEffect(url, { - headers: { - "accept-encoding": "gzip", - }, - }); - const body = yield* responseJsonEffect(response); - - assert.equal(response.status, 200); - assert.equal(response.headers["content-encoding"], "gzip"); - assert.equal(response.headers.vary, "Accept-Encoding"); - assert.deepEqual(body, descriptor); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("includes CORS headers on public environment descriptor responses", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const url = yield* getHttpServerUrl("/.well-known/t3/environment"); - const response = yield* fetchEffect(url, { - headers: { - origin: crossOriginClientOrigin, - }, - }); - const body = yield* responseJsonEffect(response); - - assert.equal(response.status, 200); - assertBrowserApiCorsResponseHeaders(response.headers); - assert.deepEqual(body, testEnvironmentDescriptor); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("reports unauthenticated session state without requiring auth", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const url = yield* getHttpServerUrl("/api/auth/session"); - const response = yield* fetchEffect(url); - const body = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly auth: { - readonly policy: string; - readonly bootstrapMethods: ReadonlyArray; - readonly sessionMethods: ReadonlyArray; - readonly sessionCookieName: string; - }; - }>(response); - - assert.equal(response.status, 200); - assert.equal(body.authenticated, false); - assert.equal(body.auth.policy, "desktop-managed-local"); - assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]); - assert.deepEqual(body.auth.sessionMethods, [ - "browser-session-cookie", - "bearer-access-token", - "dpop-access-token", - ]); - // Desktop, so port-scoped: instances scan for a free port and share - // 127.0.0.1, and cookies are not scoped by port. - assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_")); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("bootstraps a browser session and authenticates the session endpoint via cookie", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { - response: bootstrapResponse, - body: bootstrapBody, - cookie: setCookie, - } = yield* bootstrapBrowserSession(); - - assert.equal(bootstrapResponse.status, 200); - assert.equal(bootstrapBody.authenticated, true); - assert.equal(bootstrapBody.sessionMethod, "browser-session-cookie"); - assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken); - assert.isDefined(setCookie); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const sessionResponse = yield* fetchEffect(sessionUrl, { - headers: { - cookie: setCookie?.split(";")[0] ?? "", - }, - }); - const sessionBody = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - }>(sessionResponse); - - assert.equal(sessionResponse.status, 200); - assert.equal(sessionBody.authenticated, true); - assert.equal(sessionBody.sessionMethod, "browser-session-cookie"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("exchanges a bootstrap grant for a scoped bearer access token", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { response: tokenResponse, body: tokenBody } = yield* exchangeAccessToken(); - - assert.equal(tokenResponse.status, 200); - assert.equal(tokenBody.issued_token_type, AuthAccessTokenType); - assert.equal(tokenBody.token_type, "Bearer"); - assert.equal( - tokenBody.scope, - "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", - ); - assert.equal(typeof tokenBody.access_token, "string"); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const sessionResponse = yield* fetchEffect(sessionUrl, { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - }); - const sessionBody = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - readonly scopes?: ReadonlyArray; - }>(sessionResponse); - - assert.equal(sessionResponse.status, 200); - assert.equal(sessionBody.authenticated, true); - assert.equal(sessionBody.sessionMethod, "bearer-access-token"); - assert.deepEqual(sessionBody.scopes, [ - "orchestration:read", - "orchestration:operate", - "terminal:operate", - "review:write", - "relay:read", - "access:read", - "access:write", - "relay:write", - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("persists token exchange client display metadata for authorized-client listings", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - - const { response } = yield* exchangeAccessToken(pairingBody.credential, { - headers: { - "user-agent": "undici", - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - clientMetadata: { - label: "T3 Code Mobile", - deviceType: "mobile", - os: "iOS", - }, - }); - - const clientsResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clients = (yield* clientsResponse.json) as ReadonlyArray<{ - readonly current: boolean; - readonly client: { - readonly label?: string; - readonly deviceType: string; - readonly ipAddress?: string; - readonly os?: string; - readonly userAgent?: string; - }; - }>; - const mobileClient = clients.find((client) => !client.current); - - assert.equal(pairingResponse.status, 200); - assert.equal(response.status, 200); - assert.equal(clientsResponse.status, 200); - assert.deepInclude(mobileClient?.client, { - label: "T3 Code Mobile", - deviceType: "mobile", - os: "iOS", - ipAddress: "127.0.0.1", - userAgent: "undici", - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "exchanges a bootstrap credential for a DPoP-bound access token without bearer downgrade", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { cookie: ownerCookie }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { readonly credential: string }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const now = yield* DateTime.now; - const tokenProof = makeDpopProof({ - method: "POST", - url: tokenUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - jti: "token-exchange-proof", - }); - const tokenResponse = yield* fetchEffect(tokenUrl, { - method: "POST", - headers: { - "content-type": "application/x-www-form-urlencoded", - dpop: tokenProof.proof, - }, - body: new URLSearchParams({ - grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", - subject_token: credential.credential, - subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap", - requested_token_type: "urn:ietf:params:oauth:token-type:access_token", - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }).toString(), - }); - const token = yield* responseJsonEffect<{ - readonly access_token: string; - readonly token_type: string; - }>(tokenResponse); - - assert.equal(tokenResponse.status, 200); - assert.equal(tokenResponse.headers["cache-control"], "no-store"); - assert.equal(token.token_type, "DPoP"); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const bearerResponse = yield* fetchEffect(sessionUrl, { - headers: { authorization: `Bearer ${token.access_token}` }, - }); - const bearerState = yield* responseJsonEffect<{ readonly authenticated: boolean }>( - bearerResponse, - ); - assert.equal(bearerState.authenticated, false); - - const sessionProof = makeDpopProof({ - method: "GET", - url: sessionUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - jti: "session-proof", - accessToken: token.access_token, - privateKey: tokenProof.privateKey, - publicJwk: tokenProof.publicJwk, - }); - const dpopResponse = yield* fetchEffect(sessionUrl, { - headers: { - authorization: `DPoP ${token.access_token}`, - dpop: sessionProof.proof, - }, - }); - const dpopState = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - }>(dpopResponse); - assert.equal(dpopState.authenticated, true); - assert.equal(dpopState.sessionMethod, "dpop-access-token"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects replayed DPoP proofs across token exchanges", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const firstCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const firstCredential = (yield* firstCredentialResponse.json) as { - readonly credential: string; - }; - const secondCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const secondCredential = (yield* secondCredentialResponse.json) as { - readonly credential: string; - }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const now = yield* DateTime.now; - const dpop = makeDpopProof({ - method: "POST", - url: tokenUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - }); - - const firstBootstrap = yield* exchangeAccessToken(firstCredential.credential, { - headers: { - dpop: dpop.proof, - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - const replayBootstrap = yield* exchangeAccessToken(secondCredential.credential, { - headers: { - dpop: dpop.proof, - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - - assert.equal(firstBootstrap.response.status, 200); - assert.equal(replayBootstrap.response.status, 401); - assert.equal(replayBootstrap.body._tag, "EnvironmentAuthInvalidError"); - assert.equal(replayBootstrap.body.code, "auth_invalid"); - assert.equal(replayBootstrap.body.reason, "invalid_credential"); - assert.equal(typeof replayBootstrap.body.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("ignores forwarded host headers when validating token exchange DPoP URLs", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { - readonly credential: string; - }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const now = yield* DateTime.now; - const dpop = makeDpopProof({ - method: "POST", - url: tokenUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - }); - - const bootstrap = yield* exchangeAccessToken(credential.credential, { - headers: { - dpop: dpop.proof, - "x-forwarded-host": "environment.example.test", - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - - assert.equal(bootstrap.response.status, 200); - assert.equal(bootstrap.body.token_type, "DPoP"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects token exchange DPoP proofs bound to spoofed forwarded hosts", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { - readonly credential: string; - }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const spoofedUrl = new URL(tokenUrl); - spoofedUrl.hostname = "environment.example.test"; - const now = yield* DateTime.now; - const dpop = makeDpopProof({ - method: "POST", - url: spoofedUrl.href, - iat: Math.floor(now.epochMilliseconds / 1_000), - }); - - const bootstrap = yield* exchangeAccessToken(credential.credential, { - headers: { - dpop: dpop.proof, - "x-forwarded-host": spoofedUrl.host, - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - - assert.equal(bootstrap.response.status, 401); - assert.equal(bootstrap.body._tag, "EnvironmentAuthInvalidError"); - assert.equal(bootstrap.body.code, "auth_invalid"); - assert.equal(bootstrap.body.reason, "invalid_credential"); - assert.equal(typeof bootstrap.body.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs for non-loopback managed endpoint origins", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const linkProofResponse = yield* fetchEffect(linkProofUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "192.168.1.42", - localHttpPort: 3773, - }, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(linkProofResponse); - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs for unsupported endpoint providers", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* fetchEffect(linkProofUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: linkProofUrl.replace("/api/connect/link-proof", ""), - wsBaseUrl: linkProofUrl - .replace("http://", "ws://") - .replace("/api/connect/link-proof", "/ws"), - // "manual" and "cloudflare_tunnel" are supported; "t3_relay" is not. - providerKind: "t3_relay", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(linkProofResponse); - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs requested through a public managed endpoint", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - host: "environment.example.test", - "x-forwarded-host": "environment.example.test", - "x-forwarded-proto": "https", - }, - body: HttpBody.text( - jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - "application/json", - ), - }); - const body = (yield* linkProofResponse.json) as { - readonly _tag?: string; - readonly message?: string; - }; - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "rejects cloud link proofs when a public request spoofs loopback forwarded headers", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - host: "environment.example.test", - "x-forwarded-host": `127.0.0.1:${serverPort}`, - "x-forwarded-proto": "http", - }, - body: HttpBody.text( - jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - "application/json", - ), - }); - const body = (yield* linkProofResponse.json) as { - readonly _tag?: string; - readonly message?: string; - }; - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs with malformed forwarded request hosts", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - host: "bad host", - "x-forwarded-host": "bad host", - "x-forwarded-proto": "https", - }, - body: HttpBody.text( - jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - "application/json", - ), - }); - const body = (yield* linkProofResponse.json) as { - readonly _tag?: string; - readonly message?: string; - }; - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects local cloud link proofs for a different loopback port", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* fetchEffect(linkProofUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort === 65_535 ? serverPort - 1 : serverPort + 1, - }, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(linkProofResponse); - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows standard clients to read managed relay configuration state", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { cookie: ownerCookie }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { readonly credential: string }; - const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential); - const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); - const response = yield* fetchEffect(linkStateUrl, { - headers: { cookie: pairedCookie }, - }); - const body = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly publishAgentActivity?: boolean; - }>(response); - - assert.equal(response.status, 200); - assert.equal(body.linked, false); - assert.equal(body.publishAgentActivity, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "reports relay client status and streams installation progress over environment RPC", - () => - Effect.gen(function* () { - const installedRelayClient = { - status: "available" as const, - executablePath: "/tmp/t3/tools/cloudflared", - source: "managed" as const, - version: RelayClient.CLOUDFLARED_VERSION, - }; - yield* buildAppUnderTest({ - layers: { - relayClient: { - resolve: Effect.succeed({ - status: "missing", - version: RelayClient.CLOUDFLARED_VERSION, - }), - install: Effect.succeed(installedRelayClient), - installWithProgress: (report) => - report({ type: "progress", stage: "checking" }).pipe( - Effect.andThen(report({ type: "progress", stage: "downloading" })), - Effect.as(installedRelayClient), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const status = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.cloudGetRelayClientStatus]({})), - ); - const installEvents = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.cloudInstallRelayClient]({}).pipe(Stream.runCollect), - ), - ); - - assert.equal(status.status, "missing"); - assert.deepEqual(Array.from(installEvents), [ - { type: "progress", stage: "checking" }, - { type: "progress", stage: "downloading" }, - { type: "complete", status: installedRelayClient }, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("requires relay write scope to update agent activity publication", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const preferencesUrl = yield* getHttpServerUrl("/api/connect/preferences"); - const ownerResponse = yield* fetchEffect(preferencesUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ publishAgentActivity: true }), - }); - const ownerBody = yield* responseJsonEffect<{ - readonly publishAgentActivity?: boolean; - }>(ownerResponse); - assert.equal(ownerResponse.status, 200); - assert.equal(ownerBody.publishAgentActivity, true); - - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { cookie: ownerCookie }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { readonly credential: string }; - const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential); - const pairedResponse = yield* fetchEffect(preferencesUrl, { - method: "POST", - headers: { - cookie: pairedCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ publishAgentActivity: false }), - }); - const pairedBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly requiredScope?: string; - }>(pairedResponse); - assert.equal(pairedResponse.status, 403); - assert.equal(pairedBody._tag, "EnvironmentScopeRequiredError"); - assert.equal(pairedBody.requiredScope, "relay:write"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects relay config with an invalid cloud mint public key", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: "not-a-public-key", - endpointRuntime: null, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(relayConfigResponse); - - assert.equal(relayConfigResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Cloud mint public key must be a valid Ed25519 public key."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects relay config with insecure relay metadata or empty credentials", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const postRelayConfig = (body: { - readonly relayUrl: string; - readonly relayIssuer?: string; - readonly cloudUserId: string; - readonly environmentCredential: string; - }) => - fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - ...body, - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - - const insecureRelayUrl = yield* postRelayConfig({ - relayUrl: "http://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - }); - const insecureRelayIssuer = yield* postRelayConfig({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - relayIssuer: "http://relay.example.test", - environmentCredential: "t3env_test_credential", - }); - const nonOriginRelayUrl = yield* postRelayConfig({ - relayUrl: "https://relay.example.test/path", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - }); - const emptyCredential = yield* postRelayConfig({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: " ", - }); - const insecureRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>( - insecureRelayUrl, - ); - const insecureRelayIssuerBody = yield* responseJsonEffect<{ readonly message?: string }>( - insecureRelayIssuer, - ); - const nonOriginRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>( - nonOriginRelayUrl, - ); - const emptyCredentialBody = yield* responseJsonEffect<{ readonly message?: string }>( - emptyCredential, - ); - - assert.equal(insecureRelayUrl.status, 400); - assert.equal(insecureRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL."); - assert.equal(insecureRelayIssuer.status, 400); - assert.equal( - insecureRelayIssuerBody.message, - "Relay issuer must be a secure absolute HTTPS URL.", - ); - assert.equal(nonOriginRelayUrl.status, 400); - assert.equal(nonOriginRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL."); - assert.equal(emptyCredential.status, 400); - assert.equal(emptyCredentialBody.message, "Relay environment credential is required."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects relay config replacement from a different cloud account", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const postRelayConfig = (cloudUserId: string, environmentCredential: string) => - fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId, - environmentCredential, - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - - const firstResponse = yield* postRelayConfig("user_123", "t3env_first_credential"); - const replacementResponse = yield* postRelayConfig("user_456", "t3env_second_credential"); - const replacementBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(replacementResponse); - - assert.equal(firstResponse.status, 200); - assert.equal(replacementResponse.status, 409); - assert.equal(replacementBody._tag, "EnvironmentHttpConflictError"); - assert.equal( - replacementBody.message, - "This environment is already linked to a different cloud account. Unlink it before switching accounts.", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("reports local cloud link state from persisted relay config", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - - const initialResponse = yield* fetchEffect(linkStateUrl, { - headers: { - cookie: ownerCookie, - }, - }); - const initialBody = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly cloudUserId?: string | null; - }>(initialResponse); - assert.equal(initialResponse.status, 200); - assert.equal(initialBody.linked, false); - assert.equal(initialBody.cloudUserId, null); - - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://transport.example.test", - relayIssuer: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const linkedResponse = yield* fetchEffect(linkStateUrl, { - headers: { - cookie: ownerCookie, - }, - }); - const linkedBody = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly cloudUserId?: string | null; - readonly relayUrl?: string | null; - readonly relayIssuer?: string | null; - }>(linkedResponse); - - assert.equal(linkedResponse.status, 200); - assert.equal(linkedBody.linked, true); - assert.equal(linkedBody.cloudUserId, "user_123"); - assert.equal(linkedBody.relayUrl, "https://transport.example.test"); - assert.equal(linkedBody.relayIssuer, "https://relay.example.test"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not expose internal cloud reconciliation over HTTP", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const reconcileUrl = yield* getHttpServerUrl("/api/connect/reconcile"); - const response = yield* fetchEffect(reconcileUrl, { - method: "POST", - }); - - assert.equal(response.status, 404); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("unlinks local cloud state and disables the managed endpoint runtime", () => - Effect.gen(function* () { - const appliedRuntimeConfigs: Array = []; - yield* buildAppUnderTest({ - layers: { - cloudManagedEndpointRuntime: { - applyConfig: (config) => { - appliedRuntimeConfigs.push(config); - if (!config) { - return Effect.succeed({ status: "disabled" }); - } - return Effect.succeed({ - status: "running", - providerKind: "cloudflare_tunnel", - pid: 123, - ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}), - ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}), - }); - }, - }, - }, - }); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const unlinkUrl = yield* getHttpServerUrl("/api/connect/unlink"); - const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); - - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://transport.example.test", - relayIssuer: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", - tunnelId: "tunnel-id", - tunnelName: "tunnel-name", - }, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const unlinkResponse = yield* fetchEffect(unlinkUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - }, - }); - const unlinkBody = yield* responseJsonEffect<{ - readonly ok?: boolean; - readonly endpointRuntimeStatus?: { readonly status?: string }; - }>(unlinkResponse); - assert.equal(unlinkResponse.status, 200); - assert.equal(unlinkBody.ok, true); - assert.equal(unlinkBody.endpointRuntimeStatus?.status, "disabled"); - - const linkStateResponse = yield* fetchEffect(linkStateUrl, { - headers: { - cookie: ownerCookie, - }, - }); - const linkStateBody = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly cloudUserId?: string | null; - readonly relayUrl?: string | null; - readonly relayIssuer?: string | null; - }>(linkStateResponse); - assert.equal(linkStateResponse.status, 200); - assert.equal(linkStateBody.linked, false); - assert.equal(linkStateBody.cloudUserId, null); - assert.equal(linkStateBody.relayUrl, null); - assert.equal(linkStateBody.relayIssuer, null); - assert.deepEqual(appliedRuntimeConfigs, [ - { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", - tunnelId: "tunnel-id", - tunnelName: "tunnel-name", - }, - null, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects replayed cloud mint requests atomically", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - nonce: "cloud-mint-nonce-1", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential"); - const postMint = () => - fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const firstResponse = yield* postMint(); - const replayResponse = yield* postMint(); - const replayBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(replayResponse); - - assert.equal(firstResponse.status, 200); - assert.equal(replayResponse.status, 409); - assert.equal(replayBody._tag, "EnvironmentHttpConflictError"); - assert.equal(replayBody.message, "Cloud mint request was already consumed."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves the documented T3 Connect mint credential endpoint", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - jti: "cloud-mint-jti-documented-endpoint", - nonce: "cloud-mint-nonce-documented-endpoint", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const response = yield* fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - assert.equal(response.status, 200); - const body = yield* responseJsonEffect<{ - readonly credential?: string; - readonly proof?: string; - }>(response); - assert.equal(typeof body.credential, "string"); - assert.equal(typeof body.proof, "string"); - assert.equal( - decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce, - "cloud-mint-nonce-documented-endpoint", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves signed T3 Connect environment health checks", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - jti: "cloud-health-jti-documented-endpoint", - nonce: "cloud-health-nonce-documented-endpoint", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const response = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - assert.equal(response.status, 200); - const body = yield* responseJsonEffect<{ - readonly status?: string; - readonly descriptor?: { readonly environmentId?: string }; - readonly proof?: string; - }>(response); - assert.equal(body.status, "online"); - assert.equal(body.descriptor?.environmentId, testEnvironmentDescriptor.environmentId); - assert.equal(typeof body.proof, "string"); - assert.equal( - decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce, - "cloud-health-nonce-documented-endpoint", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects replayed cloud health requests atomically", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - jti: "cloud-health-jti-replay", - nonce: "cloud-health-nonce-replay", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const postHealth = () => - fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const firstResponse = yield* postHealth(); - const replayResponse = yield* postHealth(); - const replayBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(replayResponse); - - assert.equal(firstResponse.status, 200); - assert.equal(replayResponse.status, 409); - assert.equal(replayBody._tag, "EnvironmentHttpConflictError"); - assert.equal(replayBody.message, "Cloud health request was already consumed."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "validates cloud proofs against the configured relay issuer, not the transport URL", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://transport.example.test", - cloudUserId: "user_123", - relayIssuer: "https://relay.example.test", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const postMint = (request: ReturnType) => - fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const acceptedResponse = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - issuer: "https://relay.example.test", - jti: "cloud-mint-jti-explicit-relay-issuer", - nonce: "cloud-mint-nonce-explicit-relay-issuer", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - const rejectedResponse = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - issuer: "https://transport.example.test", - jti: "cloud-mint-jti-transport-url", - nonce: "cloud-mint-nonce-transport-url", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - - assert.equal(acceptedResponse.status, 200); - assert.equal(rejectedResponse.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("fails relay config when the managed endpoint connector cannot start", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - cloudManagedEndpointRuntime: { - applyConfig: () => - Effect.succeed({ - status: "failed", - providerKind: "cloudflare_tunnel", - reason: "cloudflared missing", - tunnelId: "tunnel-1", - }), - }, - }, - }); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", - tunnelId: "tunnel-1", - }, - }), - }); - - assert.equal(relayConfigResponse.status, 503); - const relayConfigBody = yield* responseJsonEffect<{ - _tag?: string; - message?: string; - endpointRuntimeStatus?: { status?: string; reason?: string }; - }>(relayConfigResponse); - assert.equal(relayConfigBody._tag, "EnvironmentCloudEndpointUnavailableError"); - assert.equal(relayConfigBody.message, "Managed endpoint runtime could not be started."); - assert.equal(relayConfigBody.endpointRuntimeStatus?.status, "failed"); - assert.equal(relayConfigBody.endpointRuntimeStatus?.reason, "cloudflared missing"); - - const now = yield* DateTime.now; - const healthRequest = makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - nonce: "cloud-health-after-failed-runtime", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const healthResponse = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(healthRequest), - }); - const healthBody = yield* responseJsonEffect<{ - _tag?: string; - message?: string; - }>(healthResponse); - assert.equal(healthResponse.status, 500); - assert.equal(healthBody._tag, "EnvironmentHttpInternalServerError"); - assert.equal( - healthBody.message, - "Cloud mint public key is not installed for this environment.", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud mint requests with the wrong issuer or audience", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential"); - const postMint = (request: ReturnType) => - fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const wrongIssuer = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - issuer: "https://attacker.example.test", - jti: "cloud-mint-jti-wrong-issuer", - nonce: "cloud-mint-nonce-wrong-issuer", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - const wrongAudience = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - audience: "t3-env:other-environment", - jti: "cloud-mint-jti-wrong-audience", - nonce: "cloud-mint-nonce-wrong-audience", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - - assert.equal(wrongIssuer.status, 401); - assert.equal(wrongAudience.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud mint requests for a cloud subject other than the linked user", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const response = yield* fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - subject: "user_other", - jti: "cloud-mint-jti-wrong-subject", - nonce: "cloud-mint-nonce-wrong-subject", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud mint requests without the exact connect scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const response = yield* fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - jti: "cloud-mint-jti-duplicate-scope", - nonce: "cloud-mint-nonce-duplicate-scope", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - scope: ["environment:connect", "environment:connect"], - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud health requests with the wrong issuer or audience", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const postHealth = (request: ReturnType) => - fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const wrongIssuer = yield* postHealth( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - issuer: "https://attacker.example.test", - jti: "cloud-health-jti-wrong-issuer", - nonce: "cloud-health-nonce-wrong-issuer", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - const wrongAudience = yield* postHealth( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - audience: "t3-env:other-environment", - jti: "cloud-health-jti-wrong-audience", - nonce: "cloud-health-nonce-wrong-audience", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - - assert.equal(wrongIssuer.status, 401); - assert.equal(wrongAudience.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud health requests for a cloud subject other than the linked user", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const response = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - subject: "user_other", - jti: "cloud-health-jti-wrong-subject", - nonce: "cloud-health-nonce-wrong-subject", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud health requests without the exact status scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const response = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - jti: "cloud-health-jti-duplicate-scope", - nonce: "cloud-health-nonce-duplicate-scope", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - scope: ["environment:status", "environment:status"], - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - // Mirrors NodeHttpServer.layerTest, which does not expose server options, - // with the production `websocket: { perMessageDeflate: true }` setting. - const NodeHttpServerTestWithWsDeflate = HttpServer.layerTestClient.pipe( - Layer.provide( - Layer.fresh(FetchHttpClient.layer).pipe( - Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false })), - ), - ), - Layer.provideMerge( - Layer.unwrap( - Effect.map( - Effect.promise(() => import("node:http")), - (NodeHttp) => - NodeHttpServer.layer(NodeHttp.createServer, { - port: 0, - websocket: { perMessageDeflate: true }, - }), - ), - ), - ), - ); - - it.effect("negotiates permessage-deflate with clients that offer it", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { cookie, url } = parseSessionCookieFromWsUrl(yield* getWsServerUrl("/ws")); - const openSocket = (perMessageDeflate: boolean) => - Effect.acquireRelease( - Effect.callback((resume) => { - const socket = new NodeSocket.NodeWS.WebSocket(url, { - perMessageDeflate, - ...(cookie ? { headers: { cookie } } : {}), - }); - socket.on("open", () => resume(Effect.succeed(socket))); - socket.on("error", (error) => resume(Effect.fail(error))); - }), - (socket) => Effect.sync(() => socket.close()), - ); - - const compressed = yield* openSocket(true); - // The ws client records the negotiated extension only when the server's - // 101 response accepted the offer. - assert.include(compressed.extensions, "permessage-deflate"); - - const plain = yield* openSocket(false); - assert.notInclude(plain.extensions, "permessage-deflate"); - }).pipe(Effect.scoped, Effect.provide(NodeHttpServerTestWithWsDeflate)), - ); - - it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - authorization: `Bearer ${bearerToken}`, - }, - }); - const wsTicketBody = yield* responseJsonEffect<{ - readonly ticket: string; - readonly expiresAt: string; - }>(wsTicketResponse); - - assert.equal(wsTicketResponse.status, 200); - assert.equal(typeof wsTicketBody.ticket, "string"); - assert.isTrue(wsTicketBody.ticket.length > 0); - assert.equal(typeof wsTicketBody.expiresAt, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not allow management-only access tokens to operate the environment", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { response: exchangeResponse, body: tokenBody } = yield* exchangeAccessToken( - defaultDesktopBootstrapToken, - { scope: "access:write" }, - ); - assert.equal(exchangeResponse.status, 200); - assert.equal(tokenBody.scope, "access:write"); - assert.isDefined(tokenBody.access_token); - - const overbroadPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - body: yield* HttpBody.json({}), - }); - const overbroadPairingBody = (yield* overbroadPairingResponse.json) as { - readonly requiredScope: string; - }; - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - body: yield* HttpBody.json({ scopes: ["access:write"] }), - }); - const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - }); - const wsTicketBody = (yield* wsTicketResponse.json) as { readonly ticket: string }; - assert.equal(overbroadPairingResponse.status, 403); - assert.equal(overbroadPairingBody.requiredScope, "orchestration:read"); - assert.equal(pairingResponse.status, 200); - assert.equal(wsTicketResponse.status, 200); - const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`; - const rpcError = yield* Effect.flip( - Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))), - ); - assert.equal(rpcError._tag, "EnvironmentAuthorizationError"); - if (rpcError._tag === "EnvironmentAuthorizationError") { - assert.equal(rpcError.requiredScope, "orchestration:read"); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("includes CORS headers on remote auth success responses", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const origin = crossOriginClientOrigin; - const { response: tokenResponse, body: tokenBody } = yield* exchangeAccessToken( - defaultDesktopBootstrapToken, - { - headers: { origin }, - }, - ); - - assert.equal(tokenResponse.status, 200); - assertBrowserApiCorsResponseHeaders(tokenResponse.headers); - assert.equal(tokenBody.token_type, "Bearer"); - assert.equal(typeof tokenBody.access_token, "string"); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const sessionResponse = yield* fetchEffect(sessionUrl, { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - origin, - }, - }); - const sessionBody = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - }>(sessionResponse); - - assert.equal(sessionResponse.status, 200); - assertBrowserApiCorsResponseHeaders(sessionResponse.headers); - assert.equal(sessionBody.authenticated, true); - assert.equal(sessionBody.sessionMethod, "bearer-access-token"); - - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - origin, - }, - }); - const wsTicketBody = yield* responseJsonEffect<{ - readonly ticket: string; - }>(wsTicketResponse); - - assert.equal(wsTicketResponse.status, 200); - assertBrowserApiCorsResponseHeaders(wsTicketResponse.headers); - assert.equal(typeof wsTicketBody.ticket, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "responds to remote auth websocket-ticket preflight requests with authorization CORS headers", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const response = yield* fetchEffect(wsTicketUrl, { - method: "OPTIONS", - headers: { - origin: crossOriginClientOrigin, - "access-control-request-method": "POST", - "access-control-request-headers": "authorization", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows credentialed cloud link proof preflights from the configured dev UI", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { devUrl: new URL(crossOriginClientOrigin) }, - }); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const response = yield* fetchEffect(linkProofUrl, { - method: "OPTIONS", - headers: { - origin: crossOriginClientOrigin, - "access-control-request-method": "POST", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers, { - origin: crossOriginClientOrigin, - credentials: true, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows configured development origins through ServerConfig", () => - Effect.gen(function* () { - const tailnetOrigin = "https://host.example.ts.net"; - yield* buildAppUnderTest({ - config: { - devUrl: new URL(crossOriginClientOrigin), - devAllowedOrigins: [tailnetOrigin], - }, - }); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const response = yield* fetchEffect(sessionUrl, { - method: "OPTIONS", - headers: { - origin: tailnetOrigin, - "access-control-request-method": "GET", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers, { - origin: tailnetOrigin, - credentials: true, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) { - it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { devUrl: new URL(crossOriginClientOrigin) }, - }); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const response = yield* fetchEffect(sessionUrl, { - method: "OPTIONS", - headers: { - origin: desktopOrigin, - "access-control-request-method": "GET", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers, { - origin: desktopOrigin, - credentials: true, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - } - - it.effect("includes CORS headers on remote websocket-ticket auth failures", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const response = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - origin: crossOriginClientOrigin, - }, - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly code?: string; - readonly reason?: string; - readonly traceId?: string; - }>(response); - - assert.equal(response.status, 401); - assertBrowserApiCorsResponseHeaders(response.headers); - assert.equal(body._tag, "EnvironmentAuthInvalidError"); - assert.equal(body.code, "auth_invalid"); - assert.equal(body.reason, "missing_credential"); - assert.equal(typeof body.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("issues authenticated one-time pairing credentials for additional clients", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - }, - body: yield* HttpBody.json({}), - }); - const body = (yield* response.json) as { - readonly credential: string; - readonly expiresAt: string; - }; - - assert.equal(response.status, 200); - assert.equal(typeof body.credential, "string"); - assert.isTrue(body.credential.length > 0); - assert.equal(typeof body.expiresAt, "string"); - - const bootstrapResult = yield* bootstrapBrowserSession(body.credential); - assert.equal(bootstrapResult.response.status, 200); - - const reusedResult = yield* bootstrapBrowserSession(body.credential); - assert.equal(reusedResult.response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("issues pairing credentials for bearer sessions with access management scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const response = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - authorization: `Bearer ${bearerToken}`, - }, - body: yield* HttpBody.json({ label: "Hosted web" }), - }); - const body = (yield* response.json) as { - readonly credential: string; - readonly label?: string; - }; - - assert.equal(response.status, 200); - assert.isTrue(body.credential.length > 0); - assert.equal(body.label, "Hosted web"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects pairing credentials with an empty scope grant", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - }, - body: yield* HttpBody.json({ scopes: [] }), - }); - const body = (yield* response.json) as { - readonly code: string; - readonly reason: string; - }; - - assert.equal(response.status, 400); - assert.equal(body.code, "invalid_request"); - assert.equal(body.reason, "invalid_scope"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects unauthenticated pairing credential requests", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.post("/api/auth/pairing-token", { - body: yield* HttpBody.json({}), - }); - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("lists and revokes pairing links for access management sessions", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const createdResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const createdBody = (yield* createdResponse.json) as { - readonly id: string; - readonly credential: string; - }; - - const listResponse = yield* HttpClient.get("/api/auth/pairing-links", { - headers: { - cookie: ownerCookie, - }, - }); - const listedLinks = (yield* listResponse.json) as ReadonlyArray<{ - readonly id: string; - readonly credential: string; - }>; - - const revokeResponse = yield* HttpClient.post("/api/auth/pairing-links/revoke", { - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: HttpBody.text(jsonRequestBody({ id: createdBody.id }), "application/json"), - }); - const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential); - - assert.equal(createdResponse.status, 200); - assert.equal(listResponse.status, 200); - assert.isTrue(listedLinks.some((entry) => entry.id === createdBody.id)); - assert.equal(revokeResponse.status, 200); - assert.equal(revokedBootstrap.response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects pairing credential requests without access management scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - }, - body: yield* HttpBody.json({}), - }); - const ownerBody = (yield* ownerResponse.json) as { - readonly credential: string; - }; - assert.equal(ownerResponse.status, 200); - - const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(ownerBody.credential); - const pairedResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: pairedSessionCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairedBody = (yield* pairedResponse.json) as { - readonly _tag: string; - readonly code: string; - readonly requiredScope: string; - readonly traceId: string; - }; - - assert.equal(pairedResponse.status, 403); - assert.equal(pairedBody._tag, "EnvironmentScopeRequiredError"); - assert.equal(pairedBody.code, "insufficient_scope"); - assert.equal(pairedBody.requiredScope, "access:write"); - assert.equal(typeof pairedBody.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("lists paired clients and revokes other sessions while keeping the administrator", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token"); - const ownerPairingResponse = yield* fetchEffect(pairingTokenUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - label: "Julius iPhone", - }), - }); - const ownerPairingBody = yield* responseJsonEffect<{ - readonly credential: string; - readonly label?: string; - }>(ownerPairingResponse); - assert.equal(ownerPairingResponse.status, 200); - const pairedSessionBootstrap = yield* bootstrapBrowserSession(ownerPairingBody.credential, { - headers: { - "user-agent": - "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1", - }, - }); - const pairedSessionCookie = pairedSessionBootstrap.cookie?.split(";")[0]; - assert.isDefined(pairedSessionCookie); - - const pairedSessionCookieHeader = pairedSessionCookie ?? ""; - const listBeforeResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clientsBefore = (yield* listBeforeResponse.json) as ReadonlyArray<{ - readonly sessionId: string; - readonly current: boolean; - readonly client: { - readonly label?: string; - readonly deviceType: string; - readonly ipAddress?: string; - readonly os?: string; - readonly browser?: string; - }; - }>; - const pairedClientBefore = clientsBefore.find((entry) => !entry.current); - const pairedSessionId = clientsBefore.find((entry) => !entry.current)?.sessionId; - - const revokeOthersResponse = yield* HttpClient.post("/api/auth/clients/revoke-others", { - headers: { - cookie: ownerCookie, - }, - }); - const revokeOthersBody = (yield* revokeOthersResponse.json) as { - readonly revokedCount: number; - }; - - const listAfterResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clientsAfter = (yield* listAfterResponse.json) as ReadonlyArray<{ - readonly sessionId: string; - readonly current: boolean; - }>; - - const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: pairedSessionCookieHeader, - }, - body: yield* HttpBody.json({}), - }); - const pairedClientPairingBody = (yield* pairedClientPairingResponse.json) as { - readonly _tag: string; - readonly code: string; - readonly reason: string; - readonly traceId: string; - }; - - assert.equal(listBeforeResponse.status, 200); - assert.equal(ownerPairingBody.label, "Julius iPhone"); - assert.lengthOf(clientsBefore, 2); - assert.isDefined(pairedSessionId); - assert.isDefined(pairedClientBefore); - assert.deepInclude(pairedClientBefore?.client, { - label: "Julius iPhone", - deviceType: "mobile", - os: "iOS", - browser: "Safari", - ipAddress: "127.0.0.1", - }); - assert.equal(revokeOthersResponse.status, 200); - assert.equal(revokeOthersBody.revokedCount, 1); - assert.equal(listAfterResponse.status, 200); - assert.lengthOf(clientsAfter, 1); - assert.equal(clientsAfter[0]?.current, true); - assert.equal(pairedClientPairingResponse.status, 401); - assert.equal(pairedClientPairingBody._tag, "EnvironmentAuthInvalidError"); - assert.equal(pairedClientPairingBody.code, "auth_invalid"); - assert.equal(pairedClientPairingBody.reason, "invalid_credential"); - assert.equal(typeof pairedClientPairingBody.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("separates access inventory reads from credential management writes", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const issueScopedSession = Effect.fnUntraced(function* ( - scope: "access:read" | "access:write", - ) { - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({ scopes: [scope] }), - }); - assert.equal(pairingResponse.status, 200); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - return yield* getAuthenticatedSessionCookieHeader(pairingBody.credential); - }); - - const readCookie = yield* issueScopedSession("access:read"); - const readListResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: readCookie, - }, - }); - const readWriteResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: readCookie, - }, - body: yield* HttpBody.json({}), - }); - const readWriteBody = (yield* readWriteResponse.json) as { - readonly requiredScope: string; - }; - - const writeCookie = yield* issueScopedSession("access:write"); - const writeListResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: writeCookie, - }, - }); - const writeListBody = (yield* writeListResponse.json) as { - readonly requiredScope: string; - }; - - assert.equal(readListResponse.status, 200); - assert.equal(readWriteResponse.status, 403); - assert.equal(readWriteBody.requiredScope, "access:write"); - assert.equal(writeListResponse.status, 403); - assert.equal(writeListBody.requiredScope, "access:read"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("revokes an individual paired client session", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader( - pairingBody.credential, - ); - - const clientsResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clients = (yield* clientsResponse.json) as ReadonlyArray<{ - readonly sessionId: string; - readonly current: boolean; - }>; - const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId; - assert.isDefined(pairedSessionId); - - const revokeResponse = yield* HttpClient.post("/api/auth/clients/revoke", { - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: HttpBody.text(jsonRequestBody({ sessionId: pairedSessionId }), "application/json"), - }); - const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: pairedSessionCookie, - }, - body: yield* HttpBody.json({}), - }); - - assert.equal(revokeResponse.status, 200); - assert.equal(pairedClientPairingResponse.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows reusing the desktop bootstrap credential", () => - Effect.gen(function* () { - // The desktop-bootstrap grant is delivered over trusted IPC at - // backend launch and needs to stay claimable after a renderer - // refresh, so it's intentionally reusable (unlike user-facing - // one-time pairing credentials). - yield* buildAppUnderTest(); - - const first = yield* bootstrapBrowserSession(); - const second = yield* bootstrapBrowserSession(); - - assert.equal(first.response.status, 200); - assert.equal(second.response.status, 200); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { response: bootstrapResponse, cookie } = yield* bootstrapBrowserSession(); - - assert.equal(bootstrapResponse.status, 200); - assert.isDefined(cookie); - - const wsUrl = appendSessionCookieToWsUrl( - yield* getWsServerUrl("/ws", { authenticated: false }), - cookie?.split(";")[0] ?? "", - ); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), - ); - - assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); - assert.equal(response.auth.policy, "desktop-managed-local"); - assert.equal(response.shellResumeCompletionMarker, true); - assert.equal(response.threadResumeCompletionMarker, true); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not block server config when editor discovery never resolves", () => - Effect.gen(function* () { - const discoveryInterrupted = yield* Deferred.make(); - const responseFiber = yield* resolveAvailableEditorsForConfig( - Effect.never.pipe( - Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)), - ), - ).pipe(Effect.forkChild); - - yield* TestClock.adjust(Duration.seconds(5)); - - const availableEditors = yield* Fiber.join(responseFiber); - yield* Deferred.await(discoveryInterrupted); - assert.deepEqual(availableEditors, []); - }), - ); - - it.effect( - "rejects websocket rpc handshake when a session token is only provided via query string", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { cookie } = yield* bootstrapBrowserSession(); - assert.isDefined(cookie); - const sessionToken = extractSessionTokenFromSetCookie(cookie ?? ""); - const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?token=${encodeURIComponent(sessionToken)}`; - - const error = yield* Effect.flip( - Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))), - ); - - assert.equal(error._tag, "RpcClientError"); - assertInclude(String(error), "SocketOpenError"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "accepts websocket rpc handshake with a dedicated websocket ticket in the query string", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - authorization: `Bearer ${bearerToken}`, - }, - }); - const wsTicketBody = yield* responseJsonEffect<{ - readonly ticket: string; - }>(wsTicketResponse); - const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`; - - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), - ); - - assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); - assert.equal(response.auth.policy, "desktop-managed-local"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("proxies browser OTLP trace exports through the server", () => - Effect.gen(function* () { - const upstreamRequests: Array<{ - readonly body: string; - readonly contentType: string | null; - }> = []; - const localTraceRecords: Array = []; - const payload = { - resourceSpans: [ - { - resource: { - attributes: [ - { - key: "service.name", - value: { stringValue: "t3-web" }, - }, - ], - }, - scopeSpans: [ - { - scope: { - name: "effect", - version: "4.0.0-beta.43", - }, - spans: [ - { - traceId: "11111111111111111111111111111111", - spanId: "2222222222222222", - parentSpanId: "3333333333333333", - name: "RpcClient.server.getSettings", - kind: 3, - startTimeUnixNano: "1000000", - endTimeUnixNano: "2000000", - attributes: [ - { - key: "rpc.method", - value: { stringValue: "server.getSettings" }, - }, - ], - events: [ - { - name: "http.request", - timeUnixNano: "1500000", - attributes: [ - { - key: "http.status_code", - value: { intValue: "200" }, - }, - ], - }, - ], - links: [], - status: { - code: "STATUS_CODE_OK", - }, - flags: 1, - }, - ], - }, - ], - }, - ], - }; - - const collector = yield* Effect.acquireRelease( - Effect.promise(async () => { - const NodeHttp = await import("node:http"); - - return await new Promise<{ - readonly close: () => Promise; - readonly url: string; - }>((resolve, reject) => { - const server = NodeHttp.createServer((request, response) => { - const chunks: Buffer[] = []; - request.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - request.on("end", () => { - upstreamRequests.push({ - body: Buffer.concat(chunks).toString("utf8"), - contentType: request.headers["content-type"] ?? null, - }); - response.statusCode = 204; - response.end(); - }); - }); - - server.on("error", reject); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - if (!address || typeof address === "string") { - reject(new Error("Expected TCP collector address")); - return; - } - - resolve({ - url: `http://127.0.0.1:${address.port}/v1/traces`, - close: () => - new Promise((resolveClose, rejectClose) => { - server.close((error) => { - if (error) { - rejectClose(error); - return; - } - resolveClose(); - }); - }), - }); - }); - }); - }), - ({ close }) => Effect.promise(close), - ); - - yield* buildAppUnderTest({ - config: { - otlpTracesUrl: collector.url, - }, - layers: { - browserTraceCollector: { - record: (records) => - Effect.sync(() => { - localTraceRecords.push(...records); - }), - }, - }, - }); - - const response = yield* HttpClient.post("/api/observability/v1/traces", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - origin: "http://localhost:5733", - }, - // @effect-diagnostics-next-line preferSchemaOverJson:off - body: HttpBody.text(JSON.stringify(payload), "application/json"), - }); - - assert.equal(response.status, 204); - assert.equal(response.headers["access-control-allow-origin"], "*"); - assert.deepEqual(localTraceRecords, [ - { - type: "otlp-span", - name: "RpcClient.server.getSettings", - traceId: "11111111111111111111111111111111", - spanId: "2222222222222222", - parentSpanId: "3333333333333333", - sampled: true, - kind: "client", - startTimeUnixNano: "1000000", - endTimeUnixNano: "2000000", - durationMs: 1, - attributes: { - "rpc.method": "server.getSettings", - }, - resourceAttributes: { - "service.name": "t3-web", - }, - scope: { - name: "effect", - version: "4.0.0-beta.43", - attributes: {}, - }, - events: [ - { - name: "http.request", - timeUnixNano: "1500000", - attributes: { - "http.status_code": "200", - }, - }, - ], - links: [], - status: { - code: "STATUS_CODE_OK", - }, - }, - ]); - assert.deepEqual(upstreamRequests, [ - { - body: jsonRequestBody(payload), - contentType: "application/json", - }, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("responds to browser OTLP trace preflight requests with CORS headers", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.options("/api/observability/v1/traces", { - headers: { - origin: "http://localhost:5733", - "access-control-request-method": "POST", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assert.equal(response.headers["access-control-allow-origin"], "*"); - assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-methods"]), [ - "GET", - "OPTIONS", - "POST", - ]); - assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-headers"]), [ - "authorization", - "b3", - "content-type", - "dpop", - "traceparent", - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "stores browser OTLP trace exports locally when no upstream collector is configured", - () => - Effect.gen(function* () { - const localTraceRecords: Array = []; - const payload = yield* makeBrowserOtlpPayload("client.test"); - const resourceSpan = payload.resourceSpans[0]; - const scopeSpan = resourceSpan?.scopeSpans[0]; - const span = scopeSpan?.spans[0]; - - assert.notEqual(resourceSpan, undefined); - assert.notEqual(scopeSpan, undefined); - assert.notEqual(span, undefined); - if (!resourceSpan || !scopeSpan || !span) { - return; - } - - yield* buildAppUnderTest({ - layers: { - browserTraceCollector: { - record: (records) => - Effect.sync(() => { - localTraceRecords.push(...records); - }), - }, - }, - }); - - const response = yield* HttpClient.post("/api/observability/v1/traces", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - }, - // @effect-diagnostics-next-line preferSchemaOverJson:off - body: HttpBody.text(JSON.stringify(payload), "application/json"), - }); - - assert.equal(response.status, 204); - assert.equal(localTraceRecords.length, 1); - const record = localTraceRecords[0] as { - readonly type: string; - readonly name: string; - readonly traceId: string; - readonly spanId: string; - readonly kind: string; - readonly attributes: Readonly>; - readonly events: ReadonlyArray; - readonly links: ReadonlyArray; - readonly scope: { - readonly name?: string; - readonly attributes: Readonly>; - }; - readonly resourceAttributes: Readonly>; - readonly status?: { - readonly code?: string; - }; - }; - - assert.equal(record.type, "otlp-span"); - assert.equal(record.name, span.name); - assert.equal(record.traceId, span.traceId); - assert.equal(record.spanId, span.spanId); - assert.equal(record.kind, "internal"); - assert.deepEqual(record.attributes, {}); - assert.deepEqual(record.events, []); - assert.deepEqual(record.links, []); - assert.equal(record.scope.name, scopeSpan.scope.name); - assert.deepEqual(record.scope.attributes, {}); - assert.equal(record.resourceAttributes["service.name"], "t3-web"); - assert.equal(record.status?.code, String(span.status.code)); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc server.upsertKeybinding", () => - Effect.gen(function* () { - const rule: KeybindingRule = { - command: "terminal.toggle", - key: "ctrl+k", - }; - const resolved: ResolvedKeybindingRule = { - command: "terminal.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: false, - modKey: true, - }, - }; - - yield* buildAppUnderTest({ - layers: { - keybindings: { - upsertKeybindingRule: () => Effect.succeed([resolved]), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverUpsertKeybinding](rule)), - ); - - assert.deepEqual(response.issues, []); - assert.deepEqual(response.keybindings, [resolved]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc server.removeKeybinding", () => - Effect.gen(function* () { - const rule: KeybindingRule = { - command: "terminal.toggle", - key: "ctrl+k", - }; - const resolved: ResolvedKeybindingRule = { - command: "terminal.toggle", - shortcut: { - key: "j", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - }; - - yield* buildAppUnderTest({ - layers: { - keybindings: { - removeKeybindingRule: () => Effect.succeed([resolved]), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)), - ); - - assert.deepEqual(response.issues, []); - assert.deepEqual(response.keybindings, [resolved]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("shares one preview automation broker across websocket sessions", () => - Effect.scoped( - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const firstConnected = yield* Deferred.make(); - const firstClosed = yield* Deferred.make(); - const host = { - clientId: "shared-preview-host", - environmentId: testEnvironmentDescriptor.environmentId, - } as const; - - yield* withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.previewAutomationConnect](host).pipe( - Stream.tap((event) => - event.type === "connected" - ? Deferred.succeed(firstConnected, event.connectionId) - : Effect.void, - ), - Stream.runDrain, - Effect.ensuring(Deferred.succeed(firstClosed, undefined)), - ), - ).pipe(Effect.forkScoped); - - const firstConnectionId = yield* Deferred.await(firstConnected); - const replacementEvent = yield* withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead), - ).pipe(Effect.map(Option.getOrThrow)); - const firstStreamClosed = yield* Deferred.await(firstClosed).pipe( - Effect.timeoutOption("2 seconds"), - ); - - assert.equal(replacementEvent.type, "connected"); - assert.notEqual(replacementEvent.connectionId, firstConnectionId); - assert.isTrue(Option.isSome(firstStreamClosed)); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects websocket rpc handshake when session authentication is missing", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-required-" }); - yield* fs.writeFileString( - path.join(workspaceDir, "needle-file.ts"), - "export const needle = 1;", - ); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws", { authenticated: false }); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "needle", - limit: 10, - }), - ).pipe(Effect.result), - ); - - assertTrue(result._tag === "Failure"); - const failureMessage = String(result.failure); - assertTrue( - failureMessage.includes("SocketOpenError") || failureMessage.includes("SocketCloseError"), - ); - assertTrue( - failureMessage.includes("Unauthorized") || - failureMessage.includes("An error occurred during Open"), - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () => - Effect.gen(function* () { - const providers = [ - { - instanceId: ProviderInstanceId.make("codex"), - driver: ProviderDriverKind.make("codex"), - enabled: true, - installed: true, - version: "1.0.0", - status: "ready" as const, - auth: { status: "authenticated" as const }, - checkedAt: "2026-04-11T00:00:00.000Z", - models: [], - slashCommands: [], - skills: [], - }, - ] as const; - const changeEvent = { - keybindings: [], - issues: [], - } as const; - - yield* buildAppUnderTest({ - config: { - otlpTracesUrl: "http://localhost:4318/v1/traces", - otlpMetricsUrl: "http://localhost:4318/v1/metrics", - }, - layers: { - keybindings: { - loadConfigState: Effect.succeed({ - keybindings: [], - issues: [], - }), - streamChanges: Stream.succeed(changeEvent), - }, - providerRegistry: { - getProviders: Effect.succeed(providers), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const events = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(events); - assert.equal(first?.type, "snapshot"); - if (first?.type === "snapshot") { - assert.equal(first.version, 1); - assert.deepEqual(first.config.keybindings, []); - assert.deepEqual(first.config.issues, []); - assert.deepEqual(first.config.providers, providers); - assert.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true); - assert.equal(first.config.observability.localTracingEnabled, true); - assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces"); - assert.equal(first.config.observability.otlpTracesEnabled, true); - assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics"); - assert.equal(first.config.observability.otlpMetricsEnabled, true); - assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS); - } - assert.deepEqual(second, { - version: 1, - type: "keybindingsUpdated", - payload: { keybindings: [], issues: [] }, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket resource telemetry through the subscription", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const snapshot = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeResourceTelemetry]({}).pipe(Stream.runHead), - ), - ); - - assertTrue(Option.isSome(snapshot)); - assert.equal(snapshot.value.processes.length, 0); - assert.equal(snapshot.value.groups.backend.processCount, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () => - Effect.gen(function* () { - const nextProviders = [ - { - instanceId: ProviderInstanceId.make("codex"), - driver: ProviderDriverKind.make("codex"), - enabled: true, - installed: true, - version: "1.0.0", - status: "ready" as const, - auth: { status: "authenticated" as const }, - checkedAt: "2026-04-11T00:00:00.000Z", - models: [], - slashCommands: [], - skills: [], - }, - ] as const; - - yield* buildAppUnderTest({ - layers: { - keybindings: { - loadConfigState: Effect.succeed({ - keybindings: [], - issues: [], - }), - streamChanges: Stream.empty, - }, - providerRegistry: { - getProviders: Effect.succeed([]), - streamChanges: Stream.succeed(nextProviders), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const events = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(events); - assert.equal(first?.type, "snapshot"); - if (first?.type === "snapshot") { - assert.deepEqual(first.config.providers, []); - } - assert.deepEqual(second, { - version: 1, - type: "providerStatuses", - payload: { providers: nextProviders }, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "routes websocket rpc subscribeServerLifecycle replays snapshot and streams updates", - () => - Effect.gen(function* () { - const lifecycleEvents = [ - { - version: 1 as const, - sequence: 1, - type: "welcome" as const, - payload: { - environment: testEnvironmentDescriptor, - cwd: "/tmp/project", - projectName: "project", - }, - }, - ] as const; - const liveEvents = Stream.make({ - version: 1 as const, - sequence: 2, - type: "ready" as const, - payload: { at: "2026-01-01T00:00:00.000Z", environment: testEnvironmentDescriptor }, - }); - - yield* buildAppUnderTest({ - layers: { - serverLifecycleEvents: { - snapshot: Effect.succeed({ - sequence: 1, - events: lifecycleEvents, - }), - stream: liveEvents, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const events = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeServerLifecycle]({}).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(events); - assert.equal(first?.type, "welcome"); - assert.equal(first?.sequence, 1); - assert.equal(second?.type, "ready"); - assert.equal(second?.sequence, 2); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc projects.searchEntries", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-search-" }); - yield* fs.writeFileString( - path.join(workspaceDir, "needle-file.ts"), - "export const needle = 1;", - ); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "needle", - limit: 10, - }), - ), - ); - - assert.isAtLeast(response.entries.length, 1); - assert.isTrue(response.entries.some((entry) => entry.path === "needle-file.ts")); - assert.equal(response.truncated, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("routes websocket rpc projects.listEntries and projects.readFile", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-files-" }); - yield* fs.makeDirectory(path.join(workspaceDir, "src"), { recursive: true }); - yield* fs.writeFileString( - path.join(workspaceDir, "src", "index.ts"), - "export const answer = 42;\n", - ); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - Effect.all({ - listing: client[WS_METHODS.projectsListEntries]({ cwd: workspaceDir }), - file: client[WS_METHODS.projectsReadFile]({ - cwd: workspaceDir, - relativePath: "src/index.ts", - }), - }), - ), - ); - - assert.isTrue(response.listing.entries.some((entry) => entry.path === "src/index.ts")); - assert.deepEqual(response.file, { - relativePath: "src/index.ts", - contents: "export const answer = 42;\n", - byteLength: 26, - truncated: false, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-project-search-gitignored-", - }); - yield* fs.writeFileString(path.join(workspaceDir, ".gitignore"), ".venv/\n"); - yield* fs.makeDirectory(path.join(workspaceDir, ".venv", "lib"), { recursive: true }); - yield* fs.writeFileString( - path.join(workspaceDir, ".venv", "lib", "ignored-search-target.ts"), - "export const ignored = true;", - ); - yield* fs.makeDirectory(path.join(workspaceDir, "src"), { recursive: true }); - yield* fs.writeFileString( - path.join(workspaceDir, "src", "tracked.ts"), - "export const ok = 1;", - ); - - yield* buildAppUnderTest({ - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - listWorkspaceFiles: () => - Effect.succeed({ - paths: ["src/tracked.ts"], - truncated: false, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - filterIgnoredPaths: (_cwd, relativePaths) => - Effect.succeed( - relativePaths.filter((relativePath) => !relativePath.startsWith(".venv/")), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "ignored-search-target", - limit: 10, - }), - ), - ); - - assert.equal(response.entries.length, 0); - assert.equal(response.truncated, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("preserves structured workspace rpc failures", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-workspace-errors-", - }); - const outsideDir = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-workspace-errors-outside-", - }); - const outsideFile = path.join(outsideDir, "outside.txt"); - yield* fs.writeFileString(outsideFile, "outside\n"); - yield* fs.symlink(outsideFile, path.join(workspaceDir, "linked-outside.txt")); - const resolvedOutsideFile = yield* fs.realPath(outsideFile); - - yield* buildAppUnderTest(); - - const invalidWorkspace = path.join(workspaceDir, "missing-workspace"); - const missingBrowseParent = path.join(workspaceDir, "missing-browse"); - const sensitiveQuery = "authorization: Bearer secret-token"; - const wsUrl = yield* getWsServerUrl("/ws"); - const results = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - Effect.all({ - search: client[WS_METHODS.projectsSearchEntries]({ - cwd: invalidWorkspace, - query: sensitiveQuery, - limit: 10, - }).pipe(Effect.result), - list: client[WS_METHODS.projectsListEntries]({ cwd: invalidWorkspace }).pipe( - Effect.result, - ), - read: client[WS_METHODS.projectsReadFile]({ - cwd: workspaceDir, - relativePath: "linked-outside.txt", - }).pipe(Effect.result), - browse: client[WS_METHODS.filesystemBrowse]({ - cwd: workspaceDir, - partialPath: "./missing-browse/child", - }).pipe(Effect.result), - }), - ), - ); - - if ( - results.search._tag !== "Failure" || - results.search.failure._tag !== "ProjectSearchEntriesError" - ) { - assert.fail("Expected a ProjectSearchEntriesError"); - } - const searchError = results.search.failure; - assert.equal( - searchError.message, - `Failed to search workspace entries in '${invalidWorkspace}'.`, - ); - assert.equal(searchError.cwd, invalidWorkspace); - assert.equal(searchError.queryLength, sensitiveQuery.length); - assert.notProperty(searchError, "query"); - assert.notInclude(searchError.message, "Bearer"); - assert.notInclude(searchError.message, "secret-token"); - assert.equal(searchError.limit, 10); - assert.equal(searchError.failure, "workspace_root_not_found"); - assert.equal(searchError.normalizedCwd, invalidWorkspace); - assert.isDefined(searchError.cause); - - if ( - results.list._tag !== "Failure" || - results.list.failure._tag !== "ProjectListEntriesError" - ) { - assert.fail("Expected a ProjectListEntriesError"); - } - const listError = results.list.failure; - assert.equal(listError.message, `Failed to list workspace entries in '${invalidWorkspace}'.`); - assert.equal(listError.cwd, invalidWorkspace); - assert.equal(listError.failure, "workspace_root_not_found"); - assert.equal(listError.normalizedCwd, invalidWorkspace); - assert.isDefined(listError.cause); - - if (results.read._tag !== "Failure" || results.read.failure._tag !== "ProjectReadFileError") { - assert.fail("Expected a ProjectReadFileError"); - } - const readError = results.read.failure; - assert.equal( - readError.message, - `Failed to read workspace file 'linked-outside.txt' in '${workspaceDir}'.`, - ); - assert.equal(readError.cwd, workspaceDir); - assert.equal(readError.relativePath, "linked-outside.txt"); - assert.equal(readError.failure, "resolved_path_outside_root"); - assert.equal(readError.resolvedPath, resolvedOutsideFile); - assert.isDefined(readError.cause); - - if ( - results.browse._tag !== "Failure" || - results.browse.failure._tag !== "FilesystemBrowseError" - ) { - assert.fail("Expected a FilesystemBrowseError"); - } - const browseError = results.browse.failure; - assert.equal( - browseError.message, - `Failed to browse filesystem path './missing-browse/child' from '${workspaceDir}'.`, - ); - assert.equal(browseError.cwd, workspaceDir); - assert.equal(browseError.partialPath, "./missing-browse/child"); - assert.equal(browseError.failure, "read_directory_failed"); - assert.equal(browseError.parentPath, missingBrowseParent); - assert.isDefined(browseError.cause); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("reports workspace root stat failures without relabeling them as missing", () => - Effect.gen(function* () { - if ((yield* HostProcessPlatform) === "win32") return; - - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const blockedRoot = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-workspace-stat-error-", - }); - const workspaceRoot = path.join(blockedRoot, "workspace"); - yield* fs.makeDirectory(workspaceRoot); - yield* fs.chmod(blockedRoot, 0o000); - - const result = yield* Effect.gen(function* () { - yield* buildAppUnderTest(); - const wsUrl = yield* getWsServerUrl("/ws"); - return yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsListEntries]({ cwd: workspaceRoot }).pipe(Effect.result), - ), - ); - }).pipe(Effect.ensuring(fs.chmod(blockedRoot, 0o700).pipe(Effect.ignore))); - - if (result._tag !== "Failure" || result.failure._tag !== "ProjectListEntriesError") { - assert.fail("Expected a ProjectListEntriesError"); - } - const error = result.failure; - assert.equal(error.failure, "workspace_root_stat_failed"); - assert.equal(error.normalizedCwd, workspaceRoot); - assert.equal(error.detail, "validate-existing"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc projects.writeFile", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsWriteFile]({ - cwd: workspaceDir, - relativePath: "nested/created.txt", - contents: "written-by-rpc", - }), - ), - ); - - assert.equal(response.relativePath, "nested/created.txt"); - const persisted = yield* fs.readFileString(path.join(workspaceDir, "nested", "created.txt")); - assert.equal(persisted, "written-by-rpc"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("creates a missing workspace root during websocket project.create dispatch", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-create-" }); - const missingWorkspaceRoot = path.join(parentDir, "nested", "new-project"); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "project.create", - commandId: CommandId.make("cmd-project-create-missing-root"), - projectId: ProjectId.make("project-create-missing-root"), - title: "New Project", - workspaceRoot: missingWorkspaceRoot, - createWorkspaceRootIfMissing: true, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - createdAt: "2026-01-01T00:00:00.000Z", - }), - ), - ); - const stat = yield* fs.stat(missingWorkspaceRoot); - - assert.isAtLeast(response.sequence, 0); - assert.equal(stat.type, "Directory"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc projects.writeFile errors", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsWriteFile]({ - cwd: workspaceDir, - relativePath: "../escape.txt", - contents: "nope", - }), - ).pipe(Effect.result), - ); - - if (result._tag !== "Failure" || result.failure._tag !== "ProjectWriteFileError") { - assert.fail("Expected a ProjectWriteFileError"); - } - const writeError = result.failure; - assert.equal( - writeError.message, - `Failed to write workspace file '../escape.txt' in '${workspaceDir}'.`, - ); - assert.equal(writeError.cwd, workspaceDir); - assert.equal(writeError.relativePath, "../escape.txt"); - assert.equal(writeError.failure, "workspace_path_outside_root"); - assert.isDefined(writeError.cause); - assert.notProperty(writeError, "contents"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc shell.openInEditor", () => - Effect.gen(function* () { - let openedInput: { cwd: string; editor: EditorId } | null = null; - yield* buildAppUnderTest({ - layers: { - externalLauncher: { - launchEditor: (input) => - Effect.sync(() => { - openedInput = input; - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.shellOpenInEditor]({ - cwd: "/tmp/project", - editor: "cursor", - }), - ), - ); - - assert.deepEqual(openedInput, { cwd: "/tmp/project", editor: "cursor" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc shell.openInEditor errors", () => - Effect.gen(function* () { - const externalLauncherError = new ExternalLauncherCommandNotFoundError({ - editor: "cursor", - command: "cursor", - }); - yield* buildAppUnderTest({ - layers: { - externalLauncher: { - launchEditor: () => Effect.fail(externalLauncherError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.shellOpenInEditor]({ - cwd: "/tmp/project", - editor: "cursor", - }), - ).pipe(Effect.result), - ); - - assertFailure(result, externalLauncherError); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc git methods", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - cwd: "/tmp/repo", - }, - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.succeed({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - status: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - runStackedAction: (input, options) => - Effect.gen(function* () { - const result = { - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc123", - subject: "feat: demo", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - toast: { - title: "Committed abc123", - description: "feat: demo", - cta: { - kind: "run_action" as const, - label: "Push", - action: { - kind: "push" as const, - }, - }, - }, - }; - - yield* ( - options?.progressReporter?.publish({ - actionId: options.actionId ?? input.actionId, - cwd: input.cwd, - action: input.action, - kind: "phase_started", - phase: "commit", - label: "Committing...", - }) ?? Effect.void - ); - - yield* ( - options?.progressReporter?.publish({ - actionId: options.actionId ?? input.actionId, - cwd: input.cwd, - action: input.action, - kind: "action_finished", - result, - }) ?? Effect.void - ); - - return result; - }), - resolvePullRequest: () => - Effect.succeed({ - pullRequest: { - number: 1, - title: "Demo PR", - url: "https://example.com/pr/1", - baseBranch: "main", - headBranch: "feature/demo", - state: "open", - }, - }), - preparePullRequestThread: () => - Effect.succeed({ - pullRequest: { - number: 1, - title: "Demo PR", - url: "https://example.com/pr/1", - baseBranch: "main", - headBranch: "feature/demo", - state: "open", - }, - branch: "feature/demo", - worktreePath: null, - }), - }, - gitVcsDriver: { - pullCurrentBranch: () => - Effect.succeed({ - status: "pulled", - refName: "main", - upstreamRef: "origin/main", - }), - listRefs: () => - Effect.succeed({ - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - ], - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 1, - }), - createWorktree: () => - Effect.succeed({ - worktree: { path: "/tmp/wt", refName: "feature/demo" }, - }), - removeWorktree: () => Effect.void, - createRef: (input) => Effect.succeed({ refName: input.refName }), - switchRef: (input) => Effect.succeed({ refName: input.refName }), - }, - vcsStatusBroadcaster: { - refreshStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - }, - reviewService: { - getDiffPreview: (input) => - Effect.succeed({ - cwd: input.cwd, - generatedAt: DateTime.nowUnsafe(), - sources: [ - { - id: "working-tree", - kind: "working-tree", - title: "Dirty worktree", - baseRef: "HEAD", - headRef: null, - diff: "dirty-diff", - diffHash: "hash-dirty", - truncated: false, - }, - { - id: "branch-range", - kind: "branch-range", - title: "Against main", - baseRef: "main", - headRef: "feature/demo", - diff: "base-diff", - diffHash: "hash-base", - truncated: false, - }, - ], - }), - getDiffFileContents: () => - Effect.succeed({ - oldContents: "before\n", - newContents: "after\n", - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - - const pull = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })), - ); - assert.equal(pull.status, "pulled"); - - const refreshedStatus = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsRefreshStatus]({ cwd: "/tmp/repo" }), - ), - ); - assert.equal(refreshedStatus.isRepo, true); - - const stackedEvents = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe( - Stream.runCollect, - Effect.map((events) => Array.from(events)), - ), - ), - ); - const lastStackedEvent = stackedEvents.at(-1); - assert.equal(lastStackedEvent?.kind, "action_finished"); - if (lastStackedEvent?.kind === "action_finished") { - assert.equal(lastStackedEvent.result.action, "commit"); - } - - const resolvedPr = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitResolvePullRequest]({ - cwd: "/tmp/repo", - reference: "1", - }), - ), - ); - assert.equal(resolvedPr.pullRequest.number, 1); - - const prepared = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitPreparePullRequestThread]({ - cwd: "/tmp/repo", - reference: "1", - mode: "local", - }), - ), - ); - assert.equal(prepared.branch, "feature/demo"); - - const refs = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsListRefs]({ cwd: "/tmp/repo" })), - ); - assert.equal(refs.refs[0]?.name, "main"); - - const worktree = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsCreateWorktree]({ - cwd: "/tmp/repo", - refName: "main", - path: null, - }), - ), - ); - assert.equal(worktree.worktree.refName, "feature/demo"); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsRemoveWorktree]({ - cwd: "/tmp/repo", - path: "/tmp/wt", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsCreateRef]({ - cwd: "/tmp/repo", - refName: "feature/new", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsSwitchRef]({ - cwd: "/tmp/repo", - refName: "main", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsInit]({ - cwd: "/tmp/repo", - }), - ), - ); - - const diffPreview = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.reviewGetDiffPreview]({ cwd: "/tmp/repo" }), - ), - ); - assert.equal(diffPreview.sources[0]?.diff, "dirty-diff"); - - const diffFileContents = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.reviewGetDiffFileContents]({ - cwd: "/tmp/repo", - sourceKind: "working-tree", - changeType: "change", - baseRef: "HEAD", - headRef: null, - oldPath: "README.md", - newPath: "README.md", - }), - ), - ); - assert.equal(diffFileContents.oldContents, "before\n"); - assert.equal(diffFileContents.newContents, "after\n"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc git.pull errors", () => - Effect.gen(function* () { - const gitError = new GitCommandError({ - operation: "pull", - command: "git pull --ff-only", - cwd: "/tmp/repo", - detail: "upstream missing", - }); - let invalidationCalls = 0; - let statusCalls = 0; - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - pullCurrentBranch: () => Effect.fail(gitError), - }, - gitManager: { - invalidateLocalStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateRemoteStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sync(() => { - statusCalls += 1; - return { - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - status: () => - Effect.sync(() => { - statusCalls += 1; - return { - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })).pipe( - Effect.result, - ), - ); - - assertFailure(result, gitError); - assert.equal(invalidationCalls, 0); - assert.equal(statusCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc git.runStackedAction errors after refreshing git status", () => - Effect.gen(function* () { - const gitError = new GitCommandError({ - operation: "commit", - command: "git commit", - cwd: "/tmp/repo", - detail: "nothing to commit", - }); - let invalidationCalls = 0; - let statusCalls = 0; - yield* buildAppUnderTest({ - layers: { - gitManager: { - invalidateLocalStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateRemoteStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sync(() => { - statusCalls += 1; - return { - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - status: () => - Effect.sync(() => { - statusCalls += 1; - return { - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - runStackedAction: () => Effect.fail(gitError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe(Stream.runCollect, Effect.result), - ), - ); - - assertFailure(result, gitError); - assert.equal(invalidationCalls, 0); - assert.equal(statusCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("completes websocket rpc git.pull before background git status refresh finishes", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - pullCurrentBranch: () => - Effect.succeed({ - status: "pulled" as const, - refName: "main", - upstreamRef: "origin/main", - }), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sleep(Duration.seconds(2)).pipe( - Effect.as({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const startedAt = yield* Clock.currentTimeMillis; - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })), - ); - const elapsedMs = (yield* Clock.currentTimeMillis) - startedAt; - - assert.equal(result.status, "pulled"); - assertTrue(elapsedMs < 1_000); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "completes websocket rpc git.runStackedAction before background git status refresh finishes", - () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sleep(Duration.seconds(2)).pipe( - Effect.as({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ), - runStackedAction: () => - Effect.succeed({ - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc123", - subject: "feat: demo", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - toast: { - title: "Committed abc123", - description: "feat: demo", - cta: { - kind: "run_action" as const, - label: "Push", - action: { - kind: "push" as const, - }, - }, - }, - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const startedAt = yield* Clock.currentTimeMillis; - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe(Stream.runCollect), - ), - ); - const elapsedMs = (yield* Clock.currentTimeMillis) - startedAt; - - assertTrue(elapsedMs < 1_000); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "starts a background local git status refresh after a successful git.runStackedAction", - () => - Effect.gen(function* () { - const localRefreshStarted = yield* Deferred.make(); - - yield* buildAppUnderTest({ - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Deferred.succeed(localRefreshStarted, undefined).pipe( - Effect.ignore, - Effect.andThen( - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - ), - ), - remoteStatus: () => - Effect.sleep(Duration.seconds(2)).pipe( - Effect.as({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ), - runStackedAction: () => - Effect.succeed({ - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc123", - subject: "feat: demo", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - toast: { - title: "Committed abc123", - description: "feat: demo", - cta: { - kind: "run_action" as const, - label: "Push", - action: { - kind: "push" as const, - }, - }, - }, - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe(Stream.runCollect), - ), - ); - - yield* Deferred.await(localRefreshStarted); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc orchestration methods", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const snapshot = { - snapshotSequence: 1, - updatedAt: now, - projects: [ - { - id: ProjectId.make("project-a"), - title: "Project A", - workspaceRoot: "/tmp/project-a", - defaultModelSelection, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: [ - { - id: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - title: "Thread A", - modelSelection: defaultModelSelection, - interactionMode: "default" as const, - runtimeMode: "full-access" as const, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestTurn: null, - messages: [], - session: null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - }, - ], - }; - - yield* buildAppUnderTest({ - layers: { - projectionSnapshotQuery: { - getSnapshot: () => Effect.succeed(snapshot), - searchThreads: () => - Effect.succeed({ - matches: [ - { - threadId: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - source: "assistant", - snippet: "Search reached the final response.", - messageCreatedAt: now, - }, - ], - }), - }, - orchestrationEngine: { - dispatch: () => Effect.succeed({ sequence: 7 }), - readEvents: () => Stream.empty, - }, - checkpointDiffQuery: { - getTurnDiff: () => - Effect.succeed({ - threadId: ThreadId.make("thread-1"), - fromTurnCount: 0, - toTurnCount: 1, - diff: "turn-diff", - }), - getFullThreadDiff: () => - Effect.succeed({ - threadId: ThreadId.make("thread-1"), - fromTurnCount: 0, - toTurnCount: 1, - diff: "full-diff", - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.session.stop", - commandId: CommandId.make("cmd-1"), - threadId: ThreadId.make("thread-1"), - createdAt: now, - }), - ), - ); - assert.equal(dispatchResult.sequence, 7); - - const turnDiffResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.getTurnDiff]({ - threadId: ThreadId.make("thread-1"), - fromTurnCount: 0, - toTurnCount: 1, - }), - ), - ); - assert.equal(turnDiffResult.diff, "turn-diff"); - - const fullDiffResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.getFullThreadDiff]({ - threadId: ThreadId.make("thread-1"), - toTurnCount: 1, - }), - ), - ); - assert.equal(fullDiffResult.diff, "full-diff"); - - const searchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.searchThreads]({ - query: "final response", - }), - ), - ); - assert.deepEqual(searchResult.matches, [ - { - threadId: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - source: "assistant", - snippet: "Search reached the final response.", - messageCreatedAt: now, - }, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("streams orchestration V2 replay output over websocket rpc", () => - Effect.gen(function* () { - const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((candidate) => candidate.name === "simple"); - if (!fixture) { - throw new Error("Missing simple orchestration V2 replay fixture."); - } - const provider = fixture.providers.find((candidate) => candidate.provider === "codex"); - if (!provider) { - throw new Error("Missing Codex provider variant for simple orchestration V2 fixture."); - } - - const harness = orchestrationV2ReplayHarnessFor(provider.provider); - const rawTranscript = yield* readProviderReplayTranscript(provider.transcriptFile); - const transcript = yield* harness.decodeTranscript(rawTranscript); - const materialized = yield* materializeFixtureInput({ - scenario: fixture.name, - fixtureInput: fixture.buildInput(), - modelSelection: provider.modelSelection, - }).pipe(Effect.provide(idAllocatorV2Layer), provideDeterministicTestRuntime); - const scenario = { - name: `${fixture.name}/${provider.provider}/ws`, - transcript, - commands: materialized.commands, - steps: materialized.steps, - projectionThreadIds: materialized.projectionThreadIds, - }; - const [createThreadCommand, dispatchMessageCommand] = materialized.commands; - if (createThreadCommand?.type !== "thread.create") { - throw new Error("Expected first simple fixture command to create a thread."); - } - if (dispatchMessageCommand?.type !== "message.dispatch") { - throw new Error("Expected second simple fixture command to dispatch a message."); - } - - yield* buildAppUnderTest({ - layers: { - orchestratorV2: makeOrchestratorV2ProviderReplayLayer(scenario, harness).pipe( - Layer.orDie, - ), - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const received = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - Effect.gen(function* () { - const createResult = - yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](createThreadCommand); - const duplicateCreateResult = - yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](createThreadCommand); - assert.equal(duplicateCreateResult.sequence, createResult.sequence); - - const shellItems = yield* Queue.unbounded(); - const shellFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe( - Stream.runForEach((item) => Queue.offer(shellItems, item)), - Effect.forkDetach, - ); - const shellSnapshot = yield* takeWsItem(shellItems, "orchestration V2 shell snapshot"); - assert.equal(shellSnapshot.kind, "snapshot"); - if (shellSnapshot.kind === "snapshot") { - const thread = shellSnapshot.snapshot.threads.find( - (candidate) => candidate.id === createThreadCommand.threadId, - ); - assert.isDefined(thread); - assert.equal(thread.itemCount, 0); - assert.equal(thread.status, "idle"); - } - - const streamItems = yield* Queue.unbounded(); - const streamFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({ - threadId: createThreadCommand.threadId, - }).pipe( - Stream.runForEach((item) => Queue.offer(streamItems, item)), - Effect.forkDetach, - ); - - const snapshot = yield* takeWsItem(streamItems, "orchestration V2 snapshot"); - assert.equal(snapshot.kind, "snapshot"); - if (snapshot.kind === "snapshot") { - assert.equal(snapshot.projection.thread.id, createThreadCommand.threadId); - assert.equal(snapshot.snapshotSequence, createResult.sequence); - assert.deepEqual( - snapshot.projection.turnItems.map((item) => item.type), - [], - ); - } - - yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](dispatchMessageCommand); - - const items: Array = []; - const shellUpdates: Array = []; - const turnItemTypes = new Set(); - for (let index = 0; index < 20; index += 1) { - const item = yield* takeWsItem(streamItems, `orchestration V2 event ${index + 1}`); - items.push(item); - if (item.kind === "event") { - assert.isAbove(item.sequence, createResult.sequence); - } - if (item.kind === "event" && item.event.type === "turn-item.updated") { - turnItemTypes.add(item.event.payload.type); - } - if (turnItemTypes.has("user_message") && turnItemTypes.has("assistant_message")) { - break; - } - } - for (let index = 0; index < 20; index += 1) { - const item = yield* takeWsItem( - shellItems, - `orchestration V2 shell update ${index + 1}`, - ); - shellUpdates.push(item); - if ( - item.kind === "thread.updated" && - item.thread.id === createThreadCommand.threadId && - item.thread.visibleItemCount >= 2 - ) { - break; - } - } - - const projection = yield* client[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]({ - threadId: createThreadCommand.threadId, - }); - yield* Fiber.interrupt(streamFiber); - yield* Fiber.interrupt(shellFiber); - - return { items, shellUpdates, projection }; - }), - ), - ); - - const streamedTurnItems = received.items.flatMap((item) => - item.kind === "event" && item.event.type === "turn-item.updated" - ? [item.event.payload] - : [], - ); - assert.deepEqual( - streamedTurnItems.map((item) => item.type), - ["user_message", "assistant_message"], - ); - assert.deepEqual( - received.projection.turnItems.map((item) => item.type), - ["user_message", "assistant_message"], - ); - assert.isTrue( - received.shellUpdates.some( - (item) => - item.kind === "thread.updated" && - item.thread.visibleItemCount === received.projection.visibleTurnItems.length, - ), - ); - assert.equal( - received.projection.turnItems.find((item) => item.type === "assistant_message")?.text, - "fixture simple ok", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("enriches replayed project events with repository identity metadata", () => - Effect.gen(function* () { - const projectionError = new PersistenceSqlError({ - operation: "ProjectionSnapshotQuery.getShellSnapshot:test", - detail: "failed to read projection shell snapshot", - }); - yield* buildAppUnderTest({ - layers: { - projectionSnapshotQuery: { - getShellSnapshot: () => Effect.fail(projectionError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(Stream.runCollect), - ).pipe(Effect.result), - ); - - assertTrue(result._tag === "Failure"); - assertTrue(result.failure._tag === "OrchestrationGetSnapshotError"); - assertTrue(result.failure.cause instanceof Error); - assert.include(result.failure.cause.message, projectionError.message); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("marks an empty shell catch-up replay as synchronized when requested", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - readEvents: () => Stream.empty, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const firstItem = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - afterSequence: 0, - requestCompletionMarker: true, - }).pipe(Stream.runHead), - ), - ); - - assert.deepEqual(Option.getOrThrow(firstItem), { kind: "synchronized" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("marks a socket thread snapshot as synchronized when requested", () => - Effect.gen(function* () { - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - yield* buildAppUnderTest({ - layers: { - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.succeed(Option.some({ snapshotSequence: 1, thread })), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - assert.equal(items[0]?.kind, "snapshot"); - assert.deepEqual(items[1], { kind: "synchronized" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("buffers shell events published while the fallback snapshot loads", () => - Effect.gen(function* () { - const liveEvents = yield* PubSub.unbounded(); - const deletedEvent = { - sequence: 2, - eventId: EventId.make("event-shell-thread-deleted"), - aggregateKind: "thread", - aggregateId: defaultThreadId, - occurredAt: "2026-01-01T00:00:01.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.deleted", - payload: { - threadId: defaultThreadId, - deletedAt: "2026-01-01T00:00:01.000Z", - }, - } satisfies Extract; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - streamDomainEvents: Stream.fromPubSub(liveEvents), - }, - projectionSnapshotQuery: { - getShellSnapshot: () => - Effect.gen(function* () { - yield* PubSub.publish(liveEvents, deletedEvent); - return { - snapshotSequence: 1, - projects: [], - threads: [makeDefaultOrchestrationThreadShell()], - updatedAt: "2026-01-01T00:00:00.000Z", - }; - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - requestCompletionMarker: true, - }).pipe(Stream.take(3), Stream.runCollect), - ), - ).pipe(Effect.timeout("2 seconds")); - - assert.equal(items[0]?.kind, "snapshot"); - assert.equal(items[1]?.kind, "thread-removed"); - assert.deepEqual(items[2], { kind: "synchronized" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("buffers thread events published while the initial snapshot loads", () => - Effect.gen(function* () { - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - const liveEvents = yield* PubSub.unbounded(); - const messageEvent = { - sequence: 2, - eventId: EventId.make("event-message"), - aggregateKind: "thread", - aggregateId: defaultThreadId, - occurredAt: "2026-01-01T00:00:01.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: { - threadId: defaultThreadId, - messageId: MessageId.make("message-1"), - role: "user", - text: "First message", - turnId: null, - streaming: false, - createdAt: "2026-01-01T00:00:01.000Z", - updatedAt: "2026-01-01T00:00:01.000Z", - }, - } satisfies Extract; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - streamDomainEvents: Stream.fromPubSub(liveEvents), - }, - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.gen(function* () { - yield* Effect.sleep("25 millis"); - yield* PubSub.publish(liveEvents, messageEvent); - return Option.some({ snapshotSequence: 1, thread }); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ).pipe(Effect.timeout("2 seconds")); - - assert.equal(items[0]?.kind, "snapshot"); - assert.equal(items[1]?.kind, "event"); - assert.equal(items[1]?.kind === "event" ? items[1].event.sequence : null, 2); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () => - Effect.gen(function* () { - let readEventsCalls = 0; - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - // Head is far ahead of the client's afterSequence (gap > 1000). - latestSequence: Effect.succeed(100_000), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return {} as OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.succeed(Option.some({ snapshotSequence: 100_000, thread })), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - afterSequence: 5, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(items); - // Large gap => fresh thread snapshot, and the global replay never starts. - assert.equal(first?.kind, "snapshot"); - if (first?.kind === "snapshot") { - assert.equal(first.snapshot.thread.id, defaultThreadId); - assert.equal(first.snapshot.snapshotSequence, 100_000); - } - assert.equal(second?.kind, "synchronized"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeThread replaces a cursor ahead of the authoritative head", () => - Effect.gen(function* () { - let readEventsCalls = 0; - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(5), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return {} as OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.succeed(Option.some({ snapshotSequence: 5, thread })), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const first = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - afterSequence: 10, - }).pipe(Stream.runHead), - ), - ); - - assert.equal(Option.getOrThrow(first).kind, "snapshot"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeThread bounds catch-up replay to the captured head", () => - Effect.gen(function* () { - let replayLimit: number | undefined; - const now = "2026-01-01T00:00:00.000Z"; - const messageEvent = { - sequence: 3, - eventId: EventId.make("event-replay-message"), - aggregateKind: "thread", - aggregateId: defaultThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: { - threadId: defaultThreadId, - messageId: MessageId.make("message-replay"), - role: "user", - text: "Replayed message", - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - } satisfies Extract; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(50), - readEvents: (_afterSequence, limit) => { - replayLimit = limit; - return Stream.make(messageEvent); - }, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - afterSequence: 0, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(items); - assert.equal(first?.kind, "event"); - assert.equal(first?.kind === "event" ? first.event.sequence : null, 3); - assert.equal(second?.kind, "synchronized"); - // The replay is bounded to the head captured before the read, not - // Number.MAX_SAFE_INTEGER. - assert.equal(replayLimit, 50); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell sends a fresh snapshot instead of replaying a large gap", () => - Effect.gen(function* () { - let readEventsCalls = 0; - const snapshotThreadId = ThreadId.make("thread-from-snapshot"); - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - // Head is far ahead of the client's afterSequence (gap > 1000). - latestSequence: Effect.succeed(100_000), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return { - sequence: 1, - eventId: EventId.make("event-should-not-be-read"), - aggregateKind: "thread", - aggregateId: snapshotThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.created", - payload: {} as never, - } satisfies OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 100_000, - projects: [], - threads: [makeDefaultOrchestrationThreadShell({ id: snapshotThreadId })], - updatedAt: now, - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - afterSequence: 5, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(items); - // Large gap => fresh snapshot, and the unbounded replay is never started. - assert.equal(first?.kind, "snapshot"); - if (first?.kind === "snapshot") { - assert.equal(first.snapshot.threads[0]?.id, snapshotThreadId); - } - assert.equal(second?.kind, "synchronized"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell replaces a cursor ahead of the authoritative head", () => - Effect.gen(function* () { - let readEventsCalls = 0; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(5), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return {} as OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 5, - projects: [], - threads: [], - updatedAt: "2026-01-01T00:00:00.000Z", - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const first = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 10 }).pipe( - Stream.runHead, - ), - ), - ); - - assert.equal(Option.getOrThrow(first).kind, "snapshot"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell coalesces a per-thread burst without stalling other threads", () => - Effect.gen(function* () { - const busyThreadId = ThreadId.make("thread-busy"); - const newThreadId = ThreadId.make("thread-new"); - const now = "2026-01-01T00:00:00.000Z"; - const shellFetches: Array = []; - let replayLimit: number | undefined; - - const messageEvent = (sequence: number): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-${sequence}`), - aggregateKind: "thread", - aggregateId: busyThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: {} as never, - }) satisfies OrchestrationEvent; - - const createdEvent: OrchestrationEvent = { - sequence: 50, - eventId: EventId.make("event-created"), - aggregateKind: "thread", - aggregateId: newThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.created", - payload: {} as never, - }; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(50), - // A burst of message-sent deltas for the busy thread, plus one - // thread.created for a different thread, all within one batch. - readEvents: (_afterSequence, limit) => { - replayLimit = limit; - return Stream.fromIterable([ - ...Array.from({ length: 20 }, (_unused, index) => messageEvent(index + 1)), - createdEvent, - ]); - }, - }, - projectionSnapshotQuery: { - getThreadShellById: (threadId) => - Effect.sync(() => { - shellFetches.push(threadId); - return Option.some(makeDefaultOrchestrationThreadShell({ id: threadId })); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - afterSequence: 0, - requestCompletionMarker: true, - }).pipe(Stream.take(3), Stream.runCollect), - ), - ); - - const collected = Array.from(items); - const upsertedIds = collected.flatMap((item) => - item.kind === "thread-upserted" ? [item.thread.id] : [], - ); - // Both threads surface, and the busy thread's 20-event burst collapses to - // a single shell refetch (not 20). The new thread is not stuck behind it. - assert.include(upsertedIds, busyThreadId); - assert.include(upsertedIds, newThreadId); - assert.equal(collected[2]?.kind, "synchronized"); - assert.equal(shellFetches.filter((id) => id === busyThreadId).length, 1); - assert.equal(replayLimit, 50); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell coalesces live bursts after the synchronization marker", () => - Effect.gen(function* () { - const busyThreadId = ThreadId.make("thread-live-busy"); - const newThreadId = ThreadId.make("thread-live-new"); - const now = "2026-01-01T00:00:00.000Z"; - const liveEvents = yield* PubSub.unbounded(); - const synchronized = yield* Deferred.make(); - const shellFetches: Array = []; - const observedLiveThreadIds = new Set(); - - const messageEvent = (sequence: number): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-live-${sequence}`), - aggregateKind: "thread", - aggregateId: busyThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: {} as never, - }) satisfies OrchestrationEvent; - - const createdEvent: OrchestrationEvent = { - sequence: 50, - eventId: EventId.make("event-live-created"), - aggregateKind: "thread", - aggregateId: newThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.created", - payload: {} as never, - }; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - streamDomainEvents: Stream.fromPubSub(liveEvents), - }, - projectionSnapshotQuery: { - getThreadShellById: (threadId) => - Effect.sync(() => { - shellFetches.push(threadId); - return Option.some(makeDefaultOrchestrationThreadShell({ id: threadId })); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - Effect.gen(function* () { - const itemsFiber = yield* withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - requestCompletionMarker: true, - }).pipe( - Stream.tap((item) => - item.kind === "synchronized" - ? Deferred.succeed(synchronized, undefined).pipe(Effect.ignore) - : Effect.void, - ), - Stream.takeUntil((item) => { - if (item.kind === "thread-upserted") { - observedLiveThreadIds.add(item.thread.id); - } - return ( - observedLiveThreadIds.has(busyThreadId) && observedLiveThreadIds.has(newThreadId) - ); - }), - Stream.runCollect, - ), - ).pipe(Effect.forkScoped); - - yield* Deferred.await(synchronized); - for (const event of [ - ...Array.from({ length: 20 }, (_unused, index) => messageEvent(index + 1)), - createdEvent, - ]) { - yield* PubSub.publish(liveEvents, event); - } - - return yield* Fiber.join(itemsFiber); - }), - ).pipe(Effect.timeout("2 seconds")); - - assert.equal(items[0]?.kind, "snapshot"); - assert.equal(items[1]?.kind, "synchronized"); - const liveUpsertedIds = Array.from(items) - .slice(2) - .flatMap((item) => (item.kind === "thread-upserted" ? [item.thread.id] : [])); - assert.include(liveUpsertedIds, busyThreadId); - assert.include(liveUpsertedIds, newThreadId); - assert.isBelow(shellFetches.filter((id) => id === busyThreadId).length, 20); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("subscribeShell coalescing still emits a removal for a deleted thread", () => - Effect.gen(function* () { - const goneThreadId = ThreadId.make("thread-gone"); - const now = "2026-01-01T00:00:00.000Z"; - - const makeThreadEvent = ( - sequence: number, - type: "thread.deleted" | "thread.message-sent", - ): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-${sequence}`), - aggregateKind: "thread", - aggregateId: goneThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type, - payload: type === "thread.deleted" ? { threadId: goneThreadId, deletedAt: now } : {}, - }) as OrchestrationEvent; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(2), - // A thread.deleted followed, within the same coalescing window, by a - // later refetchable event for the same thread. The later event wins - // coalescing; its shell refetch returns none (the row is gone), which - // must still surface a removal rather than be swallowed. - readEvents: () => - Stream.fromIterable([ - makeThreadEvent(1, "thread.deleted"), - makeThreadEvent(2, "thread.message-sent"), - ]), - }, - projectionSnapshotQuery: { - getThreadShellById: () => Effect.succeed(Option.none()), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe( - Stream.take(1), - Stream.runCollect, - ), - ), - ); - - const [first] = Array.from(items); - assert.equal(first?.kind, "thread-removed"); - assert.equal(first?.kind === "thread-removed" ? first.threadId : null, goneThreadId); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell retries a transient shell projection refetch failure", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-transient-refetch"); - const now = "2026-01-01T00:00:00.000Z"; - let attempts = 0; - - const event: OrchestrationEvent = { - sequence: 1, - eventId: EventId.make("event-transient-refetch"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: {} as never, - }; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(1), - readEvents: () => Stream.make(event), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.suspend(() => { - attempts += 1; - return attempts === 1 - ? Effect.fail( - new PersistenceSqlError({ - operation: "test.shell-refetch", - detail: "transient failure", - }), - ) - : Effect.succeed( - Option.some(makeDefaultOrchestrationThreadShell({ id: threadId })), - ); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe( - Stream.take(1), - Stream.runCollect, - ), - ), - ); - - const [first] = Array.from(items); - assert.equal(first?.kind, "thread-upserted"); - assert.equal(first?.kind === "thread-upserted" ? first.thread.id : null, threadId); - assert.equal(attempts, 2); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell coalescing still removes a project after a trailing update", () => - Effect.gen(function* () { - const projectId = ProjectId.make("project-gone"); - const now = "2026-01-01T00:00:00.000Z"; - - const makeProjectEvent = ( - sequence: number, - type: "project.deleted" | "project.meta-updated", - ): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-project-${sequence}`), - aggregateKind: "project", - aggregateId: projectId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type, - payload: - type === "project.deleted" - ? { projectId, deletedAt: now } - : { projectId, title: "Still deleted", updatedAt: now }, - }) as OrchestrationEvent; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(2), - readEvents: () => - Stream.fromIterable([ - makeProjectEvent(1, "project.deleted"), - makeProjectEvent(2, "project.meta-updated"), - ]), - }, - projectionSnapshotQuery: { - getProjectShellById: () => Effect.succeed(Option.none()), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe( - Stream.take(1), - Stream.runCollect, - ), - ), - ); - - const [first] = Array.from(items); - assert.equal(first?.kind, "project-removed"); - assert.equal(first?.kind === "project-removed" ? first.projectId : null, projectId); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("stops the provider session and closes thread terminals after archive", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - const sessionStopCommand = dispatchedCommands[1]; - assert.equal(sessionStopCommand?.type, "thread.session.stop"); - if (sessionStopCommand?.type === "thread.session.stop") { - assert.equal(sessionStopCommand.threadId, threadId); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("checks session status before archiving removes the thread from active lookups", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-precheck"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - let archived = false; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - if (command.type === "thread.archive") { - archived = true; - } - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.sync(() => { - effects.push(`query:thread-shell:${archived ? "archived" : "active"}`); - return archived - ? Option.none() - : Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-precheck"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "query:thread-shell:active", - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive", "thread.session.stop"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("archives without dispatching session stop when the thread has no session", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-no-session"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-no-session"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "archives without dispatching session stop when the thread session is already stopped", - () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-stopped-session"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "stopped", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-stopped-session"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("archives and still closes terminals when session stop fails", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-stop-failure"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - if (command.type === "thread.session.stop") { - return Effect.fail( - new OrchestrationListenerCallbackError({ - listener: "domain-event", - detail: "simulated archive stop failure", - }), - ); - } - return Effect.succeed({ sequence: dispatchedCommands.length }); - }, - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-stop-failure"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive", "thread.session.stop"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("archives and still closes terminals when session stop defects", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-stop-defect"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - if (command.type === "thread.session.stop") { - return Effect.die(new Error("simulated archive stop defect")); - } - return Effect.succeed({ sequence: dispatchedCommands.length }); - }, - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-stop-defect"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive", "thread.session.stop"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "bootstraps first-send worktree turns on the server before dispatching turn start", - () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const bootstrapGitOperations: string[] = []; - const refreshStatus = vi.fn((_: string) => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "t3code/bootstrap-refName", - hasWorkingTreeChanges: false, - workingTree: { - files: [], - insertions: 0, - deletions: 0, - }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ); - const fetchRemote = vi.fn( - (_: Parameters[0]) => - Effect.sync(() => { - bootstrapGitOperations.push("fetch"); - }), - ); - const fetchedOriginCommit = "0123456789abcdef0123456789abcdef01234567"; - const resolveRemoteTrackingCommit = vi.fn( - (_: Parameters[0]) => - Effect.sync(() => { - bootstrapGitOperations.push("resolve-remote-commit"); - return { - commitSha: fetchedOriginCommit, - remoteRefName: "origin/main", - }; - }), - ); - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.sync(() => { - bootstrapGitOperations.push("create-worktree"); - return { - worktree: { - refName: "t3code/bootstrap-refName", - path: "/tmp/bootstrap-worktree", - }, - }; - }), - ); - const runForThread = vi.fn( - ( - _: Parameters< - ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"] - >[0], - ) => - Effect.succeed({ - status: "started" as const, - scriptId: "setup", - scriptName: "Setup", - terminalId: "setup-setup", - cwd: "/tmp/bootstrap-worktree", - }), - ); - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - fetchRemote, - resolveRemoteTrackingCommit, - createWorktree, - }, - vcsStatusBroadcaster: { - refreshStatus, - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }), - readEvents: () => Stream.empty, - }, - projectSetupScriptRunner: { - runForThread, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start"), - threadId: ThreadId.make("thread-bootstrap"), - message: { - messageId: MessageId.make("msg-bootstrap"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - startFromOrigin: true, - }, - runSetupScript: true, - }, - createdAt, - }), - ), - ); - - assert.equal(response.sequence, 5); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - [ - "thread.create", - "thread.meta.update", - "thread.activity.append", - "thread.activity.append", - "thread.turn.start", - ], - ); - assert.deepEqual(createWorktree.mock.calls[0]?.[0], { - cwd: "/tmp/project", - refName: fetchedOriginCommit, - newRefName: "t3code/bootstrap-refName", - baseRefName: "main", - path: null, - }); - assert.deepEqual(fetchRemote.mock.calls[0]?.[0], { - cwd: "/tmp/project", - remoteName: "origin", - }); - assert.deepEqual(resolveRemoteTrackingCommit.mock.calls[0]?.[0], { - cwd: "/tmp/project", - refName: "main", - fallbackRemoteName: "origin", - }); - assert.deepEqual(bootstrapGitOperations, [ - "fetch", - "resolve-remote-commit", - "create-worktree", - ]); - assert.deepEqual(runForThread.mock.calls[0]?.[0], { - threadId: ThreadId.make("thread-bootstrap"), - projectId: defaultProjectId, - projectCwd: "/tmp/project", - worktreePath: "/tmp/bootstrap-worktree", - }); - assert.deepEqual(refreshStatus.mock.calls[0]?.[0], "/tmp/bootstrap-worktree"); - - const setupActivities = dispatchedCommands.filter( - (command): command is Extract => - command.type === "thread.activity.append", - ); - assert.deepEqual( - setupActivities.map((command) => command.activity.kind), - ["setup-script.requested", "setup-script.started"], - ); - const finalCommand = dispatchedCommands[4]; - assertTrue(finalCommand?.type === "thread.turn.start"); - if (finalCommand?.type === "thread.turn.start") { - assert.equal(finalCommand.bootstrap, undefined); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("records setup-script failures without aborting bootstrap turn start", () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.succeed({ - worktree: { - refName: "t3code/bootstrap-refName", - path: "/tmp/bootstrap-worktree", - }, - }), - ); - const runForThread = vi.fn( - ( - input: Parameters< - ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"] - >[0], - ) => - Effect.fail( - new ProjectSetupScriptRunner.ProjectSetupScriptOperationError({ - threadId: input.threadId, - worktreePath: input.worktreePath, - operation: "openTerminal", - cause: { message: "pty unavailable" }, - }), - ), - ); - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - createWorktree, - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }), - readEvents: () => Stream.empty, - }, - projectSetupScriptRunner: { - runForThread, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start-setup-failure"), - threadId: ThreadId.make("thread-bootstrap-setup-failure"), - message: { - messageId: MessageId.make("msg-bootstrap-setup-failure"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - }, - runSetupScript: true, - }, - createdAt, - }), - ), - ); - - assert.equal(response.sequence, 4); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], - ); - const setupFailureActivity = dispatchedCommands.find( - (command): command is Extract => - command.type === "thread.activity.append", - ); - assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed"); - assert.deepEqual(setupFailureActivity?.activity.payload, { - detail: "pty unavailable", - worktreePath: "/tmp/bootstrap-worktree", - }); - assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.succeed({ - worktree: { - refName: "t3code/bootstrap-refName", - path: "/tmp/bootstrap-worktree", - }, - }), - ); - const runForThread = vi.fn( - ( - _: Parameters< - ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"] - >[0], - ) => - Effect.succeed({ - status: "started" as const, - scriptId: "setup", - scriptName: "Setup", - terminalId: "setup-setup", - cwd: "/tmp/bootstrap-worktree", - }), - ); - let setupActivityAppendAttempt = 0; - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - createWorktree, - }, - orchestrationEngine: { - dispatch: (command) => { - if ( - command.type === "thread.activity.append" && - command.activity.kind.startsWith("setup-script.") - ) { - setupActivityAppendAttempt += 1; - if (setupActivityAppendAttempt === 2) { - return Effect.fail( - new OrchestrationListenerCallbackError({ - listener: "domain-event", - detail: "failed to append setup-script.started activity", - }), - ); - } - } - - return Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }); - }, - readEvents: () => Stream.empty, - }, - projectSetupScriptRunner: { - runForThread, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start-setup-activity-failure"), - threadId: ThreadId.make("thread-bootstrap-setup-activity-failure"), - message: { - messageId: MessageId.make("msg-bootstrap-setup-activity-failure"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - }, - runSetupScript: true, - }, - createdAt, - }), - ), - ); - - assert.equal(response.sequence, 4); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], - ); - const setupActivities = dispatchedCommands.filter( - (command): command is Extract => - command.type === "thread.activity.append", - ); - assert.deepEqual( - setupActivities.map((command) => command.activity.kind), - ["setup-script.requested"], - ); - assertTrue( - setupActivities.every((command) => command.activity.kind !== "setup-script.failed"), - ); - assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("cleans up created bootstrap threads when worktree creation defects", () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.die(new Error("worktree exploded")), - ); - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - createWorktree, - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }), - readEvents: () => Stream.empty, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start-defect"), - threadId: ThreadId.make("thread-bootstrap-defect"), - message: { - messageId: MessageId.make("msg-bootstrap-defect"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - }, - runSetupScript: false, - }, - createdAt, - }), - ).pipe(Effect.result), - ); - - assertTrue(result._tag === "Failure"); - assertTrue(result.failure._tag === "OrchestrationDispatchCommandError"); - assert.include(result.failure.message, "worktree exploded"); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.create", "thread.delete"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc terminal methods", () => - Effect.gen(function* () { - const snapshot = { - threadId: "thread-1", - terminalId: "default", - cwd: "/tmp/project", - worktreePath: null, - status: "running" as const, - pid: 1234, - history: "", - exitCode: null, - exitSignal: null, - label: "Primary", - updatedAt: "2026-01-01T00:00:00.000Z", - }; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - open: () => Effect.succeed(snapshot), - write: () => Effect.void, - resize: () => Effect.void, - clear: () => Effect.void, - restart: () => Effect.succeed(snapshot), - close: () => Effect.void, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - - const opened = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalOpen]({ - threadId: "thread-1", - terminalId: "default", - cwd: "/tmp/project", - }), - ), - ); - assert.equal(opened.terminalId, "default"); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalWrite]({ - threadId: "thread-1", - terminalId: "default", - data: "echo hi\n", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalResize]({ - threadId: "thread-1", - terminalId: "default", - cols: 120, - rows: 40, - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalClear]({ - threadId: "thread-1", - terminalId: "default", - }), - ), - ); - - const restarted = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalRestart]({ - threadId: "thread-1", - terminalId: "default", - cwd: "/tmp/project", - cols: 120, - rows: 40, - }), - ), - ); - assert.equal(restarted.terminalId, "default"); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalClose]({ - threadId: "thread-1", - terminalId: "default", - }), - ), - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc terminal.write errors", () => - Effect.gen(function* () { - const terminalError = new TerminalNotRunningError({ - threadId: "thread-1", - terminalId: "default", - }); - yield* buildAppUnderTest({ - layers: { - terminalManager: { - write: () => Effect.fail(terminalError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalWrite]({ - threadId: "thread-1", - terminalId: "default", - data: "echo fail\n", - }), - ).pipe(Effect.result), - ); - - assertFailure(result, terminalError); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); -}); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 4fd9b22278..6651574ebf 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -24,12 +24,6 @@ import * as ExternalLauncher from "./process/externalLauncher.ts"; import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; -import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts"; -import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts"; -import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts"; -import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts"; -import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts"; -import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts"; import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as CheckpointStore from "./checkpointing/CheckpointStore.ts"; @@ -49,12 +43,6 @@ import * as ProcessRunner from "./processRunner.ts"; import * as GitManager from "./git/GitManager.ts"; import * as Keybindings from "./keybindings.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; -import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts"; -import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.ts"; -import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts"; -import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts"; -import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts"; -import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts"; import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts"; @@ -75,7 +63,6 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts"; import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; -import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; import { ObservabilityLive } from "./observability/Layers/Observability.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts"; @@ -96,22 +83,27 @@ import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; -import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts"; -import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; -import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; -import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts"; -import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; -import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts"; +import { + OrchestrationV2ProductionLayerLive, + ProjectSetupScriptRunnerLayerLive, +} from "./orchestration-v2/runtimeLayer.ts"; +import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts"; +import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; import { clearPersistedServerRuntimeState, makePersistedServerRuntimeState, persistServerRuntimeState, } from "./serverRuntimeState.ts"; -import { - orchestrationDispatchRouteLayer, - orchestrationSnapshotRouteLayer, -} from "./orchestration/http.ts"; -import { OrchestrationV2LayerLive } from "./orchestration-v2/runtimeLayer.ts"; +import { projectHttpApiLayer } from "./project/http.ts"; +import * as NetService from "@t3tools/shared/Net"; +import * as RelayClient from "@t3tools/shared/relayClient"; +import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale"; + +// Effect's default preemptive shutdown waits 20s before finalizing request scopes. +// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer +// already closes the websocket gracefully. Do not add an artificial drain before +// those finalizers get a chance to run. +const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0; const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -220,31 +212,6 @@ const PlatformServicesLive = Layer.unwrap( }), ); -const ReactorLayerLive = Layer.empty.pipe( - Layer.provideMerge(OrchestrationReactorLive), - Layer.provideMerge(ProviderRuntimeIngestionLive), - Layer.provideMerge(ProviderCommandReactorLive), - Layer.provideMerge(CheckpointReactorLive), - Layer.provideMerge(ThreadDeletionReactorLive), - Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))), - Layer.provideMerge(RuntimeReceiptBusLive), -); - -const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe( - Layer.provide(ProviderSessionRuntime.layer), -); - -// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter -// by looking up the default `ProviderInstance` per driver in the instance -// registry. Adapter construction itself moved inside each driver's -// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical -// NDJSON writers and is provided at the outer runtime layer so both -// `ProviderService` and the per-instance drivers read the same logger pair. -const ProviderLayerLive = ProviderServiceLive.pipe( - Layer.provide(ProviderAdapterRegistryLive), - Layer.provideMerge(ProviderSessionDirectoryLayerLive), -); - const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive)); const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe( @@ -260,7 +227,7 @@ const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.lay ); const GitManagerLayerLive = GitManager.layer.pipe( - Layer.provideMerge(ProjectSetupScriptRunner.layer), + Layer.provideMerge(ProjectSetupScriptRunnerLayerLive), Layer.provideMerge(GitVcsDriver.layer), Layer.provideMerge(SourceControlProviderRegistryLayerLive), Layer.provideMerge(TextGeneration.layer), @@ -296,9 +263,8 @@ const VcsLayerLive = Layer.empty.pipe( Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))), ); -const CheckpointingLayerLive = Layer.empty.pipe( - Layer.provideMerge(CheckpointDiffQuery.layer), - Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))), +const CheckpointStoreLayerLive = CheckpointStore.layer.pipe( + Layer.provide(VcsDriverRegistryLayerLive), ); const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer)); @@ -346,19 +312,23 @@ const CloudManagedEndpointRuntimeLive = Layer.mergeAll( ), ); -const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe( - Layer.provideMerge(ProviderLayerLive), - Layer.provideMerge(OrchestrationLayerLive), +const OrchestrationV2RuntimeLayerLive = OrchestrationV2ProductionLayerLive.pipe( + Layer.provide(CheckpointStoreLayerLive), + Layer.provide(ResourceCleanupService.live), + Layer.provide(RunFinalizationService.observerLive), ); -const RuntimeCoreDependenciesBaseLive = ReactorLayerLive.pipe( +const OrchestrationApplicationLayerLive = CheckpointDiffQuery.layer.pipe( + Layer.provideMerge(CheckpointStoreLayerLive), + Layer.provideMerge(OrchestrationV2RuntimeLayerLive), +); + +const RuntimeCoreDependenciesBaseLive = AgentAwarenessRelay.layer.pipe( // Core Services - Layer.provideMerge(ServerSettingsLayerLive), - Layer.provideMerge(CheckpointingLayerLive), + Layer.provideMerge(OrchestrationApplicationLayerLive), Layer.provideMerge(SourceControlProviderRegistryLayerLive), Layer.provideMerge(GitLayerLive), Layer.provideMerge(VcsLayerLive), - Layer.provideMerge(ProviderRuntimeLayerLive), Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)), Layer.provideMerge(PersistenceLayerLive), Layer.provideMerge(Keybindings.layer), @@ -369,12 +339,6 @@ const RuntimeCoreDependenciesBaseLive = ReactorLayerLive.pipe( // `providerInstances` hydration merges `settings.providers.` // with explicit `providerInstances` entries on boot. Layer.provideMerge(ProviderInstanceRegistryHydrationLive), - // Shared native/canonical NDJSON writers used by both the per-instance - // drivers (native stream, written from inside each `Adapter`) and - // `ProviderService` (canonical stream, written after event normalization). - // Provided once at the runtime level so every consumer sees the same - // logger instances. - Layer.provideMerge(ProviderEventLoggersLive), ); const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe( @@ -421,7 +385,7 @@ export const makeRoutesLayer = Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(authHttpApiLayer), Layer.provide(connectHttpApiLayer), - Layer.provide(orchestrationHttpApiLayer), + Layer.provide(projectHttpApiLayer), Layer.provide(serverEnvironmentHttpApiLayer), Layer.provide(environmentAuthenticatedAuthLayer), ), diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index e3f7e482b2..c3731023e3 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -1,281 +1,72 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { DEFAULT_MODEL, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; -import * as Crypto from "effect/Crypto"; -import * as Deferred from "effect/Deferred"; +import { DEFAULT_MODEL, ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import * as Option from "effect/Option"; -import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; -import * as Stream from "effect/Stream"; -import * as ServerConfig from "./config.ts"; -import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts"; -import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; -import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; -it("uses the canonical Codex default for auto-bootstrapped model selection", () => { - assert.deepStrictEqual(ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(), { +it("uses the canonical Codex model for auto-bootstrap", () => { + assert.deepEqual(ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(), { instanceId: ProviderInstanceId.make("codex"), model: DEFAULT_MODEL, }); }); -it.effect("enqueueCommand waits for readiness and then drains queued work", () => +it.effect("runs projection repair, recovery, worker startup, and bootstrap in order", () => + Effect.gen(function* () { + const calls = yield* Ref.make>([]); + const record = (label: string) => Ref.update(calls, (current) => [...current, label]); + + const result = yield* ServerRuntimeStartup.runOrderedV2StartupPhases({ + verify: record("verify").pipe(Effect.as({ valid: false })), + rebuild: record("rebuild").pipe(Effect.as({ valid: true })), + recover: record("recover").pipe(Effect.as({ resumedSessions: 2 })), + startEffectWorker: record("worker"), + autoBootstrap: record("bootstrap").pipe(Effect.as({ projectId: "project-1" })), + }); + + assert.deepEqual(yield* Ref.get(calls), [ + "verify", + "rebuild", + "recover", + "worker", + "bootstrap", + ]); + assert.deepEqual(result, { + recovery: { resumedSessions: 2 }, + bootstrap: { projectId: "project-1" }, + }); + }), +); + +it.effect("does not rebuild valid projections", () => + Effect.gen(function* () { + const rebuilt = yield* Ref.make(false); + yield* ServerRuntimeStartup.runOrderedV2StartupPhases({ + verify: Effect.succeed({ valid: true }), + rebuild: Ref.set(rebuilt, true).pipe(Effect.as({ valid: true })), + recover: Effect.void, + startEffectWorker: Effect.void, + autoBootstrap: Effect.void, + }); + assert.isFalse(yield* Ref.get(rebuilt)); + }), +); + +it.effect("queues commands until startup signals readiness", () => Effect.scoped( Effect.gen(function* () { - const executionCount = yield* Ref.make(0); - const commandGate = yield* ServerRuntimeStartup.makeCommandGate; - - const queuedCommandFiber = yield* commandGate - .enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1)) + const gate = yield* ServerRuntimeStartup.makeCommandGate; + const count = yield* Ref.make(0); + const queued = yield* gate + .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1)) .pipe(Effect.forkScoped); yield* Effect.yieldNow; - assert.equal(yield* Ref.get(executionCount), 0); - - yield* commandGate.signalCommandReady; - - const result = yield* Fiber.join(queuedCommandFiber); - assert.equal(result, 1); - assert.equal(yield* Ref.get(executionCount), 1); + assert.equal(yield* Ref.get(count), 0); + yield* gate.signalCommandReady; + assert.equal(yield* Fiber.join(queued), 1); }), ), ); - -it.effect("enqueueCommand fails queued work when readiness fails", () => - Effect.scoped( - Effect.gen(function* () { - const commandGate = yield* ServerRuntimeStartup.makeCommandGate; - const failure = yield* Deferred.make(); - - const queuedCommandFiber = yield* commandGate - .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) - .pipe(Effect.forkScoped); - - yield* commandGate.failCommandReady( - new ServerRuntimeStartup.ServerRuntimeStartupError({ - mode: "web", - host: "127.0.0.1", - port: 3773, - cause: new Error("test startup failure"), - }), - ); - - const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); - assert.equal(error.message, "Server runtime startup failed before command readiness."); - }), - ), -); - -it.effect("launchStartupHeartbeat does not block the caller while counts are loading", () => - Effect.scoped( - Effect.gen(function* () { - const releaseCounts = yield* Deferred.make(); - - yield* ServerRuntimeStartup.launchStartupHeartbeat.pipe( - Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => Effect.die("unused"), - getCounts: () => - Deferred.await(releaseCounts).pipe( - Effect.as({ - projectCount: 2, - threadCount: 3, - }), - ), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - getFullThreadDiffContext: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - Effect.provideService(AnalyticsService.AnalyticsService, { - record: () => Effect.void, - flush: Effect.void, - }), - ); - }), - ), -); - -it.effect("resolveWelcomeBase derives cwd and project name from server config", () => - Effect.gen(function* () { - const welcome = yield* ServerRuntimeStartup.resolveWelcomeBase.pipe( - Effect.provideService(ServerConfig.ServerConfig, { - cwd: "/tmp/startup-project", - } as never), - ); - - assert.deepStrictEqual(welcome, { - cwd: "/tmp/startup-project", - projectName: "startup-project", - }); - }), -); - -it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and thread ids", () => { - const bootstrapProjectId = ProjectId.make("project-startup-bootstrap"); - const bootstrapThreadId = ThreadId.make("thread-startup-bootstrap"); - - return Effect.gen(function* () { - const dispatchCalls = yield* Ref.make>([]); - const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe( - Effect.provideService(ServerConfig.ServerConfig, { - cwd: "/tmp/startup-project", - autoBootstrapProjectFromCwd: true, - } as never), - Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => Effect.die("unused"), - getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: () => - Effect.succeed( - Option.some({ - id: bootstrapProjectId, - title: "Startup Project", - workspaceRoot: "/tmp/startup-project", - defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(), - scripts: [], - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - deletedAt: null, - }), - ), - getProjectShellById: () => Effect.die("unused"), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - getFullThreadDiffContext: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.die("unused"), - getThreadDetailById: () => Effect.die("unused"), - getThreadDetailSnapshot: () => Effect.die("unused"), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - Effect.provideService(OrchestrationEngine.OrchestrationEngineService, { - readEvents: () => Stream.empty, - dispatch: (command) => - Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe( - Effect.as({ sequence: 1 }), - ), - streamDomainEvents: Stream.empty, - latestSequence: Effect.succeed(0), - } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]), - Effect.provide(NodeServices.layer), - ); - - assert.deepStrictEqual(targets, { - bootstrapProjectId, - bootstrapThreadId, - }); - assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []); - }); -}); - -it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when missing", () => - Effect.gen(function* () { - const dispatchCalls = yield* Ref.make>([]); - const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe( - Effect.provideService(ServerConfig.ServerConfig, { - cwd: "/tmp/startup-project", - autoBootstrapProjectFromCwd: true, - } as never), - Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => Effect.die("unused"), - getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.die("unused"), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - getFullThreadDiffContext: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.die("unused"), - getThreadDetailById: () => Effect.die("unused"), - getThreadDetailSnapshot: () => Effect.die("unused"), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - Effect.provideService(OrchestrationEngine.OrchestrationEngineService, { - readEvents: () => Stream.empty, - dispatch: (command) => - Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe( - Effect.as({ sequence: 1 }), - ), - streamDomainEvents: Stream.empty, - latestSequence: Effect.succeed(0), - } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]), - Effect.provide(NodeServices.layer), - ); - - assert.equal(typeof targets.bootstrapProjectId, "string"); - assert.equal(typeof targets.bootstrapThreadId, "string"); - assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create", "thread.create"]); - }), -); - -it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation failures", () => - Effect.gen(function* () { - const crypto = yield* Crypto.Crypto; - const uuidError = PlatformError.systemError({ - _tag: "Unknown", - module: "Crypto", - method: "randomUUIDv4", - description: "UUID generation unavailable", - }); - const dispatchCalls = yield* Ref.make>([]); - - const error = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe( - Effect.provideService(ServerConfig.ServerConfig, { - cwd: "/tmp/startup-project", - autoBootstrapProjectFromCwd: true, - } as never), - Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => Effect.die("unused"), - getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getProjectShellById: () => Effect.die("unused"), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - getFullThreadDiffContext: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.die("unused"), - getThreadDetailById: () => Effect.die("unused"), - getThreadDetailSnapshot: () => Effect.die("unused"), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - Effect.provideService(OrchestrationEngine.OrchestrationEngineService, { - readEvents: () => Stream.empty, - dispatch: (command) => - Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe( - Effect.as({ sequence: 1 }), - ), - streamDomainEvents: Stream.empty, - latestSequence: Effect.succeed(0), - } satisfies OrchestrationEngine.OrchestrationEngineService["Service"]), - Effect.provideService(Crypto.Crypto, { - ...crypto, - randomUUIDv4: Effect.fail(uuidError), - }), - Effect.flip, - ); - - assert.strictEqual(error, uuidError); - assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []); - }).pipe(Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 5db2b75556..3bb3b1bbe7 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -15,27 +15,26 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; import * as ServerConfig from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; -import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts"; -import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; -import * as OrchestrationReactor from "./orchestration/Services/OrchestrationReactor.ts"; +import * as EffectWorker from "./orchestration-v2/EffectWorker.ts"; +import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; +import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts"; +import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "./project/ProjectService.ts"; +import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerSettings from "./serverSettings.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts"; -import { forkParked } from "./serverActivation.ts"; -import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; import { formatHeadlessServeOutput, formatHostForUrl, @@ -134,11 +133,19 @@ export const makeCommandGate = Effect.gen(function* () { export const recordStartupHeartbeat = Effect.gen(function* () { const analytics = yield* AnalyticsService.AnalyticsService; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const projects = yield* ProjectService.ProjectService; + const threads = yield* ThreadManagement.ThreadManagementService; - const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe( + const { threadCount, projectCount } = yield* Effect.all({ + projects: projects.snapshot, + threads: threads.getShellSnapshot(), + }).pipe( + Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({ + projectCount: projectSnapshot.projects.length, + threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length, + })), Effect.catch((cause) => - Effect.logWarning("failed to gather startup projection counts for telemetry", { + Effect.logWarning("failed to gather V2 startup counts for telemetry", { cause, }).pipe( Effect.as({ @@ -168,6 +175,11 @@ export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({ model: DEFAULT_MODEL, }); +interface AutoBootstrapWelcomeTargets { + readonly bootstrapProjectId?: ProjectId; + readonly bootstrapThreadId?: ThreadId; +} + export const resolveWelcomeBase = Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean); @@ -183,72 +195,52 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const randomUUID = crypto.randomUUIDv4; const serverConfig = yield* ServerConfig.ServerConfig; - const projectionReadModelQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; - const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService; + const projects = yield* ProjectService.ProjectService; + const threads = yield* ThreadManagement.ThreadManagementService; + const threadLaunch = yield* ThreadLaunch.ThreadLaunchService; const path = yield* Path.Path; let bootstrapProjectId: ProjectId | undefined; let bootstrapThreadId: ThreadId | undefined; if (serverConfig.autoBootstrapProjectFromCwd) { - yield* Effect.gen(function* () { - const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot( - serverConfig.cwd, - ); - let nextProjectId: ProjectId; - let nextProjectDefaultModelSelection: ModelSelection; - - if (Option.isNone(existingProject)) { - const createdAt = DateTime.formatIso(yield* DateTime.now); - nextProjectId = ProjectId.make(yield* randomUUID); - const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project"; - nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection(); - yield* orchestrationEngine.dispatch({ - type: "project.create", - commandId: CommandId.make(yield* randomUUID), - projectId: nextProjectId, - title: bootstrapProjectTitle, - workspaceRoot: serverConfig.cwd, - defaultModelSelection: nextProjectDefaultModelSelection, - createdAt, - }); - } else { - nextProjectId = existingProject.value.id; - nextProjectDefaultModelSelection = - existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection(); - } - - const existingThreadId = - yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId); - if (Option.isNone(existingThreadId)) { - const createdAt = DateTime.formatIso(yield* DateTime.now); - const createdThreadId = ThreadId.make(yield* randomUUID); - yield* orchestrationEngine.dispatch({ - type: "thread.create", - commandId: CommandId.make(yield* randomUUID), - threadId: createdThreadId, - projectId: nextProjectId, - title: "New thread", - modelSelection: nextProjectDefaultModelSelection, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - }); - bootstrapProjectId = nextProjectId; - bootstrapThreadId = createdThreadId; - } else { - bootstrapProjectId = nextProjectId; - bootstrapThreadId = existingThreadId.value; - } + const defaultModelSelection = getAutoBootstrapDefaultModelSelection(); + const { project } = yield* projects.bootstrap({ + commandId: CommandId.make(yield* randomUUID), + projectId: ProjectId.make(yield* randomUUID), + title: path.basename(serverConfig.cwd) || "project", + workspaceRoot: serverConfig.cwd, + defaultModelSelection, }); + const shell = yield* threads.getShellSnapshot(); + const existingThread = shell.threads.find( + (thread) => + thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent", + ); + if (existingThread === undefined) { + const launched = yield* threadLaunch.launch({ + commandId: CommandId.make(yield* randomUUID), + projectId: project.id, + title: "New thread", + modelSelection: project.defaultModelSelection ?? defaultModelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + workspaceStrategy: { type: "root" }, + createdBy: "system", + creationSource: "server", + }); + bootstrapProjectId = project.id; + bootstrapThreadId = launched.threadId; + } else { + bootstrapProjectId = project.id; + bootstrapThreadId = existingThread.id; + } } return { ...(bootstrapProjectId ? { bootstrapProjectId } : {}), ...(bootstrapThreadId ? { bootstrapThreadId } : {}), - } as const; + } satisfies AutoBootstrapWelcomeTargets; }); const resolveStartupBrowserTarget = Effect.gen(function* () { @@ -290,44 +282,150 @@ const runStartupPhase = (phase: string, effect: Effect.Effect) Effect.withSpan(`server.startup.${phase}`), ); -interface StartupOptions { - readonly activate?: Effect.Effect; - readonly awaitAuxiliaryParked?: Effect.Effect; - readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect; +export function runOrderedV2StartupPhases< + Verification extends { readonly valid: boolean }, + RebuildVerification extends { readonly valid: boolean }, + Recovery, + Bootstrap, + VerifyError, + RebuildError, + RecoveryError, + WorkerError, + BootstrapError, + VerifyContext, + RebuildContext, + RecoveryContext, + WorkerContext, + BootstrapContext, +>(input: { + readonly verify: Effect.Effect; + readonly rebuild: Effect.Effect; + readonly recover: Effect.Effect; + readonly startEffectWorker: Effect.Effect; + readonly autoBootstrap: Effect.Effect; +}) { + return Effect.gen(function* () { + const verification = yield* input.verify; + if (!verification.valid) { + const rebuilt = yield* input.rebuild; + if (!rebuilt.valid) { + return yield* Effect.die( + new Error("V2 orchestration projection rebuild did not produce a valid projection."), + ); + } + } + const recovery = yield* input.recover; + yield* input.startEffectWorker; + const bootstrap = yield* input.autoBootstrap; + return { recovery, bootstrap } as const; + }); } -export const make = (options?: StartupOptions) => - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const keybindings = yield* Keybindings.Keybindings; - const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor; - const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper; - const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; - const crypto = yield* Crypto.Crypto; - const launcher = yield* ServiceLauncherClient.ServiceLauncherClient; +export const make = Effect.gen(function* () { + const serverConfig = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; + const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; + const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; + const serverSettings = yield* ServerSettings.ServerSettingsService; + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + const crypto = yield* Crypto.Crypto; - const commandGate = yield* makeCommandGate; - const httpListening = yield* Deferred.make(); - const reactorScope = yield* Scope.make("sequential"); + const commandGate = yield* makeCommandGate; + const httpListening = yield* Deferred.make(); yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void)); - const startup = Effect.gen(function* () { - yield* Effect.logDebug("startup phase: starting keybindings runtime"); - yield* runStartupPhase( - "keybindings.start", - keybindings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start keybindings runtime", { - path: error.configPath, - detail: error.detail, - cause: error.cause, - }), + yield* Effect.logDebug("startup phase: starting server settings runtime"); + yield* runStartupPhase( + "settings.start", + serverSettings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start server settings runtime", { + path: error.settingsPath, + operation: error.operation, + providerInstanceId: error.providerInstanceId, + environmentVariable: error.environmentVariable, + cause: error.cause, + }), + ), + Effect.forkScoped, + ), + ); + + const welcomeBase = yield* resolveWelcomeBase; + const environment = yield* serverEnvironment.getDescriptor; + const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({ + verify: runStartupPhase( + "orchestration-v2.projections.verify", + projectionMaintenance.verify.pipe( + Effect.tap((verification) => + verification.valid + ? Effect.void + : Effect.logWarning("V2 orchestration projections are stale; rebuilding", { + expectedSequence: verification.expectedSequence, + projectionSequence: verification.projectionSequence, + schemaVersion: verification.schemaVersion, + missingThreadCount: verification.missingThreadIds.length, + unexpectedThreadCount: verification.unexpectedThreadIds.length, + differingThreadCount: verification.differingThreadIds.length, + }), ), ), - ); + ), + rebuild: runStartupPhase( + "orchestration-v2.projections.rebuild", + projectionMaintenance.rebuild, + ), + recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover), + startEffectWorker: runStartupPhase( + "orchestration-v2.effect-worker.start", + Effect.gen(function* () { + yield* EffectWorker.runDaemon.pipe(Effect.forkScoped); + yield* agentAwarenessRelay.start(); + }), + ), + autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd + ? runStartupPhase( + "welcome.autobootstrap", + resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)), + ) + : Effect.succeed({}) + ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)), + }); + yield* Effect.logInfo("V2 orchestration recovery completed", recovery); + + yield* Effect.logDebug("Accepting commands"); + yield* commandGate.signalCommandReady; + + yield* Effect.logDebug("startup phase: publishing welcome event", { + environmentId: environment.environmentId, + cwd: welcomeBase.cwd, + projectName: welcomeBase.projectName, + bootstrapProjectId: bootstrapTargets.bootstrapProjectId, + bootstrapThreadId: bootstrapTargets.bootstrapThreadId, + }); + yield* runStartupPhase( + "welcome.publish", + lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: { + environment, + ...welcomeBase, + ...bootstrapTargets, + }, + }), + ); + }).pipe( + Effect.annotateSpans({ + "server.mode": serverConfig.mode, + "server.port": serverConfig.port, + "server.host": serverConfig.host ?? "default", + }), + Effect.withSpan("server.startup", { kind: "server", root: true }), + ); yield* Effect.logDebug("startup phase: starting server settings runtime"); yield* runStartupPhase( @@ -397,54 +495,9 @@ export const make = (options?: StartupOptions) => ); } - yield* forkParked( - Effect.gen(function* () { - yield* Effect.logDebug("startup phase: recording startup heartbeat"); - yield* recordStartupHeartbeat.pipe( - Effect.annotateSpans({ "startup.phase": "heartbeat.record" }), - Effect.withSpan("server.startup.heartbeat.record"), - Effect.ignoreCause({ log: true }), - ); - if (serverConfig.startupPresentation === "headless") { - const accessInfo = yield* issueHeadlessServeAccessInfo(); - yield* runStartupPhase( - "headless.output", - Console.log(formatHeadlessServeOutput(accessInfo)), - ); - } else { - const startupBrowserTarget = yield* resolveStartupBrowserTarget; - if (serverConfig.mode !== "desktop") { - yield* Effect.logInfo( - "Authentication required. Open T3 Code using the pairing URL.", - ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget })); - } - yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget)); - } - }), - ); - yield* Effect.logDebug("startup phase: waiting for http listener"); yield* runStartupPhase("http.wait", Deferred.await(httpListening)); - yield* runStartupPhase( - "auxiliary-roots.parked", - options?.awaitAuxiliaryParked ?? Effect.void, - ); - - // This is the prepared boundary. Every dependency has been acquired and - // every runtime root has confirmed that it is parked before this request. - const updateOutcome = yield* launcher.prepareTrial; - yield* runStartupPhase( - "welcome.publish", - lifecycleEvents.publish({ - version: 1, - type: "welcome", - payload: { environment, ...welcomeBase }, - }), - ); - yield* options?.activate ?? Effect.void; - - yield* Effect.logDebug("Accepting commands"); - yield* commandGate.signalCommandReady; + yield* Effect.logDebug("startup phase: publishing ready event"); yield* runStartupPhase( "ready.publish", lifecycleEvents.publish({ diff --git a/apps/server/src/textGeneration/TextGeneration.test.ts b/apps/server/src/textGeneration/TextGeneration.test.ts index 9145ff3913..9966c37dda 100644 --- a/apps/server/src/textGeneration/TextGeneration.test.ts +++ b/apps/server/src/textGeneration/TextGeneration.test.ts @@ -38,7 +38,6 @@ const makeStubInstance = ( displayName: undefined, enabled: true, snapshot: {} as ProviderInstance["snapshot"], - adapter: {} as ProviderInstance["adapter"], orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration, }) satisfies ProviderInstance; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 50ec850a6d..a802539581 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,5 +1,3 @@ -import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -7,7 +5,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; +import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL, @@ -15,25 +13,16 @@ import { type AuthAccessStreamEvent, type AuthEnvironmentScope, AuthSessionId, - CommandId, type DiscoveredLocalServerList, - EventId, - type OrchestrationCommand, type GitActionProgressEvent, type GitManagerServiceError, - OrchestrationDispatchCommandError, - type OrchestrationEvent, - type OrchestrationShellStreamEvent, - type OrchestrationShellStreamItem, - type OrchestrationThreadStreamItem, OrchestrationGetFullThreadDiffError, - OrchestrationGetSnapshotError, - OrchestrationSearchThreadsError, OrchestrationGetTurnDiffError, ORCHESTRATION_V2_WS_METHODS, OrchestrationV2DispatchCommandError, OrchestrationV2GetShellSnapshotError, OrchestrationV2GetThreadProjectionError, + OrchestrationV2ThreadLaunchError, ORCHESTRATION_WS_METHODS, type ProjectId, type ProjectEntriesFailure, @@ -46,8 +35,6 @@ import { ProjectWriteFileError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, - type ServerSelfUpdateError, - type ServerSelfUpdateProgressEvent, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, @@ -62,26 +49,22 @@ import { WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; -import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http"; import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as ServerConfig from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; +import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts"; +import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; import { - projectActivityEvent, - projectThreadDetailSnapshot, -} from "./orchestration/ActivityPayloadProjection.ts"; -import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts"; -import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts"; -import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; -import { - ThreadManagementService, - withCreationProvenance, -} from "./orchestration-v2/ThreadManagementService.ts"; -import { shellStreamItemFromSnapshot } from "./orchestration-v2/ShellStream.ts"; + archivedShellStreamItemFromSnapshot, + shellStreamItemFromSnapshot, +} from "./orchestration-v2/ShellStream.ts"; +import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as OrchestrationEventStore from "./persistence/Services/OrchestrationEventStore.ts"; import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; import { observeRpcEffect as instrumentRpcEffect, @@ -107,7 +90,7 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as ReviewService from "./review/ReviewService.ts"; -import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; +import * as ProjectService from "./project/ProjectService.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; @@ -131,36 +114,11 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; import * as RelayClient from "@t3tools/shared/relayClient"; -const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError); - -const nowIso = Effect.map(DateTime.now, DateTime.formatIso); -const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5); - -export const resolveAvailableEditorsForConfig = ( - discovery: Effect.Effect, E, R>, -) => - discovery.pipe( - Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT), - Effect.map(Option.getOrElse(() => [])), - ); function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`); } -/** Preserve the setup runner's broader pre-refactor message normalization. */ -function legacySetupFailureDescription(cause: unknown): string { - if ( - typeof cause === "object" && - cause !== null && - "message" in cause && - typeof cause.message === "string" - ) { - return cause.message; - } - return String(cause); -} - function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): { readonly failure: ProjectEntriesFailure; readonly normalizedCwd?: string; @@ -265,53 +223,16 @@ function projectFileFailureContext( } } -function projectSetupScriptCompatibilityDetail( - error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError, -): string { - switch (error._tag) { - case "ProjectSetupScriptOperationError": - return legacySetupFailureDescription(error.cause); - case "ProjectSetupScriptProjectNotFoundError": - return "Project was not found for setup script execution."; - default: - return unexpectedCompatibilityError(error); - } -} - -export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< - OrchestrationEvent, - { - type: - | "thread.message-sent" - | "thread.proposed-plan-upserted" - | "thread.activity-appended" - | "thread.turn-diff-completed" - | "thread.reverted" - | "thread.session-set"; - } -> { - return ( - event.type === "thread.message-sent" || - event.type === "thread.proposed-plan-upserted" || - event.type === "thread.activity-appended" || - event.type === "thread.turn-diff-completed" || - event.type === "thread.reverted" || - event.type === "thread.session-set" - ); -} - const PROVIDER_STATUS_DEBOUNCE_MS = 200; const RPC_REQUIRED_SCOPE = new Map([ - [ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope], - [ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope], - [ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope], - [ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope], - [ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope], - [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope], - [ORCHESTRATION_WS_METHODS.subscribeThread, AuthOrchestrationReadScope], [ORCHESTRATION_V2_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope], + [ORCHESTRATION_V2_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope], + [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope], + [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope], [ORCHESTRATION_V2_WS_METHODS.getThreadProjection, AuthOrchestrationReadScope], + [ORCHESTRATION_V2_WS_METHODS.launchThread, AuthOrchestrationOperateScope], + [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell, AuthOrchestrationReadScope], [ORCHESTRATION_V2_WS_METHODS.subscribeShell, AuthOrchestrationReadScope], [ORCHESTRATION_V2_WS_METHODS.subscribeThread, AuthOrchestrationReadScope], [WS_METHODS.serverGetConfig, AuthOrchestrationReadScope], @@ -362,6 +283,16 @@ const RPC_REQUIRED_SCOPE = new Map([ [WS_METHODS.subscribeAuthAccess, AuthAccessReadScope], ]); +const ServerWsRpcGroup = WsRpcGroup.omit( + ORCHESTRATION_WS_METHODS.dispatchCommand, + ORCHESTRATION_WS_METHODS.getTurnDiff, + ORCHESTRATION_WS_METHODS.getFullThreadDiff, + ORCHESTRATION_WS_METHODS.replayEvents, + ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, + ORCHESTRATION_WS_METHODS.subscribeShell, + ORCHESTRATION_WS_METHODS.subscribeThread, +); + function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, revision: number, @@ -402,38 +333,113 @@ function toAuthAccessStreamEvent( } } -const makeWsRpcLayer = ( - currentSession: EnvironmentAuth.AuthenticatedSession, - previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], -) => - WsRpcGroup.toLayer( +const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => + ServerWsRpcGroup.toLayer( Effect.gen(function* () { - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const orchestrationEngine = yield* OrchestrationEngineService; - const threadManagement = yield* ThreadManagementService; - const checkpointDiffQuery = yield* CheckpointDiffQuery; - const keybindings = yield* Keybindings; - const open = yield* Open; - const gitManager = yield* GitManager; - const git = yield* GitCore; - const gitStatusBroadcaster = yield* GitStatusBroadcaster; - const terminalManager = yield* TerminalManager; - const providerRegistry = yield* ProviderRegistry; - const config = yield* ServerConfig; - const lifecycleEvents = yield* ServerLifecycleEvents; - const serverSettings = yield* ServerSettingsService; - const startup = yield* ServerRuntimeStartup; - const workspaceEntries = yield* WorkspaceEntries; - const workspaceFileSystem = yield* WorkspaceFileSystem; - const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; - const repositoryIdentityResolver = yield* RepositoryIdentityResolver; - const serverEnvironment = yield* ServerEnvironment; - const serverAuth = yield* ServerAuth; - const bootstrapCredentials = yield* BootstrapCredentialService; - const sessions = yield* SessionCredentialService; - const serverCommandId = (tag: string) => - randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`))); - + const currentSessionId = currentSession.sessionId; + const sql = yield* SqlClient.SqlClient; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; + const projectService = yield* ProjectService.ProjectService; + const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; + const keybindings = yield* Keybindings.Keybindings; + const externalLauncher = yield* ExternalLauncher.ExternalLauncher; + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const review = yield* ReviewService.ReviewService; + const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService; + const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const terminalManager = yield* TerminalManager.TerminalManager; + const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker; + const previewManager = yield* PreviewManager.PreviewManager; + const portDiscovery = yield* PortScanner.PortDiscovery; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; + const config = yield* ServerConfig.ServerConfig; + const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; + const serverSettings = yield* ServerSettings.ServerSettingsService; + const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery; + const automaticGitFetchInterval = serverSettings.getSettings.pipe( + Effect.map((settings) => settings.automaticGitFetchInterval), + Effect.catch((cause) => + Effect.logWarning("Failed to read automatic Git fetch interval setting", { + detail: cause.message, + }).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)), + ), + ); + const sourceControlRepositories = + yield* SourceControlRepositoryService.SourceControlRepositoryService; + const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; + const sessions = yield* SessionStore.SessionStore; + const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; + const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; + const relayClient = yield* RelayClient.RelayClient; + const authorizationError = (requiredScope: AuthEnvironmentScope) => + new EnvironmentAuthorizationError({ + message: `The authenticated token is missing required scope: ${requiredScope}.`, + requiredScope, + }); + const authorizeEffect = ( + requiredScope: AuthEnvironmentScope, + effect: Effect.Effect, + ): Effect.Effect => + currentSession.scopes.includes(requiredScope) + ? effect + : Effect.fail(authorizationError(requiredScope)); + const authorizeStream = ( + requiredScope: AuthEnvironmentScope, + stream: Stream.Stream, + ): Stream.Stream => + currentSession.scopes.includes(requiredScope) + ? stream + : Stream.fail(authorizationError(requiredScope)); + const requiredScopeForMethod = (method: string): AuthEnvironmentScope => { + const requiredScope = RPC_REQUIRED_SCOPE.get(method); + if (requiredScope === undefined) { + throw new Error(`RPC method ${method} has no declared authorization scope.`); + } + return requiredScope; + }; + const observeRpcEffect = ( + method: string, + effect: Effect.Effect, + traceAttributes?: Readonly>, + ) => + instrumentRpcEffect( + method, + authorizeEffect(requiredScopeForMethod(method), effect), + traceAttributes, + ); + const observeRpcStream = ( + method: string, + stream: Stream.Stream, + traceAttributes?: Readonly>, + ) => + instrumentRpcStream( + method, + authorizeStream(requiredScopeForMethod(method), stream), + traceAttributes, + ); + const observeRpcStreamEffect = ( + method: string, + effect: Effect.Effect< + Stream.Stream, + EffectError, + EffectContext + >, + traceAttributes?: Readonly>, + ) => + instrumentRpcStreamEffect( + method, + authorizeEffect(requiredScopeForMethod(method), effect), + traceAttributes, + ); const loadAuthAccessSnapshot = () => Effect.all({ pairingLinks: serverAuth.listPairingLinks(), @@ -447,497 +453,6 @@ const makeWsRpcLayer = ( ), ); - const appendSetupScriptActivity = (input: { - readonly threadId: ThreadId; - readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; - readonly summary: string; - readonly createdAt: string; - readonly payload: Record; - readonly tone: "info" | "error"; - }) => - Effect.all({ - commandId: serverCommandId("setup-script-activity"), - activityId: serverEventId, - }).pipe( - Effect.flatMap(({ commandId, activityId }) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId, - threadId: input.threadId, - activity: { - id: activityId, - tone: input.tone, - kind: input.kind, - summary: input.summary, - payload: input.payload, - turnId: null, - createdAt: input.createdAt, - }, - createdAt: input.createdAt, - }), - ), - ); - - const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause) => { - const error = Cause.squash(cause); - return isOrchestrationDispatchCommandError(error) - ? error - : new OrchestrationDispatchCommandError({ - message: - error instanceof Error ? error.message : "Failed to bootstrap thread turn start.", - cause, - }); - }; - - const toShellStreamEvent = ( - event: OrchestrationEvent, - ): Effect.Effect, never, never> => { - switch (event.type) { - case "project.created": - case "project.meta-updated": - return projectUpsertOrRemove(event.payload.projectId, event.sequence); - case "project.deleted": - return Effect.succeed( - Option.some({ - kind: "project-removed" as const, - sequence: event.sequence, - projectId: event.payload.projectId, - }), - ); - case "thread.deleted": - case "thread.archived": - return Effect.succeed( - Option.some({ - kind: "thread-removed" as const, - sequence: event.sequence, - threadId: event.payload.threadId, - }), - ); - case "thread.unarchived": - return threadUpsertOrRemove(event.payload.threadId, event.sequence); - default: - if (event.aggregateKind !== "thread") { - return Effect.succeed(Option.none()); - } - return threadUpsertOrRemove(ThreadId.make(event.aggregateId), event.sequence); - } - }; - - // Coalescing makes each projection read represent every event for that - // aggregate in the current window. Retry a typed persistence failure once - // so a brief read failure cannot strand the shell at its previous state. - // If both attempts fail, log and drop the stream item; treating an error as - // a missing row would incorrectly remove a still-active aggregate. - const retryShellProjectionRead = ( - aggregateKind: "project" | "thread", - aggregateId: string, - read: Effect.Effect, - ): Effect.Effect, never, never> => - read.pipe( - Effect.retry({ times: 1 }), - Effect.map(Option.some), - Effect.tapError((error) => - Effect.logWarning("orchestration shell projection refetch failed", { - aggregateKind, - aggregateId, - error, - }), - ), - Effect.orElseSucceed(() => Option.none()), - ); - - const projectUpsertOrRemove = ( - projectId: ProjectId, - sequence: number, - ): Effect.Effect, never, never> => - retryShellProjectionRead( - "project", - projectId, - projectionSnapshotQuery.getProjectShellById(projectId), - ).pipe( - Effect.map( - Option.flatMap((project) => - Option.match(project, { - onNone: () => - Option.some({ - kind: "project-removed" as const, - sequence, - projectId, - }), - onSome: (nextProject) => - Option.some({ - kind: "project-upserted" as const, - sequence, - project: nextProject, - }), - }), - ), - ), - ); - - // Refetch a thread's shell and emit an upsert if it is still active, or a - // `thread-removed` if the projection has no active row for it. Emitting a - // removal on a `none` (rather than dropping the event) is what keeps - // coalescing correct: when a burst collapses a `thread.deleted`/`archived` - // into a later refetchable event for the same thread, the refetch returns - // `none` for the now-inactive row and this still tells the sidebar to drop - // it. A `thread-removed` the client does not have is a harmless no-op. The - // projection commits in the same transaction before the event publishes, - // so a `none` reliably means the thread is deleted or archived, not - // not-yet-persisted. - const threadUpsertOrRemove = ( - threadId: ThreadId, - sequence: number, - ): Effect.Effect, never, never> => - retryShellProjectionRead( - "thread", - threadId, - projectionSnapshotQuery.getThreadShellById(threadId), - ).pipe( - Effect.map( - Option.flatMap((thread) => - Option.match(thread, { - onNone: () => - Option.some({ - kind: "thread-removed" as const, - sequence, - threadId, - }), - onSome: (nextThread) => - Option.some({ - kind: "thread-upserted" as const, - sequence, - thread: nextThread, - }), - }), - ), - ), - ); - - // Turn a batch of domain events into shell stream items, coalescing by - // aggregate first. `toShellStreamEvent` re-reads the *current* projected - // shell for an aggregate, so within a batch only the latest event per - // aggregate matters: a burst of streaming `thread.message-sent` deltas for - // one thread collapses into a single shell refetch, and an unrelated - // `thread.created` in the same batch is never stuck behind those DB reads. - // - // Input events arrive in ascending sequence; we keep the last (highest - // sequence) event per aggregate, then re-sort ascending before emitting so - // the client — which applies shell items strictly by increasing sequence - // and drops any `sequence <= snapshotSequence` — never skips a coalesced - // item. The refetch runs with bounded concurrency (order-preserving). - const SHELL_REFETCH_CONCURRENCY = 8; - const coalesceShellEvents = ( - events: ReadonlyArray, - ): Effect.Effect, never, never> => - Effect.gen(function* () { - if (events.length === 0) { - return []; - } - const latestByAggregate = new Map(); - for (const event of events) { - latestByAggregate.set(`${event.aggregateKind}:${event.aggregateId}`, event); - } - const survivors = Array.from(latestByAggregate.values()).sort( - (left, right) => left.sequence - right.sequence, - ); - const shellEvents = yield* Effect.forEach(survivors, toShellStreamEvent, { - concurrency: SHELL_REFETCH_CONCURRENCY, - }); - return shellEvents.flatMap((option) => (Option.isSome(option) ? [option.value] : [])); - }); - - // Small time/size window over which to coalesce shell events. The window - // bounds the worst-case added latency for a brand-new thread to appear in - // the sidebar (imperceptible), while collapsing high-frequency streaming - // traffic so it can't serialize the shell stream behind per-event DB reads. - const SHELL_COALESCE_WINDOW = Duration.millis(50); - const SHELL_COALESCE_MAX_CHUNK = 512; - const coalesceShellStream = ( - stream: Stream.Stream, - ): Stream.Stream => - stream.pipe( - Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW), - Stream.mapEffect(coalesceShellEvents), - Stream.flatMap((items) => Stream.fromIterable(items)), - ); - - type ShellLiveInput = - | { readonly kind: "event"; readonly event: OrchestrationEvent } - | { readonly kind: "synchronized" }; - - // A completion marker is queued alongside raw live events so it cannot - // overtake an event still waiting in the coalescing window. Split each - // batch at markers and coalesce only the event segments on either side. - const coalesceShellLiveInputs = ( - inputs: ReadonlyArray, - ): Effect.Effect, never, never> => - Effect.gen(function* () { - const output: Array = []; - let pendingEvents: Array = []; - - for (const input of inputs) { - if (input.kind === "event") { - pendingEvents.push(input.event); - continue; - } - - output.push(...(yield* coalesceShellEvents(pendingEvents))); - pendingEvents = []; - output.push({ kind: "synchronized" }); - } - - output.push(...(yield* coalesceShellEvents(pendingEvents))); - return output; - }); - - const coalesceShellLiveStream = ( - stream: Stream.Stream, - ): Stream.Stream => - stream.pipe( - Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW), - Stream.mapEffect(coalesceShellLiveInputs), - Stream.flatMap((items) => Stream.fromIterable(items)), - ); - - const dispatchBootstrapTurnStart = ( - command: Extract, - ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => - Effect.gen(function* () { - const bootstrap = command.bootstrap; - const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command; - let createdThread = false; - let targetProjectId = bootstrap?.createThread?.projectId; - let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd; - let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null; - - const cleanupCreatedThread = () => - createdThread - ? serverCommandId("bootstrap-thread-delete").pipe( - Effect.flatMap((commandId) => - orchestrationEngine.dispatch({ - type: "thread.delete", - commandId, - threadId: command.threadId, - }), - ), - Effect.ignoreCause({ log: true }), - ) - : Effect.void; - - const recordSetupScriptLaunchFailure = (input: { - readonly error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError; - readonly requestedAt: string; - readonly worktreePath: string; - }) => { - const detail = projectSetupScriptCompatibilityDetail(input.error); - return appendSetupScriptActivity({ - threadId: command.threadId, - kind: "setup-script.failed", - summary: "Setup script failed to start", - createdAt: input.requestedAt, - payload: { - detail, - worktreePath: input.worktreePath, - }, - tone: "error", - }).pipe( - Effect.ignoreCause({ log: false }), - Effect.flatMap(() => - Effect.logWarning("bootstrap turn start failed to launch setup script", { - threadId: command.threadId, - worktreePath: input.worktreePath, - detail, - }), - ), - ); - }; - - const recordSetupScriptStarted = (input: { - readonly requestedAt: string; - readonly worktreePath: string; - readonly scriptId: string; - readonly scriptName: string; - readonly terminalId: string; - }) => - Effect.gen(function* () { - const startedAt = yield* nowIso; - const payload = { - scriptId: input.scriptId, - scriptName: input.scriptName, - terminalId: input.terminalId, - worktreePath: input.worktreePath, - }; - yield* Effect.all([ - appendSetupScriptActivity({ - threadId: command.threadId, - kind: "setup-script.requested", - summary: "Starting setup script", - createdAt: input.requestedAt, - payload, - tone: "info", - }), - appendSetupScriptActivity({ - threadId: command.threadId, - kind: "setup-script.started", - summary: "Setup script started", - createdAt: startedAt, - payload, - tone: "info", - }), - ]).pipe( - Effect.asVoid, - Effect.catch((error) => - Effect.logWarning( - "bootstrap turn start launched setup script but failed to record setup activity", - { - threadId: command.threadId, - worktreePath: input.worktreePath, - scriptId: input.scriptId, - terminalId: input.terminalId, - detail: error.message, - }, - ), - ), - ); - }); - - const runSetupProgram = () => - Effect.gen(function* () { - if (!bootstrap?.runSetupScript || !targetWorktreePath) { - return; - } - const worktreePath = targetWorktreePath; - const requestedAt = yield* nowIso; - yield* projectSetupScriptRunner - .runForThread({ - threadId: command.threadId, - ...(targetProjectId ? { projectId: targetProjectId } : {}), - ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}), - worktreePath, - }) - .pipe( - Effect.matchEffect({ - onFailure: (error) => - recordSetupScriptLaunchFailure({ - error, - requestedAt, - worktreePath, - }), - onSuccess: (setupResult) => { - if (setupResult.status !== "started") { - return Effect.void; - } - return recordSetupScriptStarted({ - requestedAt, - worktreePath, - scriptId: setupResult.scriptId, - scriptName: setupResult.scriptName, - terminalId: setupResult.terminalId, - }); - }, - }), - ); - }); - - const bootstrapProgram = Effect.gen(function* () { - if (bootstrap?.createThread) { - yield* orchestrationEngine.dispatch({ - type: "thread.create", - commandId: yield* serverCommandId("bootstrap-thread-create"), - threadId: command.threadId, - projectId: bootstrap.createThread.projectId, - title: bootstrap.createThread.title, - modelSelection: bootstrap.createThread.modelSelection, - runtimeMode: bootstrap.createThread.runtimeMode, - interactionMode: bootstrap.createThread.interactionMode, - branch: bootstrap.createThread.branch, - worktreePath: bootstrap.createThread.worktreePath, - createdAt: bootstrap.createThread.createdAt, - }); - createdThread = true; - } - - if (bootstrap?.prepareWorktree) { - let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch; - // "Start from origin" is a stored default; repos without an - // origin remote fall back to the local base branch instead of - // failing the whole bootstrap on `git fetch origin`. - const startFromOrigin = - bootstrap.prepareWorktree.startFromOrigin === true && - (yield* gitWorkflow.remoteExists({ - cwd: bootstrap.prepareWorktree.projectCwd, - remoteName: "origin", - })); - if (startFromOrigin) { - yield* gitWorkflow.fetchRemote({ - cwd: bootstrap.prepareWorktree.projectCwd, - remoteName: "origin", - }); - const resolvedRemoteBase = yield* gitWorkflow.resolveRemoteTrackingCommit({ - cwd: bootstrap.prepareWorktree.projectCwd, - refName: bootstrap.prepareWorktree.baseBranch, - fallbackRemoteName: "origin", - }); - worktreeBaseRef = resolvedRemoteBase.commitSha; - } - const worktree = yield* gitWorkflow.createWorktree({ - cwd: bootstrap.prepareWorktree.projectCwd, - refName: worktreeBaseRef, - newRefName: bootstrap.prepareWorktree.branch, - baseRefName: bootstrap.prepareWorktree.baseBranch, - path: null, - }); - targetWorktreePath = worktree.worktree.path; - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: yield* serverCommandId("bootstrap-thread-meta-update"), - threadId: command.threadId, - branch: worktree.worktree.refName, - worktreePath: targetWorktreePath, - }); - yield* refreshGitStatus(targetWorktreePath); - } - - yield* runSetupProgram(); - - return yield* orchestrationEngine.dispatch(finalTurnStartCommand); - }); - - return yield* bootstrapProgram.pipe( - Effect.catchCause((cause) => { - const dispatchError = toBootstrapDispatchCommandCauseError(cause); - if (Cause.hasInterruptsOnly(cause)) { - return Effect.fail(dispatchError); - } - return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError))); - }), - ); - }); - - const dispatchNormalizedCommand = ( - normalizedCommand: OrchestrationCommand, - ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => { - const dispatchEffect = - normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap - ? dispatchBootstrapTurnStart(normalizedCommand) - : orchestrationEngine - .dispatch(normalizedCommand) - .pipe( - Effect.mapError((cause) => - toDispatchCommandError(cause, "Failed to dispatch orchestration command"), - ), - ); - - return startup - .enqueueCommand(dispatchEffect) - .pipe( - Effect.mapError((cause) => - toDispatchCommandError(cause, "Failed to dispatch orchestration command"), - ), - ); - }; - const loadServerConfig = Effect.gen(function* () { const keybindingsConfig = yield* keybindings.loadConfigState; const providers = yield* providerRegistry.getProviders; @@ -1032,429 +547,144 @@ const makeWsRpcLayer = ( const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( function* () { - const snapshot = yield* threadManagement.getShellSnapshot().pipe( - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed to load orchestration V2 shell snapshot", - cause, - }), - ), - ); - - const liveStream = threadManagement - .streamStoredEventsFrom({ afterSequence: snapshot.snapshotSequence }) + const snapshot = yield* sql + .withTransaction( + Effect.gen(function* () { + const projects = yield* projectionSnapshotQuery.getShellSnapshot(); + const threads = yield* threadManagement.getShellSnapshot(); + return { + schemaVersion: threads.schemaVersion, + snapshotSequence: yield* applicationEvents.latestApplicationSequence, + projects: projects.projects, + threads: threads.threads, + archivedThreads: threads.archivedThreads, + } as const; + }), + ) .pipe( - Stream.mapEffect((stored) => - threadManagement.getShellSnapshot().pipe( - Effect.map((nextSnapshot) => - shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }), - ), - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: `Failed while streaming orchestration V2 shell thread ${stored.event.threadId}`, - cause, - }), - ), - ), - ), - Stream.mapError( + Effect.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ - message: "Failed while streaming orchestration V2 shell", + message: "Failed to load the application shell snapshot", cause, }), ), ); - return Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshot, - }), - liveStream, + const live = applicationEvents + .streamApplicationEvents({ afterSequence: snapshot.snapshotSequence }) + .pipe( + Stream.mapEffect((stored) => + Effect.gen(function* () { + if ("aggregateKind" in stored) { + if (stored.type === "project.deleted") { + return { + kind: "project.removed" as const, + sequence: stored.sequence, + projectId: stored.payload.projectId, + }; + } + const project = yield* projectionSnapshotQuery.getProjectShellById( + stored.payload.projectId, + ); + return Option.match(project, { + onNone: () => ({ + kind: "project.removed" as const, + sequence: stored.sequence, + projectId: stored.payload.projectId, + }), + onSome: (value) => ({ + kind: "project.updated" as const, + sequence: stored.sequence, + project: value, + }), + }); + } + const nextSnapshot = yield* threadManagement.getShellSnapshot(); + return shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }); + }), + ), + Stream.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed while streaming the application shell", + cause, + }), + ), + ); + + return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live).pipe( + Stream.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed while streaming the application shell", + cause, + }), + ), ); }, ); - return WsRpcGroup.of({ - [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.dispatchCommand, - Effect.gen(function* () { - const normalizedCommand = yield* normalizeDispatchCommand(command); - const shouldStopSessionAfterArchive = - normalizedCommand.type === "thread.archive" - ? yield* projectionSnapshotQuery - .getThreadShellById(normalizedCommand.threadId) - .pipe( - Effect.map( - Option.match({ - onNone: () => false, - onSome: (thread) => - thread.session !== null && thread.session.status !== "stopped", - }), - ), - Effect.orElseSucceed(() => false), - ) - : false; - const result = yield* dispatchNormalizedCommand(normalizedCommand); - if (normalizedCommand.type === "thread.archive") { - if (shouldStopSessionAfterArchive) { - yield* Effect.gen(function* () { - const stopCommand = yield* normalizeDispatchCommand({ - type: "thread.session.stop", - commandId: CommandId.make( - `session-stop-for-archive:${normalizedCommand.commandId}`, - ), - threadId: normalizedCommand.threadId, - createdAt: yield* nowIso, - }); + const getOrchestrationV2ArchivedShellSnapshot = threadManagement.getShellSnapshot().pipe( + Effect.map((snapshot) => ({ + schemaVersion: snapshot.schemaVersion, + snapshotSequence: snapshot.snapshotSequence, + threads: snapshot.archivedThreads, + })), + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to load archived thread snapshot", + cause, + }), + ), + ); - yield* dispatchNormalizedCommand(stopCommand); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("failed to stop provider session during archive", { - threadId: normalizedCommand.threadId, - cause, - }), - ), - ); - } - - yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( - Effect.catch((error) => - Effect.logWarning("failed to close thread terminals after archive", { - threadId: normalizedCommand.threadId, - error: error.message, - }), - ), - ); - } - return result; - }).pipe( - Effect.mapError((cause) => - isOrchestrationDispatchCommandError(cause) - ? cause - : new OrchestrationDispatchCommandError({ - message: "Failed to dispatch orchestration command", - cause, - }), - ), - ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.getWorkflowScript]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getWorkflowScript, - readWorkflowScript({ scriptPath: input.scriptPath }), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getTurnDiff, - checkpointDiffQuery.getTurnDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetTurnDiffError({ - message: "Failed to load turn diff", - cause, - }), - ), - ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getFullThreadDiff, - checkpointDiffQuery.getFullThreadDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetFullThreadDiffError({ - message: "Failed to load full thread diff", - cause, - }), - ), - ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.searchThreads]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.searchThreads, - projectionSnapshotQuery.searchThreads(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationSearchThreadsError({ - message: "Failed to search threads", - cause, - }), - ), - ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.subscribeShell]: (input) => - observeRpcStreamEffect( - ORCHESTRATION_WS_METHODS.subscribeShell, - Effect.gen(function* () { - // Coalesce the live shell stream per aggregate over a small window - // so bursts of high-frequency events (streaming message deltas, - // activity appends) collapse into a single shell refetch and never - // serialize a brand-new thread's `thread.created` behind hundreds - // of per-event DB reads. See coalesceShellStream. - // Attach live delivery into a scope-bound buffer BEFORE loading any - // snapshot or draining catch-up, otherwise an event published while - // the snapshot query is in flight is lost (it is past the snapshot's - // sequence but the live subscription is not attached yet). Every - // path below emits from this same buffered live tail. Overlapping - // events are deduped by sequence on the client. - const liveBuffer = yield* Queue.unbounded(); - yield* Effect.forkScoped( - orchestrationEngine.streamDomainEvents.pipe( - Stream.runForEach((event) => - Queue.offer(liveBuffer, { kind: "event" as const, event }), - ), - ), - { startImmediately: true }, - ); - const bufferedLiveStream = coalesceShellLiveStream(Stream.fromQueue(liveBuffer)); - - const loadSnapshot = projectionSnapshotQuery.getShellSnapshot().pipe( - Effect.tapError((cause) => - Effect.logError("orchestration shell snapshot load failed", { cause }), + const subscribeOrchestrationV2ArchivedShell = Effect.fn( + "ws.orchestrationV2.subscribeArchivedShell", + )(function* () { + const snapshot = yield* getOrchestrationV2ArchivedShellSnapshot; + const live = threadManagement + .streamStoredEventsFrom({ afterSequence: snapshot.snapshotSequence }) + .pipe( + Stream.mapEffect((stored) => + threadManagement.getShellSnapshot().pipe( + Effect.map((nextSnapshot) => + archivedShellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }), ), Effect.mapError( (cause) => - new OrchestrationGetSnapshotError({ - message: "Failed to load orchestration shell snapshot", + new OrchestrationV2GetShellSnapshotError({ + message: "Failed while streaming archived threads", cause, }), ), - ); - - // Offer the completion marker into the same queue as live events. - // Anything buffered while snapshot/replay work was in flight is - // therefore delivered before the client is told it is synchronized. - const synchronizedThenLive = - input.requestCompletionMarker === true - ? Stream.concat( - Stream.fromEffect( - Queue.offer(liveBuffer, { kind: "synchronized" as const }).pipe( - Effect.andThen(Queue.takeAll(liveBuffer)), - Effect.flatMap(coalesceShellLiveInputs), - ), - ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))), - bufferedLiveStream, - ) - : bufferedLiveStream; - - // When the client already holds a shell snapshot (cached, or loaded - // over HTTP) it passes that snapshot's sequence, and we resume by - // replaying shell events after it instead of re-sending the whole - // projects/threads list over the socket. If the client is too far - // behind, we fall back to a fresh snapshot instead of an unbounded - // replay (see below). - if (input.afterSequence !== undefined) { - const afterSequence = input.afterSequence; - const headSequence = yield* orchestrationEngine.latestSequence; - const replayGap = headSequence - afterSequence; - // Gap too large: replaying every intervening event (each a shell - // refetch) is far more expensive than a single O(active-threads) - // snapshot. A cursor ahead of this engine's authoritative state - // is also invalid, so reset it with a snapshot. Send the snapshot - // followed by the buffered live tail, exactly as the - // no-afterSequence path does. - if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) { - const snapshot = yield* loadSnapshot; - return Stream.concat( - Stream.make({ kind: "snapshot" as const, snapshot }), - synchronizedThenLive, - ); - } - const catchUpStream = coalesceShellStream( - // Replay only through the head captured above. Newer events - // are already covered by the live subscription, so this bound - // cannot chase a moving event-store head or grow the live - // buffer indefinitely while waiting for an empty page. - orchestrationEngine.readEvents(afterSequence, replayGap), - ).pipe( - Stream.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: "Failed to replay orchestration shell events", - cause, - }), - ), - ); - return Stream.concat(catchUpStream, synchronizedThenLive); - } - - const snapshot = yield* loadSnapshot; - return Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshot, - }), - synchronizedThenLive, - ); - }), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, - projectionSnapshotQuery.getArchivedShellSnapshot().pipe( - Effect.tapError((cause) => - Effect.logError("orchestration archived shell snapshot load failed", { cause }), - ), - Effect.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: "Failed to load archived orchestration shell snapshot", - cause, - }), ), ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.subscribeThread]: (input) => - observeRpcStreamEffect( - ORCHESTRATION_WS_METHODS.subscribeThread, - Effect.gen(function* () { - const isThisThreadDetailEvent = (event: OrchestrationEvent) => - event.aggregateKind === "thread" && - event.aggregateId === input.threadId && - isThreadDetailEvent(event); - - const liveStream = orchestrationEngine.streamDomainEvents.pipe( - Stream.filter(isThisThreadDetailEvent), - Stream.map((event) => ({ - kind: "event" as const, - event: projectActivityEvent(event), - })), - ); - - // Attach live delivery before reading either replay or snapshot state. - // Otherwise an event published while the snapshot is loading is lost. - const liveBuffer = yield* Queue.unbounded(); - yield* Effect.forkScoped( - liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))), - ); - const bufferedLiveStream = Stream.fromQueue(liveBuffer); - - // When the client already loaded the snapshot over HTTP it passes - // that snapshot's sequence, and we resume the live subscription by - // replaying persisted events after it instead of re-sending the - // (potentially multi-KB) snapshot frame over the socket. - // - // The live PubSub subscription must be attached *before* draining - // the catch-up replay, otherwise events published during the replay - // window are dropped (they are past the persisted tail the replay - // read, but the live stream is not yet subscribed). So fork the - // live stream into a buffer bound to this stream's scope, then emit - // catch-up followed by the buffered/ongoing live events. Overlapping - // events are deduped by sequence on the client. - // - // The replay is bounded to the projection head captured below. The - // catch-up range is normally tiny (a fresh HTTP snapshot sequence), - // but a stale cached cursor can sit hundreds of thousands of global - // events behind — replaying that decodes every intervening event - // (including every other thread's tool payloads) only to discard - // almost all of them, which has OOM-killed servers on large - // databases. A truncated replay would silently drop this thread's - // events, so past the gap cap we reset the client with a fresh - // thread snapshot instead, exactly like subscribeShell above. - if (input.afterSequence !== undefined) { - const afterSequence = input.afterSequence; - const headSequence = yield* orchestrationEngine.latestSequence; - const replayGap = headSequence - afterSequence; - if (replayGap >= 0 && replayGap <= THREAD_RESUME_MAX_GAP) { - const catchUpStream = orchestrationEngine - .readEvents(afterSequence, replayGap) - .pipe( - Stream.filter(isThisThreadDetailEvent), - Stream.map((event) => ({ - kind: "event" as const, - event: projectActivityEvent(event), - })), - Stream.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: `Failed to replay thread ${input.threadId} events`, - cause, - }), - ), - ); - const afterCatchUp = - input.requestCompletionMarker === true - ? Stream.concat( - Stream.fromEffect( - Queue.offer(liveBuffer, { kind: "synchronized" as const }), - ).pipe(Stream.drain), - bufferedLiveStream, - ) - : bufferedLiveStream; - return Stream.concat(catchUpStream, afterCatchUp); - } - // Gap too large (or cursor ahead of authoritative state): fall - // through to the snapshot path so the client converges from a - // fresh thread detail instead of an unbounded replay. - } - - const snapshot = yield* projectionSnapshotQuery - .getThreadDetailSnapshot( - input.threadId, - // Windowing the fallback snapshot is opt-in per subscription: - // clients that don't send turnLimit (including all - // pre-pagination clients) get the full thread, since they - // have no way to load older pages. - input.turnLimit === undefined ? undefined : { turnLimit: input.turnLimit }, - ) - .pipe( - Effect.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: `Failed to load thread ${input.threadId}`, - cause, - }), - ), - ); - - if (Option.isNone(snapshot)) { - return yield* new OrchestrationGetSnapshotError({ - message: `Thread ${input.threadId} was not found`, - cause: input.threadId, - }); - } - - const afterSnapshot = - input.requestCompletionMarker === true - ? Stream.concat( - Stream.fromEffect( - Queue.offer(liveBuffer, { kind: "synchronized" as const }), - ).pipe(Stream.drain), - bufferedLiveStream, - ) - : bufferedLiveStream; - return Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshot: projectThreadDetailSnapshot(snapshot.value), + Stream.filterMap((item) => (item === null ? Result.failVoid : Result.succeed(item))), + Stream.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed while streaming archived threads", + cause, }), - afterSnapshot, - ); - }), - { "rpc.aggregate": "orchestration" }, - ), + ), + ); + return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live); + }); + + const handlers = ServerWsRpcGroup.of({ [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => observeRpcEffect( ORCHESTRATION_V2_WS_METHODS.dispatchCommand, - threadManagement - .dispatch( - withCreationProvenance(command, { - createdBy: "user", - creationSource: "web", - }), + startup + .enqueueCommand( + threadManagement.dispatch( + ThreadManagementService.withCreationProvenance(command, { + createdBy: "user", + creationSource: "web", + }), + ), ) .pipe( Effect.map((result) => ({ sequence: result.sequence })), @@ -1484,6 +714,40 @@ const makeWsRpcLayer = ( : {}), }, ), + [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_V2_WS_METHODS.getTurnDiff, + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff, + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => + observeRpcEffect( + ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, + getOrchestrationV2ArchivedShellSnapshot, + { "rpc.aggregate": "orchestration" }, + ), [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => observeRpcEffect( ORCHESTRATION_V2_WS_METHODS.getThreadProjection, @@ -1502,6 +766,58 @@ const makeWsRpcLayer = ( "orchestration_v2.thread_id": input.threadId, }, ), + [ORCHESTRATION_V2_WS_METHODS.launchThread]: (input) => + observeRpcEffect( + ORCHESTRATION_V2_WS_METHODS.launchThread, + startup + .enqueueCommand( + threadLaunch.launch({ + commandId: input.commandId, + projectId: input.projectId, + title: input.title, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + workspaceStrategy: + input.workspaceStrategy.type === "root" + ? { type: "root" } + : { + type: "worktree", + baseRef: input.workspaceStrategy.baseRef, + ...(input.workspaceStrategy.branch === undefined + ? {} + : { branch: input.workspaceStrategy.branch }), + }, + ...(input.initialMessage === undefined + ? {} + : { initialMessage: input.initialMessage }), + createdBy: "user", + creationSource: "web", + }), + ) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: "Failed to launch thread", + cause, + }), + ), + ), + { + "rpc.aggregate": "orchestration", + "orchestration_v2.command_id": input.commandId, + "orchestration_v2.project_id": input.projectId, + }, + ), + [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: (_input) => + observeRpcStreamEffect( + ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell, + subscribeOrchestrationV2ArchivedShell(), + { "rpc.aggregate": "orchestration" }, + ), [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (_input) => observeRpcStreamEffect( ORCHESTRATION_V2_WS_METHODS.subscribeShell, @@ -1849,24 +1165,8 @@ const makeWsRpcLayer = ( if (input.resource._tag !== "workspace-file") { return yield* issueAssetUrl({ resource: input.resource }); } - const thread = yield* projectionSnapshotQuery - .getThreadShellById(input.resource.threadId) - .pipe( - Effect.mapError( - (cause) => - new AssetWorkspaceContextResolutionError({ - resource: input.resource, - cause, - }), - ), - ); - if (Option.isNone(thread)) { - return yield* new AssetWorkspaceContextNotFoundError({ - resource: input.resource, - }); - } - const project = yield* projectionSnapshotQuery - .getProjectShellById(thread.value.projectId) + const thread = yield* threadManagement + .getThreadProjection(input.resource.threadId) .pipe( Effect.mapError( (cause) => @@ -1876,6 +1176,15 @@ const makeWsRpcLayer = ( }), ), ); + const project = yield* projectService.getById(thread.thread.projectId).pipe( + Effect.mapError( + (cause) => + new AssetWorkspaceContextResolutionError({ + resource: input.resource, + cause, + }), + ), + ); if (Option.isNone(project)) { return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource, @@ -1883,7 +1192,7 @@ const makeWsRpcLayer = ( } return yield* issueAssetUrl({ resource: input.resource, - workspaceRoot: thread.value.worktreePath ?? project.value.workspaceRoot, + workspaceRoot: thread.thread.worktreePath ?? project.value.workspaceRoot, }); }), { "rpc.aggregate": "workspace" }, @@ -2251,6 +1560,7 @@ const makeWsRpcLayer = ( { "rpc.aggregate": "server" }, ), }); + return handlers; }), ); @@ -2273,7 +1583,7 @@ export const websocketRpcRouteLayer = Layer.unwrap( failEnvironmentInternal("internal_error", error), ), ); - const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { + const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(ServerWsRpcGroup, { disableTracing: true, }).pipe( Effect.provide( diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index 4d9d48906c..ff59624056 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -1,3 +1,6 @@ +import { useAtomValue } from "@effect/atom-react"; +import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { ProviderDriverKind, ProviderInstanceId, @@ -5,7 +8,7 @@ import { type CheckpointScopeId, type ModelSelection, type OrchestrationV2Checkpoint, - type OrchestrationV2DomainEvent, + type OrchestrationV2Command, type OrchestrationV2PlanStep, type OrchestrationV2Run, type OrchestrationV2RunStatus, @@ -21,7 +24,6 @@ import { type ThreadId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; -import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline"; import { createFileRoute } from "@tanstack/react-router"; import { GitMergeIcon } from "lucide-react"; import type { CSSProperties, DragEvent, ReactNode } from "react"; @@ -29,10 +31,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ProviderModelPicker } from "../components/chat/ProviderModelPicker"; import { usePrimarySettings } from "../hooks/useSettings"; -import { - removeAndRenumberTimelineItem, - upsertTimelineItemAtStablePosition, -} from "../lib/orchestrationV2Timeline"; import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils"; import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection"; import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders"; @@ -460,185 +458,6 @@ function buildProjectionTimeline( return entries.toSorted((left, right) => left.sort - right.sort); } -function upsertProjectionEntity( - items: ReadonlyArray, - item: T, -): ReadonlyArray { - const index = items.findIndex((candidate) => candidate.id === item.id); - if (index === -1) { - return [...items, item]; - } - const next = [...items]; - next[index] = item; - return next; -} - -function upsertVisibleTurnItem( - projection: OrchestrationV2ThreadProjection, - item: OrchestrationV2TurnItem, -): OrchestrationV2ThreadProjection["visibleTurnItems"] { - return upsertTimelineItemAtStablePosition(projection.visibleTurnItems, { - position: projection.visibleTurnItems.length, - visibility: "local" as const, - sourceThreadId: item.threadId, - sourceItemId: item.id, - item, - }); -} - -function shouldShowLocalTurnItem( - projection: OrchestrationV2ThreadProjection, - item: OrchestrationV2TurnItem, -): boolean { - return isOrchestrationV2TurnItemVisible({ - item, - runs: projection.runs, - attempts: projection.attempts, - }); -} - -function activeVisibleTurnItems( - projection: OrchestrationV2ThreadProjection, -): OrchestrationV2ThreadProjection["visibleTurnItems"] { - return projection.visibleTurnItems - .filter((row) => row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item)) - .map((row, position) => ({ - position, - visibility: row.visibility, - sourceThreadId: row.sourceThreadId, - sourceItemId: row.sourceItemId, - item: row.item, - })); -} - -function applyStreamEventToProjection( - projection: OrchestrationV2ThreadProjection | null, - event: OrchestrationV2DomainEvent, -): OrchestrationV2ThreadProjection | null { - if (projection === null || event.threadId !== projection.thread.id) { - return projection; - } - - const base = { - ...projection, - updatedAt: event.occurredAt, - }; - - switch (event.type) { - case "thread.created": - return { ...base, thread: event.payload }; - case "run.created": - case "run.updated": { - const nextProjection = { - ...base, - runs: upsertProjectionEntity(base.runs, event.payload), - }; - return { - ...nextProjection, - visibleTurnItems: activeVisibleTurnItems(nextProjection), - }; - } - case "run-attempt.created": - case "run-attempt.updated": { - const nextProjection = { - ...base, - attempts: upsertProjectionEntity(base.attempts, event.payload), - }; - return { - ...nextProjection, - visibleTurnItems: activeVisibleTurnItems(nextProjection), - }; - } - case "node.updated": - return { - ...base, - nodes: upsertProjectionEntity(base.nodes, event.payload), - }; - case "subagent.updated": - return { - ...base, - subagents: upsertProjectionEntity(base.subagents, event.payload), - }; - case "provider-session.attached": - case "provider-session.updated": - return { - ...base, - providerSessions: upsertProjectionEntity(base.providerSessions, event.payload), - }; - case "provider-session.detached": - return { - ...base, - providerSessions: base.providerSessions.filter( - (session) => session.id !== event.payload.providerSessionId, - ), - }; - case "provider-thread.updated": - return { - ...base, - providerThreads: upsertProjectionEntity(base.providerThreads, event.payload), - }; - case "provider-turn.updated": - return { - ...base, - providerTurns: upsertProjectionEntity(base.providerTurns, event.payload), - }; - case "runtime-request.updated": - return { - ...base, - runtimeRequests: upsertProjectionEntity(base.runtimeRequests, event.payload), - }; - case "message.updated": - return { - ...base, - messages: upsertProjectionEntity(base.messages, event.payload), - }; - case "plan.updated": - return { - ...base, - plans: upsertProjectionEntity(base.plans, event.payload), - }; - case "turn-item.updated": { - const nextProjection = { - ...base, - turnItems: upsertProjectionEntity(base.turnItems, event.payload), - }; - const visibleProjection = { - ...nextProjection, - visibleTurnItems: activeVisibleTurnItems(nextProjection), - }; - return { - ...nextProjection, - visibleTurnItems: shouldShowLocalTurnItem(nextProjection, event.payload) - ? upsertVisibleTurnItem(visibleProjection, event.payload) - : removeAndRenumberTimelineItem(visibleProjection.visibleTurnItems, event.payload.id), - }; - } - case "checkpoint-scope.created": - return { - ...base, - checkpointScopes: upsertProjectionEntity(base.checkpointScopes, event.payload), - }; - case "checkpoint.captured": - return { - ...base, - checkpoints: upsertProjectionEntity(base.checkpoints, event.payload), - }; - case "context-handoff.updated": - return { - ...base, - contextHandoffs: upsertProjectionEntity(base.contextHandoffs, event.payload), - }; - case "context-transfer.created": - case "context-transfer.updated": - return { - ...base, - contextTransfers: upsertProjectionEntity(base.contextTransfers, event.payload), - }; - } - - return base; -} - function buildStreamTimeline(logEntries: ReadonlyArray): ReadonlyArray { return logEntries.map((entry, index) => { if (entry.type === "error") { @@ -1749,6 +1568,9 @@ function OrchestrationV2DebugRoute() { setShellThreadsById((current) => { const next = new Map(current); + if (item.kind === "project.updated" || item.kind === "project.removed") { + return next; + } if (item.kind === "thread.removed") { next.delete(item.threadId); return next; @@ -1759,10 +1581,21 @@ function OrchestrationV2DebugRoute() { }, [shellSubscription.data]); useEffect(() => { - shellUnsubscribeRef.current = api.subscribeShell((item) => { - if (item.kind === "snapshot") { - setShellThreadsById(new Map(item.snapshot.threads.map((thread) => [thread.id, thread]))); - return; + const item = threadSubscription.data; + if (item === null) return; + appendLog({ type: "stream", value: item }); + if (item.kind === "snapshot") { + setProjectionError(null); + setProjection(item.projection); + cacheProjection(item.projection); + return; + } + + setProjection((current) => { + const nextProjection = applyOrchestrationV2ProjectionEvent(current, item.event); + if (nextProjection !== null) { + setProjectionError(null); + cacheProjection(nextProjection); } setShellThreadsById((current) => { diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d1daa87165..a77f5d9edd 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -71,6 +71,10 @@ "types": "./src/state/orchestration.ts", "default": "./src/state/orchestration.ts" }, + "./state/orchestration-v2-projection": { + "types": "./src/state/orchestrationV2Projection.ts", + "default": "./src/state/orchestrationV2Projection.ts" + }, "./state/presentation": { "types": "./src/state/presentation.ts", "default": "./src/state/presentation.ts" diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts new file mode 100644 index 0000000000..839a4480d4 --- /dev/null +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + type OrchestrationV2DomainEvent, + type OrchestrationV2ThreadProjection, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; + +const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); +const threadId = ThreadId.make("thread-reducer"); +const emptyProjection = { + thread: { + id: threadId, + projectId: ProjectId.make("project-reducer"), + title: "Reducer", + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: now, +} as OrchestrationV2ThreadProjection; + +describe("applyOrchestrationV2ProjectionEvent", () => { + it("applies thread lifecycle payloads instead of leaving stale metadata", () => { + const archivedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"); + const event = { + id: "event-archive", + type: "thread.archived", + threadId, + occurredAt: archivedAt, + payload: { ...emptyProjection.thread, archivedAt, updatedAt: archivedAt }, + } as OrchestrationV2DomainEvent; + + const next = applyOrchestrationV2ProjectionEvent(emptyProjection, event); + expect(next?.thread.archivedAt).toEqual(archivedAt); + expect(next?.updatedAt).toEqual(archivedAt); + }); + + it("ignores events for another thread", () => { + const event = { + id: "event-other", + type: "thread.deleted", + threadId: ThreadId.make("thread-other"), + occurredAt: now, + payload: { ...emptyProjection.thread, id: ThreadId.make("thread-other"), deletedAt: now }, + } as OrchestrationV2DomainEvent; + + expect(applyOrchestrationV2ProjectionEvent(emptyProjection, event)).toBe(emptyProjection); + }); +}); diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts new file mode 100644 index 0000000000..7d5b6230c2 --- /dev/null +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -0,0 +1,143 @@ +import type { + OrchestrationV2DomainEvent, + OrchestrationV2ThreadProjection, + OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline"; + +function upsertEntity( + items: ReadonlyArray, + item: T, +): ReadonlyArray { + const index = items.findIndex((candidate) => candidate.id === item.id); + if (index === -1) return [...items, item]; + const next = [...items]; + next[index] = item; + return next; +} + +function removeVisibleItem( + rows: OrchestrationV2ThreadProjection["visibleTurnItems"], + sourceItemId: OrchestrationV2TurnItem["id"], +): OrchestrationV2ThreadProjection["visibleTurnItems"] { + return rows + .filter((row) => row.sourceItemId !== sourceItemId) + .map((row, position) => ({ ...row, position })); +} + +function shouldShowLocalTurnItem( + projection: OrchestrationV2ThreadProjection, + item: OrchestrationV2TurnItem, +): boolean { + return isOrchestrationV2TurnItemVisible({ + item, + runs: projection.runs, + attempts: projection.attempts, + }); +} + +function activeVisibleTurnItems( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection["visibleTurnItems"] { + return projection.visibleTurnItems + .filter((row) => row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item)) + .map((row, position) => ({ ...row, position })); +} + +function upsertVisibleTurnItem( + projection: OrchestrationV2ThreadProjection, + item: OrchestrationV2TurnItem, +): OrchestrationV2ThreadProjection["visibleTurnItems"] { + const rows = projection.visibleTurnItems; + const index = rows.findIndex((row) => row.sourceItemId === item.id); + const next = { + position: index === -1 ? rows.length : rows[index]!.position, + visibility: "local" as const, + sourceThreadId: item.threadId, + sourceItemId: item.id, + item, + }; + return index === -1 + ? [...rows, next] + : rows.map((row, rowIndex) => (rowIndex === index ? next : row)); +} + +/** Applies one committed event to a matching thread projection. */ +export function applyOrchestrationV2ProjectionEvent( + projection: OrchestrationV2ThreadProjection | null, + event: OrchestrationV2DomainEvent, +): OrchestrationV2ThreadProjection | null { + if (projection === null || event.threadId !== projection.thread.id) return projection; + + const base = { ...projection, updatedAt: event.occurredAt }; + switch (event.type) { + case "thread.created": + case "thread.archived": + case "thread.unarchived": + case "thread.deleted": + case "thread.metadata-updated": + case "thread.runtime-mode-updated": + case "thread.interaction-mode-updated": + case "thread.model-selection-updated": + case "thread.provider-switched": + return { ...base, thread: event.payload }; + case "run.created": + case "run.updated": { + const next = { ...base, runs: upsertEntity(base.runs, event.payload) }; + return { ...next, visibleTurnItems: activeVisibleTurnItems(next) }; + } + case "run-attempt.created": + case "run-attempt.updated": { + const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) }; + return { ...next, visibleTurnItems: activeVisibleTurnItems(next) }; + } + case "node.updated": + return { ...base, nodes: upsertEntity(base.nodes, event.payload) }; + case "subagent.updated": + return { ...base, subagents: upsertEntity(base.subagents, event.payload) }; + case "provider-session.attached": + case "provider-session.updated": + return { + ...base, + providerSessions: upsertEntity(base.providerSessions, event.payload), + }; + case "provider-session.detached": + return { + ...base, + providerSessions: base.providerSessions.filter( + (session) => session.id !== event.payload.providerSessionId, + ), + }; + case "provider-thread.updated": + return { ...base, providerThreads: upsertEntity(base.providerThreads, event.payload) }; + case "provider-turn.updated": + return { ...base, providerTurns: upsertEntity(base.providerTurns, event.payload) }; + case "runtime-request.updated": + return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) }; + case "message.updated": + return { ...base, messages: upsertEntity(base.messages, event.payload) }; + case "plan.updated": + return { ...base, plans: upsertEntity(base.plans, event.payload) }; + case "turn-item.updated": { + const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) }; + const visible = { ...next, visibleTurnItems: activeVisibleTurnItems(next) }; + return { + ...next, + visibleTurnItems: shouldShowLocalTurnItem(next, event.payload) + ? upsertVisibleTurnItem(visible, event.payload) + : removeVisibleItem(visible.visibleTurnItems, event.payload.id), + }; + } + case "checkpoint-scope.created": + return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) }; + case "checkpoint.captured": + return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) }; + case "checkpoint.rollback-requested": + return base; + case "context-handoff.updated": + return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) }; + case "context-transfer.created": + case "context-transfer.updated": + return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) }; + } +} diff --git a/packages/contracts/src/applicationEvent.ts b/packages/contracts/src/applicationEvent.ts new file mode 100644 index 0000000000..5a0cd0b485 --- /dev/null +++ b/packages/contracts/src/applicationEvent.ts @@ -0,0 +1,12 @@ +import type { OrchestrationEvent } from "./orchestration.ts"; +import type { OrchestrationV2StoredEvent } from "./orchestrationV2.ts"; + +export type ApplicationProjectEvent = Extract< + OrchestrationEvent, + { + readonly type: "project.created" | "project.meta-updated" | "project.deleted"; + } +>; + +/** Events exposed by the retained application event source. */ +export type ApplicationStoredEvent = ApplicationProjectEvent | OrchestrationV2StoredEvent; diff --git a/packages/contracts/src/checkpointDiff.ts b/packages/contracts/src/checkpointDiff.ts new file mode 100644 index 0000000000..ad74c0e63b --- /dev/null +++ b/packages/contracts/src/checkpointDiff.ts @@ -0,0 +1,66 @@ +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SchemaIssue from "effect/SchemaIssue"; +import * as Struct from "effect/Struct"; + +import { NonNegativeInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +export const TurnCountRange = Schema.Struct({ + fromTurnCount: NonNegativeInt, + toTurnCount: NonNegativeInt, +}).check( + Schema.makeFilter( + (input) => + input.fromTurnCount <= input.toTurnCount || + new SchemaIssue.InvalidValue(Option.some(input.fromTurnCount), { + message: "fromTurnCount must be less than or equal to toTurnCount", + }), + { identifier: "OrchestrationTurnDiffRange" }, + ), +); + +export const ThreadTurnDiff = TurnCountRange.mapFields( + Struct.assign({ + threadId: ThreadId, + diff: Schema.String, + }), + { unsafePreserveChecks: true }, +); + +export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields( + Struct.assign({ + threadId: ThreadId, + ignoreWhitespace: Schema.optionalKey(Schema.Boolean), + }), + { unsafePreserveChecks: true }, +); +export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type; + +export const OrchestrationGetTurnDiffResult = ThreadTurnDiff; +export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type; + +export const OrchestrationGetFullThreadDiffInput = Schema.Struct({ + threadId: ThreadId, + toTurnCount: NonNegativeInt, + ignoreWhitespace: Schema.optionalKey(Schema.Boolean), +}); +export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type; + +export const OrchestrationGetFullThreadDiffResult = ThreadTurnDiff; +export type OrchestrationGetFullThreadDiffResult = typeof OrchestrationGetFullThreadDiffResult.Type; + +export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass()( + "OrchestrationGetTurnDiffError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass()( + "OrchestrationGetFullThreadDiffError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect()), + }, +) {} diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index f385a2eff2..a34d33bc33 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -26,13 +26,7 @@ import { } from "./auth.ts"; import { AuthSessionId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ExecutionEnvironmentDescriptor } from "./environment.ts"; -import { - ClientOrchestrationCommand, - DispatchResult, - OrchestrationReadModel, - OrchestrationShellSnapshot, - OrchestrationThreadDetailSnapshot, -} from "./orchestration.ts"; +import { Project, ProjectMutation, ProjectSnapshot } from "./project.ts"; import { RelayCloudEnvironmentHealthRequest, RelayCloudMintCredentialRequest, @@ -81,9 +75,8 @@ export const EnvironmentInternalErrorReason = Schema.Literals([ "pairing_link_revoke_failed", "client_sessions_load_failed", "client_session_revoke_failed", - "orchestration_snapshot_failed", - "orchestration_thread_snapshot_failed", - "orchestration_dispatch_failed", + "project_snapshot_failed", + "project_mutation_failed", "internal_error", ]); export type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type; @@ -286,16 +279,11 @@ const EnvironmentSessionRevokeErrors = [ EnvironmentOperationForbiddenError, EnvironmentInternalError, ] as const; -const EnvironmentOrchestrationSnapshotErrors = [ +const EnvironmentProjectSnapshotErrors = [ EnvironmentScopeRequiredError, EnvironmentInternalError, ] as const; -const EnvironmentOrchestrationThreadSnapshotErrors = [ - EnvironmentScopeRequiredError, - EnvironmentResourceNotFoundError, - EnvironmentInternalError, -] as const; -const EnvironmentOrchestrationDispatchErrors = [ +const EnvironmentProjectMutationErrors = [ EnvironmentRequestInvalidError, EnvironmentScopeRequiredError, EnvironmentInternalError, @@ -453,50 +441,20 @@ export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth") }).middleware(EnvironmentAuthenticatedAuth), ) {} -const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ - threadId: ThreadId, -}); - -// Query-string window for windowed thread snapshots (GET payloads must encode -// to strings). Both fields optional: omitting them keeps the full-snapshot -// behavior, so pagination stays opt-in per request. -const EnvironmentOrchestrationThreadSnapshotQuery = { - turnLimit: Schema.optional( - Schema.FiniteFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1)), - ), - beforeCursor: Schema.optional(TrimmedNonEmptyString), -}; - -export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration") +export class EnvironmentProjectsHttpApi extends HttpApiGroup.make("projects") .add( - HttpApiEndpoint.get("snapshot", "/api/orchestration/snapshot", { + HttpApiEndpoint.get("snapshot", "/api/projects", { headers: OptionalBearerHeaders, - success: OrchestrationReadModel, - error: EnvironmentOrchestrationSnapshotErrors, + success: ProjectSnapshot, + error: EnvironmentProjectSnapshotErrors, }).middleware(EnvironmentAuthenticatedAuth), ) .add( - HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", { + HttpApiEndpoint.post("mutate", "/api/projects/mutate", { headers: OptionalBearerHeaders, - success: OrchestrationShellSnapshot, - error: EnvironmentOrchestrationSnapshotErrors, - }).middleware(EnvironmentAuthenticatedAuth), - ) - .add( - HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", { - headers: OptionalBearerHeaders, - params: EnvironmentOrchestrationThreadSnapshotParams, - payload: EnvironmentOrchestrationThreadSnapshotQuery, - success: OrchestrationThreadDetailSnapshot, - error: EnvironmentOrchestrationThreadSnapshotErrors, - }).middleware(EnvironmentAuthenticatedAuth), - ) - .add( - HttpApiEndpoint.post("dispatch", "/api/orchestration/dispatch", { - headers: OptionalBearerHeaders, - payload: ClientOrchestrationCommand, - success: DispatchResult, - error: EnvironmentOrchestrationDispatchErrors, + payload: ProjectMutation, + success: Project, + error: EnvironmentProjectMutationErrors, }).middleware(EnvironmentAuthenticatedAuth), ) {} @@ -564,5 +522,5 @@ export class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect") export class EnvironmentHttpApi extends HttpApi.make("environment") .add(EnvironmentMetadataHttpApi) .add(EnvironmentAuthHttpApi) - .add(EnvironmentOrchestrationHttpApi) + .add(EnvironmentProjectsHttpApi) .add(EnvironmentConnectHttpApi) {} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 10225eae6a..ec6a64da28 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -23,6 +23,7 @@ export * from "./vcs.ts"; export * from "./sourceControl.ts"; export * from "./orchestration.ts"; export * from "./orchestrationV2.ts"; +export * from "./applicationEvent.ts"; export * from "./orchestratorMcp.ts"; export * from "./editor.ts"; export * from "./project.ts"; diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 45c172a422..7f7b1d50b1 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1,6 +1,5 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import * as SchemaIssue from "effect/SchemaIssue"; import * as Struct from "effect/Struct"; import { RepositoryIdentity } from "./environment.ts"; import { @@ -20,6 +19,12 @@ import { TurnId, } from "./baseSchemas.ts"; import { ChatAttachment, UploadChatAttachment } from "./chatAttachment.ts"; +import { + OrchestrationGetFullThreadDiffInput, + OrchestrationGetFullThreadDiffResult, + OrchestrationGetTurnDiffInput, + OrchestrationGetTurnDiffResult, +} from "./checkpointDiff.ts"; import { ModelSelection } from "./modelSelection.ts"; import { DEFAULT_PROVIDER_INTERACTION_MODE, @@ -32,15 +37,25 @@ import { import { ProviderInstanceId } from "./providerInstance.ts"; import { Project, ProjectScript } from "./project.ts"; +export { + OrchestrationGetFullThreadDiffError, + OrchestrationGetFullThreadDiffInput, + OrchestrationGetFullThreadDiffResult, + OrchestrationGetTurnDiffError, + OrchestrationGetTurnDiffInput, + OrchestrationGetTurnDiffResult, + ThreadTurnDiff, + TurnCountRange, +} from "./checkpointDiff.ts"; + export const ORCHESTRATION_WS_METHODS = { - dispatchCommand: "orchestration.dispatchCommand", - getWorkflowScript: "orchestration.getWorkflowScript", - getTurnDiff: "orchestration.getTurnDiff", - getFullThreadDiff: "orchestration.getFullThreadDiff", - searchThreads: "orchestration.searchThreads", - getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot", - subscribeShell: "orchestration.subscribeShell", - subscribeThread: "orchestration.subscribeThread", + dispatchCommand: "orchestrationV1.dispatchCommand", + getTurnDiff: "orchestrationV1.getTurnDiff", + getFullThreadDiff: "orchestrationV1.getFullThreadDiff", + replayEvents: "orchestrationV1.replayEvents", + getArchivedShellSnapshot: "orchestrationV1.getArchivedShellSnapshot", + subscribeShell: "orchestrationV1.subscribeShell", + subscribeThread: "orchestrationV1.subscribeThread", } as const; // Correlation id is command id by design in this model. @@ -433,10 +448,11 @@ export const ProjectCreateCommand = Schema.Struct({ workspaceRoot: TrimmedNonEmptyString, createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean), defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), + scripts: Schema.optional(Schema.Array(ProjectScript)), createdAt: IsoDateTime, }); -const ProjectMetaUpdateCommand = Schema.Struct({ +export const ProjectMetaUpdateCommand = Schema.Struct({ type: Schema.Literal("project.meta.update"), commandId: CommandId, projectId: ProjectId, @@ -446,13 +462,20 @@ const ProjectMetaUpdateCommand = Schema.Struct({ scripts: Schema.optional(Schema.Array(ProjectScript)), }); -const ProjectDeleteCommand = Schema.Struct({ +export const ProjectDeleteCommand = Schema.Struct({ type: Schema.Literal("project.delete"), commandId: CommandId, projectId: ProjectId, force: Schema.optional(Schema.Boolean), }); +export const ProjectOrchestrationCommand = Schema.Union([ + ProjectCreateCommand, + ProjectMetaUpdateCommand, + ProjectDeleteCommand, +]); +export type ProjectOrchestrationCommand = typeof ProjectOrchestrationCommand.Type; + const ThreadCreateCommand = Schema.Struct({ type: Schema.Literal("thread.create"), commandId: CommandId, @@ -1254,28 +1277,6 @@ export type OrchestrationThreadStreamItem = typeof OrchestrationThreadStreamItem export const OrchestrationCommandReceiptStatus = Schema.Literals(["accepted", "rejected"]); export type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type; -export const TurnCountRange = Schema.Struct({ - fromTurnCount: NonNegativeInt, - toTurnCount: NonNegativeInt, -}).check( - Schema.makeFilter( - (input) => - input.fromTurnCount <= input.toTurnCount || - new SchemaIssue.InvalidValue({ - message: "fromTurnCount must be less than or equal to toTurnCount", - }), - { identifier: "OrchestrationTurnDiffRange" }, - ), -); - -export const ThreadTurnDiff = TurnCountRange.mapFields( - Struct.assign({ - threadId: ThreadId, - diff: Schema.String, - }), - { unsafePreserveChecks: true }, -); - export const ProviderSessionRuntimeStatus = Schema.Literals([ "starting", "running", @@ -1315,30 +1316,10 @@ export const DispatchResult = Schema.Struct({ }); export type DispatchResult = typeof DispatchResult.Type; -export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields( - Struct.assign({ - threadId: ThreadId, - ignoreWhitespace: Schema.optionalKey(Schema.Boolean), - }), - { unsafePreserveChecks: true }, -); -export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type; - -export const OrchestrationGetTurnDiffResult = ThreadTurnDiff; -export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type; - -export const OrchestrationGetFullThreadDiffInput = Schema.Struct({ - threadId: ThreadId, - toTurnCount: NonNegativeInt, - ignoreWhitespace: Schema.optionalKey(Schema.Boolean), +export const OrchestrationReplayEventsInput = Schema.Struct({ + fromSequenceExclusive: NonNegativeInt, }); -export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type; - -export const OrchestrationGetFullThreadDiffResult = ThreadTurnDiff; -export type OrchestrationGetFullThreadDiffResult = typeof OrchestrationGetFullThreadDiffResult.Type; - -export const OrchestrationThreadSearchSource = Schema.Literals(["user", "assistant"]); -export type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSource.Type; +export type OrchestrationReplayEventsInput = typeof OrchestrationReplayEventsInput.Type; // The server's SQLite client is synchronous and single-connection. Bound both // scan input and response size so a search cannot monopolize that connection. @@ -1461,24 +1442,8 @@ export class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass()( - "OrchestrationGetTurnDiffError", - { - message: TrimmedNonEmptyString, - cause: Schema.optional(Schema.Defect()), - }, -) {} - -export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass()( - "OrchestrationGetFullThreadDiffError", - { - message: TrimmedNonEmptyString, - cause: Schema.optional(Schema.Defect()), - }, -) {} - -export class OrchestrationSearchThreadsError extends Schema.TaggedErrorClass()( - "OrchestrationSearchThreadsError", +export class OrchestrationReplayEventsError extends Schema.TaggedErrorClass()( + "OrchestrationReplayEventsError", { message: TrimmedNonEmptyString, cause: Schema.optional(Schema.Defect()), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8f6d233e24..6f413c9734 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -26,6 +26,12 @@ import { TurnItemId, } from "./baseSchemas.ts"; import { ChatAttachment } from "./chatAttachment.ts"; +import { + OrchestrationGetFullThreadDiffInput, + OrchestrationGetFullThreadDiffResult, + OrchestrationGetTurnDiffInput, + OrchestrationGetTurnDiffResult, +} from "./checkpointDiff.ts"; import { ModelSelection } from "./modelSelection.ts"; import { ProviderApprovalDecision, @@ -36,6 +42,7 @@ import { RuntimeMode, } from "./providerPolicy.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; +import { OrchestrationProjectShell } from "./orchestration.ts"; export const OrchestrationV2Actor = Schema.Literals(["user", "agent", "system"]); export type OrchestrationV2Actor = typeof OrchestrationV2Actor.Type; @@ -1099,12 +1106,18 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ }); export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type; -export const OrchestrationV2ShellSnapshot = Schema.Struct({ +export const OrchestrationV2ThreadShellSnapshot = Schema.Struct({ schemaVersion: PositiveInt, snapshotSequence: NonNegativeInt, threads: Schema.Array(OrchestrationV2ThreadShell), archivedThreads: Schema.Array(OrchestrationV2ThreadShell), }); +export type OrchestrationV2ThreadShellSnapshot = typeof OrchestrationV2ThreadShellSnapshot.Type; + +export const OrchestrationV2ShellSnapshot = Schema.Struct({ + ...OrchestrationV2ThreadShellSnapshot.fields, + projects: Schema.Array(OrchestrationProjectShell), +}); export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type; export const OrchestrationV2ShellStreamItem = Schema.Union([ @@ -1112,6 +1125,16 @@ export const OrchestrationV2ShellStreamItem = Schema.Union([ kind: Schema.Literal("snapshot"), snapshot: OrchestrationV2ShellSnapshot, }), + Schema.Struct({ + kind: Schema.Literal("project.updated"), + sequence: NonNegativeInt, + project: OrchestrationProjectShell, + }), + Schema.Struct({ + kind: Schema.Literal("project.removed"), + sequence: NonNegativeInt, + projectId: ProjectId, + }), Schema.Struct({ kind: Schema.Literal("thread.updated"), sequence: NonNegativeInt, @@ -1730,12 +1753,75 @@ export const OrchestrationV2Command = Schema.Union([ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type; export const ORCHESTRATION_V2_WS_METHODS = { - dispatchCommand: "orchestrationV2.dispatchCommand", - getThreadProjection: "orchestrationV2.getThreadProjection", - subscribeShell: "orchestrationV2.subscribeShell", - subscribeThread: "orchestrationV2.subscribeThread", + dispatchCommand: "orchestration.dispatchCommand", + getTurnDiff: "orchestration.getTurnDiff", + getFullThreadDiff: "orchestration.getFullThreadDiff", + getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot", + getThreadProjection: "orchestration.getThreadProjection", + launchThread: "orchestration.launchThread", + subscribeArchivedShell: "orchestration.subscribeArchivedShell", + subscribeShell: "orchestration.subscribeShell", + subscribeThread: "orchestration.subscribeThread", } as const; +export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({ + schemaVersion: PositiveInt, + snapshotSequence: NonNegativeInt, + threads: Schema.Array(OrchestrationV2ThreadShell), +}); +export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2ArchivedShellSnapshot.Type; + +export const OrchestrationV2ArchivedShellStreamItem = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("snapshot"), + snapshot: OrchestrationV2ArchivedShellSnapshot, + }), + Schema.Struct({ + kind: Schema.Literal("thread.updated"), + sequence: NonNegativeInt, + thread: OrchestrationV2ThreadShell, + }), + Schema.Struct({ + kind: Schema.Literal("thread.removed"), + sequence: NonNegativeInt, + threadId: ThreadId, + }), +]); +export type OrchestrationV2ArchivedShellStreamItem = + typeof OrchestrationV2ArchivedShellStreamItem.Type; + +export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([ + Schema.Struct({ type: Schema.Literal("root") }), + Schema.Struct({ + type: Schema.Literal("worktree"), + baseRef: TrimmedNonEmptyString, + branch: Schema.optional(TrimmedNonEmptyString), + }), +]); +export type OrchestrationV2ThreadLaunchWorkspaceStrategy = + typeof OrchestrationV2ThreadLaunchWorkspaceStrategy.Type; + +export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ + commandId: CommandId, + projectId: ProjectId, + title: TrimmedNonEmptyString, + modelSelection: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, + workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy, + initialMessage: Schema.optional( + Schema.Struct({ text: Schema.String, attachments: Schema.Array(ChatAttachment) }), + ), +}); +export type OrchestrationV2ThreadLaunchInput = typeof OrchestrationV2ThreadLaunchInput.Type; + +export const OrchestrationV2ThreadLaunchResult = Schema.Struct({ + threadId: ThreadId, + projection: OrchestrationV2ThreadProjection, + resumed: Schema.Boolean, +}); +export type OrchestrationV2ThreadLaunchResult = typeof OrchestrationV2ThreadLaunchResult.Type; + export const OrchestrationV2DispatchCommandResult = Schema.Struct({ sequence: NonNegativeInt, }); @@ -1789,10 +1875,21 @@ export class OrchestrationV2GetShellSnapshotError extends Schema.TaggedErrorClas }, ) {} +export class OrchestrationV2ThreadLaunchError extends Schema.TaggedErrorClass()( + "OrchestrationV2ThreadLaunchError", + { + commandId: CommandId, + projectId: ProjectId, + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + export const OrchestrationV2RpcError = Schema.Union([ OrchestrationV2DispatchCommandError, OrchestrationV2GetThreadProjectionError, OrchestrationV2GetShellSnapshotError, + OrchestrationV2ThreadLaunchError, ]); export type OrchestrationV2RpcError = typeof OrchestrationV2RpcError.Type; @@ -1801,10 +1898,30 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2Command, output: OrchestrationV2DispatchCommandResult, }, + getTurnDiff: { + input: OrchestrationGetTurnDiffInput, + output: OrchestrationGetTurnDiffResult, + }, + getFullThreadDiff: { + input: OrchestrationGetFullThreadDiffInput, + output: OrchestrationGetFullThreadDiffResult, + }, + getArchivedShellSnapshot: { + input: Schema.Struct({}), + output: OrchestrationV2ArchivedShellSnapshot, + }, getThreadProjection: { input: OrchestrationV2GetThreadProjectionInput, output: OrchestrationV2ThreadProjection, }, + launchThread: { + input: OrchestrationV2ThreadLaunchInput, + output: OrchestrationV2ThreadLaunchResult, + }, + subscribeArchivedShell: { + input: Schema.Struct({}), + output: OrchestrationV2ArchivedShellStreamItem, + }, subscribeShell: { input: Schema.Struct({}), output: OrchestrationV2ShellStreamItem, diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 5fe592c461..f37e0d9760 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -2,6 +2,7 @@ import * as Schema from "effect/Schema"; import { RepositoryIdentity } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; import { + CommandId, IsoDateTime, NonNegativeInt, PositiveInt, @@ -65,6 +66,33 @@ export const ProjectChange = Schema.Union([ ]); export type ProjectChange = typeof ProjectChange.Type; +export const ProjectMutation = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("project.create"), + commandId: CommandId, + projectId: ProjectId, + title: TrimmedNonEmptyString, + workspaceRoot: TrimmedNonEmptyString, + defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), + scripts: Schema.optional(Schema.Array(ProjectScript)), + }), + Schema.Struct({ + type: Schema.Literal("project.update"), + commandId: CommandId, + projectId: ProjectId, + title: Schema.optional(TrimmedNonEmptyString), + workspaceRoot: Schema.optional(TrimmedNonEmptyString), + defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), + scripts: Schema.optional(Schema.Array(ProjectScript)), + }), + Schema.Struct({ + type: Schema.Literal("project.delete"), + commandId: CommandId, + projectId: ProjectId, + }), +]); +export type ProjectMutation = typeof ProjectMutation.Type; + export const ProjectSearchEntriesInput = Schema.Struct({ cwd: TrimmedNonEmptyString, // An empty query is a bounded browse: the index returns frecency-ordered diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 2afeb9bea2..72c75a19cc 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -19,6 +19,12 @@ import { FilesystemBrowseError, } from "./filesystem.ts"; import { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts"; +import { + OrchestrationGetFullThreadDiffError, + OrchestrationGetFullThreadDiffInput, + OrchestrationGetTurnDiffError, + OrchestrationGetTurnDiffInput, +} from "./checkpointDiff.ts"; import { GitActionProgressEvent, VcsSwitchRefInput, @@ -56,13 +62,9 @@ import { ClientOrchestrationCommand, ORCHESTRATION_WS_METHODS, OrchestrationDispatchCommandError, - OrchestrationGetFullThreadDiffError, - OrchestrationGetFullThreadDiffInput, OrchestrationGetSnapshotError, - OrchestrationSearchThreadsError, - OrchestrationSearchThreadsInput, - OrchestrationGetTurnDiffError, - OrchestrationGetTurnDiffInput, + OrchestrationReplayEventsError, + OrchestrationReplayEventsInput, OrchestrationRpcSchemas, OrchestrationGetWorkflowScriptError, } from "./orchestration.ts"; @@ -73,6 +75,7 @@ import { OrchestrationV2GetShellSnapshotError, OrchestrationV2GetThreadProjectionError, OrchestrationV2RpcSchemas, + OrchestrationV2ThreadLaunchError, } from "./orchestrationV2.ts"; import { ProjectSearchEntriesError, @@ -755,6 +758,30 @@ export const WsOrchestrationV2DispatchCommandRpc = Rpc.make( }, ); +export const WsOrchestrationV2GetTurnDiffRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.getTurnDiff, { + payload: OrchestrationV2RpcSchemas.getTurnDiff.input, + success: OrchestrationV2RpcSchemas.getTurnDiff.output, + error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]), +}); + +export const WsOrchestrationV2GetFullThreadDiffRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff, + { + payload: OrchestrationV2RpcSchemas.getFullThreadDiff.input, + success: OrchestrationV2RpcSchemas.getFullThreadDiff.output, + error: Schema.Union([OrchestrationGetFullThreadDiffError, EnvironmentAuthorizationError]), + }, +); + +export const WsOrchestrationV2GetArchivedShellSnapshotRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, + { + payload: OrchestrationV2RpcSchemas.getArchivedShellSnapshot.input, + success: OrchestrationV2RpcSchemas.getArchivedShellSnapshot.output, + error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]), + }, +); + export const WsOrchestrationV2GetThreadProjectionRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { @@ -764,6 +791,22 @@ export const WsOrchestrationV2GetThreadProjectionRpc = Rpc.make( }, ); +export const WsOrchestrationV2LaunchThreadRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.launchThread, { + payload: OrchestrationV2RpcSchemas.launchThread.input, + success: OrchestrationV2RpcSchemas.launchThread.output, + error: Schema.Union([OrchestrationV2ThreadLaunchError, EnvironmentAuthorizationError]), +}); + +export const WsOrchestrationV2SubscribeArchivedShellRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell, + { + payload: OrchestrationV2RpcSchemas.subscribeArchivedShell.input, + success: OrchestrationV2RpcSchemas.subscribeArchivedShell.output, + error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]), + stream: true, + }, +); + export const WsOrchestrationV2SubscribeShellRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.subscribeShell, { @@ -916,7 +959,12 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationSubscribeShellRpc, WsOrchestrationSubscribeThreadRpc, WsOrchestrationV2DispatchCommandRpc, + WsOrchestrationV2GetTurnDiffRpc, + WsOrchestrationV2GetFullThreadDiffRpc, + WsOrchestrationV2GetArchivedShellSnapshotRpc, WsOrchestrationV2GetThreadProjectionRpc, + WsOrchestrationV2LaunchThreadRpc, + WsOrchestrationV2SubscribeArchivedShellRpc, WsOrchestrationV2SubscribeShellRpc, WsOrchestrationV2SubscribeThreadRpc, ); diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.ts index 28e07c04e6..44b73f1690 100644 --- a/packages/shared/src/agentAwareness.test.ts +++ b/packages/shared/src/agentAwareness.test.ts @@ -2,14 +2,16 @@ import { describe, expect, it } from "@effect/vitest"; import type { EnvironmentId, + OrchestrationV2ThreadShell, OrchestrationProjectShell, OrchestrationThreadShell, ThreadId, TurnId, } from "@t3tools/contracts"; -import { ProviderInstanceId } from "@t3tools/contracts"; +import { ProviderInstanceId, RuntimeRequestId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; -import { projectThreadAwareness } from "./agentAwareness.ts"; +import { projectThreadAwareness, projectThreadAwarenessV2 } from "./agentAwareness.ts"; const NOW = "2026-05-22T12:00:00.000Z"; @@ -178,3 +180,44 @@ describe("projectThreadAwareness", () => { }); }); }); + +describe("projectThreadAwarenessV2", () => { + const updatedAt = DateTime.makeUnsafe(NOW); + const v2Thread = ( + overrides: Partial> = {}, + ) => ({ + id: "thread-2" as ThreadId, + title: "Integrate orchestration", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + status: "running" as const, + pendingRuntimeRequest: null, + updatedAt, + ...overrides, + }); + + it("projects V2 run state", () => { + expect( + projectThreadAwarenessV2({ + environmentId: "env-1" as EnvironmentId, + project, + thread: v2Thread(), + }), + ).toMatchObject({ phase: "running", headline: "Agent is working" }); + }); + + it("prioritizes V2 user-input requests", () => { + expect( + projectThreadAwarenessV2({ + environmentId: "env-1" as EnvironmentId, + project, + thread: v2Thread({ + pendingRuntimeRequest: { + id: RuntimeRequestId.make("request-1"), + kind: "user_input", + createdAt: updatedAt, + }, + }), + }), + ).toMatchObject({ phase: "waiting_for_input", headline: "Waiting for input" }); + }); +}); diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts index c0f5842eb7..eb9655d364 100644 --- a/packages/shared/src/agentAwareness.ts +++ b/packages/shared/src/agentAwareness.ts @@ -1,9 +1,12 @@ import type { EnvironmentId, + OrchestrationV2ThreadShell, OrchestrationProjectShell, OrchestrationThreadShell, + Project, ThreadId, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; export type AgentAwarenessPhase = | "starting" @@ -74,6 +77,72 @@ export function projectThreadAwareness( }; } +export interface ProjectThreadAwarenessV2Input { + readonly environmentId: EnvironmentId; + readonly project: Pick; + readonly thread: Pick< + OrchestrationV2ThreadShell, + "id" | "title" | "modelSelection" | "status" | "pendingRuntimeRequest" | "updatedAt" + >; +} + +/** Build relay activity directly from the V2 shell projection. */ +export function projectThreadAwarenessV2( + input: ProjectThreadAwarenessV2Input, +): AgentAwarenessState | null { + const { environmentId, project, thread } = input; + const phase = resolveThreadAwarenessPhaseV2(thread); + if (phase === null) { + return null; + } + const detail = + phase === "completed" + ? "Review the completed task." + : phase === "failed" + ? "The agent run failed." + : undefined; + return { + environmentId, + threadId: thread.id, + projectTitle: project.title, + threadTitle: thread.title, + phase, + headline: headlineForPhase(phase), + ...(detail === undefined ? {} : { detail }), + modelTitle: thread.modelSelection.model, + updatedAt: DateTime.formatIso(thread.updatedAt), + deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }), + }; +} + +function resolveThreadAwarenessPhaseV2( + thread: ProjectThreadAwarenessV2Input["thread"], +): AgentAwarenessPhase | null { + if (thread.pendingRuntimeRequest?.kind === "user_input") { + return "waiting_for_input"; + } + if (thread.pendingRuntimeRequest !== null) { + return "waiting_for_approval"; + } + switch (thread.status) { + case "starting": + return "starting"; + case "running": + case "waiting": + return "running"; + case "completed": + return "completed"; + case "failed": + return "failed"; + case "idle": + case "queued": + case "interrupted": + case "cancelled": + case "rolled_back": + return null; + } +} + function resolveThreadAwarenessPhase( thread: ProjectThreadAwarenessInput["thread"], ): AgentAwarenessPhase | null {