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
fix(cli): `t3 auth session revoke` closes the revoked client's open connections (#38974)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 19, 2026 at 00:26 UTC
55b14ac51d2d30222d52aa8ef798b5e09a62c04a
4 files changed
+349
-36
apps/server/src/auth/EnvironmentAuth.ts
+35
-23
@@ -560,10 +560,10 @@ export class EnvironmentAuth extends Context.Service<
560
readonly approveConnectDeviceByCode: (
561
verificationCode: string,
562
) => Effect.Effect<boolean, ServerAuthInternalError>;
563
- /** Revokes the one trusted device that shows this code; two that share it are ambiguous. */
564
- readonly revokeConnectDeviceByCode: (
563
+ /** Trusted devices that show this code; more than one is ambiguous. */
564
+ readonly connectDevicesShowingCode: (
565
verificationCode: string,
566
- ) => Effect.Effect<"revoked" | "not-found" | "ambiguous", ServerAuthInternalError>;
566
+ ) => Effect.Effect<ReadonlyArray<AuthConnectDevice>, ServerAuthInternalError>;
567
readonly listConnectDevices: () => Effect.Effect<
568
ReadonlyArray<AuthConnectDevice>,
569
ServerAuthInternalError
@@ -602,6 +602,10 @@ export class EnvironmentAuth extends Context.Service<
602
readonly listClientSessions: (
603
currentSessionId: AuthSessionId,
604
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
605
+ /** Revokes a session; one bound to a device key takes the device's trust and sessions with it. */
606
+ readonly revokeClient: (
607
+ sessionId: AuthSessionId,
608
+ ) => Effect.Effect<boolean, ServerAuthInternalError>;
609
readonly revokeClientSession: (
610
currentSessionId: AuthSessionId,
611
targetSessionId: AuthSessionId,
@@ -1315,16 +1319,12 @@ export const make = Effect.gen(function* () {
1319
}).pipe(connectTrustLock.withPermits(1));
1320
});
1321
1318
- const revokeConnectDeviceByCode: EnvironmentAuth["Service"]["revokeConnectDeviceByCode"] =
1319
- Effect.fn("EnvironmentAuth.revokeConnectDeviceByCode")(function* (verificationCode) {
1322
+ const connectDevicesShowingCode: EnvironmentAuth["Service"]["connectDevicesShowingCode"] =
1323
+ Effect.fn("EnvironmentAuth.connectDevicesShowingCode")(function* (verificationCode) {
1324
const wanted = normalizeVerificationCode(verificationCode);
1321
- const matches = (yield* listConnectDevices()).filter(
1325
+ return (yield* listConnectDevices()).filter(
1326
(device) => normalizeVerificationCode(device.verificationCode) === wanted,
1327
);
1324
- if (matches.length === 0) return "not-found" as const;
1325
- if (matches.length > 1) return "ambiguous" as const;
1326
- yield* revokeConnectDevice(matches[0]!.proofKeyThumbprint);
1327
- return "revoked" as const;
1328
});
1329
1330
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
@@ -1437,25 +1437,36 @@ export const make = Effect.gen(function* () {
1437
Effect.withSpan("EnvironmentAuth.listClientSessions"),
1438
);
1439
1440
+ const proofKeyOf = (sessionId: AuthSessionId) =>
1441
+ sessions
1442
+ .proofKeyThumbprintOf(sessionId)
1443
+ .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1444
+
1445
+ const revokeClient: EnvironmentAuth["Service"]["revokeClient"] = Effect.fn(
1446
+ "EnvironmentAuth.revokeClient",
1447
+ )(function* (sessionId) {
1448
+ // A T3 Connect device would otherwise mint itself a new session right away.
1449
+ return yield* Option.match(yield* proofKeyOf(sessionId), {
1450
+ onNone: () => revokeSession(sessionId),
1451
+ onSome: revokeConnectDevice,
1452
+ });
1453
+ });
1454
+
1455
const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
1456
"EnvironmentAuth.revokeClientSession",
1457
)(function* (currentSessionId, targetSessionId) {
1458
if (currentSessionId === targetSessionId) {
1459
return yield* new ServerAuthForbiddenOperationError({});
1460
}
1446
- const proofKeyThumbprint = yield* sessions
1447
- .proofKeyThumbprintOf(targetSessionId)
1448
- .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1449
- // A T3 Connect device would otherwise mint itself a new session right away.
1450
- if (Option.isSome(proofKeyThumbprint)) {
1451
- const currentProofKey = yield* sessions
1452
- .proofKeyThumbprintOf(currentSessionId)
1453
- .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1454
- if (Option.getOrUndefined(currentProofKey) !== proofKeyThumbprint.value) {
1455
- return yield* revokeConnectDevice(proofKeyThumbprint.value);
1456
- }
1461
+ const targetProofKey = Option.getOrUndefined(yield* proofKeyOf(targetSessionId));
1462
+ // Revoking the caller's own device would cut off the caller too.
1463
+ if (
1464
+ targetProofKey !== undefined &&
1465
+ Option.getOrUndefined(yield* proofKeyOf(currentSessionId)) === targetProofKey
1466
+ ) {
1467
+ return yield* revokeSession(targetSessionId);
1468
}
1458
- return yield* revokeSession(targetSessionId);
1469
+ return yield* revokeClient(targetSessionId);
1470
});
1471
1472
const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] =
@@ -1658,7 +1669,7 @@ export const make = Effect.gen(function* () {
1669
approveConnectDeviceByCode,
1670
listConnectDevices,
1671
revokeConnectDevice,
1661
- revokeConnectDeviceByCode,
1672
+ connectDevicesShowingCode,
1673
issuePairingCredential,
1674
issueStartupPairingCredential,
1675
listPairingLinks,
@@ -1667,6 +1678,7 @@ export const make = Effect.gen(function* () {
1678
listSessions,
1679
revokeSession,
1680
listClientSessions,
1681
+ revokeClient,
1682
revokeClientSession,
1683
revokeOtherClientSessions,
1684
authenticateHttpRequest,
apps/server/src/cli/auth.ts
+40
-13
@@ -1,4 +1,4 @@
1
-import { AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts";
1
+import { AuthAccessWriteScope, AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts";
2
import * as Console from "effect/Console";
3
import * as Effect from "effect/Effect";
4
import * as Layer from "effect/Layer";
@@ -24,10 +24,11 @@ import {
24
DurationFromString,
25
resolveCliAuthConfig,
26
} from "./config.ts";
27
+import * as RunningServer from "./runningServer.ts";
28
28
-const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E>(
29
+const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E, R>(
30
flags: CliAuthLocationFlags,
30
- run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
31
+ run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E, R>,
32
options?: {
33
readonly quietLogs?: boolean;
34
},
@@ -40,14 +41,20 @@ const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function
41
return yield* run(environmentAuth);
42
}).pipe(
43
Effect.provide(
43
- Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
44
- Layer.provide(ServerConfig.layer(config)),
44
+ EnvironmentAuth.layerRuntime.pipe(
45
+ Layer.provideMerge(ServerConfig.layer(config)),
46
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
47
),
48
),
49
);
50
});
51
52
+/** Access changes go through a running server, which applies them to its open connections. */
53
+const changeAccess = <A, E, R, E2, R2>(change: {
54
+ readonly viaServer: (client: RunningServer.ServerClient) => Effect.Effect<A, E, R>;
55
+ readonly locally: Effect.Effect<A, E2, R2>;
56
+}) => RunningServer.changeState({ scopes: [AuthAccessWriteScope], ...change });
57
+
58
const ttlFlag = Flag.String("ttl").pipe(
59
Flag.withSchema(DurationFromString),
60
Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
@@ -221,13 +228,25 @@ const connectDeviceRevokeCommand = Command.make("revoke", {
228
Command.withHandler((flags) =>
229
runWithEnvironmentAuth(flags, (environmentAuth) =>
230
Effect.gen(function* () {
224
- const outcome = yield* environmentAuth.revokeConnectDeviceByCode(flags.code);
231
+ const [device, ...others] = yield* environmentAuth.connectDevicesShowingCode(flags.code);
232
+ if (device === undefined) {
233
+ return yield* Console.log(`No trusted device shows ${flags.code}.\n`);
234
+ }
235
+ if (others.length > 0) {
236
+ return yield* Console.log(
237
+ `More than one trusted device shows ${flags.code}; revoke it from a client.\n`,
238
+ );
239
+ }
240
+ const { proofKeyThumbprint } = device;
241
+ yield* changeAccess({
242
+ viaServer: (client) =>
243
+ client.auth
244
+ .revokeConnectDevice({ headers: {}, payload: { proofKeyThumbprint } })
245
+ .pipe(Effect.map((result) => result.revoked)),
246
+ locally: environmentAuth.revokeConnectDevice(proofKeyThumbprint),
247
+ });
248
yield* Console.log(
226
- outcome === "revoked"
227
- ? `Revoked ${flags.code}. If approval for new devices is off, it can connect again on its own.\n`
228
- : outcome === "ambiguous"
229
- ? `More than one trusted device shows ${flags.code}; revoke it from a client.\n`
230
- : `No trusted device shows ${flags.code}.\n`,
249
+ `Revoked ${flags.code}. If approval for new devices is off, it can connect again on its own.\n`,
250
);
251
}),
252
),
@@ -305,11 +324,19 @@ const sessionRevokeCommand = Command.make("revoke", {
324
Argument.withSchema(AuthSessionId),
325
),
326
}).pipe(
308
- Command.withDescription("Revoke an active session."),
327
+ Command.withDescription(
328
+ "Revoke an active session. A T3 Connect device's session takes the device's trust and other sessions with it; if approval for new devices is off, the device can connect again on its own.",
329
+ ),
330
Command.withHandler((flags) =>
331
runWithEnvironmentAuth(flags, (environmentAuth) =>
332
Effect.gen(function* () {
312
- const revoked = yield* environmentAuth.revokeSession(flags.sessionId);
333
+ const revoked = yield* changeAccess({
334
+ viaServer: (client) =>
335
+ client.auth
336
+ .revokeClient({ headers: {}, payload: { sessionId: flags.sessionId } })
337
+ .pipe(Effect.map((result) => result.revoked)),
338
+ locally: environmentAuth.revokeClient(flags.sessionId),
339
+ });
340
yield* Console.log(
341
revoked
342
? `Revoked session ${flags.sessionId}.\n`
apps/server/src/cli/pair.test.ts
+145
@@ -14,6 +14,7 @@ import * as Cause from "effect/Cause";
14
import * as ConfigProvider from "effect/ConfigProvider";
15
import * as Effect from "effect/Effect";
16
import * as Exit from "effect/Exit";
17
+import * as Fiber from "effect/Fiber";
18
import * as Layer from "effect/Layer";
19
import * as Sink from "effect/Sink";
20
import * as Stream from "effect/Stream";
@@ -29,6 +30,8 @@ import {
30
SERVICE_LAUNCHER_PROTOCOL,
31
} from "../cloud/serviceProtocol.ts";
32
import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
33
+import * as ProcessRunner from "../processRunner.ts";
34
+import * as ServerOwnership from "../serverOwnership.ts";
35
import {
36
makePersistedServerRuntimeState,
37
persistServerRuntimeState,
@@ -691,6 +694,148 @@ describe("t3 pair", () => {
694
);
695
});
696
697
+describe("auth session revoke", () => {
698
+ // Nothing listens on the recorded port; `server` stubs what fetch meets there instead.
699
+ it.effect.each([
700
+ {
701
+ label: "goes through a running server, which closes open connections",
702
+ recorded: true,
703
+ lockHeld: false,
704
+ server: "answers",
705
+ outcome: "revoked by server",
706
+ },
707
+ {
708
+ label: "writes the database when no server runs",
709
+ recorded: false,
710
+ lockHeld: false,
711
+ server: "none",
712
+ outcome: "revoked locally",
713
+ },
714
+ {
715
+ label: "writes the database when the recorded server has stopped",
716
+ recorded: true,
717
+ lockHeld: false,
718
+ server: "none",
719
+ outcome: "revoked locally",
720
+ },
721
+ {
722
+ label: "changes nothing when a running server refuses the connection",
723
+ recorded: true,
724
+ lockHeld: true,
725
+ server: "none",
726
+ outcome: "RunningServerUnreachableError",
727
+ },
728
+ {
729
+ label: "does not repeat a change locally when the server stops replying mid-request",
730
+ recorded: true,
731
+ lockHeld: false,
732
+ server: "hangs",
733
+ outcome: "RunningServerNoReplyError",
734
+ },
735
+ {
736
+ label: "does not repeat a change locally when the server answers with an error",
737
+ recorded: true,
738
+ lockHeld: false,
739
+ server: "fails",
740
+ outcome: "HttpClientError",
741
+ },
742
+ ] as const)("$label", ({ recorded, lockHeld, server, outcome }) =>
743
+ provideCliTestLayers(
744
+ Effect.gen(function* () {
745
+ const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-revoke-test-"));
746
+ const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
747
+ const issued = JSON.parse(
748
+ yield* captureStdout(
749
+ runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
750
+ ),
751
+ ) as { readonly sessionId: string };
752
+ if (recorded) {
753
+ // A port just released has no listener, so connecting to it is refused.
754
+ const port = yield* (yield* NetService.NetService).reserveLoopbackPort("127.0.0.1");
755
+ yield* persistServerRuntimeState({
756
+ path: statePath,
757
+ // An owner id skips the legacy liveness probe, so only the lock decides.
758
+ state: {
759
+ ...baseState,
760
+ pid: process.pid,
761
+ ownerId: "test-owner",
762
+ port,
763
+ origin: `http://127.0.0.1:${port}`,
764
+ },
765
+ });
766
+ }
767
+ if (lockHeld) {
768
+ yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
769
+ Effect.provide(ProcessRunner.layer),
770
+ );
771
+ }
772
+
773
+ const requests: Array<{ readonly path: string; readonly body: unknown }> = [];
774
+ const requestStarted = Promise.withResolvers<void>();
775
+ const fetch: typeof globalThis.fetch | undefined =
776
+ server === "answers" || server === "fails"
777
+ ? async (input, init) => {
778
+ requests.push({
779
+ path: new URL(String(input)).pathname,
780
+ body: JSON.parse(String(init?.body)),
781
+ });
782
+ return server === "answers"
783
+ ? Response.json({ revoked: true })
784
+ : new Response(null, { status: 502 });
785
+ }
786
+ : server === "hangs"
787
+ ? (_input, init) => {
788
+ requestStarted.resolve();
789
+ return new Promise((_resolve, reject) =>
790
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason)),
791
+ );
792
+ }
793
+ : undefined;
794
+ const revoke = runCli([
795
+ "auth",
796
+ "session",
797
+ "revoke",
798
+ "--base-dir",
799
+ baseDir,
800
+ issued.sessionId,
801
+ ]);
802
+ const running = yield* (
803
+ fetch === undefined
804
+ ? revoke
805
+ : revoke.pipe(Effect.provideService(FetchHttpClient.Fetch, fetch))
806
+ ).pipe(Effect.exit, Effect.forkChild);
807
+ if (server === "hangs") {
808
+ yield* Effect.promise(() => requestStarted.promise);
809
+ yield* TestClock.adjust("30 seconds");
810
+ }
811
+ const exit = yield* Fiber.join(running);
812
+ const listed = JSON.parse(
813
+ yield* captureStdout(
814
+ runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
815
+ ),
816
+ ) as ReadonlyArray<{ readonly sessionId: string }>;
817
+
818
+ assert.deepEqual(
819
+ requests,
820
+ server === "answers" || server === "fails"
821
+ ? [{ path: "/api/auth/clients/revoke", body: { sessionId: issued.sessionId } }]
822
+ : [],
823
+ );
824
+ if (outcome === "revoked by server" || outcome === "revoked locally") {
825
+ assert.isTrue(Exit.isSuccess(exit));
826
+ } else {
827
+ assert.include(Cause.pretty(Exit.isFailure(exit) ? exit.cause : Cause.empty), outcome);
828
+ }
829
+ // The stub server revokes nothing, and the CLI's own session is gone either way.
830
+ assert.deepEqual(
831
+ listed.map((session) => session.sessionId),
832
+ outcome === "revoked locally" ? [] : [issued.sessionId],
833
+ );
834
+ }).pipe(Effect.scoped),
835
+ ),
836
+ );
837
+});
838
+
839
describe("auth scope options", () => {
840
it.effect.each([
841
{ group: "pairing", action: "create" },
apps/server/src/cli/runningServer.ts
new
+129
@@ -0,0 +1,129 @@
1
+import { type AuthEnvironmentScope, EnvironmentHttpApi } from "@t3tools/contracts";
2
+import * as Cause from "effect/Cause";
3
+import * as Duration from "effect/Duration";
4
+import * as Effect from "effect/Effect";
5
+import * as Option from "effect/Option";
6
+import * as Predicate from "effect/Predicate";
7
+import * as Schema from "effect/Schema";
8
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
9
+import * as HttpClient from "effect/http/HttpClient";
10
+import * as HttpClientError from "effect/http/HttpClientError";
11
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
12
+import * as HttpApiClient from "effect/http-api/HttpApiClient";
13
+
14
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
15
+import * as ServerConfig from "../config.ts";
16
+import * as ProcessRunner from "../processRunner.ts";
17
+import * as ServerOwnership from "../serverOwnership.ts";
18
+import {
19
+ clearPersistedServerRuntimeState,
20
+ readLiveServerRuntimeState,
21
+} from "../serverRuntimeState.ts";
22
+
23
+export class RunningServerUnreachableError extends Schema.TaggedError<RunningServerUnreachableError>()(
24
+ "RunningServerUnreachableError",
25
+ { origin: Schema.String, cause: Schema.Defect() },
26
+) {
27
+ override get message(): string {
28
+ return `The T3 Code server at ${this.origin} is running but refused the connection, so nothing was changed. Retry, or restart the server and retry.`;
29
+ }
30
+}
31
+
32
+export class RunningServerNoReplyError extends Schema.TaggedError<RunningServerNoReplyError>()(
33
+ "RunningServerNoReplyError",
34
+ { origin: Schema.String, cause: Schema.Defect() },
35
+) {
36
+ override get message(): string {
37
+ return `The T3 Code server at ${this.origin} did not reply, so the change may or may not have been made. Check the current state before you retry.`;
38
+ }
39
+}
40
+
41
+export type ServerClient = HttpApiClient.ForApi<typeof EnvironmentHttpApi>;
42
+
43
+// The scope revokes the session; the TTL bounds it if that never runs.
44
+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* (
49
+ origin: string,
50
+ scopes: ReadonlyArray<AuthEnvironmentScope>,
51
+) {
52
+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
53
+ const session = yield* Effect.acquireRelease(
54
+ environmentAuth.issueSession({ scopes, subject: "cli", label: "t3 cli", ttl: SESSION_TTL }),
55
+ ({ sessionId }) => environmentAuth.revokeSession(sessionId).pipe(Effect.ignore({ log: true })),
56
+ );
57
+ return yield* HttpApiClient.make(EnvironmentHttpApi, {
58
+ baseUrl: origin,
59
+ transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(session.token)),
60
+ }).pipe(Effect.provide(FetchHttpClient.layer));
61
+});
62
+
63
+// The request never reached a server, so it changed nothing there.
64
+const NOT_CONNECTED_CODES = new Set([
65
+ "ECONNREFUSED",
66
+ "ENOTFOUND",
67
+ "EHOSTUNREACH",
68
+ "ENETUNREACH",
69
+ "EADDRNOTAVAIL",
70
+ "UND_ERR_CONNECT_TIMEOUT",
71
+]);
72
+const systemErrorCode = (error: unknown) =>
73
+ [error, Predicate.hasProperty(error, "cause") ? error.cause : undefined]
74
+ .map((candidate) => (Predicate.hasProperty(candidate, "code") ? candidate.code : undefined))
75
+ .find(Predicate.isString);
76
+const neverConnected = (cause: unknown) => {
77
+ if (!HttpClientError.isHttpClientError(cause) || cause.reason._tag !== "TransportError") {
78
+ return false;
79
+ }
80
+ const code = systemErrorCode(cause.reason.cause);
81
+ return code !== undefined && NOT_CONNECTED_CODES.has(code);
82
+};
83
+const isUnanswered = (cause: unknown) =>
84
+ Cause.isTimeoutError(cause) ||
85
+ (HttpClientError.isHttpClientError(cause) && cause.response === undefined);
86
+
87
+/**
88
+ * Makes a change through the running server, so the server applies it and its clients see it.
89
+ * With no server, makes it locally while holding the ownership lock, so none starts midway.
90
+ */
91
+export const changeState = Effect.fn("RunningServer.changeState")(function* <A, E, R, E2, R2>({
92
+ scopes,
93
+ viaServer,
94
+ locally,
95
+}: {
96
+ readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
97
+ readonly viaServer: (client: ServerClient) => Effect.Effect<A, E, R>;
98
+ readonly locally: Effect.Effect<A, E2, R2>;
99
+}) {
100
+ const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
101
+ const changeLocally = <E3>(
102
+ ifServerRuns: (error: ServerOwnership.ServerAlreadyRunningError) => Effect.Effect<never, E3>,
103
+ ) =>
104
+ ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe(
105
+ Effect.provide(ProcessRunner.layer),
106
+ Effect.catchTags({ ServerAlreadyRunningError: ifServerRuns }),
107
+ Effect.andThen(locally),
108
+ // The lock proves the recorded server is gone; drop its record once the change lands.
109
+ Effect.tap(() => clearPersistedServerRuntimeState(serverRuntimeStatePath)),
110
+ Effect.scoped,
111
+ );
112
+
113
+ const running = yield* readLiveServerRuntimeState(serverRuntimeStatePath);
114
+ if (Option.isNone(running)) return yield* changeLocally(Effect.fail);
115
+ const { origin } = running.value;
116
+ return yield* serverClient(origin, scopes).pipe(
117
+ Effect.flatMap(viaServer),
118
+ Effect.timeout(REQUEST_TIMEOUT),
119
+ Effect.scoped,
120
+ // A refused connection reached no server, so the lock decides whether one still runs.
121
+ Effect.catchIf(neverConnected, (cause) =>
122
+ changeLocally(() => Effect.fail(new RunningServerUnreachableError({ origin, cause }))),
123
+ ),
124
+ // Once connected, the server may have made the change; writing it again could repeat it.
125
+ Effect.catchIf(isUnanswered, (cause) =>
126
+ Effect.fail(new RunningServerNoReplyError({ origin, cause })),
127
+ ),
128
+ );
129
+});