Skip to content

Commit e8d5b02

Browse files
injaneityf-trycua
andcommitted
fix(desktop): clear cua config after daemon exit
Co-authored-by: Francesco Bonacci <[email protected]>
1 parent e7d3629 commit e8d5b02

5 files changed

Lines changed: 133 additions & 7 deletions

File tree

‎apps/desktop/src/app/DesktopApp.ts‎

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,22 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr
141141
const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
142142
handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
143143

144+
export const restartBackendAfterCuaDriverExit = Effect.fn(
145+
"desktop.restartBackendAfterCuaDriverExit",
146+
)(function* (
147+
backend: Pick<DesktopBackendPool.DesktopBackendInstance, "snapshot" | "stop" | "start">,
148+
isQuitting: Effect.Effect<boolean>,
149+
) {
150+
const snapshot = yield* backend.snapshot;
151+
if (!snapshot.desiredRunning || (yield* isQuitting)) return false;
152+
153+
yield* backend.stop();
154+
if (yield* isQuitting) return false;
155+
156+
yield* backend.start;
157+
return true;
158+
});
159+
144160
const bootstrap = Effect.gen(function* () {
145161
const pool = yield* DesktopBackendPool.DesktopBackendPool;
146162
const primaryBackend = yield* pool.primary;
@@ -308,20 +324,44 @@ const startup = Effect.gen(function* () {
308324
})
309325
.pipe(Effect.ignore);
310326
});
311-
yield* cuaDriver.start.pipe(
327+
const cuaStarted = yield* cuaDriver.start.pipe(
328+
Effect.as(true),
312329
Effect.catchTags({
313330
CuaDriverModuleLoadError: (error) =>
314-
continueWithoutCua({ modulePath: error.modulePath, cause: error.cause }),
315-
CuaDriverNotConfiguredError: () => continueWithoutCua({}),
331+
continueWithoutCua({ modulePath: error.modulePath, cause: error.cause }).pipe(
332+
Effect.as(false),
333+
),
334+
CuaDriverNotConfiguredError: () => continueWithoutCua({}).pipe(Effect.as(false)),
316335
CuaDriverPermissionError: (error) =>
317336
continueWithoutCua({
318337
accessibility: error.accessibility,
319338
screenRecording: error.screenRecording,
320-
}),
339+
}).pipe(Effect.as(false)),
321340
CuaDriverStartError: (error) =>
322-
continueWithoutCua({ binaryPath: error.binaryPath, cause: error.cause }),
341+
continueWithoutCua({ binaryPath: error.binaryPath, cause: error.cause }).pipe(
342+
Effect.as(false),
343+
),
323344
}),
324345
);
346+
if (cuaStarted) {
347+
const pool = yield* DesktopBackendPool.DesktopBackendPool;
348+
const primaryBackend = yield* pool.primary;
349+
const state = yield* DesktopState.DesktopState;
350+
yield* cuaDriver.awaitUnavailable.pipe(
351+
Effect.andThen(restartBackendAfterCuaDriverExit(primaryBackend, Ref.get(state.quitting))),
352+
Effect.tap((restarted) =>
353+
restarted
354+
? logStartupInfo("desktop backend restarted without unavailable cua-driver")
355+
: Effect.void,
356+
),
357+
Effect.catchCause((cause) =>
358+
logStartupError("failed to remove unavailable cua-driver from desktop backend", {
359+
cause,
360+
}),
361+
),
362+
Effect.forkScoped,
363+
);
364+
}
325365
}
326366
yield* appIdentity.configure;
327367
yield* applicationMenu.configure;

‎apps/desktop/src/app/DesktopAppErrors.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { assert, describe, it } from "@effect/vitest";
2+
import * as Effect from "effect/Effect";
3+
import * as Option from "effect/Option";
24

35
import {
46
DesktopBackendPortUnavailableError,
57
DesktopDevelopmentBackendPortRequiredError,
8+
restartBackendAfterCuaDriverExit,
69
} from "./DesktopApp.ts";
710

811
describe("DesktopApp errors", () => {
@@ -27,4 +30,33 @@ describe("DesktopApp errors", () => {
2730

2831
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
2932
});
33+
34+
it.effect("restarts a running backend so stale Cua launch args are discarded", () => {
35+
const events: Array<string> = [];
36+
const backend = {
37+
snapshot: Effect.succeed({
38+
desiredRunning: true,
39+
ready: true,
40+
activePid: Option.some(42),
41+
restartAttempt: 0,
42+
restartScheduled: false,
43+
}),
44+
stop: () =>
45+
Effect.sync(() => {
46+
events.push("stop");
47+
}),
48+
start: Effect.sync(() => {
49+
events.push("start");
50+
}),
51+
};
52+
53+
return restartBackendAfterCuaDriverExit(backend, Effect.succeed(false)).pipe(
54+
Effect.tap((restarted) =>
55+
Effect.sync(() => {
56+
assert.isTrue(restarted);
57+
assert.deepEqual(events, ["stop", "start"]);
58+
}),
59+
),
60+
);
61+
});
3062
});

‎apps/desktop/src/backend/DesktopBackendConfiguration.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const cuaDriverLayer = (enabled: boolean) =>
3232
start: Effect.die("unexpected start"),
3333
stop: Effect.void,
3434
mcpConfiguration: Effect.succeed(enabled ? Option.some(testCuaDriverMcp) : Option.none()),
35+
awaitUnavailable: Effect.never,
3536
}),
3637
);
3738

‎apps/desktop/src/cua/DesktopCuaDriver.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { describe, expect, it } from "@effect/vitest";
33
import * as Effect from "effect/Effect";
4+
import * as Fiber from "effect/Fiber";
45
import * as Layer from "effect/Layer";
56
import * as Option from "effect/Option";
67

@@ -137,6 +138,46 @@ describe("DesktopCuaDriver", () => {
137138
).pipe(Effect.provide(environmentLayer(true)));
138139
});
139140

141+
it.effect("reports an unexpected daemon exit after clearing its MCP descriptor", () => {
142+
return Effect.scoped(
143+
Effect.gen(function* () {
144+
let resolveExit: (exit: EmbeddedDriverExit) => void = () => {};
145+
const exit = new Promise<EmbeddedDriverExit>((resolve) => {
146+
resolveExit = resolve;
147+
});
148+
149+
class ExitingEmbeddedCuaDriverHost {
150+
start = () => Promise.resolve(connection);
151+
stop = () => Promise.resolve();
152+
waitForExit = () => exit;
153+
uniffiDestroy = () => {};
154+
}
155+
156+
const service = yield* make({
157+
loadElectron: () =>
158+
Promise.resolve({
159+
requestMacOSPermissions: () => ({
160+
accessibility: true,
161+
screenRecording: true,
162+
}),
163+
hasRequiredMacOSPermissions: () => true,
164+
} as unknown as typeof import("@trycua/cua-driver/electron")),
165+
loadEmbedded: () =>
166+
Promise.resolve({
167+
EmbeddedCuaDriverHost: ExitingEmbeddedCuaDriverHost,
168+
} as unknown as typeof import("@trycua/cua-driver/embedded")),
169+
});
170+
171+
yield* service.start;
172+
const unavailable = yield* service.awaitUnavailable.pipe(Effect.forkScoped);
173+
resolveExit({ generation: connection.generation, code: 9, success: false });
174+
yield* Fiber.await(unavailable);
175+
176+
expect(Option.isNone(yield* service.mcpConfiguration)).toBe(true);
177+
}),
178+
).pipe(Effect.provide(environmentLayer(true)));
179+
});
180+
140181
it.effect("requires an explicit driver path in development", () => {
141182
const previous = process.env.T3CODE_CUA_DRIVER_PATH;
142183
delete process.env.T3CODE_CUA_DRIVER_PATH;

‎apps/desktop/src/cua/DesktopCuaDriver.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { CuaDriverMcpConfiguration } from "@t3tools/contracts";
22
import * as Context from "effect/Context";
3+
import * as Deferred from "effect/Deferred";
34
import * as Effect from "effect/Effect";
45
import * as Layer from "effect/Layer";
56
import * as Option from "effect/Option";
@@ -110,6 +111,7 @@ export class DesktopCuaDriver extends Context.Service<
110111
readonly start: Effect.Effect<CuaDriverMcpConfiguration, DesktopCuaDriverError, Scope.Scope>;
111112
readonly stop: Effect.Effect<void>;
112113
readonly mcpConfiguration: Effect.Effect<Option.Option<CuaDriverMcpConfiguration>>;
114+
readonly awaitUnavailable: Effect.Effect<void>;
113115
}
114116
>()("@t3tools/desktop/cua/DesktopCuaDriver") {}
115117

@@ -121,6 +123,7 @@ export const make = Effect.fn("desktop.cuaDriver.make")(function* (
121123
) {
122124
const environment = yield* DesktopEnvironment.DesktopEnvironment;
123125
const state = yield* Ref.make(Option.none<HostedDriver>());
126+
const unavailable = yield* Deferred.make<void>();
124127

125128
const stop = Ref.getAndSet(state, Option.none()).pipe(
126129
Effect.flatMap(
@@ -195,7 +198,11 @@ export const make = Effect.fn("desktop.cuaDriver.make")(function* (
195198
generation: exit.generation,
196199
code: exit.code,
197200
success: exit.success,
198-
}).pipe(Effect.ensuring(destroyHost(host)))
201+
}).pipe(
202+
Effect.andThen(Deferred.succeed(unavailable, undefined)),
203+
Effect.asVoid,
204+
Effect.ensuring(destroyHost(host)),
205+
)
199206
: Effect.void,
200207
),
201208
),
@@ -215,7 +222,11 @@ export const make = Effect.fn("desktop.cuaDriver.make")(function* (
215222
? Effect.logWarning(
216223
"embedded cua-driver exit monitor failed; computer use is unavailable",
217224
{ component: "embedded-cua-driver", cause },
218-
).pipe(Effect.ensuring(destroyHost(host)))
225+
).pipe(
226+
Effect.andThen(Deferred.succeed(unavailable, undefined)),
227+
Effect.asVoid,
228+
Effect.ensuring(destroyHost(host)),
229+
)
219230
: Effect.void,
220231
),
221232
),
@@ -237,6 +248,7 @@ export const make = Effect.fn("desktop.cuaDriver.make")(function* (
237248
mcpConfiguration: Ref.get(state).pipe(
238249
Effect.map(Option.map(({ connection }) => connection.mcp)),
239250
),
251+
awaitUnavailable: Deferred.await(unavailable),
240252
});
241253
});
242254

0 commit comments

Comments
 (0)