The best way to control Claude Code, Codex and more from any computer or phone
fix(opencode): updating restarts the background service on the new version (#34606)
Continues #31152. Co-authored-by: Miley <mkantenko@gmail.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Theo Browne committed
Nov 12, 2026 at 00:49 UTC
b68aedfdb71534bfdfbe55771ef2e686742faa8e
10 files changed
+374
-6
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts
+1
@@ -257,6 +257,7 @@ export const replayServer = (
257
borrowers.current -= 1;
258
}),
259
),
260
+ forget: Effect.void,
261
});
262
});
263
apps/server/src/provider/ProviderRegistry.test.ts
+47
-2
@@ -76,6 +76,7 @@ import type {
76
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
77
import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
78
import * as ProviderRegistry from "./ProviderRegistry.ts";
79
+import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
80
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
81
import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
82
vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
@@ -1703,6 +1704,8 @@ it.layer(
1704
Effect.gen(function* () {
1705
const forceRefreshCalls = yield* Ref.make(0);
1706
const manifest = yield* Ref.make(ModelManifest.BUNDLED_MODEL_MANIFEST);
1707
+ const updateEvents = yield* Ref.make<ReadonlyArray<string>>([]);
1708
+ const hookFails = yield* Ref.make(false);
1709
const makeInstance = (name: string) =>
1710
Effect.gen(function* () {
1711
const driver = ProviderDriverKind.make("codex");
@@ -1722,7 +1725,7 @@ it.layer(
1725
} as const satisfies ServerProvider;
1726
const invalidations = yield* Ref.make(0);
1727
const probes = yield* Ref.make(0);
1725
- const maintenanceReads = yield* Ref.make<ReadonlyArray<boolean>>([]);
1728
+ const maintenanceReads = yield* Ref.make<ReadonlyArray<boolean | "afterUpdate">>([]);
1729
const instance = {
1730
instanceId,
1731
driverKind: driver,
@@ -1747,7 +1750,25 @@ it.layer(
1750
streamChanges: Stream.empty,
1751
applyUsageLimits: () => Effect.void,
1752
},
1750
- invalidateCaches: Ref.update(invalidations, (count) => count + 1),
1753
+ invalidateCaches: Ref.update(invalidations, (count) => count + 1).pipe(
1754
+ Effect.andThen(
1755
+ Ref.update(updateEvents, (events) => [...events, `invalidate:${name}`]),
1756
+ ),
1757
+ ),
1758
+ afterUpdate: Ref.update(maintenanceReads, (reads) => [
1759
+ ...reads,
1760
+ "afterUpdate" as const,
1761
+ ]).pipe(
1762
+ Effect.andThen(
1763
+ Ref.update(updateEvents, (events) => [...events, `afterUpdate:${name}`]),
1764
+ ),
1765
+ Effect.andThen(Ref.get(hookFails)),
1766
+ Effect.flatMap((fails) =>
1767
+ fails
1768
+ ? Effect.fail(new ProviderDriverError({ driver, instanceId, detail: "hook" }))
1769
+ : Effect.void,
1770
+ ),
1771
+ ),
1772
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
1773
textGeneration: {} as ProviderInstance["textGeneration"],
1774
} satisfies ProviderInstance;
@@ -1835,6 +1856,30 @@ it.layer(
1856
assert.strictEqual(yield* Ref.get(second.probes), probesBefore + 1);
1857
// A changed manifest also rechecks latest CLI versions.
1858
assert.strictEqual(yield* readCachedVersion("codex_second-package", "3.0.0"), "3.0.0");
1859
+
1860
+ yield* first.takeMaintenanceReads;
1861
+ yield* Ref.set(updateEvents, []);
1862
+ yield* registry.refreshAfterUpdate(first.instance.driverKind, first.instance.instanceId);
1863
+ assert.deepStrictEqual((yield* first.takeMaintenanceReads).slice(0, 2), [
1864
+ "afterUpdate",
1865
+ true,
1866
+ ]);
1867
+ assert.notInclude(yield* second.takeMaintenanceReads, "afterUpdate");
1868
+ // Instances sharing the replaced service must not cache its old version.
1869
+ assert.strictEqual((yield* Ref.get(updateEvents))[0], "afterUpdate:codex_first");
1870
+
1871
+ // A failed hook leaves the probe to report what is running.
1872
+ yield* Ref.set(hookFails, true);
1873
+ const probesBeforeFailedHook = yield* Ref.get(first.probes);
1874
+ const refreshed = yield* registry.refreshAfterUpdate(
1875
+ first.instance.driverKind,
1876
+ first.instance.instanceId,
1877
+ );
1878
+ assert.strictEqual(yield* Ref.get(first.probes), probesBeforeFailedHook + 1);
1879
+ assert.include(
1880
+ refreshed.map((provider) => provider.instanceId),
1881
+ first.instance.instanceId,
1882
+ );
1883
}).pipe(
1884
Effect.provide(
1885
ProviderRegistry.layer.pipe(
apps/server/src/provider/ProviderRegistry.ts
+17
@@ -771,6 +771,23 @@ export const layer = Layer.effect(
771
),
772
);
773
});
774
+ // Instances can share the replaced service, so none may invalidate before it restarts.
775
+ const selectedInstance = instances.find(
776
+ (instance) => instance.instanceId === selectedInstanceId,
777
+ );
778
+ if (selectedInstance?.afterUpdate !== undefined) {
779
+ // The probe below reports what is running, so a failed hook needs no status of its own.
780
+ yield* selectedInstance.afterUpdate.pipe(
781
+ Effect.catchCause((cause) =>
782
+ Cause.hasInterruptsOnly(cause)
783
+ ? Effect.interrupt
784
+ : Effect.logError("provider post-update hook failed", {
785
+ instanceId: selectedInstance.instanceId,
786
+ cause: Cause.pretty(cause),
787
+ }),
788
+ ),
789
+ );
790
+ }
791
// Accounts can share an installation, but discovery must use each
792
// instance's own executable, environment, and credentials.
793
yield* Effect.forEach(
docs/user/providers-opencode.md
+12
-4
@@ -42,10 +42,18 @@ does not forward a local `OPENCODE_SERVER_PASSWORD`. If connection or version ch
42
fail, check the URL, credentials, and OpenCode version, then refresh provider status.
43
44
When **Server URL** points to a locally running server (such as `127.0.0.1`),
45
-the update button upgrades its installed CLI without terminating the running server.
46
-The server can still report the previous version until you restart it. T3 Code
47
-shows that restart requirement instead of treating the CLI update as a failure.
48
-Restart the server when active sessions can safely be interrupted.
45
+the update button upgrades its installed CLI. If that server is this machine's
46
+OpenCode background service, T3 Code then restarts it on the new version. The URL
47
+must use the service's own protocol, host, and port. For a service listening on
48
+`0.0.0.0` use `127.0.0.1`, and for `[::]` use `[::1]`.
49
+
50
+Restarting interrupts running turns, and the service then runs with T3 Code's
51
+environment. Set any variables it needs with `opencode service set env <name> <value>`.
52
+
53
+T3 Code does not restart any other server, including the background service
54
+reached through `localhost`. That server can still report the previous version
55
+until you restart it. For a loopback URL, T3 Code shows that restart requirement
56
+instead of treating the CLI update as a failure.
57
58
After a lost connection, send another prompt to reconnect to the same OpenCode
59
session.
packages/provider-core/src/server/driver.ts
+2
@@ -50,6 +50,8 @@ export interface ProviderInstance {
50
) => Effect.Effect<ProviderWorkspaceSnapshot, ProviderDriverError>;
51
readonly refreshModels?: () => Effect.Effect<void, ProviderDriverError>;
52
readonly invalidateCaches?: Effect.Effect<void>;
53
+ /** Moves a long-lived service onto a newly updated binary before its version is read back. */
54
+ readonly afterUpdate?: Effect.Effect<void, ProviderDriverError>;
55
readonly consumeResetCredit?: (
56
creditId: string | undefined,
57
) => Effect.Effect<ProviderConsumeResetCreditOutcome, ProviderDriverError>;
packages/provider-opencode/src/server/driver.ts
+30
@@ -22,6 +22,7 @@ import { makeOpenCodeTextGeneration } from "./textGeneration.ts";
22
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
23
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
24
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
25
+import { AgentScope } from "@t3tools/shared/AgentScope";
26
import * as HostProcess from "@t3tools/shared/HostProcess";
27
import { compareSemverVersions } from "@t3tools/shared/semver";
28
import * as OpenCodeAdapterV2 from "./adapter.ts";
@@ -56,6 +57,7 @@ import {
57
import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
58
import * as OpenCode2Client from "./v2/OpenCode2Client.ts";
59
import * as OpenCode2Server from "./v2/OpenCode2Server.ts";
60
+import { replaceOutdatedService } from "./v2/OpenCode2Service.ts";
61
import {
62
defaultProviderContinuationIdentity,
63
type ProviderDriver,
@@ -267,6 +269,7 @@ export const OpenCodeDriver: ProviderDriver<
269
const fileSystem = yield* FileSystem.FileSystem;
270
const pathService = yield* Path.Path;
271
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
272
+ const agentScope = yield* AgentScope;
273
const httpClient = yield* HttpClient.HttpClient;
274
const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
275
const digest = yield* Digest.Digest;
@@ -577,6 +580,31 @@ export const OpenCodeDriver: ProviderDriver<
580
),
581
);
582
583
+ const serverUrl = effectiveConfig.serverUrl.trim();
584
+ const afterUpdate =
585
+ serverUrl.length > 0
586
+ ? replaceOutdatedService({
587
+ binaryPath: effectiveConfig.binaryPath,
588
+ serverUrl,
589
+ environment: processEnv,
590
+ }).pipe(
591
+ Effect.ensuring(openCode2Server.forget),
592
+ Effect.mapError(
593
+ (cause) =>
594
+ new ProviderDriverError({
595
+ driver: DRIVER_KIND,
596
+ instanceId,
597
+ detail: "Failed to replace the OpenCode service after an update.",
598
+ cause,
599
+ }),
600
+ ),
601
+ Effect.provideService(AgentScope, agentScope),
602
+ Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
603
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
604
+ Effect.provideService(Path.Path, pathService),
605
+ )
606
+ : Effect.void;
607
+
608
const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
609
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({
610
resolveMaintenance,
@@ -709,6 +737,8 @@ export const OpenCodeDriver: ProviderDriver<
737
}),
738
),
739
),
740
+ invalidateCaches: openCode2Server.forget,
741
+ afterUpdate,
742
orchestrationAdapter,
743
textGeneration,
744
} satisfies ProviderInstance;
packages/provider-opencode/src/server/v2/OpenCode2Server.test.ts
+45
@@ -149,6 +149,51 @@ describe("OpenCode2Server error details", () => {
149
);
150
});
151
152
+describe("OpenCode2Server external server", () => {
153
+ it.effect("reverifies after forgetting, so a replaced service's version is seen", () =>
154
+ Effect.gen(function* () {
155
+ let version = "2.2.4";
156
+ const layerService = Layer.succeed(
157
+ HttpClient.HttpClient,
158
+ HttpClient.make((request) =>
159
+ Effect.succeed(
160
+ HttpClientResponse.fromWeb(
161
+ request,
162
+ new Response(JSON.stringify({ version, pid: 1, urls: [], paths: { tmp: "/tmp" } }), {
163
+ status: 200,
164
+ headers: { "content-type": "application/json" },
165
+ }),
166
+ ),
167
+ ),
168
+ ),
169
+ );
170
+ const versions = yield* Effect.gen(function* () {
171
+ const server = yield* OpenCode2Server.make({
172
+ binaryPath: "opencode",
173
+ serverUrl: "http://127.0.0.1:49374",
174
+ serverPassword: "secret",
175
+ directory: "/project",
176
+ environment: {},
177
+ });
178
+ const read = server.withConnection((connection) => Effect.succeed(connection.version));
179
+ const before = yield* read;
180
+ version = "2.2.5";
181
+ const cached = yield* read;
182
+ yield* server.forget;
183
+ return [before, cached, yield* read];
184
+ }).pipe(
185
+ Effect.provide(
186
+ Layer.mergeAll(
187
+ OpenCode2Client.layer.pipe(Layer.provide(layerService)),
188
+ OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
189
+ ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
190
+ ),
191
+ );
192
+ assert.deepStrictEqual(versions, ["2.2.4", "2.2.4", "2.2.5"]);
193
+ }),
194
+ );
195
+});
196
+
197
describe("OpenCode2Server passwords", () => {
198
it("hands the spawned server only the T3 password", () => {
199
const password = Redacted.make("t3-generated");
packages/provider-opencode/src/server/v2/OpenCode2Server.ts
+6
@@ -26,6 +26,8 @@ export class OpenCode2Server extends Context.Service<
26
readonly withConnection: <A, E, R>(
27
use: (connection: OpenCode2Connection) => Effect.Effect<A, E, R>,
28
) => Effect.Effect<A, E | OpenCodeRuntime.OpenCodeRuntimeError, R>;
29
+ /** Drops a configured server's verified connection, so the next use reads its version again. */
30
+ readonly forget: Effect.Effect<void>;
31
}
32
>()("@t3tools/provider-opencode/server/v2/OpenCode2Server") {}
33
@@ -144,6 +146,9 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {
146
Effect.flatMap(use),
147
);
148
}),
149
+ forget: Effect.sync(() => {
150
+ latest = undefined;
151
+ }),
152
});
153
}
154
@@ -162,5 +167,6 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {
167
: Effect.die(new Error("OpenCode 2 server was lent before verification.")),
168
);
169
}),
170
+ forget: Effect.void,
171
});
172
});
packages/provider-opencode/src/server/v2/OpenCode2Service.test.ts
new
+96
@@ -0,0 +1,96 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { it } from "@effect/vitest";
3
+import * as HostProcess from "@t3tools/shared/HostProcess";
4
+import * as Effect from "effect/Effect";
5
+import * as FileSystem from "effect/FileSystem";
6
+import * as Path from "effect/Path";
7
+import { expect, vi } from "vite-plus/test";
8
+
9
+import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
10
+import { replaceOutdatedService } from "./OpenCode2Service.ts";
11
+
12
+const service = vi.hoisted(() => ({ discover: vi.fn(), stop: vi.fn(), ensure: vi.fn() }));
13
+vi.mock("@opencode/client/effect/service", () => ({ Service: service }));
14
+
15
+const runtimeWithBinaryVersion = (stdout: string) =>
16
+ ({
17
+ runOpenCodeCommand: () => Effect.succeed({ stdout, stderr: "", code: 0 }),
18
+ }) as unknown as OpenCodeRuntime.OpenCodeRuntime["Service"];
19
+
20
+it.layer(NodeServices.layer)("replaceOutdatedService", (it) => {
21
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
22
+ "replaces only this install's 2.x service, keeping its configured env",
23
+ () =>
24
+ Effect.gen(function* () {
25
+ const fileSystem = yield* FileSystem.FileSystem;
26
+ const path = yield* Path.Path;
27
+ const home = yield* fileSystem.makeTempDirectoryScoped();
28
+ const binDirectory = path.join(home, "bin");
29
+ yield* fileSystem.makeDirectory(binDirectory);
30
+ yield* fileSystem.writeFileString(path.join(binDirectory, "opencode"), "");
31
+ yield* fileSystem.chmod(path.join(binDirectory, "opencode"), 0o755);
32
+ const environment = {
33
+ HOME: home,
34
+ PATH: binDirectory,
35
+ OPENCODE_CONFIG_DIR: home,
36
+ ELECTRON_RUN_AS_NODE: "1",
37
+ };
38
+ yield* fileSystem.writeFileString(
39
+ path.join(home, "service.json"),
40
+ JSON.stringify({ env: { PATH: "/nowhere", XDG_STATE_HOME: "/elsewhere" } }),
41
+ );
42
+ const file = path.join(home, ".local", "state", "opencode", "service.json");
43
+ const run = (binary: string, serverUrl = "http://127.0.0.1:49374") =>
44
+ replaceOutdatedService({
45
+ binaryPath: "opencode",
46
+ serverUrl,
47
+ environment,
48
+ }).pipe(
49
+ Effect.provideService(
50
+ OpenCodeRuntime.OpenCodeRuntime,
51
+ runtimeWithBinaryVersion(binary),
52
+ ),
53
+ );
54
+ service.stop.mockReturnValue(Effect.void);
55
+ service.ensure.mockReturnValue(Effect.void);
56
+ const outdated = (options: { readonly version?: string }) =>
57
+ Effect.succeed(
58
+ options.version === undefined ? { url: "http://0.0.0.0:49374" } : undefined,
59
+ );
60
+
61
+ service.discover.mockImplementation(outdated);
62
+ yield* run("opencode v1.18.32");
63
+ expect(service.discover).not.toHaveBeenCalled();
64
+
65
+ for (const elsewhere of [
66
+ "http://192.168.1.5:49374",
67
+ "http://127.0.0.1:49999",
68
+ "http://[::1]:49374",
69
+ "http://localhost:49374",
70
+ ]) {
71
+ yield* run("opencode v2.2.5", elsewhere);
72
+ }
73
+ expect(service.discover).toHaveBeenCalledWith({ file });
74
+ service.discover.mockReturnValue(Effect.succeed({ url: "http://0.0.0.0" }));
75
+ yield* run("opencode v2.2.5", "https://127.0.0.1");
76
+ expect(service.ensure).not.toHaveBeenCalled();
77
+
78
+ service.discover.mockReturnValue(Effect.undefined);
79
+ yield* run("opencode v2.2.5");
80
+ expect(service.ensure).not.toHaveBeenCalled();
81
+
82
+ service.discover.mockReturnValue(Effect.succeed({ url: "http://0.0.0.0:49374" }));
83
+ yield* run("opencode v2.2.5");
84
+ expect(service.stop).not.toHaveBeenCalled();
85
+
86
+ service.discover.mockImplementation(outdated);
87
+ yield* run("opencode v2.2.5");
88
+ expect(service.stop).toHaveBeenCalledWith({ file, pty: "handoff" });
89
+ expect(service.ensure).toHaveBeenCalledWith({
90
+ file,
91
+ command: [path.join(binDirectory, "opencode"), "serve", "--service"],
92
+ env: { ...environment, PATH: "/nowhere", ELECTRON_RUN_AS_NODE: undefined },
93
+ });
94
+ }).pipe(Effect.scoped),
95
+ );
96
+});
packages/provider-opencode/src/server/v2/OpenCode2Service.ts
new
+118
@@ -0,0 +1,118 @@
1
+import { Service } from "@opencode/client/effect/service";
2
+import { AgentScope } from "@t3tools/shared/AgentScope";
3
+import * as HostProcess from "@t3tools/shared/HostProcess";
4
+import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
5
+import * as Effect from "effect/Effect";
6
+import * as FileSystem from "effect/FileSystem";
7
+import * as Option from "effect/Option";
8
+import * as Path from "effect/Path";
9
+import * as Schema from "effect/Schema";
10
+
11
+import { probeOpenCodeBinary } from "../versionProbe.ts";
12
+
13
+const decodeServiceConfig = Schema.decodeUnknownOption(
14
+ Schema.fromJsonString(
15
+ Schema.Struct({ env: Schema.optional(Schema.Record(Schema.String, Schema.String)) }),
16
+ ),
17
+);
18
+
19
+function isRegisteredService(registeredUrl: string, serverUrl: string): boolean {
20
+ const registered = URL.parse(registeredUrl);
21
+ const configured = URL.parse(serverUrl);
22
+ if (
23
+ registered === null ||
24
+ configured === null ||
25
+ registered.protocol !== configured.protocol ||
26
+ registered.port !== configured.port
27
+ ) {
28
+ return false;
29
+ }
30
+ // A wildcard listener covers only its own address family's loopback; `localhost` could be either.
31
+ return (
32
+ registered.hostname === configured.hostname ||
33
+ (registered.hostname === "0.0.0.0" && configured.hostname === "127.0.0.1") ||
34
+ (registered.hostname === "[::]" && configured.hostname === "[::1]")
35
+ );
36
+}
37
+
38
+/**
39
+ * Replaces the way the TUI's restart does, which hands persistent terminals to the new process.
40
+ * `opencode service restart` shuts them down instead.
41
+ */
42
+export const replaceOutdatedService = Effect.fn("OpenCode2Service.replaceOutdatedService")(
43
+ function* (input: {
44
+ readonly binaryPath: string;
45
+ readonly serverUrl: string;
46
+ readonly environment: NodeJS.ProcessEnv;
47
+ }) {
48
+ const { generation, version } = yield* probeOpenCodeBinary(input.binaryPath, input.environment);
49
+ if (generation !== "v2") return;
50
+
51
+ const path = yield* Path.Path;
52
+ const fileSystem = yield* FileSystem.FileSystem;
53
+ const home = input.environment.HOME ?? (yield* HostProcess.HomeDirectory);
54
+ const file = path.join(
55
+ input.environment.XDG_STATE_HOME ?? path.join(home, ".local", "state"),
56
+ "opencode",
57
+ "service.json",
58
+ );
59
+ // `Service.incumbent` would send the local service's password to the configured URL, which may
60
+ // be another machine. `discover` only contacts the address in the local registration.
61
+ const service = yield* Service.discover({ file });
62
+ if (service === undefined || !isRegisteredService(service.url, input.serverUrl)) return;
63
+
64
+ // Configured variables below can change PATH, which a bare name would then resolve against.
65
+ const executable = yield* resolveCommandPath(input.binaryPath, { env: input.environment });
66
+ if (executable === null) return;
67
+ // A scope of its own keeps the service alive when T3 Code's systemd unit stops.
68
+ const launch = yield* (yield* AgentScope).wrap({
69
+ command: executable,
70
+ args: ["serve", "--service"],
71
+ name: "opencode-service",
72
+ env: input.environment,
73
+ shared: true,
74
+ survivesRestart: true,
75
+ });
76
+ const command = yield* resolveSpawnCommand(launch.command, launch.args, {
77
+ env: input.environment,
78
+ extendEnv: true,
79
+ bypassNpmShim: true,
80
+ });
81
+ // The service spawns without a shell; stopping it first would leave nothing running.
82
+ if (command.shell) {
83
+ return yield* Effect.logWarning("OpenCode service cannot be replaced through a shell shim");
84
+ }
85
+
86
+ const config = yield* fileSystem
87
+ .readFileString(
88
+ path.join(
89
+ input.environment.OPENCODE_CONFIG_DIR ??
90
+ path.join(input.environment.XDG_CONFIG_HOME ?? path.join(home, ".config"), "opencode"),
91
+ "service.json",
92
+ ),
93
+ )
94
+ .pipe(Effect.option, Effect.map(Option.flatMap(decodeServiceConfig)));
95
+ // The CLI passes configured variables but never lets them move the registration file.
96
+ const { XDG_STATE_HOME: _state, ...configured } = Option.getOrUndefined(config)?.env ?? {};
97
+ const env: Record<string, string> = {};
98
+ for (const [name, value] of Object.entries({ ...input.environment, ...configured })) {
99
+ if (value !== undefined) env[name] = value;
100
+ }
101
+
102
+ if ((yield* Service.discover({ file, version })) !== undefined) return;
103
+
104
+ // `ensure` with a version would kill every new service whose version never matches the probe,
105
+ // and being interrupted between the stop and the start would leave no service running.
106
+ yield* Service.stop({ file, pty: "handoff" }).pipe(
107
+ Effect.andThen(
108
+ Service.ensure({
109
+ file,
110
+ command: [command.command, ...command.args],
111
+ // T3 Desktop's backend sets this; undefined overrides the inherited value at spawn.
112
+ env: { ...env, ELECTRON_RUN_AS_NODE: undefined } as unknown as Record<string, string>,
113
+ }),
114
+ ),
115
+ Effect.uninterruptible,
116
+ );
117
+ },
118
+);