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 { AuthAccessTokenType, AuthEnvironmentBootstrapTokenType, AuthTokenExchangeGrantType, CommandId, DEFAULT_SERVER_SETTINGS, EnvironmentId, EventId, GitCommandError, KeybindingRule, MessageId, ExternalLauncherError, type OrchestrationThreadShell, TerminalNotRunningError, type OrchestrationCommand, type OrchestrationEvent, ORCHESTRATION_WS_METHODS, 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 * as Clock from "effect/Clock";import * as Deferred from "effect/Deferred";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as ManagedRuntime from "effect/ManagedRuntime";import * as Option from "effect/Option";import * as Path from "effect/Path";import * as Stream from "effect/Stream";import { ChildProcessSpawner } from "effect/unstable/process";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 "vite-plus/test"; const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); 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 { GitManager, type GitManagerShape } from "./git/GitManager.ts";import { Keybindings, type KeybindingsShape } from "./keybindings.ts";import * as ExternalLauncher from "./process/externalLauncher.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 { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";import { PersistenceSqlError } from "./persistence/Errors.ts";import { ProviderRegistry, type ProviderRegistryShape,} from "./provider/Services/ProviderRegistry.ts";import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.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, ProjectSetupScriptRunnerError, type ProjectSetupScriptRunnerShape,} from "./project/Services/ProjectSetupScriptRunner.ts";import { RepositoryIdentityResolver, type RepositoryIdentityResolverShape,} from "./project/Services/RepositoryIdentityResolver.ts";import { ServerEnvironment, type ServerEnvironmentShape,} from "./environment/Services/ServerEnvironment.ts";import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";import { WorkspacePathsLive } from "./workspace/Layers/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 { CloudManagedEndpointRuntime, type CloudManagedEndpointRuntimeShape,} 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 Data from "effect/Data"; 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, latestTurn: null, messages: [], session: null, activities: [], proposedPlans: [], checkpoints: [], deletedAt: null, }, ], };}; const makeDefaultOrchestrationThreadShell = ( overrides: Partial<OrchestrationThreadShell> = {},): 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, 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<void>; 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<void>((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<ServerConfigShape>; layers?: { keybindings?: Partial<KeybindingsShape>; providerRegistry?: Partial<ProviderRegistryShape>; serverSettings?: Partial<ServerSettingsShape>; externalLauncher?: Partial<ExternalLauncher.ExternalLauncherShape>; vcsDriver?: Partial<VcsDriver.VcsDriverShape>; vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>; gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>; gitManager?: Partial<GitManagerShape>; sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>; reviewService?: Partial<ReviewService.ReviewServiceShape>; vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>; projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>; terminalManager?: Partial<TerminalManagerShape>; orchestrationEngine?: Partial<OrchestrationEngineShape>; projectionSnapshotQuery?: Partial<ProjectionSnapshotQueryShape>; checkpointDiffQuery?: Partial<CheckpointDiffQueryShape>; browserTraceCollector?: Partial<BrowserTraceCollectorShape>; serverLifecycleEvents?: Partial<ServerLifecycleEventsShape>; serverRuntimeStartup?: Partial<ServerRuntimeStartupShape>; serverEnvironment?: Partial<ServerEnvironmentShape>; repositoryIdentityResolver?: Partial<RepositoryIdentityResolverShape>; cloudManagedEndpointRuntime?: Partial<CloudManagedEndpointRuntimeShape>; relayClient?: Partial<RelayClient.RelayClientShape>; cloudCliTokenManager?: Partial<CloudCliTokenManager.CloudCliTokenManagerShape>; };}) => 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: "desktop", port: 0, host: "127.0.0.1", cwd: process.cwd(), baseDir, ...derivedPaths, staticDir: undefined, devUrl, noBrowser: true, startupPresentation: "browser", desktopBootstrapToken: defaultDesktopBootstrapToken, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, tailscaleServeEnabled: false, tailscaleServePort: 443, ...options?.config, }; const layerConfig = Layer.succeed(ServerConfig, config); const defaultVcsDriver: VcsDriver.VcsDriverShape = { 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, });Lines 1–500 of 6575. Load more
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 { AuthAccessTokenType, AuthEnvironmentBootstrapTokenType, AuthTokenExchangeGrantType, CommandId, DEFAULT_SERVER_SETTINGS, EnvironmentId, EventId, GitCommandError, KeybindingRule, MessageId, ExternalLauncherError, type OrchestrationThreadShell, TerminalNotRunningError, type OrchestrationCommand, type OrchestrationEvent, ORCHESTRATION_WS_METHODS, 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 * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/unstable/process"; 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 "vite-plus/test"; const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); 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 { GitManager, type GitManagerShape } from "./git/GitManager.ts"; import { Keybindings, type KeybindingsShape } from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.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 { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts"; import { PersistenceSqlError } from "./persistence/Errors.ts"; import { ProviderRegistry, type ProviderRegistryShape, } from "./provider/Services/ProviderRegistry.ts"; import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.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, ProjectSetupScriptRunnerError, type ProjectSetupScriptRunnerShape, } from "./project/Services/ProjectSetupScriptRunner.ts"; import { RepositoryIdentityResolver, type RepositoryIdentityResolverShape, } from "./project/Services/RepositoryIdentityResolver.ts"; import { ServerEnvironment, type ServerEnvironmentShape, } from "./environment/Services/ServerEnvironment.ts"; import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; import { WorkspacePathsLive } from "./workspace/Layers/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 { CloudManagedEndpointRuntime, type CloudManagedEndpointRuntimeShape, } 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 Data from "effect/Data"; 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, latestTurn: null, messages: [], session: null, activities: [], proposedPlans: [], checkpoints: [], deletedAt: null, }, ], }; }; const makeDefaultOrchestrationThreadShell = ( overrides: Partial<OrchestrationThreadShell> = {}, ): 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, 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<void>; 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<void>((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<ServerConfigShape>; layers?: { keybindings?: Partial<KeybindingsShape>; providerRegistry?: Partial<ProviderRegistryShape>; serverSettings?: Partial<ServerSettingsShape>; externalLauncher?: Partial<ExternalLauncher.ExternalLauncherShape>; vcsDriver?: Partial<VcsDriver.VcsDriverShape>; vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>; gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>; gitManager?: Partial<GitManagerShape>; sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>; reviewService?: Partial<ReviewService.ReviewServiceShape>; vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>; projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>; terminalManager?: Partial<TerminalManagerShape>; orchestrationEngine?: Partial<OrchestrationEngineShape>; projectionSnapshotQuery?: Partial<ProjectionSnapshotQueryShape>; checkpointDiffQuery?: Partial<CheckpointDiffQueryShape>; browserTraceCollector?: Partial<BrowserTraceCollectorShape>; serverLifecycleEvents?: Partial<ServerLifecycleEventsShape>; serverRuntimeStartup?: Partial<ServerRuntimeStartupShape>; serverEnvironment?: Partial<ServerEnvironmentShape>; repositoryIdentityResolver?: Partial<RepositoryIdentityResolverShape>; cloudManagedEndpointRuntime?: Partial<CloudManagedEndpointRuntimeShape>; relayClient?: Partial<RelayClient.RelayClientShape>; cloudCliTokenManager?: Partial<CloudCliTokenManager.CloudCliTokenManagerShape>; }; }) => 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: "desktop", port: 0, host: "127.0.0.1", cwd: process.cwd(), baseDir, ...derivedPaths, staticDir: undefined, devUrl, noBrowser: true, startupPresentation: "browser", desktopBootstrapToken: defaultDesktopBootstrapToken, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, tailscaleServeEnabled: false, tailscaleServePort: 443, ...options?.config, }; const layerConfig = Layer.succeed(ServerConfig, config); const defaultVcsDriver: VcsDriver.VcsDriverShape = { 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, });