Skip to content

Commit ba46b5b

Browse files
feat(desktop): share macOS permission onboarding with Safari imports
1 parent ab8d56b commit ba46b5b

30 files changed

Lines changed: 726 additions & 211 deletions

‎apps/desktop/src/electron/ElectronShell.ts‎

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts";
12
import {
23
REMOTE_CAPABLE_EDITOR_IDS,
34
remoteSchemeForEditor,
@@ -10,20 +11,6 @@ import * as Option from "effect/Option";
1011

1112
import * as Electron from "electron";
1213

13-
/**
14-
* Deep links to individual System Settings panes. These are app-fixed, not
15-
* renderer-supplied, so they skip `parseSafeExternalUrl` — which exists to keep
16-
* arbitrary link schemes from reaching the OS handler — and open through their
17-
* own path below. The pane rather than the URL crosses the IPC boundary, so a
18-
* renderer can only ask for one of these known destinations.
19-
*
20-
* Full Disk Access uses the post-Ventura `PrivacySecurity.extension` anchor.
21-
*/
22-
const SYSTEM_SETTINGS_URLS: Record<SystemSettingsPane, string> = {
23-
"full-disk-access":
24-
"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles",
25-
};
26-
2714
// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`,
2815
// `zed://ssh/<host>/<path>`) must reach the OS handler; every other non-web
2916
// scheme stays blocked.
@@ -88,7 +75,7 @@ export const make = ElectronShell.of({
8875
}),
8976
openSystemSettings: (pane) =>
9077
Effect.promise(() =>
91-
Electron.shell.openExternal(SYSTEM_SETTINGS_URLS[pane]).then(
78+
Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(
9279
() => true,
9380
() => false,
9481
),

‎apps/desktop/src/ipc/DesktopIpcHandlers.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
getWindowFullscreenState,
4040
openExternal,
4141
openSystemSettings,
42+
checkSystemPermission,
4243
probeRemoteEditors,
4344
pickFolder,
4445
pickProjectFavicon,
@@ -122,6 +123,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
122123
yield* ipc.handle(showContextMenu);
123124
yield* ipc.handle(openExternal);
124125
yield* ipc.handle(openSystemSettings);
126+
yield* ipc.handle(checkSystemPermission);
125127
yield* ipc.handle(probeRemoteEditors);
126128
yield* ipc.handle(getUpdateState);
127129
yield* ipc.handle(setUpdateChannel);

‎apps/desktop/src/ipc/channels.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,6 @@ export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame"
106106
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
107107
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
108108

109-
export const SNAP_SHOT_PERMISSION_HELPER_CHANNEL = "desktop:snapshot-permission-helper";
109+
export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper";
110+
111+
export const CHECK_SYSTEM_PERMISSION_CHANNEL = "desktop:check-system-permission";

‎apps/desktop/src/ipc/methods/window.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ import * as ElectronMenu from "../../electron/ElectronMenu.ts";
3434
import * as ElectronShell from "../../electron/ElectronShell.ts";
3535
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
3636
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
37+
import * as Electron from "electron";
38+
import * as MacPermissions from "../../permissions/MacPermissions.ts";
39+
import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
3740
import * as IpcChannels from "../channels.ts";
3841
import * as DesktopIpc from "../DesktopIpc.ts";
3942
import {
@@ -305,7 +308,16 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({
305308
result: Schema.Boolean,
306309
handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
307310
const shell = yield* ElectronShell.ElectronShell;
308-
return yield* shell.openSystemSettings(pane);
311+
const environment = yield* DesktopEnvironment.DesktopEnvironment;
312+
if (environment.platform !== "darwin") return false;
313+
const owner = Electron.BrowserWindow.getFocusedWindow();
314+
const opened = yield* shell.openSystemSettings(pane);
315+
if (opened && environment.isPackaged) {
316+
const permissions = yield* MacPermissions.MacPermissions;
317+
const isGranted = yield* safariPermissionCheck;
318+
yield* permissions.showHelper(pane, owner, isGranted);
319+
}
320+
return opened;
309321
}),
310322
});
311323

@@ -379,3 +391,15 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({
379391
});
380392
}),
381393
});
394+
395+
export const checkSystemPermission = DesktopIpc.makeIpcMethod({
396+
channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
397+
payload: SystemSettingsPaneSchema,
398+
result: Schema.Boolean,
399+
handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
400+
const environment = yield* DesktopEnvironment.DesktopEnvironment;
401+
if (environment.platform !== "darwin") return false;
402+
const check = yield* safariPermissionCheck;
403+
return yield* Effect.promise(check);
404+
}),
405+
});

apps/desktop/src/snapshot-permission-preload.ts renamed to apps/desktop/src/mac-permission-preload.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { ipcRenderer } from "electron";
2-
import { SNAP_SHOT_PERMISSION_HELPER_CHANNEL } from "./ipc/channels.ts";
2+
import { MAC_PERMISSION_HELPER_CHANNEL } from "./ipc/channels.ts";
33

44
// This preload belongs only to the static permission panel. No general desktop bridge is exposed.
55
window.addEventListener("DOMContentLoaded", () => {
66
const send = (action: "drag" | "finder" | "close") =>
7-
ipcRenderer.send(SNAP_SHOT_PERMISSION_HELPER_CHANNEL, action);
7+
ipcRenderer.send(MAC_PERMISSION_HELPER_CHANNEL, action);
88
document.getElementById("app")?.addEventListener("dragstart", (event) => {
99
event.preventDefault();
1010
send("drag");

‎apps/desktop/src/main.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as MacPermissions from "./permissions/MacPermissions.ts";
12
for (const stream of [process.stdout, process.stderr]) {
23
stream.on("error", (err: NodeJS.ErrnoException) => {
34
if (err.code !== "EPIPE") throw err;
@@ -133,6 +134,7 @@ const electronLayer = Layer.mergeAll(
133134
);
134135

135136
const desktopFoundationLayer = Layer.mergeAll(
137+
MacPermissions.layer,
136138
DesktopState.layer,
137139
DesktopShutdown.layer,
138140
DesktopAppSettings.layer,
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export const MAC_PERMISSION_SETTINGS_URLS = {
2+
"screen-recording":
3+
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
4+
accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
5+
"full-disk-access":
6+
"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles",
7+
};
8+
9+
export type MacPermission = keyof typeof MAC_PERMISSION_SETTINGS_URLS;
10+
11+
export const MAC_PERMISSION_TITLES: Record<MacPermission, string> = {
12+
"screen-recording": "Screen Recording",
13+
accessibility: "Accessibility",
14+
"full-disk-access": "Full Disk Access",
15+
};

apps/desktop/src/snapShot/MacPermissionHelper.test.ts renamed to apps/desktop/src/permissions/MacPermissionHelper.test.ts

Lines changed: 64 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
22
import * as Electron from "electron";
33
import { MacPermissionHelper, macAppBundlePath } from "./MacPermissionHelper.ts";
44
import type { SettingsWindow } from "./MacSettingsWindow.ts";
5-
import { SNAP_SHOT_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
5+
import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
66

77
const mocks = vi.hoisted(() => ({
88
granted: false,
@@ -109,11 +109,11 @@ afterEach(() => {
109109
});
110110
const iconPaths = ["/bundle/prod-resources/icon.png"];
111111
const open = () =>
112-
helper.show("accessibility", "/bundle/snapshot-permission-preload.cjs", null, iconPaths);
112+
helper.show("accessibility", "/bundle/mac-permission-preload.cjs", null, iconPaths);
113113
function send(action: string, trusted = true) {
114114
const window = windows.at(-1)!;
115115
Electron.ipcMain.emit(
116-
SNAP_SHOT_PERMISSION_HELPER_CHANNEL,
116+
MAC_PERMISSION_HELPER_CHANNEL,
117117
{
118118
sender: trusted ? window.webContents : {},
119119
senderFrame: window.webContents.mainFrame,
@@ -147,16 +147,16 @@ it("drags the running app bundle only for the helper's own renderer", async () =
147147
it("rechecks permissions and releases resources when granted", async () => {
148148
await open();
149149
mocks.granted = true;
150-
vi.advanceTimersByTime(1000);
150+
await vi.advanceTimersByTimeAsync(1000);
151151
expect(windows[0]!.destroyed).toBe(true);
152-
expect(Electron.ipcMain.listenerCount(SNAP_SHOT_PERMISSION_HELPER_CHANNEL)).toBe(0);
152+
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0);
153153
expect(vi.getTimerCount()).toBe(0);
154154
});
155155
it("keeps only one helper and cleans up on dismissal", async () => {
156156
await open();
157157
await helper.show("screen-recording", "/preload.cjs", null, iconPaths);
158158
expect(windows[0]!.destroyed).toBe(true);
159-
expect(Electron.ipcMain.listenerCount(SNAP_SHOT_PERMISSION_HELPER_CHANNEL)).toBe(1);
159+
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(1);
160160
send("close");
161161
expect(windows[1]!.destroyed).toBe(true);
162162
expect(vi.getTimerCount()).toBe(0);
@@ -174,7 +174,7 @@ it("does not show a helper with a missing packaged icon", async () => {
174174
it("cleans up when the helper page fails to load", async () => {
175175
mocks.loadURL.mockRejectedValueOnce(new Error("load failed"));
176176
await expect(open()).rejects.toThrow("load failed");
177-
expect(Electron.ipcMain.listenerCount(SNAP_SHOT_PERMISSION_HELPER_CHANNEL)).toBe(0);
177+
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0);
178178
expect(vi.getTimerCount()).toBe(0);
179179
});
180180

@@ -192,7 +192,7 @@ it("returns focus to onboarding when the permission is granted", async () => {
192192
const owner = new Electron.BrowserWindow({});
193193
await helper.show("screen-recording", "/preload.cjs", owner, iconPaths);
194194
mocks.granted = true;
195-
vi.advanceTimersByTime(1000);
195+
await vi.advanceTimersByTimeAsync(1000);
196196
expect(owner.show).toHaveBeenCalledOnce();
197197
expect(owner.focus).toHaveBeenCalledOnce();
198198
expect(windows[1]!.destroyed).toBe(true);
@@ -203,7 +203,7 @@ it("closes the helper and stops checking when onboarding's window closes", async
203203
await helper.show("accessibility", "/preload.cjs", owner, iconPaths);
204204
owner.destroy();
205205
expect(windows[1]!.destroyed).toBe(true);
206-
expect(Electron.ipcMain.listenerCount(SNAP_SHOT_PERMISSION_HELPER_CHANNEL)).toBe(0);
206+
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0);
207207
expect(vi.getTimerCount()).toBe(0);
208208
});
209209

@@ -257,3 +257,58 @@ it("hides on tracking failure and resumes on a valid update", async () => {
257257
mocks.settingsChanged!(state);
258258
expect(windows[0]!.showInactive).toHaveBeenCalledTimes(2);
259259
});
260+
261+
it("waits for an asynchronous Full Disk Access check and returns to the owner", async () => {
262+
const owner = new Electron.BrowserWindow();
263+
const probe = vi.fn<() => Promise<boolean>>().mockResolvedValue(false);
264+
await helper.show(
265+
"full-disk-access",
266+
"/bundle/mac-permission-preload.cjs",
267+
owner,
268+
iconPaths,
269+
probe,
270+
);
271+
const pending = Promise.withResolvers<boolean>();
272+
probe.mockReturnValue(pending.promise);
273+
await vi.advanceTimersByTimeAsync(3000);
274+
expect(probe).toHaveBeenCalledTimes(2);
275+
expect(windows[1]!.destroyed).toBe(false);
276+
pending.resolve(true);
277+
await pending.promise;
278+
expect(windows[1]!.destroyed).toBe(true);
279+
expect(owner.focus).toHaveBeenCalledOnce();
280+
expect(vi.getTimerCount()).toBe(0);
281+
});
282+
283+
it("keeps the helper open after a failed access check and retries", async () => {
284+
const probe = vi.fn<() => Promise<boolean>>().mockResolvedValue(false);
285+
await helper.show(
286+
"full-disk-access",
287+
"/bundle/mac-permission-preload.cjs",
288+
null,
289+
iconPaths,
290+
probe,
291+
);
292+
probe.mockRejectedValueOnce(new Error("temporarily unavailable"));
293+
await vi.advanceTimersByTimeAsync(1000);
294+
expect(windows[0]!.destroyed).toBe(false);
295+
probe.mockResolvedValue(true);
296+
await vi.advanceTimersByTimeAsync(1000);
297+
expect(windows[0]!.destroyed).toBe(true);
298+
});
299+
300+
it("does not reopen a superseded helper when its initial probe completes", async () => {
301+
const pending = Promise.withResolvers<boolean>();
302+
const first = helper.show(
303+
"full-disk-access",
304+
"/bundle/mac-permission-preload.cjs",
305+
null,
306+
iconPaths,
307+
() => pending.promise,
308+
);
309+
await open();
310+
pending.resolve(false);
311+
await first;
312+
expect(windows).toHaveLength(1);
313+
expect(windows[0]!.destroyed).toBe(false);
314+
});

apps/desktop/src/snapShot/MacPermissionHelper.ts renamed to apps/desktop/src/permissions/MacPermissionHelper.ts

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
// @effect-diagnostics globalTimers:off -- Poll TCC only while the native permission helper is open.
22
import * as Electron from "electron";
3-
import { SNAP_SHOT_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
3+
import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
44

55
import {
66
settingsHelperBounds,
77
watchMacSettingsWindow,
88
type SettingsWindow,
99
} from "./MacSettingsWindow.ts";
1010

11-
type Permission = "screen-recording" | "accessibility";
11+
import { MAC_PERMISSION_TITLES, type MacPermission } from "./MacPermission.ts";
1212

13-
const permissionGranted = (permission: Permission) =>
14-
permission === "screen-recording"
15-
? Electron.systemPreferences.getMediaAccessStatus("screen") === "granted"
16-
: Electron.systemPreferences.isTrustedAccessibilityClient(false);
13+
const permissionGranted = (permission: MacPermission) => {
14+
if (permission === "screen-recording")
15+
return Electron.systemPreferences.getMediaAccessStatus("screen") === "granted";
16+
if (permission === "accessibility")
17+
return Electron.systemPreferences.isTrustedAccessibilityClient(false);
18+
return false;
19+
};
1720

1821
/** Resolve the outer app bundle, never the executable or the ASAR inside it. */
1922
export function macAppBundlePath(executable: string): string | undefined {
@@ -36,8 +39,8 @@ const escapeHtml = (value: string) =>
3639
}
3740
});
3841

39-
function helperHtml(permission: Permission, icon: string) {
40-
const title = permission === "screen-recording" ? "Screen Recording" : "Accessibility";
42+
function helperHtml(permission: MacPermission, icon: string) {
43+
const title = MAC_PERMISSION_TITLES[permission];
4144
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
4245
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'">
4346
<title>Set up ${title}</title><style>
@@ -64,21 +67,26 @@ img { width: 32px; height: 32px; pointer-events: none; }
6467

6568
/** Owns one temporary panel and its IPC listener. Closing it releases all resources. */
6669
export class MacPermissionHelper {
70+
private generation = 0;
6771
private window: Electron.BrowserWindow | undefined;
6872

6973
close() {
74+
this.generation++;
7075
this.window?.destroy();
7176
this.window = undefined;
7277
}
7378

7479
async show(
75-
permission: Permission,
80+
permission: MacPermission,
7681
preload: string,
7782
owner: Electron.BrowserWindow | null,
7883
iconPaths: readonly string[],
84+
isGranted: () => boolean | Promise<boolean> = () => permissionGranted(permission),
7985
) {
8086
this.close();
81-
if (permissionGranted(permission)) return;
87+
const generation = this.generation;
88+
if (await isGranted()) return;
89+
if (generation !== this.generation) return;
8290
const bundle = macAppBundlePath(Electron.app.getPath("exe"));
8391
if (!bundle) return;
8492
if (owner?.isDestroyed()) return;
@@ -104,7 +112,7 @@ export class MacPermissionHelper {
104112
fullscreenable: false,
105113
alwaysOnTop: true,
106114
skipTaskbar: true,
107-
title: "Set up snapshots",
115+
title: `Set up ${MAC_PERMISSION_TITLES[permission]}`,
108116
webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false },
109117
});
110118
this.window = window;
@@ -115,12 +123,17 @@ export class MacPermissionHelper {
115123
owner.focus();
116124
}
117125
};
118-
const check = () => {
119-
if (!window.isDestroyed() && permissionGranted(permission)) {
120-
finish();
121-
return true;
126+
let checking = false;
127+
const check = async () => {
128+
if (checking || window.isDestroyed()) return;
129+
checking = true;
130+
try {
131+
if ((await isGranted()) && !window.isDestroyed()) finish();
132+
} catch {
133+
// An unavailable probe is not evidence of a grant; the wizard can retry.
134+
} finally {
135+
checking = false;
122136
}
123-
return false;
124137
};
125138
const onMessage = (event: Electron.IpcMainEvent, action: unknown) => {
126139
if (event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame)
@@ -169,13 +182,13 @@ export class MacPermissionHelper {
169182
let stopTracking = () => {};
170183
window.on("blur", syncPosition);
171184
const onOwnerClosed = () => window.destroy();
172-
Electron.ipcMain.on(SNAP_SHOT_PERMISSION_HELPER_CHANNEL, onMessage);
185+
Electron.ipcMain.on(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
173186
const timer = setInterval(check, 1_000);
174187
owner?.once("closed", onOwnerClosed);
175188
window.once("closed", () => {
176189
clearInterval(timer);
177190
stopTracking();
178-
Electron.ipcMain.removeListener(SNAP_SHOT_PERMISSION_HELPER_CHANNEL, onMessage);
191+
Electron.ipcMain.removeListener(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
179192
owner?.removeListener("closed", onOwnerClosed);
180193
if (this.window === window) this.window = undefined;
181194
});

0 commit comments

Comments
 (0)