Skip to content

Commit 07c887d

Browse files
fix(desktop): resume macOS snapshot setup and preserve accessibility access
1 parent 7a63f20 commit 07c887d

11 files changed

Lines changed: 301 additions & 12 deletions

File tree

‎apps/desktop/src/snapShot/DesktopSnapShot.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3593,3 +3593,58 @@ it.effect("waits to apply settings while permissions are pending", () => {
35933593
}),
35943594
).pipe(Effect.provide(layer));
35953595
});
3596+
3597+
for (const fails of [false, true]) {
3598+
it.effect(`tests macOS capture without publishing it and cleans up, failure=${fails}`, () => {
3599+
const active = {
3600+
platform: "macos",
3601+
id: 42,
3602+
title: "Setup",
3603+
owner: { name: "T3 Code", processId: 123, path: "/Applications/T3 Code.app" },
3604+
bounds: { x: 0, y: 0, width: 800, height: 600 },
3605+
};
3606+
activeWindowMock.mockReset().mockResolvedValue(active);
3607+
macCaptureMock.mockReset();
3608+
if (fails) macCaptureMock.mockRejectedValue(new Error("Capture denied"));
3609+
else macCaptureMock.mockResolvedValue({ source: { name: "Setup" }, png: Buffer.from("png") });
3610+
accessibilityProcessReadMock.mockClear();
3611+
const cleanup = vi.fn();
3612+
return Effect.scoped(
3613+
Effect.gen(function* () {
3614+
const service = yield* DesktopSnapShot.make;
3615+
if (fails) {
3616+
const error = yield* service.setup("test-mac-capture").pipe(Effect.flip);
3617+
assert.equal(error.reason, "setup-failed");
3618+
} else yield* service.setup("test-mac-capture");
3619+
assert.equal(macCaptureMock.mock.calls.length, 1);
3620+
assert.equal(macCaptureMock.mock.calls[0]?.[0], active);
3621+
assert.equal(macCaptureMock.mock.calls[0]?.[1], "/tmp/setup-test/test.png");
3622+
assert.equal(cleanup.mock.calls.length, 1);
3623+
assert.equal(accessibilityProcessReadMock.mock.calls.length, 0);
3624+
assert.deepEqual(yield* service.listPending, []);
3625+
}),
3626+
).pipe(
3627+
Effect.provide(
3628+
testLayer("darwin", {
3629+
makeTempDirectoryScoped: () =>
3630+
Effect.acquireRelease(Effect.succeed("/tmp/setup-test"), () =>
3631+
Effect.sync(() => {
3632+
cleanup();
3633+
}),
3634+
),
3635+
readDirectory: () => Effect.succeed([]),
3636+
}),
3637+
),
3638+
);
3639+
});
3640+
}
3641+
3642+
it.effect("rejects macOS test capture on other platforms", () =>
3643+
Effect.scoped(
3644+
Effect.gen(function* () {
3645+
const service = yield* DesktopSnapShot.make;
3646+
const error = yield* service.setup("test-mac-capture").pipe(Effect.flip);
3647+
assert.equal(error.reason, "unsupported-session");
3648+
}),
3649+
).pipe(Effect.provide(testLayer("win32"))),
3650+
);

‎apps/desktop/src/snapShot/DesktopSnapShot.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1310,7 +1310,33 @@ export const make = Effect.gen(function* () {
13101310
);
13111311

13121312
const setup = Effect.fn("desktop.snapShot.setup")(function* (action: DesktopSnapShotSetupAction) {
1313-
if (action === "install-kde-helper" || action === "remove-kde-helper") {
1313+
if (action === "test-mac-capture") {
1314+
if (environment.platform !== "darwin")
1315+
return yield* new DesktopSnapShotSetupError({ action, reason: "unsupported-session" });
1316+
// Exercise the real capture path during setup without attaching a snapshot
1317+
// or running capture feedback. The temporary image is discarded on failure too.
1318+
yield* Effect.scoped(
1319+
Effect.gen(function* () {
1320+
const directory = yield* fileSystem.makeTempDirectoryScoped({
1321+
prefix: "t3-snapshot-test-",
1322+
});
1323+
yield* Effect.tryPromise(async () => {
1324+
const active = await activeWindow("darwin");
1325+
if (!active) throw new Error("No window is available to test capture.");
1326+
await captureMacWindowSnapshot(
1327+
active,
1328+
path.join(directory, "test.png"),
1329+
snapShotThumbnailSize(active),
1330+
);
1331+
});
1332+
}),
1333+
).pipe(
1334+
Effect.mapError(
1335+
(cause) => new DesktopSnapShotSetupError({ action, reason: "setup-failed", cause }),
1336+
),
1337+
);
1338+
return;
1339+
} else if (action === "install-kde-helper" || action === "remove-kde-helper") {
13141340
if (captureMode(environment.platform) !== "portal" || !isKdeCaptureSession())
13151341
return yield* new DesktopSnapShotSetupError({
13161342
action,

‎apps/desktop/src/snapShot/SnapShotAccessibilityProcess.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
import { assert, beforeEach, it } from "@effect/vitest";
22
import * as NodeEvents from "node:events";
3+
import * as NodeProcess from "node:process";
34
import { vi } from "vite-plus/test";
45

56
const forkMock = vi.hoisted(() =>
67
vi.fn<
7-
(_path: string, _args: ReadonlyArray<string>, _options: { env?: NodeJS.ProcessEnv }) => unknown
8+
(
9+
_path: string,
10+
_args: ReadonlyArray<string>,
11+
_options: { env?: NodeJS.ProcessEnv; execPath?: string },
12+
) => unknown
813
>(),
914
);
1015

@@ -68,6 +73,7 @@ it("returns accessibility extracted by the helper", async () => {
6873
await read.started;
6974
assert.deepEqual(await read.result, context);
7075
assert.strictEqual(forkMock.mock.calls[0]?.[2]?.env?.ELECTRON_RUN_AS_NODE, "1");
76+
assert.strictEqual(forkMock.mock.calls[0]?.[2]?.execPath, NodeProcess.execPath);
7177
});
7278

7379
it("hands a warm helper to the capture and prewarms its replacement", async () => {

‎apps/desktop/src/snapShot/SnapShotAccessibilityProcess.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ export function startSnapShotAccessibilityProcess(workerPath: string): Accessibi
4949
let worker: NodeChildProcess.ChildProcess;
5050
try {
5151
worker = NodeChildProcess.fork(workerPath, ["read"], {
52+
// Electron defaults to its Helper executable on macOS, which does not
53+
// share the main app's Accessibility grant checked during setup.
54+
execPath: process.execPath,
5255
env: {
5356
...process.env,
5457
ELECTRON_RUN_AS_NODE: "1",

‎apps/web/src/components/settings/SnapShotSettings.test.tsx‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const bridge = vi.hoisted(() => ({
3333
previewSnapShotConfig: vi.fn(),
3434
applySnapShotConfig: vi.fn(),
3535
setupSnapShot: vi.fn(),
36+
requestSnapShotPermissions: vi.fn().mockResolvedValue(undefined),
3637
onMenuAction: vi.fn(),
3738
onSnapShotEvent: vi.fn(() => () => undefined),
3839
}));
@@ -337,3 +338,79 @@ it("keeps setup errors in the wizard and does not toast them after closing it",
337338
expect(wizard(renderWithEffects())).toBeNull();
338339
expect(toastManager.add).not.toHaveBeenCalled();
339340
});
341+
342+
it.each([false, true])(
343+
"resumes macOS permission setup after restart and clears it on close, completed=%s",
344+
async (completed) => {
345+
const { readSnapShotSetupResume } = await import("../../lib/snapShotSetupResume");
346+
const values = new Map<string, string>();
347+
Object.assign(window, {
348+
localStorage: {
349+
getItem: (key: string) => values.get(key) ?? null,
350+
setItem: (key: string, value: string) => values.set(key, value),
351+
removeItem: (key: string) => values.delete(key),
352+
},
353+
});
354+
settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
355+
state = {
356+
mode: "direct",
357+
shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
358+
shortcutRegistered: false,
359+
shortcutMessage: null,
360+
message: null,
361+
macPermissions: { screenRecording: false, accessibility: false },
362+
};
363+
const tree = await mount();
364+
const toggle = visitElements(
365+
tree,
366+
(element) => element.props["aria-label"] === "Enable snapshots",
367+
);
368+
(toggle!.props.onCheckedChange as (checked: boolean) => void)(true);
369+
await finish(bridge.getSnapShotState.mock.results[1]!.value);
370+
bridge.setupSnapShot.mockImplementationOnce(async () => {
371+
expect(readSnapShotSetupResume()).toEqual({ wasEnabled: false });
372+
});
373+
await (wizard(render())!.props.onAction as (action: string) => Promise<void>)(
374+
"allow-screen-recording",
375+
);
376+
377+
hooks.reset();
378+
effects.length = 0;
379+
bridge.getSnapShotState.mockClear();
380+
state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };
381+
const resumed = wizard(await mount());
382+
expect(resumed).not.toBeNull();
383+
expect(resumed!.props.initialStep).toBe("access");
384+
expect(resumed!.props.wasEnabled).toBe(false);
385+
await (resumed!.props.onClose as (completed: boolean) => Promise<void>)(completed);
386+
expect(wizard(render())).toBeNull();
387+
expect(readSnapShotSetupResume()).toBeNull();
388+
},
389+
);
390+
391+
it("requires a successful macOS test capture before enabling and allows retry", async () => {
392+
settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: false };
393+
state = {
394+
mode: "direct",
395+
shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
396+
shortcutRegistered: false,
397+
shortcutMessage: null,
398+
message: null,
399+
macPermissions: { screenRecording: true, accessibility: true },
400+
};
401+
const tree = await mount();
402+
const toggle = visitElements(
403+
tree,
404+
(element) => element.props["aria-label"] === "Enable snapshots",
405+
);
406+
(toggle!.props.onCheckedChange as (checked: boolean) => void)(true);
407+
await finish(bridge.getSnapShotState.mock.results[1]!.value);
408+
bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));
409+
const enable = () => (wizard(render())!.props.onEnable as () => Promise<boolean>)();
410+
expect(await enable()).toBe(false);
411+
expect(wizard(render())!.props.error).toBe("Capture was denied");
412+
expect(settingsStore.current.snapShotEnabled).toBe(false);
413+
expect(await enable()).toBe(true);
414+
expect(bridge.setupSnapShot.mock.calls).toEqual([["test-mac-capture"], ["test-mac-capture"]]);
415+
expect(settingsStore.current.snapShotEnabled).toBe(true);
416+
});

‎apps/web/src/components/settings/SnapShotSettings.tsx‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ import { cn } from "~/lib/utils";
1414

1515
import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
1616
import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";
17+
import {
18+
readSnapShotSetupResume,
19+
saveSnapShotSetupResume,
20+
clearSnapShotSetupResume,
21+
} from "../../lib/snapShotSetupResume";
1722
import { sameSnapShotShortcut, snapShotKeybindingConflict } from "../../lib/snapShotShortcut";
1823
import { playSnapShotSound } from "../../lib/snapShotSound";
1924
import { primaryServerKeybindingsAtom } from "../../state/server";
@@ -125,6 +130,14 @@ export function SnapShotSettings() {
125130
setSetupBusy(true);
126131
setSetupError(null);
127132
try {
133+
if (
134+
state?.macPermissions &&
135+
wizard &&
136+
(action === "allow-screen-recording" || action === "allow-accessibility")
137+
) {
138+
// macOS can quit the app from its permission prompt.
139+
saveSnapShotSetupResume(wizard.wasEnabled);
140+
}
128141
await bridge.setupSnapShot(action);
129142
await refreshState();
130143
} catch (error) {
@@ -140,7 +153,7 @@ export function SnapShotSettings() {
140153
setSetupBusy(false);
141154
}
142155
},
143-
[bridge, refreshState, setupBusy],
156+
[bridge, refreshState, setupBusy, state, wizard],
144157
);
145158

146159
useEffect(() => {
@@ -154,9 +167,18 @@ export function SnapShotSettings() {
154167
}, [setupError, wizard]);
155168

156169
useEffect(() => {
157-
void refreshState();
170+
let cancelled = false;
171+
void refreshState().then((current) => {
172+
const resume = readSnapShotSetupResume();
173+
if (!cancelled && current?.macPermissions && resume) {
174+
setWizard({ initialStep: "access", wasEnabled: resume.wasEnabled });
175+
}
176+
});
158177
window.addEventListener("focus", refreshState);
159-
return () => window.removeEventListener("focus", refreshState);
178+
return () => {
179+
cancelled = true;
180+
window.removeEventListener("focus", refreshState);
181+
};
160182
}, [refreshState]);
161183

162184
useEffect(
@@ -270,6 +292,7 @@ export function SnapShotSettings() {
270292
try {
271293
let current = await refreshState();
272294
if (!current) return;
295+
if (current.macPermissions) requested = "access";
273296
if (!settings.snapShotEnabled && captureSetupInitialStep(current, requested) !== "access") {
274297
// Opening setup is the opt-in. Restore registration before resuming a
275298
// later step, just as Continue does on the access step.
@@ -295,6 +318,11 @@ export function SnapShotSettings() {
295318
setSetupBusy(true);
296319
setSetupError(null);
297320
try {
321+
if (state?.macPermissions) {
322+
saveSnapShotSetupResume(wizard?.wasEnabled ?? settings.snapShotEnabled);
323+
if (!bridge?.setupSnapShot) throw new Error("Restart T3 Code to finish capture setup.");
324+
await bridge.setupSnapShot("test-mac-capture");
325+
}
298326
if (state?.mode === "direct")
299327
await bridge?.requestSnapShotPermissions(settings.snapShotIncludeAccessibility);
300328
const nextState =
@@ -303,7 +331,7 @@ export function SnapShotSettings() {
303331
: await save({ snapShotEnabled: true });
304332
return nextState !== undefined && captureSetupAccessReady(nextState);
305333
} catch (error) {
306-
setSetupError(captureSettingsError("Couldn't request capture permissions", error));
334+
setSetupError(captureSettingsError("Couldn't verify capture access", error));
307335
return false;
308336
} finally {
309337
setSetupBusy(false);
@@ -327,6 +355,7 @@ export function SnapShotSettings() {
327355
}
328356
stopRecording();
329357
setSetupError(null);
358+
clearSnapShotSetupResume();
330359
setWizard(null);
331360
} catch (error) {
332361
setSetupError(captureSettingsError("Couldn't close capture setup", error));

‎apps/web/src/components/settings/SnapShotSetupDialog.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ export function SnapShotSetupDialog({
296296
? "Your desktop may ask for permission when you first capture."
297297
: macPermissions
298298
? macPermissionsReady
299-
? "Permissions are in place. Continue to choose your shortcut."
299+
? "Test a snapshot of the current window. If macOS asks to bypass its window picker, choose Allow. The test image is discarded."
300300
: "Allow each permission, then continue."
301301
: "Allow access when prompted to start capturing windows.",
302302
};
@@ -545,11 +545,13 @@ export function SnapShotSetupDialog({
545545
>
546546
{busy
547547
? "Working…"
548-
: backend === "direct" && !macPermissions
549-
? "Allow capture"
550-
: !accessReady && !macPermissions
551-
? "Try again"
552-
: "Continue"}
548+
: macPermissions
549+
? "Test capture and continue"
550+
: backend === "direct"
551+
? "Allow capture"
552+
: !accessReady && !macPermissions
553+
? "Try again"
554+
: "Continue"}
553555
</Button>
554556
)
555557
) : !configShortcut ? (
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { afterEach, expect, it, vi } from "vite-plus/test";
2+
3+
function storage() {
4+
const values = new Map<string, string>();
5+
vi.stubGlobal("window", {
6+
localStorage: {
7+
getItem: (key: string) => values.get(key) ?? null,
8+
setItem: (key: string, value: string) => values.set(key, value),
9+
removeItem: (key: string) => values.delete(key),
10+
},
11+
});
12+
}
13+
14+
afterEach(() => vi.unstubAllGlobals());
15+
16+
it("resumes once after a restart and retains the opt-in until setup is closed", async () => {
17+
storage();
18+
vi.resetModules();
19+
const before = await import("./snapShotSetupResume");
20+
expect(before.shouldResumeSnapShotSetupOnStartup()).toBe(false);
21+
before.saveSnapShotSetupResume(false);
22+
expect(before.shouldResumeSnapShotSetupOnStartup()).toBe(false);
23+
24+
vi.resetModules();
25+
const after = await import("./snapShotSetupResume");
26+
expect(after.shouldResumeSnapShotSetupOnStartup()).toBe(true);
27+
expect(after.shouldResumeSnapShotSetupOnStartup()).toBe(false);
28+
expect(after.readSnapShotSetupResume()).toEqual({ wasEnabled: false });
29+
after.clearSnapShotSetupResume();
30+
31+
vi.resetModules();
32+
const closed = await import("./snapShotSetupResume");
33+
expect(closed.shouldResumeSnapShotSetupOnStartup()).toBe(false);
34+
});
35+
36+
it("does not interrupt setup when storage is unavailable", async () => {
37+
vi.stubGlobal("window", {});
38+
const resume = await import("./snapShotSetupResume");
39+
expect(() => resume.saveSnapShotSetupResume(true)).not.toThrow();
40+
expect(resume.readSnapShotSetupResume()).toBeNull();
41+
expect(() => resume.clearSnapShotSetupResume()).not.toThrow();
42+
});

0 commit comments

Comments
 (0)