@devries-cameron20 / t3code Mirror · read-only / commits / 51e5ba694e
Fork 0

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, 06:00 UTC

refactor(cli): commands that change state go through a running server (#38991)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 19, 2026 at 00:26 UTC 51e5ba694ef52a9e58112fc6a3e43ec3b72a3384
7 files changed +107 -218
apps/server/src/auth/EnvironmentAuth.ts
+11 -13
@@ -556,10 +556,10 @@ export class EnvironmentAuth extends Context.Service<
556 readonly approveConnectDevice: (
557 pairingLinkId: string,
558 ) => Effect.Effect<boolean, ServerAuthInternalError>;
559 - /** Approves the waiting device that shows this code, for hosts without a client at hand. */
560 - readonly approveConnectDeviceByCode: (
559 + /** Pairing link ids of waiting devices that show this code; more than one is ambiguous. */
560 + readonly connectRequestsShowingCode: (
561 verificationCode: string,
562 - ) => Effect.Effect<boolean, ServerAuthInternalError>;
562 + ) => Effect.Effect<ReadonlyArray<string>, ServerAuthInternalError>;
563 /** Trusted devices that show this code; more than one is ambiguous. */
564 readonly connectDevicesShowingCode: (
565 verificationCode: string,
@@ -1283,20 +1283,18 @@ export const make = Effect.gen(function* () {
1283 Effect.withSpan("EnvironmentAuth.approveConnectDevice"),
1284 );
1285
1286 - const approveConnectDeviceByCode: EnvironmentAuth["Service"]["approveConnectDeviceByCode"] =
1287 - Effect.fn("EnvironmentAuth.approveConnectDeviceByCode")(function* (verificationCode) {
1286 + const connectRequestsShowingCode: EnvironmentAuth["Service"]["connectRequestsShowingCode"] =
1287 + Effect.fn("EnvironmentAuth.connectRequestsShowingCode")(function* (verificationCode) {
1288 const wanted = normalizeVerificationCode(verificationCode);
1289 const links = yield* bootstrapCredentials
1290 .listActive()
1291 .pipe(Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })));
1292 - const matches = links.filter(
1293 - (link) =>
1294 - link.connectDeviceRequest !== undefined &&
1295 - normalizeVerificationCode(link.connectDeviceRequest.verificationCode) === wanted,
1292 + return links.flatMap((link) =>
1293 + link.connectDeviceRequest !== undefined &&
1294 + normalizeVerificationCode(link.connectDeviceRequest.verificationCode) === wanted
1295 + ? [link.id]
1296 + : [],
1297 );
1297 - // Two waiting devices that share a code are ambiguous; approve neither.
1298 - if (matches.length !== 1) return false;
1299 - return yield* approveConnectDevice(matches[0]!.id);
1298 });
1299
1300 const listConnectDevices: EnvironmentAuth["Service"]["listConnectDevices"] = () =>
@@ -1666,7 +1664,7 @@ export const make = Effect.gen(function* () {
1664 createPairingLink,
1665 issueConnectCredential,
1666 approveConnectDevice,
1669 - approveConnectDeviceByCode,
1667 + connectRequestsShowingCode,
1668 listConnectDevices,
1669 revokeConnectDevice,
1670 connectDevicesShowingCode,
apps/server/src/cli/auth.ts
+32 -4
@@ -1,4 +1,9 @@
1 -import { AuthAccessWriteScope, AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts";
1 +import {
2 + AuthAccessWriteScope,
3 + AuthRevokePairingLinkInput,
4 + AuthSessionId,
5 + AuthStandardClientScopes,
6 +} from "@t3tools/contracts";
7 import * as Console from "effect/Console";
8 import * as Effect from "effect/Effect";
9 import * as Layer from "effect/Layer";
@@ -152,13 +157,23 @@ const pairingListCommand = Command.make("list", {
157
158 const pairingRevokeCommand = Command.make("revoke", {
159 ...authLocationFlags,
155 - id: Argument.String("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
160 + id: Argument.String("id").pipe(
161 + Argument.withDescription("Pairing credential id to revoke."),
162 + // Same schema the server applies, so both paths revoke the same id.
163 + Argument.withSchema(AuthRevokePairingLinkInput.fields.id),
164 + ),
165 }).pipe(
166 Command.withDescription("Revoke an active client pairing token."),
167 Command.withHandler((flags) =>
168 runWithEnvironmentAuth(flags, (environmentAuth) =>
169 Effect.gen(function* () {
161 - const revoked = yield* environmentAuth.revokePairingLink(flags.id);
170 + const revoked = yield* changeAccess({
171 + viaServer: (client) =>
172 + client.auth
173 + .revokePairingLink({ headers: {}, payload: { id: flags.id } })
174 + .pipe(Effect.map((result) => result.revoked)),
175 + locally: environmentAuth.revokePairingLink(flags.id),
176 + });
177 yield* Console.log(
178 revoked
179 ? `Revoked pairing credential ${flags.id}.\n`
@@ -209,7 +224,20 @@ const connectDeviceApproveCommand = Command.make("approve", {
224 Command.withHandler((flags) =>
225 runWithEnvironmentAuth(flags, (environmentAuth) =>
226 Effect.gen(function* () {
212 - const approved = yield* environmentAuth.approveConnectDeviceByCode(flags.code);
227 + const [pairingLinkId, ...others] = yield* environmentAuth.connectRequestsShowingCode(
228 + flags.code,
229 + );
230 + // Two waiting devices that share a code are ambiguous; approve neither.
231 + const approved =
232 + pairingLinkId !== undefined &&
233 + others.length === 0 &&
234 + (yield* changeAccess({
235 + viaServer: (client) =>
236 + client.auth
237 + .approveConnectDevice({ headers: {}, payload: { pairingLinkId } })
238 + .pipe(Effect.map((result) => result.approved)),
239 + locally: environmentAuth.approveConnectDevice(pairingLinkId),
240 + }));
241 yield* Console.log(
242 approved
243 ? `Approved ${flags.code}. The device connects on its next try.\n`
apps/server/src/cli/connect.ts
+11 -37
@@ -1,9 +1,7 @@
1 import {
2 AuthRelayReadScope,
3 AuthRelayWriteScope,
4 - type AuthEnvironmentScope,
4 type EnvironmentConnectReachability,
6 - EnvironmentHttpApi,
5 formatConnectReachable,
6 type RelayClientInstallProgressEvent,
7 type RelayClientInstallProgressStage,
@@ -27,7 +25,6 @@ import * as References from "effect/References";
25 import * as Schema from "effect/Schema";
26 import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
27 import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
30 -import * as HttpApiClient from "effect/http-api/HttpApiClient";
28
29 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
30 import * as ManagedLimits from "../policy/managedLimits.ts";
@@ -56,6 +53,7 @@ import {
53 readPersistedServerRuntimeState,
54 } from "../serverRuntimeState.ts";
55 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
56 +import * as RunningServer from "./runningServer.ts";
57 import { resolveHostCliHint } from "./invocation.ts";
58 import * as CliService from "./service.ts";
59
@@ -297,21 +295,6 @@ export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_clie
295 },
296 );
297
300 -const withCloudCliSessionToken = <A, E, R>(
301 - environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
302 - scope: AuthEnvironmentScope,
303 - run: (token: string) => Effect.Effect<A, E, R>,
304 -) =>
305 - Effect.acquireUseRelease(
306 - environmentAuth.issueSession({
307 - scopes: [scope],
308 - subject: "cloud-cli",
309 - label: "t3 connect cli",
310 - }),
311 - (issued) => run(issued.token),
312 - (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
313 - );
314 -
298 type LiveCloudActionResult =
299 | { readonly status: "not-running" }
300 | { readonly status: "server-gone" }
@@ -329,17 +312,11 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
312 return { status: "server-gone" } satisfies LiveCloudActionResult;
313 }
314
332 - const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
315 const result = yield* Effect.exit(
334 - withCloudCliSessionToken(environmentAuth, AuthRelayWriteScope, (token) =>
335 - HttpApiClient.make(EnvironmentHttpApi, {
336 - baseUrl: runtimeState.value.origin,
337 - }).pipe(
338 - Effect.flatMap((client) =>
339 - client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
340 - ),
341 - Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
342 - ),
316 + RunningServer.serverClient(runtimeState.value.origin, [AuthRelayWriteScope]).pipe(
317 + Effect.flatMap((client) => client.connect.unlink({ headers: {} })),
318 + Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
319 + Effect.scoped,
320 ),
321 );
322 return Exit.isSuccess(result)
@@ -357,15 +334,12 @@ const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(fun
334 const config = yield* ServerConfig.ServerConfig;
335 const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
336 if (Option.isNone(runtimeState)) return null;
360 - const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
361 - return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>
362 - HttpApiClient.make(EnvironmentHttpApi, { baseUrl: runtimeState.value.origin }).pipe(
363 - Effect.flatMap((client) =>
364 - client.connect.checkReachability({ headers: { authorization: `Bearer ${token}` } }),
365 - ),
366 - Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),
367 - ),
368 - ).pipe(Effect.orElseSucceed(() => null));
337 + return yield* RunningServer.serverClient(runtimeState.value.origin, [AuthRelayReadScope]).pipe(
338 + Effect.flatMap((client) => client.connect.checkReachability({ headers: {} })),
339 + Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),
340 + Effect.scoped,
341 + Effect.orElseSucceed(() => null),
342 + );
343 });
344
345 function formatAlertBox(text: string): string {
apps/server/src/cli/deferredImports.test.ts
+13 -5
@@ -80,13 +80,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CLI deferred imp
80 const runtimeStatePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
81 yield* persistServerRuntimeState({
82 path: runtimeStatePath,
83 - state: yield* makePersistedServerRuntimeState({
84 - config: { host: "127.0.0.1", devUrl: undefined },
85 - port: 3_773,
86 - }),
83 + // An owner id skips the legacy liveness probe, so only the free lock decides.
84 + state: {
85 + ...(yield* makePersistedServerRuntimeState({
86 + config: { host: "127.0.0.1", devUrl: undefined },
87 + port: 3_773,
88 + })),
89 + ownerId: "dead-server",
90 + },
91 });
92 const unreachable: typeof globalThis.fetch = () =>
89 - Promise.reject(new Error("connection refused"));
93 + Promise.reject(
94 + new TypeError("fetch failed", {
95 + cause: Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }),
96 + }),
97 + );
98
99 const exit = yield* runCli(["project", "add", root, "--base-dir", baseDir]).pipe(
100 Effect.provideService(FetchHttpClient.Fetch, unreachable),
apps/server/src/cli/project.test.ts
+2 -2
@@ -162,7 +162,7 @@ it.effect.each(["snapshot", "mutation"] as const)(
162 const isMutation = init?.method === "POST";
163 if (isMutation) mutations++;
164 else snapshotRequests++;
165 - if (slowRequest === "mutation" ? isMutation : !isMutation && snapshotRequests === 2) {
165 + if (slowRequest === "mutation" ? isMutation : !isMutation) {
166 requestReceived.resolve();
167 await releaseResponse.promise;
168 }
@@ -191,7 +191,7 @@ it.effect.each(["snapshot", "mutation"] as const)(
191 releaseResponse.resolve();
192 yield* Fiber.join(add);
193
194 - assert.equal(snapshotRequests, 2);
194 + assert.equal(snapshotRequests, 1);
195 assert.equal(mutations, 1);
196 assert.deepEqual((yield* readProjects(baseDir)).projects, []);
197 }).pipe(Effect.provide(NodeServices.layer)),
apps/server/src/cli/project.ts
+37 -156
@@ -1,7 +1,6 @@
1 import {
2 AuthStandardClientScopes,
3 CommandId,
4 - EnvironmentHttpApi,
4 EnvironmentHttpCommonError,
5 type ProjectMutation,
6 type ProjectSnapshot,
@@ -9,7 +8,6 @@ import {
8 } from "@t3tools/contracts";
9 import * as Console from "effect/Console";
10 import * as SecureRandom from "effect/crypto/SecureRandom";
12 -import * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Layer from "effect/Layer";
@@ -19,15 +17,12 @@ import * as References from "effect/References";
17 import * as Schema from "effect/Schema";
18 import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
19 import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
22 -import * as HttpApiClient from "effect/http-api/HttpApiClient";
20
21 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
22 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23
24 import * as ServerConfig from "../config.ts";
25 import * as SqlitePersistence from "../persistence/Sqlite.ts";
29 -import * as ProcessRunner from "../processRunner.ts";
30 -import * as ServerOwnership from "../serverOwnership.ts";
26 import type * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
27 import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
28 import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
@@ -37,12 +32,9 @@ import { projectMutationOperation } from "../project/ProjectMutation.ts";
32 import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
33 import * as ServerSettings from "../serverSettings.ts";
34 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
40 -import {
41 - clearPersistedServerRuntimeState,
42 - readLiveServerRuntimeState,
43 -} from "../serverRuntimeState.ts";
35 import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
36 import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
37 +import * as RunningServer from "./runningServer.ts";
38
39 type ProjectMutationTarget = {
40 readonly id: ProjectId;
@@ -50,7 +42,6 @@ type ProjectMutationTarget = {
42 readonly workspaceRoot: string;
43 };
44
53 -type ProjectCommandExecutionMode = "live" | "offline";
45 type ProjectCliDispatchCommand = ProjectMutation;
46
47 const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
@@ -94,18 +85,6 @@ export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError<P
85 }
86 }
87
97 -export class ProjectLiveServerRequestError extends Schema.TaggedError<ProjectLiveServerRequestError>()(
98 - "ProjectLiveServerRequestError",
99 - {
100 - operation: Schema.Literal("callLiveServer"),
101 - cause: Schema.Defect(),
102 - },
103 -) {
104 - override get message(): string {
105 - return "Failed to call the running server.";
106 - }
107 -}
108 -
88 export class ProjectTitleEmptyError extends Schema.TaggedError<ProjectTitleEmptyError>()(
89 "ProjectTitleEmptyError",
90 {
@@ -162,7 +141,6 @@ export const ProjectCommandError = Schema.Union([
141 ProjectCommandIdGenerationError,
142 ProjectLiveServerDeclaredResponseError,
143 ProjectLiveServerUndeclaredStatusError,
165 - ProjectLiveServerRequestError,
144 ProjectTitleEmptyError,
145 ProjectIdentifierEmptyError,
146 ProjectNotFoundError,
@@ -170,7 +148,8 @@ export const ProjectCommandError = Schema.Union([
148 ]);
149 export type ProjectCommandError = typeof ProjectCommandError.Type;
150
173 -function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
151 +/** Names a server's error answer; unanswered requests pass through for `changeState`. */
152 +function projectCommandErrorFromServerAnswer<E>(cause: E) {
153 if (isEnvironmentHttpCommonError(cause)) {
154 return new ProjectLiveServerDeclaredResponseError({
155 operation: "callLiveServer",
@@ -186,8 +165,7 @@ function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectComman
165 cause,
166 });
167 }
189 -
190 - return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
168 + return cause;
169 }
170
171 const projectCommandUuid = SecureRandom.SecureRandom.pipe(
@@ -221,26 +199,6 @@ const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.lay
199 Layer.provideMerge(SqlitePersistence.layerConfig),
200 );
201
224 -const PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT = Duration.seconds(1);
225 -const PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT = Duration.seconds(10);
226 -const withProjectCliSessionToken = <A, E, R>(
227 - environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
228 - run: (token: string) => Effect.Effect<A, E, R>,
229 -) =>
230 - Effect.acquireUseRelease(
231 - environmentAuth.issueSession({
232 - scopes: AuthStandardClientScopes,
233 - label: "t3 project cli",
234 - }),
235 - (issued) => run(issued.token),
236 - (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
237 - );
238 -
239 -const makeLiveServerClient = (origin: string) =>
240 - HttpApiClient.make(EnvironmentHttpApi, {
241 - baseUrl: origin,
242 - });
243 -
202 const normalizeWorkspaceRootForProjectCommand = Effect.fn(
203 "normalizeWorkspaceRootForProjectCommand",
204 )(function* (workspaceRoot: string) {
@@ -324,72 +282,6 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
282 } satisfies ProjectMutationTarget;
283 });
284
327 -const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(
328 - function* (origin: string, bearerToken: string, _timeout?: Duration.Duration) {
329 - const client = yield* makeLiveServerClient(origin);
330 - return yield* client.projects.snapshot({
331 - headers: { authorization: `Bearer ${bearerToken}` },
332 - });
333 - },
334 - (effect, _origin, _bearerToken, timeout = PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT) =>
335 - effect.pipe(Effect.timeout(timeout), Effect.mapError(projectCommandErrorFromLiveServerRequest)),
336 -);
337 -
338 -const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(
339 - function* (origin: string, bearerToken: string, command: ProjectCliDispatchCommand) {
340 - const client = yield* makeLiveServerClient(origin);
341 - yield* client.projects.mutate({
342 - headers: { authorization: `Bearer ${bearerToken}` },
343 - payload: command,
344 - } as Parameters<typeof client.projects.mutate>[0]);
345 - },
346 - (effect, _origin, _bearerToken, _command) =>
347 - effect.pipe(
348 - Effect.timeout(PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT),
349 - Effect.mapError(projectCommandErrorFromLiveServerRequest),
350 - ),
351 -);
352 -
353 -const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
354 - const projects = yield* ProjectService.ProjectService;
355 - return yield* projects.snapshot;
356 -});
357 -
358 -const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
359 - function* (
360 - environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
361 - config: ServerConfig.ServerConfig["Service"],
362 - ) {
363 - const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
364 - if (Option.isNone(runtimeState)) {
365 - return Option.none<{ readonly origin: string }>();
366 - }
367 -
368 - const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
369 - fetchLiveOrchestrationSnapshot(
370 - runtimeState.value.origin,
371 - token,
372 - PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT,
373 - ).pipe(
374 - Effect.as({
375 - origin: runtimeState.value.origin,
376 - }),
377 - ),
378 - );
379 -
380 - const attempted = yield* Effect.result(attempt);
381 - if (attempted._tag === "Success") {
382 - return Option.some(attempted.success);
383 - }
384 -
385 - yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
386 - origin: runtimeState.value.origin,
387 - cause: attempted.failure,
388 - });
389 - return Option.none<{ readonly origin: string }>();
390 - },
391 -);
392 -
285 const runProjectMutation = Effect.fn("runProjectMutation")(function* (
286 flags: CliAuthLocationFlags,
287 run: (input: {
@@ -397,7 +289,6 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
289 readonly dispatch: (
290 command: ProjectCliDispatchCommand,
291 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
400 - readonly mode: ProjectCommandExecutionMode;
292 }) => Effect.Effect<
293 string,
294 Error,
@@ -413,54 +304,44 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
304 const minimumLogLevel = config.logLevel;
305
306 return yield* Effect.gen(function* () {
416 - const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
417 - const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
418 -
419 - if (Option.isSome(liveMode)) {
420 - return yield* withProjectCliSessionToken(environmentAuth, (token) =>
421 - Effect.gen(function* () {
422 - const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
423 - const output = yield* run({
424 - snapshot,
425 - dispatch: (command) =>
426 - dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
427 - mode: "live",
428 - });
429 - yield* Console.log(output);
430 - }),
431 - );
432 - }
433 -
434 - // Before ownership and clearing, so a failed import leaves server state alone.
435 - const { layerProjectService } = yield* Effect.promise(
436 - () => import("../orchestration-v2/runtimeLayer.ts"),
437 - );
438 - const layerOfflineRuntime = makeProjectCliRuntimeLayer(layerProjectService).pipe(
439 - Layer.provide(ServerConfig.layer(config)),
440 - Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
441 - );
442 -
443 - // An unreachable server may still be running; never write behind it.
444 - yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath).pipe(
445 - Effect.provide(ProcessRunner.layer),
446 - );
447 - yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
448 - return yield* Effect.gen(function* () {
449 - const snapshot = yield* getOfflineSnapshot();
450 - const projects = yield* ProjectService.ProjectService;
451 - const output = yield* run({
452 - snapshot,
453 - dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
454 - mode: "offline",
455 - });
456 - yield* Console.log(output);
457 - }).pipe(Effect.provide(layerOfflineRuntime));
307 + const output = yield* RunningServer.changeState({
308 + scopes: AuthStandardClientScopes,
309 + viaServer: Effect.fn("project.viaServer")(function* (client) {
310 + return yield* run({
311 + snapshot: yield* client.projects.snapshot({ headers: {} }),
312 + dispatch: (command) =>
313 + client.projects.mutate({ headers: {}, payload: command } as Parameters<
314 + typeof client.projects.mutate
315 + >[0]),
316 + });
317 + }, Effect.mapError(projectCommandErrorFromServerAnswer)),
318 + locally: Effect.promise(() => import("../orchestration-v2/runtimeLayer.ts")).pipe(
319 + Effect.flatMap(({ layerProjectService }) =>
320 + Effect.gen(function* () {
321 + const projects = yield* ProjectService.ProjectService;
322 + return yield* run({
323 + snapshot: yield* projects.snapshot,
324 + dispatch: (command) =>
325 + projectMutationOperation(projects, command).pipe(Effect.asVoid),
326 + });
327 + }).pipe(
328 + Effect.provide(
329 + makeProjectCliRuntimeLayer(layerProjectService).pipe(
330 + Layer.provide(ServerConfig.layer(config)),
331 + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
332 + ),
333 + ),
334 + ),
335 + ),
336 + ),
337 + });
338 + yield* Console.log(output);
339 }).pipe(
340 Effect.scoped,
341 Effect.provide(
342 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
343 Layer.provideMerge(FetchHttpClient.layer),
463 - Layer.provide(ServerConfig.layer(config)),
344 + Layer.provideMerge(ServerConfig.layer(config)),
345 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
346 ),
347 ),
apps/server/src/cli/runningServer.ts
+1 -1
@@ -45,7 +45,7 @@ const SESSION_TTL = Duration.minutes(2);
45 const REQUEST_TIMEOUT = Duration.seconds(30);
46
47 /** A client of the server at `origin`, signed in as a short-lived session for the scope. */
48 -const serverClient = Effect.fn("RunningServer.serverClient")(function* (
48 +export const serverClient = Effect.fn("RunningServer.serverClient")(function* (
49 origin: string,
50 scopes: ReadonlyArray<AuthEnvironmentScope>,
51 ) {