The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { assert, it } from "@effect/vitest"; |
| 2 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 3 | import { |
| 4 | DEFAULT_SERVER_SETTINGS, |
| 5 | ProjectId, |
| 6 | ProviderInstanceId, |
| 7 | ProviderDriverKind, |
| 8 | CommandId, |
| 9 | EnvironmentId, |
| 10 | type ServerLifecycleStreamEvent, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; |
| 13 | import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; |
| 14 | import { HttpServer } from "effect/http"; |
| 15 | import * as NetAddress from "effect/net/NetAddress"; |
| 16 | import * as Deferred from "effect/Deferred"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as FileSystem from "effect/FileSystem"; |
| 19 | import * as Exit from "effect/Exit"; |
| 20 | import * as Fiber from "effect/Fiber"; |
| 21 | import * as Ref from "effect/Ref"; |
| 22 | import * as Layer from "effect/Layer"; |
| 23 | import * as Path from "effect/Path"; |
| 24 | |
| 25 | import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; |
| 26 | |
| 27 | import * as ServerConfig from "./config.ts"; |
| 28 | import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; |
| 29 | import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; |
| 30 | import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; |
| 31 | import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; |
| 32 | import * as Keybindings from "./keybindings.ts"; |
| 33 | import * as EffectWorker from "./orchestration-v2/EffectWorker.ts"; |
| 34 | import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; |
| 35 | import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; |
| 36 | import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; |
| 37 | import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts"; |
| 38 | import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; |
| 39 | import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts"; |
| 40 | import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; |
| 41 | import * as ExternalLauncher from "./process/externalLauncher.ts"; |
| 42 | import * as ProjectService from "./project/ProjectService.ts"; |
| 43 | import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; |
| 44 | import { ServerActivation } from "./serverActivation.ts"; |
| 45 | import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; |
| 46 | import * as ServerSettings from "./serverSettings.ts"; |
| 47 | import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; |
| 48 | import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; |
| 49 | |
| 50 | it.effect.each([ |
| 51 | "disabled-codex", |
| 52 | "disabled-default", |
| 53 | "launch-failure", |
| 54 | "project-failure", |
| 55 | "project-refused", |
| 56 | ] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) => |
| 57 | Effect.gen(function* () { |
| 58 | const projectId = ProjectId.make("bootstrap-project"); |
| 59 | const instanceId = ProviderInstanceId.make( |
| 60 | scenario === "disabled-default" ? "custom" : "codex", |
| 61 | ); |
| 62 | const events: ServerLifecycleStreamEvent[] = []; |
| 63 | const recovery = { |
| 64 | terminalizedRuns: 0, |
| 65 | stoppedSessions: 0, |
| 66 | closedRequests: 0, |
| 67 | retiredEffects: 0, |
| 68 | requeuedEffects: 0, |
| 69 | }; |
| 70 | const imports = { importedThreadCount: 0, importedMessageCount: 0 }; |
| 71 | const dependencies = Layer.mergeAll( |
| 72 | NodeCrypto.layer, |
| 73 | Path.layer, |
| 74 | Layer.mock(ServerConfig.ServerConfig)({ |
| 75 | ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe( |
| 76 | Effect.provide(Path.layer), |
| 77 | )), |
| 78 | baseDir: "/bootstrap-project", |
| 79 | logLevel: "Error", |
| 80 | traceMinLevel: "Info", |
| 81 | traceTimingEnabled: false, |
| 82 | traceBatchWindowMs: 200, |
| 83 | traceMaxBytes: 1024, |
| 84 | traceMaxFiles: 1, |
| 85 | otlpTracesUrl: undefined, |
| 86 | otlpMetricsUrl: undefined, |
| 87 | otlpLogsUrl: undefined, |
| 88 | otlpTracesExport: DEFAULT_SIGNAL_EXPORT, |
| 89 | otlpMetricsExport: DEFAULT_SIGNAL_EXPORT, |
| 90 | otlpLogsExport: DEFAULT_SIGNAL_EXPORT, |
| 91 | otelEnvironment: OtelEnvironment.none, |
| 92 | staticDir: undefined, |
| 93 | devAllowedOrigins: [], |
| 94 | desktopBootstrapToken: undefined, |
| 95 | logWebSocketEvents: false, |
| 96 | tailscaleServeEnabled: false, |
| 97 | tailscaleServePort: 443, |
| 98 | mode: "web", |
| 99 | cwd: "/bootstrap-project", |
| 100 | host: "localhost", |
| 101 | port: 3773, |
| 102 | devUrl: undefined, |
| 103 | noBrowser: true, |
| 104 | startupPresentation: "browser", |
| 105 | autoBootstrapProjectFromCwd: true, |
| 106 | }), |
| 107 | Layer.mock(Keybindings.Keybindings)({ start: Effect.void }), |
| 108 | Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ |
| 109 | pendingThreadCount: Effect.succeed(0), |
| 110 | reconcileShells: Effect.succeed(imports), |
| 111 | importPendingTranscripts: Effect.succeed(imports), |
| 112 | }), |
| 113 | Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({ |
| 114 | recover: Effect.succeed(recovery), |
| 115 | prepareForShutdown: Effect.void, |
| 116 | reconcile: () => Effect.succeed(recovery), |
| 117 | }), |
| 118 | Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }), |
| 119 | Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }), |
| 120 | Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }), |
| 121 | Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }), |
| 122 | Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ |
| 123 | publish: (event) => |
| 124 | Effect.sync(() => { |
| 125 | const published = { ...event, sequence: events.length + 1 }; |
| 126 | events.push(published); |
| 127 | return published; |
| 128 | }), |
| 129 | }), |
| 130 | Layer.mock(ServerSettings.ServerSettingsService)({ |
| 131 | start: Effect.void, |
| 132 | getSettings: Effect.succeed({ |
| 133 | ...DEFAULT_SERVER_SETTINGS, |
| 134 | defaultModelSelection: |
| 135 | scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, |
| 136 | providerInstances: { |
| 137 | [instanceId]: { |
| 138 | driver: ProviderDriverKind.make("codex"), |
| 139 | enabled: false, |
| 140 | config: {}, |
| 141 | }, |
| 142 | }, |
| 143 | }), |
| 144 | }), |
| 145 | Layer.mock(ServerEnvironment.ServerEnvironment)({ |
| 146 | getDescriptor: Effect.succeed({ |
| 147 | environmentId: EnvironmentId.make("bootstrap-environment"), |
| 148 | label: "Test environment", |
| 149 | platform: { os: "linux", arch: "x64" }, |
| 150 | serverVersion: "0.0.0-test", |
| 151 | capabilities: { repositoryIdentity: true }, |
| 152 | }), |
| 153 | }), |
| 154 | Layer.mock(ProjectStore.ProjectStoreV2)({}), |
| 155 | Layer.mock(ProjectService.ProjectService)({ |
| 156 | bootstrap: () => |
| 157 | scenario === "project-failure" |
| 158 | ? Effect.die("project bootstrap failed") |
| 159 | : scenario === "project-refused" |
| 160 | ? Effect.fail( |
| 161 | new ProjectService.ProjectInvalidError({ projectId, detail: "refused folder" }), |
| 162 | ) |
| 163 | : Effect.succeed({ |
| 164 | created: true, |
| 165 | project: { |
| 166 | id: projectId, |
| 167 | title: "Project", |
| 168 | workspaceRoot: "/bootstrap-project", |
| 169 | repositoryIdentity: null, |
| 170 | faviconPath: null, |
| 171 | scripts: [], |
| 172 | createdAt: "2026-01-01T00:00:00Z", |
| 173 | updatedAt: "2026-01-01T00:00:00Z", |
| 174 | deletedAt: null, |
| 175 | defaultModelSelection: |
| 176 | scenario === "disabled-default" |
| 177 | ? { instanceId, model: "custom-model" } |
| 178 | : null, |
| 179 | }, |
| 180 | }), |
| 181 | }), |
| 182 | Layer.mock(ThreadManagement.ThreadManagementService)({ |
| 183 | countThreads: () => Effect.succeed(0), |
| 184 | listActiveShellIndex: () => Effect.succeed([]), |
| 185 | }), |
| 186 | Layer.mock(ThreadLaunch.ThreadLaunchService)({ |
| 187 | launch: (input) => { |
| 188 | assert.equal(input.modelSelection.instanceId, instanceId); |
| 189 | return scenario === "launch-failure" |
| 190 | ? Effect.fail( |
| 191 | new ThreadLaunch.ThreadLaunchError({ |
| 192 | operation: "create-thread", |
| 193 | commandId: CommandId.make("bootstrap-command"), |
| 194 | projectId, |
| 195 | cause: "test launch failure", |
| 196 | }), |
| 197 | ) |
| 198 | : Effect.fail( |
| 199 | new ThreadManagement.ThreadManagementProviderInstanceDisabledError({ |
| 200 | projectId, |
| 201 | instanceId, |
| 202 | }), |
| 203 | ); |
| 204 | }, |
| 205 | }), |
| 206 | Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ |
| 207 | managed: false, |
| 208 | protocol: undefined, |
| 209 | prepareTrial: () => Effect.undefined, |
| 210 | }), |
| 211 | Layer.mock(GitVcsDriver.GitVcsDriver)({}), |
| 212 | Layer.mock(AnalyticsService.AnalyticsService)({}), |
| 213 | // No provider logins or Connect link, so startup records no owners. |
| 214 | FileSystem.layerNoop({}), |
| 215 | Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), |
| 216 | Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), |
| 217 | Layer.mock(ExternalLauncher.ExternalLauncher)({}), |
| 218 | Layer.mock(HttpServer.HttpServer)({ |
| 219 | address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), |
| 220 | }), |
| 221 | ); |
| 222 | yield* Effect.gen(function* () { |
| 223 | const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; |
| 224 | yield* startup.markHttpListening; |
| 225 | const ready = yield* Effect.exit(startup.awaitCommandReady); |
| 226 | assert.equal(Exit.isSuccess(ready), scenario !== "project-failure"); |
| 227 | const welcome = events.find((event) => event.type === "welcome"); |
| 228 | if (scenario === "project-failure") { |
| 229 | assert.isUndefined(welcome); |
| 230 | } else { |
| 231 | assert.isDefined(welcome); |
| 232 | if (welcome?.type === "welcome") { |
| 233 | assert.equal( |
| 234 | welcome.payload.bootstrapProjectId, |
| 235 | scenario === "project-refused" ? undefined : projectId, |
| 236 | ); |
| 237 | assert.isUndefined(welcome.payload.bootstrapThreadId); |
| 238 | } |
| 239 | } |
| 240 | }).pipe( |
| 241 | Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))), |
| 242 | Effect.provideService(ServerActivation, Effect.never), |
| 243 | ); |
| 244 | }), |
| 245 | ); |
| 246 | |
| 247 | it.effect("interrupts the effect worker when awareness relay startup fails", () => |
| 248 | Effect.gen(function* () { |
| 249 | const workerInterrupted = yield* Ref.make(false); |
| 250 | const workerFiberRef = yield* Ref.make<Fiber.Fiber<void, never> | null>(null); |
| 251 | |
| 252 | const exit = yield* ServerRuntimeStartup.startEffectWorkerWithRelay({ |
| 253 | runWorker: Effect.never.pipe(Effect.ensuring(Ref.set(workerInterrupted, true))), |
| 254 | startRelay: Effect.yieldNow.pipe( |
| 255 | Effect.andThen(Effect.die("awareness relay startup failed")), |
| 256 | ), |
| 257 | workerFiberRef, |
| 258 | }).pipe(Effect.exit); |
| 259 | |
| 260 | assert.isTrue(Exit.isFailure(exit)); |
| 261 | assert.isTrue(yield* Ref.get(workerInterrupted)); |
| 262 | assert.isNull(yield* Ref.get(workerFiberRef)); |
| 263 | }), |
| 264 | ); |
| 265 | |
| 266 | it.effect("queues commands until startup signals readiness", () => |
| 267 | Effect.gen(function* () { |
| 268 | const gate = yield* ServerRuntimeStartup.makeCommandGate; |
| 269 | const count = yield* Ref.make(0); |
| 270 | const queued = yield* gate |
| 271 | .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1)) |
| 272 | .pipe(Effect.forkScoped); |
| 273 | |
| 274 | yield* Effect.yieldNow; |
| 275 | assert.equal(yield* Ref.get(count), 0); |
| 276 | yield* gate.signalCommandReady; |
| 277 | assert.equal(yield* Fiber.join(queued), 1); |
| 278 | }), |
| 279 | ); |
| 280 | |
| 281 | it.effect("enqueueCommand fails queued work when readiness fails", () => |
| 282 | Effect.gen(function* () { |
| 283 | const commandGate = yield* ServerRuntimeStartup.makeCommandGate; |
| 284 | const failure = yield* Deferred.make<void, never>(); |
| 285 | |
| 286 | const queuedCommandFiber = yield* commandGate |
| 287 | .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) |
| 288 | .pipe(Effect.forkScoped); |
| 289 | |
| 290 | yield* commandGate.failCommandReady( |
| 291 | new ServerRuntimeStartup.ServerRuntimeStartupError({ |
| 292 | mode: "web", |
| 293 | host: "127.0.0.1", |
| 294 | port: 3773, |
| 295 | cause: new Error("test startup failure"), |
| 296 | }), |
| 297 | ); |
| 298 | |
| 299 | const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); |
| 300 | assert.equal(error.message, "Server runtime startup failed before command readiness."); |
| 301 | }), |
| 302 | ); |
| 303 | |
| 304 | it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () => |
| 305 | Effect.gen(function* () { |
| 306 | const pulled: string[] = []; |
| 307 | const git = { |
| 308 | statusDetails: (cwd: string) => |
| 309 | Effect.succeed({ |
| 310 | isRepo: true, |
| 311 | isDefaultBranch: cwd !== "/feature", |
| 312 | hasUpstream: true, |
| 313 | hasWorkingTreeChanges: cwd === "/dirty", |
| 314 | aheadCount: cwd === "/ahead" ? 1 : 0, |
| 315 | behindCount: cwd === "/current" ? 0 : 1, |
| 316 | } as never), |
| 317 | pullCurrentBranch: (cwd: string) => |
| 318 | Effect.sync(() => { |
| 319 | pulled.push(cwd); |
| 320 | return { |
| 321 | status: "pulled" as const, |
| 322 | refName: "main", |
| 323 | upstreamRef: "origin/main", |
| 324 | }; |
| 325 | }), |
| 326 | } as unknown as GitVcsDriver.GitVcsDriver["Service"]; |
| 327 | const project = (workspaceRoot: string) => |
| 328 | ({ id: ProjectId.make(workspaceRoot), workspaceRoot }) as never; |
| 329 | const overrides = (entries: Record<string, boolean>) => ({ |
| 330 | ...DEFAULT_SERVER_SETTINGS, |
| 331 | projectSettingsOverrides: Object.fromEntries( |
| 332 | Object.entries(entries).map(([root, defaultAutoPull]) => [ |
| 333 | ProjectId.make(root), |
| 334 | { defaultAutoPull }, |
| 335 | ]), |
| 336 | ), |
| 337 | }); |
| 338 | |
| 339 | yield* ServerRuntimeStartup.autoPullProjects( |
| 340 | [ |
| 341 | project("/clean"), |
| 342 | project("/current"), |
| 343 | project("/dirty"), |
| 344 | project("/ahead"), |
| 345 | project("/feature"), |
| 346 | project("/disabled"), |
| 347 | ], |
| 348 | overrides({ |
| 349 | "/clean": true, |
| 350 | "/current": true, |
| 351 | "/dirty": true, |
| 352 | "/ahead": true, |
| 353 | "/feature": true, |
| 354 | "/disabled": false, |
| 355 | }), |
| 356 | ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git)); |
| 357 | |
| 358 | assert.deepStrictEqual(pulled, ["/clean"]); |
| 359 | |
| 360 | pulled.length = 0; |
| 361 | yield* ServerRuntimeStartup.autoPullProjects( |
| 362 | [project("/inherited"), project("/opted-out"), project("/dirty")], |
| 363 | { ...overrides({ "/opted-out": false }), defaultAutoPull: true }, |
| 364 | ).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, git)); |
| 365 | assert.deepStrictEqual(pulled, ["/inherited"]); |
| 366 | }), |
| 367 | ); |