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 { CommandId, DEFAULT_SERVER_SETTINGS, GitCommandError, KeybindingRule, MessageId, OpenError, TerminalNotRunningError, type OrchestrationCommand, type OrchestrationEvent, ORCHESTRATION_WS_METHODS, ProjectId, ResolvedKeybindingRule, ThreadId, WS_METHODS, WsRpcGroup, EditorId, } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; import { Deferred, Duration, Effect, FileSystem, Layer, ManagedRuntime, Path, Stream, } from "effect"; import { FetchHttpClient, HttpBody, HttpClient, HttpRouter, HttpServer, } from "effect/unstable/http"; import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; import { vi } from "vitest"; import type { ServerConfigShape } from "./config.ts"; import { deriveServerPaths, 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 { Keybindings, type KeybindingsShape } from "./keybindings.ts"; import { Open, type OpenShape } from "./open.ts"; import { OrchestrationEngineService, type OrchestrationEngineShape, } from "./orchestration/Services/OrchestrationEngine.ts"; import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; import { ProjectionSnapshotQuery, type ProjectionSnapshotQueryShape, } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import { PersistenceSqlError } from "./persistence/Errors.ts"; import { ProviderRegistry, type ProviderRegistryShape, } from "./provider/Services/ProviderRegistry.ts"; import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts"; import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts"; import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts"; import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts"; import { BrowserTraceCollector, type BrowserTraceCollectorShape, } from "./observability/Services/BrowserTraceCollector.ts"; import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; import { ProjectSetupScriptRunner, type ProjectSetupScriptRunnerShape, } from "./project/Services/ProjectSetupScriptRunner.ts"; import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; const defaultProjectId = ProjectId.makeUnsafe("project-default"); const defaultThreadId = ThreadId.makeUnsafe("thread-default"); const defaultModelSelection = { provider: "codex", model: "gpt-5-codex", } as const; const makeDefaultOrchestrationReadModel = () => { const now = new Date().toISOString(); 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, latestTurn: null, messages: [], session: null, activities: [], proposedPlans: [], checkpoints: [], deletedAt: null, }, ], }; }; const workspaceAndProjectServicesLayer = Layer.mergeAll( WorkspacePathsLive, WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)), WorkspaceFileSystemLive.pipe( Layer.provide(WorkspacePathsLive), Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), ), ProjectFaviconResolverLive, ); const browserOtlpTracingLayer = Layer.mergeAll( FetchHttpClient.layer, OtlpSerialization.layerJson, Layer.succeed(HttpClient.TracerDisabledWhen, () => true), ); 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.promise(() => Promise.race([ collector.firstRequest, new Promise((_, reject) => { setTimeout(() => reject(new Error("Timed out waiting for OTLP trace export")), 1_000); }), ]), ); 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; projectSetupScriptRunner?: Partial; terminalManager?: Partial; orchestrationEngine?: Partial; projectionSnapshotQuery?: Partial; checkpointDiffQuery?: Partial; browserTraceCollector?: Partial; serverLifecycleEvents?: Partial; serverRuntimeStartup?: Partial; }; }) => 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* deriveServerPaths(baseDir, devUrl); const config: ServerConfigShape = { 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, noBrowser: true, authToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, ...options?.config, }; const layerConfig = Layer.succeed(ServerConfig, config); const gitManagerLayer = Layer.mock(GitManager)({ ...options?.layers?.gitManager, }); const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer)); const appLayer = HttpRouter.serve(makeRoutesLayer, { disableListenLog: true, disableLogger: true, }).pipe( Layer.provide( Layer.mock(Keybindings)({ streamChanges: Stream.empty, ...options?.layers?.keybindings, }), ), Layer.provide( Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]), refresh: () => Effect.succeed([]), streamChanges: Stream.empty, ...options?.layers?.providerRegistry, }), ), Layer.provide( Layer.mock(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(Open)({ ...options?.layers?.open, }), ), Layer.provide( Layer.mock(GitCore)({ ...options?.layers?.gitCore, }), ), Layer.provide(gitManagerLayer), Layer.provideMerge(gitStatusBroadcasterLayer), Layer.provide( Layer.mock(ProjectSetupScriptRunner)({ runForThread: () => Effect.succeed({ status: "no-script" as const }), ...options?.layers?.projectSetupScriptRunner, }), ), Layer.provide( Layer.mock(TerminalManager)({ ...options?.layers?.terminalManager, }), ), Layer.provide( Layer.mock(OrchestrationEngineService)({ getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()), readEvents: () => Stream.empty, dispatch: () => Effect.succeed({ sequence: 0 }), streamDomainEvents: Stream.empty, ...options?.layers?.orchestrationEngine, }), ), Layer.provide( Layer.mock(ProjectionSnapshotQuery)({ getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()), ...options?.layers?.projectionSnapshotQuery, }), ), Layer.provide( Layer.mock(CheckpointDiffQuery)({ getTurnDiff: () => Effect.succeed({ threadId: defaultThreadId, fromTurnCount: 0, toTurnCount: 0, diff: "", }), getFullThreadDiff: () => Effect.succeed({ threadId: defaultThreadId, fromTurnCount: 0, toTurnCount: 0, diff: "", }), ...options?.layers?.checkpointDiffQuery, }), ), Layer.provide( Layer.mock(BrowserTraceCollector)({ record: () => Effect.void, ...options?.layers?.browserTraceCollector, }), ), Layer.provide( Layer.mock(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)({ awaitCommandReady: Effect.void, markHttpListening: Effect.void, enqueueCommand: (effect) => effect, ...options?.layers?.serverRuntimeStartup, }), ), Layer.provide(workspaceAndProjectServicesLayer), Layer.provideMerge(FetchHttpClient.layer), Layer.provide(layerConfig), ); yield* Layer.build(appLayer); return config; }); const wsRpcProtocolLayer = (wsUrl: string) => RpcClient.layerProtocolSocket().pipe( Layer.provide(NodeSocket.layerWebSocket(wsUrl)), Layer.provide(RpcSerialization.layerJson), ); const makeWsRpcClient = RpcClient.make(WsRpcGroup); type WsRpcClient = typeof makeWsRpcClient extends Effect.Effect ? Client : never; const withWsRpcClient = ( wsUrl: string, f: (client: WsRpcClient) => Effect.Effect, ) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl))); 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 getWsServerUrl = (pathname = "") => Effect.gen(function* () { const server = yield* HttpServer.HttpServer; const address = server.address as HttpServer.TcpAddress; return `ws://127.0.0.1:${address.port}${pathname}`; }); it.layer(NodeServices.layer)("server router seam", (it) => { 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"); const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" })); assert.equal(response.status, 302); assert.equal(response.headers.get("location"), "http://127.0.0.1:5173/"); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("serves project favicon requests before the dev URL redirect", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const projectDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-project-favicon-", }); yield* fileSystem.writeFileString( path.join(projectDir, "favicon.svg"), "router-project-favicon", ); yield* buildAppUnderTest({ config: { devUrl: new URL("http://127.0.0.1:5173") }, }); const response = yield* HttpClient.get( `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, ); assert.equal(response.status, 200); assert.equal(yield* response.text, "router-project-favicon"); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("serves the fallback project favicon when no icon exists", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const projectDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-project-favicon-fallback-", }); yield* buildAppUnderTest({ config: { devUrl: new URL("http://127.0.0.1:5173") }, }); const response = yield* HttpClient.get( `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, ); assert.equal(response.status, 200); assert.include(yield* response.text, 'data-fallback="project-favicon"'); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("serves attachment files from state dir", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const attachmentId = "thread-11111111-1111-4111-8111-111111111111"; const config = yield* buildAppUnderTest(); const attachmentPath = resolveAttachmentRelativePath({ attachmentsDir: config.attachmentsDir, relativePath: `${attachmentId}.bin`, }); assert.isNotNull(attachmentPath, "Attachment path should be resolvable"); yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); yield* fileSystem.writeFileString(attachmentPath, "attachment-ok"); const response = yield* HttpClient.get(`/attachments/${attachmentId}`); assert.equal(response.status, 200); assert.equal(yield* response.text, "attachment-ok"); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("serves attachment files for URL-encoded paths", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const config = yield* buildAppUnderTest(); const attachmentPath = resolveAttachmentRelativePath({ attachmentsDir: config.attachmentsDir, relativePath: "thread%20folder/message%20folder/file%20name.png", }); assert.isNotNull(attachmentPath, "Attachment path should be resolvable"); yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); yield* fileSystem.writeFileString(attachmentPath, "attachment-encoded-ok"); const response = yield* HttpClient.get( "/attachments/thread%20folder/message%20folder/file%20name.png", ); assert.equal(response.status, 200); assert.equal(yield* response.text, "attachment-encoded-ok"); }).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: { "content-type": "application/json", origin: "http://localhost:5733", }, 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: JSON.stringify(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 url = yield* getHttpServerUrl("/api/observability/v1/traces"); const response = yield* Effect.promise(() => fetch(url, { method: "OPTIONS", 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.get("access-control-allow-origin"), "*"); assert.equal(response.headers.get("access-control-allow-methods"), "POST, OPTIONS"); assert.equal(response.headers.get("access-control-allow-headers"), "content-type"); }).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: { "content-type": "application/json", }, 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("returns 404 for missing attachment id lookups", () => Effect.gen(function* () { yield* buildAppUnderTest(); const response = yield* HttpClient.get( "/attachments/missing-11111111-1111-4111-8111-111111111111", ); assert.equal(response.status, 404); }).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("rejects websocket rpc handshake when auth token 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({ config: { authToken: "secret-token", }, }); const wsUrl = yield* getWsServerUrl("/ws"); 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"); assertInclude(String(result.failure), "SocketOpenError"); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("accepts websocket rpc handshake when auth token is provided", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-ok-" }); yield* fs.writeFileString( path.join(workspaceDir, "needle-file.ts"), "export const needle = 1;", ); yield* buildAppUnderTest({ config: { authToken: "secret-token", }, }); const wsUrl = yield* getWsServerUrl("/ws?token=secret-token"); 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.equal(response.truncated, false); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () => Effect.gen(function* () { const providers = [] 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: { issues: [] }, }); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () => Effect.gen(function* () { const providers = [] as const; yield* buildAppUnderTest({ layers: { keybindings: { loadConfigState: Effect.succeed({ keybindings: [], issues: [], }), streamChanges: Stream.empty, }, providerRegistry: { getProviders: Effect.succeed([]), streamChanges: Stream.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"); assert.deepEqual(second, { version: 1, type: "providerStatuses", payload: { providers }, }); }).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: { cwd: "/tmp/project", projectName: "project", }, }, ] as const; const liveEvents = Stream.make({ version: 1 as const, sequence: 2, type: "ready" as const, payload: { at: new Date().toISOString() }, }); 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)), ); it.effect("routes websocket rpc projects.searchEntries errors", () => Effect.gen(function* () { yield* buildAppUnderTest(); const wsUrl = yield* getWsServerUrl("/ws"); const result = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.projectsSearchEntries]({ cwd: "/definitely/not/a/real/workspace/path", query: "needle", limit: 10, }), ).pipe(Effect.result), ); assertTrue(result._tag === "Failure"); assertTrue(result.failure._tag === "ProjectSearchEntriesError"); assertInclude( result.failure.message, "Workspace root does not exist: /definitely/not/a/real/workspace/path", ); }).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("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), ); assertTrue(result._tag === "Failure"); assertTrue(result.failure._tag === "ProjectWriteFileError"); assert.equal( result.failure.message, "Workspace file path must stay within the project root.", ); }).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: { open: { openInEditor: (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 openError = new OpenError({ message: "Editor command not found: cursor" }); yield* buildAppUnderTest({ layers: { open: { openInEditor: () => Effect.fail(openError), }, }, }); 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, openError); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("routes websocket rpc git methods", () => Effect.gen(function* () { yield* buildAppUnderTest({ layers: { gitManager: { invalidateLocalStatus: () => Effect.void, invalidateRemoteStatus: () => Effect.void, invalidateStatus: () => Effect.void, localStatus: () => Effect.succeed({ isRepo: true, hasOriginRemote: true, isDefaultBranch: true, branch: "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, hasOriginRemote: true, isDefaultBranch: true, branch: "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, }), }, gitCore: { pullCurrentBranch: () => Effect.succeed({ status: "pulled", branch: "main", upstreamBranch: "origin/main", }), listBranches: () => Effect.succeed({ branches: [ { name: "main", current: true, isDefault: true, worktreePath: null, }, ], isRepo: true, hasOriginRemote: true, nextCursor: null, totalCount: 1, }), createWorktree: () => Effect.succeed({ worktree: { path: "/tmp/wt", branch: "feature/demo" }, }), removeWorktree: () => Effect.void, createBranch: (input) => Effect.succeed({ branch: input.branch }), checkoutBranch: (input) => Effect.succeed({ branch: input.branch }), initRepo: () => Effect.void, }, }, }); const wsUrl = yield* getWsServerUrl("/ws"); const pull = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })), ); assert.equal(pull.status, "pulled"); const refreshedStatus = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitRefreshStatus]({ 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 branches = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitListBranches]({ cwd: "/tmp/repo" }), ), ); assert.equal(branches.branches[0]?.name, "main"); const worktree = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitCreateWorktree]({ cwd: "/tmp/repo", branch: "main", path: null, }), ), ); assert.equal(worktree.worktree.branch, "feature/demo"); yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitRemoveWorktree]({ cwd: "/tmp/repo", path: "/tmp/wt", }), ), ); yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitCreateBranch]({ cwd: "/tmp/repo", branch: "feature/new", }), ), ); yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitCheckout]({ cwd: "/tmp/repo", branch: "main", }), ), ); yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitInit]({ cwd: "/tmp/repo", }), ), ); }).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: { gitCore: { 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, hasOriginRemote: true, isDefaultBranch: true, branch: "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, hasOriginRemote: true, isDefaultBranch: true, branch: "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.gitPull]({ 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, hasOriginRemote: true, isDefaultBranch: false, branch: "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, hasOriginRemote: true, isDefaultBranch: false, branch: "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: { gitCore: { pullCurrentBranch: () => Effect.succeed({ status: "pulled" as const, branch: "main", upstreamBranch: "origin/main", }), }, gitManager: { invalidateLocalStatus: () => Effect.void, invalidateRemoteStatus: () => Effect.void, localStatus: () => Effect.succeed({ isRepo: true, hasOriginRemote: true, isDefaultBranch: true, branch: "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 = Date.now(); const result = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })), ); const elapsedMs = Date.now() - 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: { gitManager: { invalidateLocalStatus: () => Effect.void, invalidateRemoteStatus: () => Effect.void, localStatus: () => Effect.succeed({ isRepo: true, hasOriginRemote: true, isDefaultBranch: false, branch: "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 = Date.now(); yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitRunStackedAction]({ actionId: "action-1", cwd: "/tmp/repo", action: "commit", }).pipe(Stream.runCollect), ), ); const elapsedMs = Date.now() - 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: { gitManager: { invalidateLocalStatus: () => Effect.void, invalidateRemoteStatus: () => Effect.void, localStatus: () => Deferred.succeed(localRefreshStarted, undefined).pipe( Effect.ignore, Effect.andThen( Effect.succeed({ isRepo: true, hasOriginRemote: true, isDefaultBranch: false, branch: "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 = new Date().toISOString(); const snapshot = { snapshotSequence: 1, updatedAt: now, projects: [ { id: ProjectId.makeUnsafe("project-a"), title: "Project A", workspaceRoot: "/tmp/project-a", defaultModelSelection, scripts: [], createdAt: now, updatedAt: now, deletedAt: null, }, ], threads: [ { id: ThreadId.makeUnsafe("thread-1"), projectId: ProjectId.makeUnsafe("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, latestTurn: null, messages: [], session: null, activities: [], proposedPlans: [], checkpoints: [], deletedAt: null, }, ], }; yield* buildAppUnderTest({ layers: { projectionSnapshotQuery: { getSnapshot: () => Effect.succeed(snapshot), }, orchestrationEngine: { dispatch: () => Effect.succeed({ sequence: 7 }), readEvents: () => Stream.empty, }, checkpointDiffQuery: { getTurnDiff: () => Effect.succeed({ threadId: ThreadId.makeUnsafe("thread-1"), fromTurnCount: 0, toTurnCount: 1, diff: "turn-diff", }), getFullThreadDiff: () => Effect.succeed({ threadId: ThreadId.makeUnsafe("thread-1"), fromTurnCount: 0, toTurnCount: 1, diff: "full-diff", }), }, }, }); const wsUrl = yield* getWsServerUrl("/ws"); const snapshotResult = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})), ); assert.equal(snapshotResult.snapshotSequence, 1); const dispatchResult = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ type: "thread.session.stop", commandId: CommandId.makeUnsafe("cmd-1"), threadId: ThreadId.makeUnsafe("thread-1"), createdAt: now, }), ), ); assert.equal(dispatchResult.sequence, 7); const turnDiffResult = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff]({ threadId: ThreadId.makeUnsafe("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.makeUnsafe("thread-1"), toTurnCount: 1, }), ), ); assert.equal(fullDiffResult.diff, "full-diff"); const replayResult = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.replayEvents]({ fromSequenceExclusive: 0, }), ), ); assert.deepEqual(replayResult, []); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("closes thread terminals after a successful archive command", () => Effect.gen(function* () { const threadId = ThreadId.makeUnsafe("thread-archive"); const closeInputs: Array[0]> = []; yield* buildAppUnderTest({ layers: { terminalManager: { close: (input) => Effect.sync(() => { closeInputs.push(input); }), }, orchestrationEngine: { dispatch: () => Effect.succeed({ sequence: 8 }), }, }, }); const wsUrl = yield* getWsServerUrl("/ws"); const dispatchResult = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ type: "thread.archive", commandId: CommandId.makeUnsafe("cmd-thread-archive"), threadId, }), ), ); assert.equal(dispatchResult.sequence, 8); assert.deepEqual(closeInputs, [{ threadId }]); }).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 createWorktree = vi.fn((_: Parameters[0]) => Effect.succeed({ worktree: { branch: "t3code/bootstrap-branch", path: "/tmp/bootstrap-worktree", }, }), ); const runForThread = vi.fn( (_: Parameters[0]) => Effect.succeed({ status: "started" as const, scriptId: "setup", scriptName: "Setup", terminalId: "setup-setup", cwd: "/tmp/bootstrap-worktree", }), ); yield* buildAppUnderTest({ layers: { gitCore: { createWorktree, }, orchestrationEngine: { dispatch: (command) => Effect.sync(() => { dispatchedCommands.push(command); return { sequence: dispatchedCommands.length }; }), readEvents: () => Stream.empty, }, projectSetupScriptRunner: { runForThread, }, }, }); const createdAt = new Date().toISOString(); const wsUrl = yield* getWsServerUrl("/ws"); const response = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ type: "thread.turn.start", commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start"), threadId: ThreadId.makeUnsafe("thread-bootstrap"), message: { messageId: MessageId.makeUnsafe("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-branch", }, 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", branch: "main", newBranch: "t3code/bootstrap-branch", path: null, }); assert.deepEqual(runForThread.mock.calls[0]?.[0], { threadId: ThreadId.makeUnsafe("thread-bootstrap"), projectId: defaultProjectId, projectCwd: "/tmp/project", worktreePath: "/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: { branch: "t3code/bootstrap-branch", path: "/tmp/bootstrap-worktree", }, }), ); const runForThread = vi.fn( (_: Parameters[0]) => Effect.fail(new Error("pty unavailable")), ); yield* buildAppUnderTest({ layers: { gitCore: { createWorktree, }, orchestrationEngine: { dispatch: (command) => Effect.sync(() => { dispatchedCommands.push(command); return { sequence: dispatchedCommands.length }; }), readEvents: () => Stream.empty, }, projectSetupScriptRunner: { runForThread, }, }, }); const createdAt = new Date().toISOString(); const wsUrl = yield* getWsServerUrl("/ws"); const response = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ type: "thread.turn.start", commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-failure"), threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-failure"), message: { messageId: MessageId.makeUnsafe("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-branch", }, 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: { branch: "t3code/bootstrap-branch", path: "/tmp/bootstrap-worktree", }, }), ); const runForThread = vi.fn( (_: Parameters[0]) => Effect.succeed({ status: "started" as const, scriptId: "setup", scriptName: "Setup", terminalId: "setup-setup", cwd: "/tmp/bootstrap-worktree", }), ); let setupActivityAppendAttempt = 0; yield* buildAppUnderTest({ layers: { gitCore: { 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 = new Date().toISOString(); const wsUrl = yield* getWsServerUrl("/ws"); const response = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ type: "thread.turn.start", commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-activity-failure"), threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-activity-failure"), message: { messageId: MessageId.makeUnsafe("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-branch", }, 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: { gitCore: { createWorktree, }, orchestrationEngine: { dispatch: (command) => Effect.sync(() => { dispatchedCommands.push(command); return { sequence: dispatchedCommands.length }; }), readEvents: () => Stream.empty, }, }, }); const createdAt = new Date().toISOString(); const wsUrl = yield* getWsServerUrl("/ws"); const result = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ type: "thread.turn.start", commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-defect"), threadId: ThreadId.makeUnsafe("thread-bootstrap-defect"), message: { messageId: MessageId.makeUnsafe("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-branch", }, 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 subscribeOrchestrationDomainEvents with replay/live overlap resilience", () => Effect.gen(function* () { const now = new Date().toISOString(); const threadId = ThreadId.makeUnsafe("thread-1"); let replayCursor: number | null = null; const makeEvent = (sequence: number): OrchestrationEvent => ({ sequence, eventId: `event-${sequence}`, aggregateKind: "thread", aggregateId: threadId, occurredAt: now, commandId: null, causationEventId: null, correlationId: null, metadata: {}, type: "thread.reverted", payload: { threadId, turnCount: sequence, }, }) as OrchestrationEvent; yield* buildAppUnderTest({ layers: { orchestrationEngine: { getReadModel: () => Effect.succeed({ ...makeDefaultOrchestrationReadModel(), snapshotSequence: 1, }), readEvents: (fromSequenceExclusive) => { replayCursor = fromSequenceExclusive; return Stream.make(makeEvent(2), makeEvent(3)); }, streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)), }, }, }); const wsUrl = yield* getWsServerUrl("/ws"); const events = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe( Stream.take(3), Stream.runCollect, ), ), ); assert.equal(replayCursor, 1); assert.deepEqual( Array.from(events).map((event) => event.sequence), [2, 3, 4], ); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); it.effect("routes websocket rpc orchestration.getSnapshot errors", () => Effect.gen(function* () { yield* buildAppUnderTest({ layers: { projectionSnapshotQuery: { getSnapshot: () => Effect.fail( new PersistenceSqlError({ operation: "ProjectionSnapshotQuery.getSnapshot", detail: "projection unavailable", }), ), }, }, }); const wsUrl = yield* getWsServerUrl("/ws"); const result = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe( Effect.result, ), ); assertTrue(result._tag === "Failure"); assertTrue(result.failure._tag === "OrchestrationGetSnapshotError"); assertInclude(result.failure.message, "Failed to load orchestration snapshot"); }).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, updatedAt: new Date().toISOString(), }; 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)), ); });