feat(desktop): share macOS permission onboarding (#11289)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-11 16:42:11 -07:00
1 parent a92161a050
commit 36668dbe4f
30 files changed
+1368 -162

No files matched your search

+2 -15
View File
@@ -1,3 +1,4 @@
import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts";
import {
REMOTE_CAPABLE_EDITOR_IDS,
remoteSchemeForEditor,
@@ -10,20 +11,6 @@ import * as Option from "effect/Option";
import * as Electron from "electron";
/**
* Deep links to individual System Settings panes. These are app-fixed, not
* renderer-supplied, so they skip `parseSafeExternalUrl` — which exists to keep
* arbitrary link schemes from reaching the OS handler — and open through their
* own path below. The pane rather than the URL crosses the IPC boundary, so a
* renderer can only ask for one of these known destinations.
*
* Full Disk Access uses the post-Ventura `PrivacySecurity.extension` anchor.
*/
const SYSTEM_SETTINGS_URLS: Record<SystemSettingsPane, string> = {
"full-disk-access":
"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles",
};
// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`,
// `zed://ssh/<host>/<path>`) must reach the OS handler; every other non-web
// scheme stays blocked.
@@ -88,7 +75,7 @@ export const make = ElectronShell.of({
}),
openSystemSettings: (pane) =>
Effect.promise(() =>
Electron.shell.openExternal(SYSTEM_SETTINGS_URLS[pane]).then(
Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(
() => true,
() => false,
),
@@ -39,6 +39,7 @@ import {
getWindowFullscreenState,
openExternal,
openSystemSettings,
checkSystemPermission,
probeRemoteEditors,
pickFolder,
pickProjectFavicon,
@@ -122,6 +123,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(openSystemSettings);
yield* ipc.handle(checkSystemPermission);
yield* ipc.handle(probeRemoteEditors);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
+4
View File
@@ -105,3 +105,7 @@ export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper";
export const CHECK_SYSTEM_PERMISSION_CHANNEL = "desktop:check-system-permission";
+25 -1
View File
@@ -34,6 +34,9 @@ import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as Electron from "electron";
import * as MacPermissions from "../../permissions/MacPermissions.ts";
import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import {
@@ -305,7 +308,16 @@ export const openSystemSettings = DesktopIpc.makeIpcMethod({
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
const shell = yield* ElectronShell.ElectronShell;
return yield* shell.openSystemSettings(pane);
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.platform !== "darwin") return false;
const owner = Electron.BrowserWindow.getFocusedWindow();
const opened = yield* shell.openSystemSettings(pane);
if (opened && environment.isPackaged) {
const permissions = yield* MacPermissions.MacPermissions;
const isGranted = yield* safariPermissionCheck;
yield* permissions.showHelper(pane, owner, isGranted);
}
return opened;
}),
});
@@ -379,3 +391,15 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({
});
}),
});
export const checkSystemPermission = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
payload: SystemSettingsPaneSchema,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.platform !== "darwin") return false;
const check = yield* safariPermissionCheck;
return yield* Effect.promise(check);
}),
});
@@ -0,0 +1,17 @@
import { ipcRenderer } from "electron";
import { MAC_PERMISSION_HELPER_CHANNEL } from "./ipc/channels.ts";
// This preload belongs only to the static permission panel. No general desktop bridge is exposed.
window.addEventListener("DOMContentLoaded", () => {
const send = (action: "drag" | "finder" | "close") =>
ipcRenderer.send(MAC_PERMISSION_HELPER_CHANNEL, action);
document.getElementById("app")?.addEventListener("dragstart", (event) => {
event.preventDefault();
send("drag");
});
document.getElementById("app")?.addEventListener("click", () => send("finder"));
document.getElementById("close")?.addEventListener("click", () => send("close"));
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") send("close");
});
});
+2
View File
@@ -1,3 +1,4 @@
import * as MacPermissions from "./permissions/MacPermissions.ts";
for (const stream of [process.stdout, process.stderr]) {
stream.on("error", (err: NodeJS.ErrnoException) => {
if (err.code !== "EPIPE") throw err;
@@ -133,6 +134,7 @@ const electronLayer = Layer.mergeAll(
);
const desktopFoundationLayer = Layer.mergeAll(
MacPermissions.layer,
DesktopState.layer,
DesktopShutdown.layer,
DesktopAppSettings.layer,
@@ -0,0 +1,15 @@
export const MAC_PERMISSION_SETTINGS_URLS = {
"screen-recording":
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
"full-disk-access":
"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles",
};
export type MacPermission = keyof typeof MAC_PERMISSION_SETTINGS_URLS;
export const MAC_PERMISSION_TITLES: Record<MacPermission, string> = {
"screen-recording": "Screen Recording",
accessibility: "Accessibility",
"full-disk-access": "Full Disk Access",
};
@@ -0,0 +1,314 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as Electron from "electron";
import { MacPermissionHelper, macAppBundlePath } from "./MacPermissionHelper.ts";
import type { SettingsWindow } from "./MacSettingsWindow.ts";
import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
const mocks = vi.hoisted(() => ({
granted: false,
createFromPath: vi.fn(),
startDrag: vi.fn(),
showItemInFolder: vi.fn(),
send: vi.fn(),
loadURL: vi.fn(),
stopTracking: vi.fn(),
trackingFailed: undefined as (() => void) | undefined,
settingsChanged: undefined as ((state: SettingsWindow) => void) | undefined,
}));
const windows = vi.hoisted(
() =>
[] as Array<{
destroyed: boolean;
webContents: { mainFrame: object };
setBounds: ReturnType<typeof vi.fn>;
hide: ReturnType<typeof vi.fn>;
showInactive: ReturnType<typeof vi.fn>;
}>,
);
vi.mock("electron", async () => {
const { EventEmitter } = await import("node:events");
class MockWindow extends EventEmitter {
destroyed = false;
webContents = Object.assign(new EventEmitter(), {
mainFrame: {},
startDrag: mocks.startDrag,
send: mocks.send,
setWindowOpenHandler: vi.fn(),
});
constructor(_options: unknown) {
super();
windows.push(this);
}
isDestroyed() {
return this.destroyed;
}
destroy() {
this.destroyed = true;
this.emit("closed");
}
close() {
this.destroy();
}
loadURL = mocks.loadURL;
showInactive = vi.fn();
hide = vi.fn();
setBounds = vi.fn();
isVisible = () => false;
isFocused = () => false;
show = vi.fn();
focus = vi.fn();
getBounds = () => ({ x: 0, y: 0, width: 800, height: 600 });
}
return {
app: {
getPath: () => "/Applications/T3 Code (Nightly).app/Contents/MacOS/T3 Code",
},
nativeImage: { createFromPath: mocks.createFromPath },
BrowserWindow: class extends MockWindow {},
ipcMain: new EventEmitter(),
screen: {
getDisplayMatching: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 900 } }),
getCursorScreenPoint: () => ({ x: 10, y: 10 }),
getDisplayNearestPoint: () => ({ workArea: { x: -1200, y: 0, width: 1200, height: 900 } }),
},
systemPreferences: {
getMediaAccessStatus: () => (mocks.granted ? "granted" : "denied"),
isTrustedAccessibilityClient: () => mocks.granted,
},
shell: { showItemInFolder: mocks.showItemInFolder },
};
});
vi.mock("./MacSettingsWindow.ts", async (importOriginal) => {
const actual = await importOriginal<typeof import("./MacSettingsWindow.ts")>();
return {
...actual,
watchMacSettingsWindow: (
onChange: (state: SettingsWindow) => void,
onUnavailable: () => void,
) => {
mocks.settingsChanged = onChange;
mocks.trackingFailed = onUnavailable;
return mocks.stopTracking;
},
};
});
let helper: MacPermissionHelper;
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
mocks.granted = false;
const icon = { toDataURL: () => "data:image/png;base64,abc" };
mocks.createFromPath.mockReturnValue({ isEmpty: () => false, resize: () => icon });
mocks.loadURL.mockResolvedValue(undefined);
windows.length = 0;
helper = new MacPermissionHelper();
});
afterEach(() => {
helper.close();
vi.useRealTimers();
});
const iconPaths = ["/bundle/prod-resources/icon.png"];
const open = () =>
helper.show("accessibility", "/bundle/mac-permission-preload.cjs", null, iconPaths);
function send(action: string, trusted = true) {
const window = windows.at(-1)!;
Electron.ipcMain.emit(
MAC_PERMISSION_HELPER_CHANNEL,
{
sender: trusted ? window.webContents : {},
senderFrame: window.webContents.mainFrame,
},
action,
);
}
describe("macAppBundlePath", () => {
it("resolves bundles with spaces and refuses non-bundle executables", () => {
expect(macAppBundlePath("/Applications/T3 Code.app/Contents/MacOS/T3 Code")).toBe(
"/Applications/T3 Code.app",
);
expect(macAppBundlePath("/usr/local/bin/electron")).toBeUndefined();
expect(macAppBundlePath("/Applications/T3 Code.app/other/MacOS/T3 Code")).toBeUndefined();
});
});
it("drags the running app bundle only for the helper's own renderer", async () => {
await open();
send("drag", false);
expect(mocks.startDrag).not.toHaveBeenCalled();
send("drag");
expect(mocks.createFromPath).toHaveBeenCalledWith("/bundle/prod-resources/icon.png");
expect(mocks.startDrag).toHaveBeenCalledWith({
file: "/Applications/T3 Code (Nightly).app",
icon: mocks.createFromPath.mock.results[0]!.value.resize(),
});
send("finder");
expect(mocks.showItemInFolder).toHaveBeenCalledWith("/Applications/T3 Code (Nightly).app");
});
it("rechecks permissions and releases resources when granted", async () => {
await open();
mocks.granted = true;
await vi.advanceTimersByTimeAsync(1000);
expect(windows[0]!.destroyed).toBe(true);
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it("keeps only one helper and cleans up on dismissal", async () => {
await open();
await helper.show("screen-recording", "/preload.cjs", null, iconPaths);
expect(windows[0]!.destroyed).toBe(true);
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(1);
send("close");
expect(windows[1]!.destroyed).toBe(true);
expect(vi.getTimerCount()).toBe(0);
});
it("does not open for a permission already granted", async () => {
mocks.granted = true;
await open();
expect(windows).toHaveLength(0);
});
it("does not show a helper with a missing packaged icon", async () => {
mocks.createFromPath.mockReturnValueOnce({ isEmpty: () => true });
await expect(open()).rejects.toThrow("packaged T3 Code icon is missing");
expect(windows).toHaveLength(0);
});
it("cleans up when the helper page fails to load", async () => {
mocks.loadURL.mockRejectedValueOnce(new Error("load failed"));
await expect(open()).rejects.toThrow("load failed");
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it("offers the Finder fallback when native dragging fails", async () => {
await open();
mocks.startDrag.mockImplementationOnce(() => {
throw new Error("drag failed");
});
send("drag");
expect(mocks.showItemInFolder).toHaveBeenCalledWith("/Applications/T3 Code (Nightly).app");
expect(windows[0]!.destroyed).toBe(false);
});
it("returns focus to onboarding when the permission is granted", async () => {
const owner = new Electron.BrowserWindow({});
await helper.show("screen-recording", "/preload.cjs", owner, iconPaths);
mocks.granted = true;
await vi.advanceTimersByTimeAsync(1000);
expect(owner.show).toHaveBeenCalledOnce();
expect(owner.focus).toHaveBeenCalledOnce();
expect(windows[1]!.destroyed).toBe(true);
expect(owner.listenerCount("closed")).toBe(0);
});
it("closes the helper and stops checking when onboarding's window closes", async () => {
const owner = new Electron.BrowserWindow({});
await helper.show("accessibility", "/preload.cjs", owner, iconPaths);
owner.destroy();
expect(windows[1]!.destroyed).toBe(true);
expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it("uses the packaged PNG when an earlier resource candidate is absent", async () => {
mocks.createFromPath.mockReturnValueOnce({ isEmpty: () => true });
await helper.show("accessibility", "/preload.cjs", null, ["/missing/icon.png", ...iconPaths]);
send("drag");
expect(mocks.startDrag).toHaveBeenCalled();
expect(mocks.createFromPath).toHaveBeenLastCalledWith(iconPaths[0]);
});
it("docks inside Settings and hides when it is covered or closed", async () => {
await open();
const window = windows[0]!;
const settings = { x: 367, y: 100, width: 723, height: 719, frontmost: true };
mocks.settingsChanged!(settings);
expect(window.setBounds).toHaveBeenLastCalledWith(
{ x: 599, y: 663, width: 475, height: 140 },
false,
);
expect(window.showInactive).toHaveBeenCalledOnce();
mocks.settingsChanged!({ ...settings, x: -800, y: 200 });
expect(window.setBounds).toHaveBeenLastCalledWith(
{ x: -568, y: 763, width: 475, height: 140 },
false,
);
mocks.settingsChanged!({ ...settings, frontmost: false });
expect(window.hide).toHaveBeenCalledOnce();
mocks.settingsChanged!(null);
expect(window.destroyed).toBe(true);
helper.close();
expect(mocks.stopTracking).toHaveBeenCalledOnce();
});
it("returns to onboarding when the Settings window disappears", async () => {
const owner = new Electron.BrowserWindow({});
owner.hide();
await helper.show("accessibility", "/preload.cjs", owner, iconPaths);
mocks.settingsChanged!({ x: 100, y: 100, width: 723, height: 719, frontmost: true });
mocks.settingsChanged!(null);
expect(owner.show).toHaveBeenCalledOnce();
expect(owner.focus).toHaveBeenCalledOnce();
});
it("hides on tracking failure and resumes on a valid update", async () => {
await open();
const state = { x: 100, y: 100, width: 723, height: 719, frontmost: true };
mocks.settingsChanged!(state);
mocks.trackingFailed!();
expect(windows[0]!.destroyed).toBe(false);
expect(windows[0]!.hide).toHaveBeenCalledOnce();
mocks.settingsChanged!(state);
expect(windows[0]!.showInactive).toHaveBeenCalledTimes(2);
});
it("waits for an asynchronous Full Disk Access check and returns to the owner", async () => {
const owner = new Electron.BrowserWindow();
const probe = vi.fn<() => Promise<boolean>>().mockResolvedValue(false);
await helper.show(
"full-disk-access",
"/bundle/mac-permission-preload.cjs",
owner,
iconPaths,
probe,
);
const pending = Promise.withResolvers<boolean>();
probe.mockReturnValue(pending.promise);
await vi.advanceTimersByTimeAsync(3000);
expect(probe).toHaveBeenCalledTimes(2);
expect(windows[1]!.destroyed).toBe(false);
pending.resolve(true);
await pending.promise;
expect(windows[1]!.destroyed).toBe(true);
expect(owner.focus).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
it("keeps the helper open after a failed access check and retries", async () => {
const probe = vi.fn<() => Promise<boolean>>().mockResolvedValue(false);
await helper.show(
"full-disk-access",
"/bundle/mac-permission-preload.cjs",
null,
iconPaths,
probe,
);
probe.mockRejectedValueOnce(new Error("temporarily unavailable"));
await vi.advanceTimersByTimeAsync(1000);
expect(windows[0]!.destroyed).toBe(false);
probe.mockResolvedValue(true);
await vi.advanceTimersByTimeAsync(1000);
expect(windows[0]!.destroyed).toBe(true);
});
it("does not reopen a superseded helper when its initial probe completes", async () => {
const pending = Promise.withResolvers<boolean>();
const first = helper.show(
"full-disk-access",
"/bundle/mac-permission-preload.cjs",
null,
iconPaths,
() => pending.promise,
);
await open();
pending.resolve(false);
await first;
expect(windows).toHaveLength(1);
expect(windows[0]!.destroyed).toBe(false);
});
@@ -0,0 +1,220 @@
// @effect-diagnostics globalTimers:off -- Poll TCC only while the native permission helper is open.
import * as Electron from "electron";
import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
import {
settingsHelperBounds,
watchMacSettingsWindow,
type SettingsWindow,
} from "./MacSettingsWindow.ts";
import { MAC_PERMISSION_TITLES, type MacPermission } from "./MacPermission.ts";
const permissionGranted = (permission: MacPermission) => {
if (permission === "screen-recording")
return Electron.systemPreferences.getMediaAccessStatus("screen") === "granted";
if (permission === "accessibility")
return Electron.systemPreferences.isTrustedAccessibilityClient(false);
return false;
};
/** Resolve the outer app bundle, never the executable or the ASAR inside it. */
export function macAppBundlePath(executable: string): string | undefined {
return /^(.+\.app)\/Contents\/MacOS\/[^/]+$/.exec(executable)?.[1];
}
const escapeHtml = (value: string) =>
value.replace(/[&<>"']/g, (character) => {
switch (character) {
case "&":
return "&amp;";
case "<":
return "&lt;";
case ">":
return "&gt;";
case '"':
return "&quot;";
default:
return "&#39;";
}
});
function helperHtml(permission: MacPermission, icon: string) {
const title = MAC_PERMISSION_TITLES[permission];
return `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'">
<title>Set up ${title}</title><style>
:root { color-scheme: light dark; --base: #fff; --row: #e7e7e7; --text: #292929; --line: #e3e3e3; }
@media (prefers-color-scheme: dark) { :root { --base: #242424; --row: #383838; --text: #f5f5f5; --line: #484848; } }
* { box-sizing: border-box; }
html { background: transparent; }
body { margin: 0; background: transparent; color: var(--text); font: 15px/22px -apple-system, BlinkMacSystemFont, sans-serif; user-select: none; }
#panel { position: relative; margin: 2px; padding: 20px; height: 136px; border: 1px solid var(--line); border-radius: 24px; background: var(--base); }
header { font-weight: 600; white-space: nowrap; }
button { font: inherit; color: inherit; }
button:focus-visible { outline: 2px solid #007aff; outline-offset: 3px; }
#close { position: absolute; right: 8px; top: 6px; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: var(--base); font-size: 18px; cursor: pointer; opacity: 0; }
#panel:hover #close, #close:focus-visible { opacity: 1; }
#app { display: flex; align-items: center; gap: 12px; width: 100%; height: 52px; margin-top: 20px; padding: 8px 12px; border: 0; border-radius: 10px; background: var(--row); cursor: grab; text-align: left; font-size: 16px; font-weight: 600; }
#app:active { cursor: grabbing; }
img { width: 32px; height: 32px; pointer-events: none; }
</style></head><body><main id="panel">
<button id="close" aria-label="Close permission helper">×</button>
<header>↑ Drag T3 Code into the list above</header>
<button id="app" draggable="true" aria-label="Drag T3 Code to System Settings, or click to reveal in Finder"><img src="${escapeHtml(icon)}" alt="" draggable="false">T3 Code</button>
</main></body></html>`;
}
/** Owns one temporary panel and its IPC listener. Closing it releases all resources. */
export class MacPermissionHelper {
private generation = 0;
private window: Electron.BrowserWindow | undefined;
close() {
this.generation++;
this.window?.destroy();
this.window = undefined;
}
async show(
permission: MacPermission,
preload: string,
owner: Electron.BrowserWindow | null,
iconPaths: readonly string[],
isGranted: () => boolean | Promise<boolean> = () => permissionGranted(permission),
) {
this.close();
const generation = this.generation;
if (await isGranted()) return;
if (generation !== this.generation) return;
const bundle = macAppBundlePath(Electron.app.getPath("exe"));
if (!bundle) return;
if (owner?.isDestroyed()) return;
// Finder's bundle-icon lookup can return the generic app icon for mounted artifacts.
// Use the same PNG that packaging uses to generate the app's macOS icon.
const appIcon = iconPaths
.map((iconPath) => Electron.nativeImage.createFromPath(iconPath))
.find((image) => !image.isEmpty());
if (!appIcon) throw new Error("The packaged T3 Code icon is missing.");
const icon = appIcon.resize({ width: 64, height: 64 });
const window = new Electron.BrowserWindow({
width: 560,
height: 140,
show: false,
frame: false,
transparent: true,
roundedCorners: false,
backgroundColor: "#00000000",
hasShadow: false,
resizable: false,
minimizable: false,
maximizable: false,
fullscreenable: false,
alwaysOnTop: true,
skipTaskbar: true,
title: `Set up ${MAC_PERMISSION_TITLES[permission]}`,
webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false },
});
this.window = window;
const finish = () => {
window.close();
if (owner && !owner.isDestroyed()) {
owner.show();
owner.focus();
}
};
let checking = false;
const check = async () => {
if (checking || window.isDestroyed()) return;
checking = true;
try {
if ((await isGranted()) && !window.isDestroyed()) finish();
} catch {
// An unavailable probe is not evidence of a grant; the wizard can retry.
} finally {
checking = false;
}
};
const onMessage = (event: Electron.IpcMainEvent, action: unknown) => {
if (event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame)
return;
if (action === "drag") {
try {
window.webContents.startDrag({ file: bundle, icon });
} catch {
Electron.shell.showItemInFolder(bundle);
}
} else if (action === "finder") {
Electron.shell.showItemInFolder(bundle);
} else if (action === "close") {
finish();
}
};
let settingsWindow: SettingsWindow = null;
let foundSettings = false;
let trackingAvailable = true;
const syncPosition = () => {
if (window.isDestroyed()) return;
if (!trackingAvailable) {
window.hide();
return;
}
if (!settingsWindow && foundSettings) {
finish();
return;
}
if (!settingsWindow || (!settingsWindow.frontmost && !window.isFocused())) {
window.hide();
return;
}
const bounds = settingsHelperBounds(settingsWindow);
const current = window.getBounds();
if (
current.x !== bounds.x ||
current.y !== bounds.y ||
current.width !== bounds.width ||
current.height !== bounds.height
) {
window.setBounds(bounds, false);
}
if (!window.isVisible()) window.showInactive();
};
let stopTracking = () => {};
window.on("blur", syncPosition);
const onOwnerClosed = () => window.destroy();
Electron.ipcMain.on(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
const timer = setInterval(check, 1_000);
owner?.once("closed", onOwnerClosed);
window.once("closed", () => {
clearInterval(timer);
stopTracking();
Electron.ipcMain.removeListener(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
owner?.removeListener("closed", onOwnerClosed);
if (this.window === window) this.window = undefined;
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.webContents.on("will-navigate", (event) => event.preventDefault());
try {
await window.loadURL(
`data:text/html;charset=utf-8,${encodeURIComponent(helperHtml(permission, icon.toDataURL()))}`,
);
if (!window.isDestroyed()) {
stopTracking = watchMacSettingsWindow(
(current) => {
trackingAvailable = true;
settingsWindow = current;
if (current) foundSettings = true;
syncPosition();
},
() => {
trackingAvailable = false;
syncPosition();
},
);
}
} catch (error) {
if (!window.isDestroyed()) window.destroy();
throw error;
}
}
}
@@ -0,0 +1,45 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Electron from "electron";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { MacPermissionHelper } from "./MacPermissionHelper.ts";
import type { MacPermission } from "./MacPermission.ts";
export class MacPermissions extends Context.Service<
MacPermissions,
{
readonly showHelper: (
permission: MacPermission,
owner: Electron.BrowserWindow | null,
isGranted?: () => boolean | Promise<boolean>,
) => Effect.Effect<void>;
}
>()("@t3tools/desktop/permissions/MacPermissions") {}
export const layer = Layer.effect(
MacPermissions,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const path = yield* Path.Path;
const helper = new MacPermissionHelper();
yield* Effect.addFinalizer(() => Effect.sync(() => helper.close()));
return MacPermissions.of({
showHelper: Effect.fn("MacPermissions.showHelper")(function* (permission, owner, isGranted) {
if (environment.platform !== "darwin" || !environment.isPackaged) return;
yield* Effect.tryPromise(() =>
helper.show(
permission,
path.join(environment.dirname, "mac-permission-preload.cjs"),
owner,
environment.resolveResourcePathCandidates("icon.png"),
isGranted,
),
).pipe(
Effect.catch((cause) => Effect.logWarning("Could not show permission helper", cause)),
);
}),
});
}),
);
@@ -0,0 +1,55 @@
import * as NodeEvents from "node:events";
import { beforeEach, expect, it, vi } from "vite-plus/test";
import { settingsHelperBounds, watchMacSettingsWindow } from "./MacSettingsWindow.ts";
const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
let child: NodeEvents.EventEmitter & {
stdout: NodeEvents.EventEmitter & { setEncoding: ReturnType<typeof vi.fn> };
kill: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
child = Object.assign(new NodeEvents.EventEmitter(), {
stdout: Object.assign(new NodeEvents.EventEmitter(), { setEncoding: vi.fn() }),
kill: vi.fn(),
});
mocks.spawn.mockReturnValue(child);
});
it("places the helper inside small and large Settings windows across displays", () => {
for (const x of [-900, 20]) {
for (const width of [668, 1000]) {
const state = { x, y: 30, width, height: 700, frontmost: true };
const helper = settingsHelperBounds(state);
expect(helper.x).toBeGreaterThanOrEqual(x + 216);
expect(helper.x + helper.width).toBeLessThanOrEqual(x + width - 16);
expect(helper.y + helper.height).toBe(714);
}
}
});
it("decodes partial updates and stops the one watcher process on disposal", () => {
const changed = vi.fn();
const unavailable = vi.fn();
const stop = watchMacSettingsWindow(changed, unavailable);
const state = { x: 10, y: 20, width: 723, height: 719, frontmost: true };
const line = JSON.stringify(state);
child.stdout.emit("data", line.slice(0, 8));
expect(changed).not.toHaveBeenCalled();
child.stdout.emit("data", line.slice(8) + "\nnull\n");
expect(changed.mock.calls).toEqual([[state], [null]]);
stop();
expect(child.kill).toHaveBeenCalledOnce();
child.emit("exit", 0);
expect(changed).toHaveBeenCalledTimes(2);
});
it("distinguishes unavailable tracking from a valid absent window", () => {
const changed = vi.fn();
const unavailable = vi.fn();
const stop = watchMacSettingsWindow(changed, unavailable);
child.stdout.emit("data", '{"x":"bad"}\n');
expect(changed).not.toHaveBeenCalled();
expect(unavailable).toHaveBeenCalledOnce();
child.emit("error", new Error("spawn failed"));
expect(changed).not.toHaveBeenCalled();
expect(unavailable).toHaveBeenCalledTimes(2);
stop();
});
@@ -0,0 +1,114 @@
// @effect-diagnostics nodeBuiltinImport:off -- This native boundary keeps one JXA process open while the permission helper tracks System Settings.
import * as NodeChildProcess from "node:child_process";
import * as Schema from "effect/Schema";
import type * as Electron from "electron";
const SettingsWindow = Schema.NullOr(
Schema.Struct({
x: Schema.Finite,
y: Schema.Finite,
width: Schema.Finite,
height: Schema.Finite,
frontmost: Schema.Boolean,
}),
);
export type SettingsWindow = typeof SettingsWindow.Type;
const decodeSettingsWindow = Schema.decodeUnknownSync(Schema.fromJsonString(SettingsWindow));
// Window bounds and owner PIDs are available before Screen Recording is granted.
// Use the bundle identifier rather than the localized app/window title. A single
// process avoids launching osascript repeatedly while the user moves Settings.
const SETTINGS_WINDOW_SCRIPT = `
ObjC.import("CoreGraphics");
ObjC.import("AppKit");
function run() {
let previous = "";
while (true) {
const apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier("com.apple.systempreferences");
let result = null;
if (apps.count > 0) {
const pid = apps.objectAtIndex(0).processIdentifier;
const front = $.NSWorkspace.sharedWorkspace.frontmostApplication;
const list = $.CGWindowListCopyWindowInfo(
$.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements,
$.kCGNullWindowID
);
if (list) {
$.CFMakeCollectable(list);
const count = $.CFArrayGetCount(list);
for (let i = 0; i < count; i++) {
const w = ObjC.castRefToObject($.CFArrayGetValueAtIndex(list, i));
if (w.objectForKey("kCGWindowOwnerPID").js !== pid || w.objectForKey("kCGWindowLayer").js !== 0) continue;
const b = ObjC.deepUnwrap(w.objectForKey("kCGWindowBounds"));
if (b.Width < 500 || b.Height < 350) continue;
result = { x: b.X, y: b.Y, width: b.Width, height: b.Height, frontmost: !front.isNil() && front.processIdentifier === pid };
break;
}
}
}
const line = JSON.stringify(result);
if (line !== previous) {
const data = $(line + "\\n").dataUsingEncoding($.NSUTF8StringEncoding);
$.NSFileHandle.fileHandleWithStandardOutput.writeData(data);
previous = line;
}
$.NSThread.sleepForTimeInterval(result && result.frontmost ? 0.5 : 1);
}
}`;
/** Place the panel inside Settings' content column, above its bottom edge. */
export function settingsHelperBounds(settings: NonNullable<SettingsWindow>): Electron.Rectangle {
const sidebarWidth = 216;
const inset = 16;
const width = Math.min(560, settings.width - sidebarWidth - inset * 2);
return {
x: Math.round(settings.x + sidebarWidth + (settings.width - sidebarWidth - width) / 2),
y: Math.round(settings.y + settings.height - 140 - inset),
width: Math.round(width),
height: 140,
};
}
/** Track only metadata; this does not request Accessibility or Screen Recording. */
export function watchMacSettingsWindow(
onChange: (window: SettingsWindow) => void,
onUnavailable: () => void,
): () => void {
const child = NodeChildProcess.spawn(
"/usr/bin/osascript",
["-l", "JavaScript", "-e", SETTINGS_WINDOW_SCRIPT],
{
stdio: ["ignore", "pipe", "ignore"],
},
);
let pending = "";
let closed = false;
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => {
pending += chunk;
let end: number;
while ((end = pending.indexOf("\n")) !== -1) {
const line = pending.slice(0, end);
pending = pending.slice(end + 1);
if (closed) return;
let settings: SettingsWindow;
try {
settings = decodeSettingsWindow(line);
} catch {
onUnavailable();
continue;
}
onChange(settings);
}
});
const onExit = () => {
if (!closed) onUnavailable();
};
child.on("error", onExit);
child.on("exit", onExit);
return () => {
closed = true;
child.stdout.removeAllListeners("data");
child.kill();
};
}
+2
View File
@@ -152,6 +152,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
checkSystemPermission: (pane: string) =>
ipcRenderer.invoke(IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL, pane),
openSystemSettings: (pane: string) =>
ipcRenderer.invoke(IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL, pane),
probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined),
@@ -11,6 +11,7 @@ import {
parseBinaryCookies,
readSafariCookies,
safariAccessDenied,
safariAccessGranted,
SafariCookieReadError,
} from "./SafariCookies.ts";
@@ -441,3 +442,36 @@ describe("isPermissionDenied", () => {
expect(isPermissionDenied(platformError("Unknown", "EIO"))).toBe(false);
});
});
describe("safariAccessGranted", () => {
it.effect("only reports a successful read-only open as granted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-safari-permission-",
});
const jar = `${directory}/Cookies.binarycookies`;
assert.isFalse(yield* safariAccessGranted(jar));
yield* fileSystem.writeFileString(jar, "no cookie parsing needed");
assert.isTrue(yield* safariAccessGranted(jar));
yield* fileSystem.remove(jar);
assert.isFalse(yield* safariAccessGranted(jar));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("does not mistake TCC denial for a grant", () =>
Effect.gen(function* () {
const denied = PlatformError.systemError({
_tag: "Unknown",
module: "FileSystem",
method: "open",
cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }),
});
assert.isFalse(
yield* safariAccessGranted("/protected/Cookies.binarycookies").pipe(
Effect.provide(FileSystem.layerNoop({ open: () => Effect.fail(denied) })),
),
);
}),
);
});
@@ -225,6 +225,16 @@ export const safariAccessDenied = Effect.fnUntraced(function* (cookiePath: strin
);
});
/** A missing or unreadable jar is never evidence that access was granted. */
export const safariAccessGranted = Effect.fnUntraced(function* (cookiePath: string) {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
Effect.scoped,
);
});
export const readSafariCookies = Effect.fn("SafariCookies.readSafariCookies")(function* (
cookiePath: string,
) {
@@ -0,0 +1,59 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as PlatformError from "effect/PlatformError";
import { safariPermissionCheck } from "./SafariPermission.ts";
it.effect("detects Safari access becoming available without reading or importing cookies", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-safari-access-" });
const directory = `${home}/Library/Containers/com.apple.Safari/Data/Library/Cookies`;
yield* fs.makeDirectory(directory, { recursive: true });
const jar = `${directory}/Cookies.binarycookies`;
yield* fs.writeFileString(jar, "not a valid cookie database");
let allowed = false;
const guardedFs = FileSystem.FileSystem.of({
...fs,
open: (path, options) =>
allowed
? fs.open(path, options)
: Effect.fail(
PlatformError.systemError({
_tag: "Unknown",
module: "FileSystem",
method: "open",
cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }),
}),
),
});
const check = yield* safariPermissionCheck.pipe(
Effect.provideService(HostProcessEnvironment, { HOME: home }),
Effect.provideService(HostProcessPlatform, "darwin"),
Effect.provideService(FileSystem.FileSystem, guardedFs),
);
assert.isFalse(yield* Effect.promise(check));
allowed = true;
assert.isTrue(yield* Effect.promise(check));
yield* fs.remove(jar);
assert.isFalse(yield* Effect.promise(check));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("recognizes access when cookies exist only in a named Safari profile", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-safari-named-access-" });
const check = yield* safariPermissionCheck.pipe(
Effect.provideService(HostProcessEnvironment, { HOME: home }),
Effect.provideService(HostProcessPlatform, "darwin"),
);
assert.isFalse(yield* Effect.promise(check));
const directory = `${home}/Library/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteDataStore/12345678-1234-1234-1234-123456789abc/Cookies`;
yield* fs.makeDirectory(directory, { recursive: true });
yield* fs.writeFileString(`${directory}/Cookies.binarycookies`, "not parsed");
assert.isTrue(yield* Effect.promise(check));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
@@ -0,0 +1,31 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { safariAccessGranted } from "./SafariCookies.ts";
import {
BROWSER_IMPORT_SOURCES,
resolveCookieDatabase,
listSourceProfiles,
sourcePathContext,
} from "./Sources.ts";
export const safariPermissionCheck = Effect.gen(function* () {
const context = yield* sourcePathContext;
const services = yield* Effect.context<FileSystem.FileSystem>();
const runPromise = Effect.runPromiseWith(services);
const safari = BROWSER_IMPORT_SOURCES.find((source) => source.engine === "safari");
const check = Effect.gen(function* () {
if (!safari || context.platform !== "darwin") return false;
const defaultJar = yield* resolveCookieDatabase(safari, context, ".");
if (defaultJar !== undefined) return yield* safariAccessGranted(defaultJar);
// A Safari installation can have cookies only in a named profile. Rediscover
// those stores after a grant, since TCC may have hidden their metadata before.
const profiles = yield* listSourceProfiles(safari, context);
for (const profile of profiles) {
const jar = yield* resolveCookieDatabase(safari, context, profile.directory);
if (jar !== undefined && (yield* safariAccessGranted(jar))) return true;
}
return false;
});
// Open and close the jar without reading cookies or attempting an import.
return () => runPromise(check);
});
@@ -1,3 +1,4 @@
import * as MacPermissions from "../permissions/MacPermissions.ts";
import { assert, it } from "@effect/vitest";
import {
DEFAULT_CLIENT_SETTINGS,
@@ -488,41 +489,45 @@ const testLayer = (
DesktopClientSettings.DesktopClientSettingsReadError
> = Effect.succeed(initialSettings),
) =>
Layer.mergeAll(
Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({
platform,
stateDir: "/state",
linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
appRoot: "/repo",
linuxApplicationsDir: "/test-data/applications",
} as DesktopEnvironment.DesktopEnvironment["Service"]),
),
Layer.succeed(
DesktopClientSettings.DesktopClientSettings,
DesktopClientSettings.DesktopClientSettings.of({
get: settingsGet,
set: () => Effect.void,
}),
),
Layer.succeed(
DesktopWindow.DesktopWindow,
DesktopWindow.DesktopWindow.of({
activate: Effect.void,
prepareCaptureReveal: Effect.sync(prepareCaptureRevealMock),
dispatchMenuAction: () => Effect.void,
dispatchSnapShotEvent: () => Effect.void,
} as unknown as DesktopWindow.DesktopWindow["Service"]),
),
FileSystem.layerNoop(fileSystemOverrides),
Path.layer,
Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size),
digest: (_algorithm, data) => Effect.succeed(data),
}),
MacPermissions.layer.pipe(
Layer.provideMerge(
Layer.mergeAll(
Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({
platform,
stateDir: "/state",
linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
appRoot: "/repo",
linuxApplicationsDir: "/test-data/applications",
} as DesktopEnvironment.DesktopEnvironment["Service"]),
),
Layer.succeed(
DesktopClientSettings.DesktopClientSettings,
DesktopClientSettings.DesktopClientSettings.of({
get: settingsGet,
set: () => Effect.void,
}),
),
Layer.succeed(
DesktopWindow.DesktopWindow,
DesktopWindow.DesktopWindow.of({
activate: Effect.void,
prepareCaptureReveal: Effect.sync(prepareCaptureRevealMock),
dispatchMenuAction: () => Effect.void,
dispatchSnapShotEvent: () => Effect.void,
} as unknown as DesktopWindow.DesktopWindow["Service"]),
),
FileSystem.layerNoop(fileSystemOverrides),
Path.layer,
Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size),
digest: (_algorithm, data) => Effect.succeed(data),
}),
),
),
),
);
+39 -13
View File
@@ -76,6 +76,8 @@ import {
type AccessibilityProcessPool,
makeSnapShotAccessibilityProcessPool,
} from "./SnapShotAccessibilityProcess.ts";
import * as MacPermissions from "../permissions/MacPermissions.ts";
import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts";
import { showWindowsCaptureOverlay } from "./WindowsCaptureFeedback.ts";
import {
@@ -96,8 +98,7 @@ const FLASH_ANIMATION_DURATION_MS = 180;
const FLASH_STATIC_DURATION_MS = 60;
const FLASH_FRAME_INTERVAL_MS = 16;
const FLASH_PEAK_OPACITY = 0.08;
const MAC_SCREEN_CAPTURE_SETTINGS_URL =
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture";
const MAC_SCREEN_CAPTURE_SETTINGS_URL = MAC_PERMISSION_SETTINGS_URLS["screen-recording"];
const MAC_SCREEN_CAPTURE_PERMISSION_MESSAGE =
"Allow Screen Recording in System Settings, then restart T3 Code.";
const MAC_ACCESSIBILITY_PERMISSION_MESSAGE =
@@ -704,6 +705,7 @@ function probeGlobalShortcut(accelerator: string): DesktopSnapShotShortcutAvaila
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const permissions = yield* MacPermissions.MacPermissions;
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const fileSystem = yield* FileSystem.FileSystem;
@@ -1300,14 +1302,26 @@ export const make = Effect.gen(function* () {
yield* configurationMutex.withPermits(1)(applySettings(settings, null));
});
const requestPermissions = (includeAccessibility: boolean) =>
configurationMutex.withPermits(1)(
environment.platform === "darwin"
? Effect.promise(() => requestMacSnapShotPermissions(includeAccessibility)).pipe(
Effect.asVoid,
)
: Effect.void,
);
const requestPermissions = Effect.fn("desktop.snapShot.requestPermissions")(function* (
includeAccessibility: boolean,
) {
if (environment.platform !== "darwin") return;
const owner = Electron.BrowserWindow.getFocusedWindow();
yield* Effect.promise(() => requestMacSnapShotPermissions(includeAccessibility));
if (Electron.systemPreferences.getMediaAccessStatus("screen") !== "granted") {
yield* permissions.showHelper("screen-recording", owner);
} else if (
includeAccessibility &&
!Electron.systemPreferences.isTrustedAccessibilityClient(false)
) {
yield* Effect.promise(() =>
Electron.shell
.openExternal(MAC_PERMISSION_SETTINGS_URLS.accessibility)
.catch(() => undefined),
);
yield* permissions.showHelper("accessibility", owner);
}
}, configurationMutex.withPermits(1));
const setup = Effect.fn("desktop.snapShot.setup")(function* (action: DesktopSnapShotSetupAction) {
if (action === "test-mac-capture") {
@@ -1372,9 +1386,21 @@ export const make = Effect.gen(function* () {
action,
reason: "unsupported-session",
});
if (action === "allow-accessibility")
Electron.systemPreferences.isTrustedAccessibilityClient(true);
else yield* Effect.promise(requestMacScreenCapturePermission);
const owner = Electron.BrowserWindow.getFocusedWindow();
if (action === "allow-accessibility") {
const granted = Electron.systemPreferences.isTrustedAccessibilityClient(true);
if (!granted && environment.isPackaged) {
yield* Effect.promise(() =>
Electron.shell
.openExternal(MAC_PERMISSION_SETTINGS_URLS.accessibility)
.catch(() => undefined),
);
}
} else yield* Effect.promise(requestMacScreenCapturePermission);
yield* permissions.showHelper(
action === "allow-accessibility" ? "accessibility" : "screen-recording",
owner,
);
} else if (action !== "retry-shortcut") {
if (!hasGnomeSetup())
return yield* new DesktopSnapShotSetupError({
+9
View File
@@ -93,6 +93,15 @@ export default defineConfig({
outExtensions: () => ({ js: ".cjs" }),
entry: ["src/preview-pip-preload.ts"],
},
{
// Sandboxed preloads must be self-contained, without shared runtime chunks.
format: "cjs",
outDir: "dist-electron",
dts: false,
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
entry: ["src/mac-permission-preload.ts"],
},
],
test: {
// The Windows lane runs workspace suites concurrently; filesystem-heavy
@@ -0,0 +1,57 @@
import { CircleCheckIcon } from "lucide-react";
import type { ComponentProps, ReactNode } from "react";
import { Button } from "../ui/button";
export interface PermissionItem {
id: string;
icon: ReactNode;
title: string;
description: string;
granted: boolean;
onAllow: () => void;
}
export function PermissionChecklist({
permissions,
busy = false,
}: {
permissions: readonly PermissionItem[];
busy?: boolean;
}) {
return (
<div className="space-y-2">
{permissions.map((permission) => (
<div key={permission.id} className="flex items-center gap-3 rounded-lg border px-3 py-2">
{permission.icon}
<div className="min-w-0 flex-1">
<p className="font-medium">{permission.title}</p>
<p className="text-xs text-muted-foreground">{permission.description}</p>
</div>
{permission.granted ? (
<span role="status" className="flex items-center gap-1 text-xs text-success">
<CircleCheckIcon className="size-4" aria-hidden="true" />
Allowed
</span>
) : (
<Button size="xs" variant="outline" disabled={busy} onClick={permission.onAllow}>
Allow
</Button>
)}
</div>
))}
</div>
);
}
export function PermissionContinueButton({
ready,
busy = false,
children = "Continue",
...props
}: Omit<ComponentProps<typeof Button>, "disabled"> & { ready: boolean; busy?: boolean }) {
return (
<Button {...props} disabled={!ready || busy}>
{children}
</Button>
);
}
@@ -0,0 +1,96 @@
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
import { usePermissionStatus } from "./usePermissionStatus";
const effects = vi.hoisted(() => [] as Array<() => (() => void) | undefined>);
vi.mock("react", async (original) => {
const actual = await original<typeof import("react")>();
const { reactHookHarness } = await import("../../test/reactHookHarness");
return {
...actual,
useState: reactHookHarness.useState,
useEffect: (effect: () => (() => void) | undefined) => effects.push(effect),
useEffectEvent: <T>(callback: T) => callback,
};
});
vi.mock("react/compiler-runtime", async () => {
const { reactHookHarness } = await import("../../test/reactHookHarness");
return { c: reactHookHarness.useMemoCache };
});
const check = vi.fn<() => Promise<{ screen: boolean; accessibility: boolean }>>();
let cleanup: (() => void) | undefined;
let page: EventTarget & { visibilityState: string };
const render = () => {
hooks.beginRender();
return usePermissionStatus(check, { screen: false, accessibility: false });
};
beforeEach(() => {
hooks.reset();
effects.length = 0;
vi.useFakeTimers();
page = Object.assign(new EventTarget(), { visibilityState: "visible" });
vi.stubGlobal("document", page);
vi.stubGlobal("window", Object.assign(new EventTarget(), { setInterval, clearInterval }));
check.mockReset().mockResolvedValue({ screen: false, accessibility: false });
});
afterEach(() => {
cleanup?.();
vi.useRealTimers();
vi.unstubAllGlobals();
});
const start = async () => {
render();
cleanup = effects[0]!();
await Promise.resolve();
};
it("unlocks Continue only for required grants and relocks on revocation", async () => {
await start();
expect(render().isReady(["screen"])).toBe(false);
check.mockResolvedValue({ screen: true, accessibility: false });
await vi.advanceTimersByTimeAsync(1500);
expect(render().isReady(["screen"])).toBe(true);
expect(render().isReady(["screen", "accessibility"])).toBe(false);
check.mockResolvedValue({ screen: true, accessibility: true });
await vi.advanceTimersByTimeAsync(1500);
expect(render().isReady(["screen", "accessibility"])).toBe(true);
check.mockResolvedValue({ screen: false, accessibility: true });
window.dispatchEvent(new Event("focus"));
await Promise.resolve();
expect(render().isReady(["screen"])).toBe(false);
});
it("does not overlap checks and discards completion after closing", async () => {
let resolve!: (status: { screen: boolean; accessibility: boolean }) => void;
const promise = new Promise<{ screen: boolean; accessibility: boolean }>((done) => {
resolve = done;
});
const pending = { promise, resolve };
check.mockReturnValue(pending.promise);
await start();
await vi.advanceTimersByTimeAsync(4500);
window.dispatchEvent(new Event("focus"));
expect(check).toHaveBeenCalledTimes(1);
cleanup?.();
pending.resolve({ screen: true, accessibility: true });
await pending.promise;
expect(render().isReady(["screen"])).toBe(false);
expect(vi.getTimerCount()).toBe(0);
});
it("pauses in the background and blocks stale grants after a check failure", async () => {
check.mockResolvedValue({ screen: true, accessibility: true });
await start();
expect(render().isReady(["screen"])).toBe(true);
page.visibilityState = "hidden";
await vi.advanceTimersByTimeAsync(3000);
expect(check).toHaveBeenCalledTimes(1);
check.mockRejectedValue(new Error("IPC unavailable"));
page.visibilityState = "visible";
page.dispatchEvent(new Event("visibilitychange"));
await Promise.resolve();
expect(render().isReady(["screen"])).toBe(false);
check.mockResolvedValue({ screen: true, accessibility: true });
await vi.advanceTimersByTimeAsync(1500);
expect(render().isReady(["screen"])).toBe(true);
});
@@ -0,0 +1,45 @@
import { useEffect, useEffectEvent, useState } from "react";
export function usePermissionStatus<Id extends string>(
check: () => Promise<Record<Id, boolean>>,
initialStatus: Record<Id, boolean>,
enabled = true,
) {
const [status, setStatus] = useState(initialStatus);
const [error, setError] = useState<string | null>(null);
const checkLatest = useEffectEvent(check);
useEffect(() => {
if (!enabled) return;
let disposed = false;
let checking = false;
const refresh = async () => {
if (disposed || checking || document.visibilityState === "hidden") return;
checking = true;
try {
const next = await checkLatest();
if (!disposed) {
setStatus(next);
setError(null);
}
} catch {
if (!disposed) setError("Could not check permissions. We'll try again automatically.");
}
checking = false;
};
void refresh();
const timer = window.setInterval(() => void refresh(), 1500);
window.addEventListener("focus", refresh);
document.addEventListener("visibilitychange", refresh);
return () => {
disposed = true;
window.clearInterval(timer);
window.removeEventListener("focus", refresh);
document.removeEventListener("visibilitychange", refresh);
};
}, [enabled]);
return {
status,
error,
isReady: (required: readonly Id[]) => error === null && required.every((id) => status[id]),
};
}
@@ -1,6 +1,8 @@
import { PermissionChecklist, PermissionContinueButton } from "../permissions/PermissionChecklist";
import { usePermissionStatus } from "../permissions/usePermissionStatus";
import type { BrowserImportSource } from "@t3tools/contracts";
import { BROWSER_IMPORT_FAILURE_COPY } from "@t3tools/contracts";
import { ArrowDownIcon, ArrowRightIcon, CheckIcon } from "lucide-react";
import { ArrowDownIcon, ArrowRightIcon, CheckIcon, HardDriveIcon } from "lucide-react";
import { useRef, useState } from "react";
import { cn, randomUUID } from "~/lib/utils";
@@ -57,7 +59,8 @@ interface BrowserImportWizardProps {
/** Re-checks the source's availability after the user quits the browser. */
readonly onRefreshSource: () => Promise<BrowserImportSource | undefined>;
/** Opens the OS setting that grants access to a protected cookie store. */
readonly onOpenFullDiskAccessSettings: () => void;
readonly onOpenFullDiskAccessSettings: () => void | Promise<void>;
readonly onCheckFullDiskAccess?: (() => Promise<boolean>) | undefined;
readonly onClose: () => void;
}
@@ -76,6 +79,7 @@ export function BrowserImportWizard({
onImport,
onRefreshSource,
onOpenFullDiskAccessSettings,
onCheckFullDiskAccess,
onClose,
}: BrowserImportWizardProps) {
const [source, setSource] = useState(initialSource);
@@ -147,6 +151,13 @@ export function BrowserImportWizard({
source={source}
onCancel={onClose}
onOpenSettings={onOpenFullDiskAccessSettings}
onCheck={
onCheckFullDiskAccess ??
(async () => {
const refreshed = await onRefreshSource();
return refreshed !== undefined && refreshed.unavailable === undefined;
})
}
onGranted={step.resume === "import" ? runImport : recheckFullDiskAccess}
stillRequired={step.checked === true}
/>
@@ -248,13 +259,29 @@ function FullDiskAccessStep({
onOpenSettings,
onGranted,
stillRequired,
onCheck,
}: {
readonly source: BrowserImportSource;
readonly onCancel: () => void;
readonly onOpenSettings: () => void;
readonly onOpenSettings: () => void | Promise<void>;
readonly onCheck: () => Promise<boolean>;
readonly onGranted: () => void;
readonly stillRequired: boolean;
}) {
const [opening, setOpening] = useState(false);
const [openingError, setOpeningError] = useState<string | null>(null);
const permission = usePermissionStatus(async () => ({ fullDiskAccess: await onCheck() }), {
fullDiskAccess: false,
});
const allow = () => {
if (opening) return;
setOpening(true);
setOpeningError(null);
void Promise.resolve()
.then(onOpenSettings)
.catch(() => setOpeningError("Could not open System Settings. Try Allow again."))
.finally(() => setOpening(false));
};
return (
<>
<DialogHeader>
@@ -265,22 +292,49 @@ function FullDiskAccessStep({
done.
</DialogDescription>
</DialogHeader>
{stillRequired ? (
<DialogPanel>
<p role="status" className="text-sm text-muted-foreground">
Full Disk Access is still required. If you just turned it on, quit and reopen T3 Code,
then try again.
<DialogPanel>
<PermissionChecklist
busy={opening}
permissions={[
{
id: "fullDiskAccess",
icon: (
<HardDriveIcon
className="size-8 shrink-0 text-muted-foreground"
aria-hidden="true"
/>
),
title: "Full Disk Access",
description: `Read ${source.name}'s cookies for this import.`,
granted: permission.status.fullDiskAccess,
onAllow: () => void allow(),
},
]}
/>
{openingError || permission.error ? (
<p role="status" className="mt-3 text-xs text-muted-foreground">
{openingError ?? permission.error}
</p>
</DialogPanel>
) : null}
) : null}
{!permission.isReady(["fullDiskAccess"]) ? (
<p className="mt-3 text-xs text-muted-foreground">
{stillRequired
? "Access is still required. Quit and reopen T3 Code if you just allowed it, then retry the import."
: "If access doesn't update after you allow it, quit and reopen T3 Code, then retry the import."}
</p>
) : null}
</DialogPanel>
<DialogFooter>
<Button variant="outline" onClick={onCancel}>
Cancel
</Button>
<Button variant="outline" onClick={onOpenSettings}>
Open System Settings
</Button>
<Button onClick={onGranted}>I&rsquo;ve turned it on</Button>
<PermissionContinueButton
ready={permission.isReady(["fullDiskAccess"])}
busy={opening}
onClick={onGranted}
>
Continue
</PermissionContinueButton>
</DialogFooter>
</>
);
@@ -1260,10 +1260,15 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
runWizardImport(importSession.source, importSession.environmentId, input)
}
onRefreshSource={() => refreshImportSource(importSession.source.id)}
onOpenFullDiskAccessSettings={() => {
onCheckFullDiskAccess={
window.desktopBridge?.checkSystemPermission
? () => window.desktopBridge!.checkSystemPermission!("full-disk-access")
: undefined
}
onOpenFullDiskAccessSettings={async () => {
// Rejects outside the desktop shell (and on shells that predate the
// method), so the one toast covers every way the link can fail.
void readLocalApi()
await readLocalApi()
?.shell.openSystemSettings("full-disk-access")
.catch(() => {
toastManager.add({
@@ -338,11 +338,6 @@ export function SnapShotSettings() {
}
};
const refreshSetup = useCallback(() => {
setSetupError(null);
return refreshState();
}, [refreshState]);
const closeSetup = async (completed: boolean) => {
if (!wizard || setupBusy) return;
setSetupBusy(true);
@@ -612,7 +607,7 @@ export function SnapShotSettings() {
onSaveShortcut={saveShortcut}
onEnable={enableForSetup}
onAction={setup}
onRefresh={refreshSetup}
onRefresh={refreshState}
onClose={closeSetup}
onLeaveStep={stopRecording}
/>
@@ -1,10 +1,11 @@
import { PermissionChecklist, PermissionContinueButton } from "../permissions/PermissionChecklist";
import { usePermissionStatus } from "../permissions/usePermissionStatus";
import {
isModifierPairShortcut,
type DesktopSnapShotSetupAction,
type DesktopSnapShotState,
} from "@t3tools/contracts";
import { CircleCheckIcon } from "lucide-react";
import { useEffect, useId, useState, type ReactNode } from "react";
import { useId, useState, type ReactNode } from "react";
import { CaptureShortcutConfig } from "./CaptureShortcutConfig";
import { Button } from "../ui/button";
import { Dialog, DialogDescription } from "../ui/dialog";
@@ -15,7 +16,6 @@ import {
captureSetupCheckMessage,
captureSetupDesktopName,
captureSetupInitialStep,
captureSetupMacPermissionsReady,
captureSetupShortcutReady,
type CaptureSetupStep,
} from "./SnapShotSetupDialog.logic";
@@ -127,42 +127,6 @@ function AccessibilityPermissionIcon() {
);
}
function MacPermissionRow({
icon,
title,
description,
granted,
busy,
onAllow,
}: {
icon: ReactNode;
title: string;
description: string;
granted: boolean;
busy: boolean;
onAllow: () => void;
}) {
return (
<div className="flex items-center gap-3 rounded-lg border px-3 py-2">
{icon}
<div className="min-w-0 flex-1">
<p className="font-medium">{title}</p>
<p className="text-xs text-muted-foreground">{description}</p>
</div>
{granted ? (
<span className="flex items-center gap-1 text-xs text-success">
<CircleCheckIcon className="size-4" aria-hidden="true" />
Allowed
</span>
) : (
<Button size="xs" variant="outline" disabled={busy} onClick={onAllow}>
Allow
</Button>
)}
</div>
);
}
export function SnapShotSetupDialog({
state,
initialStep,
@@ -212,17 +176,24 @@ export function SnapShotSetupDialog({
const installHelper = backend === "hyprland" ? "install-hyprland-helper" : "install-kde-helper";
const removeHelper = backend === "hyprland" ? "remove-hyprland-helper" : "remove-kde-helper";
const accessReady = captureSetupAccessReady(state);
const macPermissions = state.macPermissions;
const macPermissionsReady = captureSetupMacPermissionsReady(state, includeAccessibility);
const permissionStatus = usePermissionStatus(
async () => {
const refreshed = await onRefresh();
if (!refreshed?.macPermissions) throw new Error("Permission status unavailable");
return refreshed.macPermissions;
},
state.macPermissions ?? { screenRecording: false, accessibility: false },
Boolean(state.macPermissions) && step === "access" && !busy,
);
const macPermissions = state.macPermissions ? permissionStatus.status : undefined;
const macPermissionsReady =
!macPermissions ||
permissionStatus.isReady(
includeAccessibility ? ["screenRecording", "accessibility"] : ["screenRecording"],
);
const shortcutReady = captureSetupShortcutReady(state, shortcutChanged);
const install = extension?.status === "not-installed" || extension?.status === "update-required";
const enable = extension?.status === "disabled";
useEffect(() => {
if (!macPermissions || step !== "access") return;
const refresh = () => void onRefresh();
window.addEventListener("focus", refresh);
return () => window.removeEventListener("focus", refresh);
}, [macPermissions, onRefresh, step]);
const changeStep = (next: CaptureSetupStep) => {
onLeaveStep();
setChecked(false);
@@ -357,28 +328,34 @@ export function SnapShotSetupDialog({
{checked && !busy && !error ? captureSetupCheckMessage(state) : null}
</p>
{macPermissions ? (
<div className="space-y-2">
<MacPermissionRow
icon={<ScreenRecordingIcon />}
title="Screen Recording"
description="Capture the window you're using."
granted={macPermissions.screenRecording}
busy={busy}
onAllow={() => void onAction("allow-screen-recording")}
/>
<MacPermissionRow
icon={<AccessibilityPermissionIcon />}
title="Accessibility"
description={
includeAccessibility
<PermissionChecklist
busy={busy}
permissions={[
{
id: "screenRecording",
icon: <ScreenRecordingIcon />,
title: "Screen Recording",
description: "Capture the window you're using.",
granted: macPermissions.screenRecording,
onAllow: () => void onAction("allow-screen-recording"),
},
{
id: "accessibility",
icon: <AccessibilityPermissionIcon />,
title: "Accessibility",
description: includeAccessibility
? "Include text and controls from the captured app."
: "Optional. Include text and controls from the captured app."
}
granted={macPermissions.accessibility}
busy={busy}
onAllow={() => void onAction("allow-accessibility")}
/>
</div>
: "Optional. Include text and controls from the captured app.",
granted: macPermissions.accessibility,
onAllow: () => void onAction("allow-accessibility"),
},
]}
/>
) : null}
{permissionStatus.error && macPermissions ? (
<p role="status" className="text-xs text-muted-foreground">
{permissionStatus.error}
</p>
) : null}
{helperBackend && helper?.status === "error" ? (
<Button
@@ -527,8 +504,9 @@ export function SnapShotSetupDialog({
: "Check again"}
</Button>
) : (
<Button
disabled={busy || !macPermissionsReady}
<PermissionContinueButton
ready={macPermissionsReady}
busy={busy}
onClick={async () => {
if (await onEnable()) changeStep("shortcut");
}}
@@ -542,7 +520,7 @@ export function SnapShotSetupDialog({
: !accessReady && !macPermissions
? "Try again"
: "Continue"}
</Button>
</PermissionContinueButton>
)
) : !configShortcut ? (
<Button
+4 -5
View File
@@ -10,11 +10,10 @@ unlock prompt if one appears.
This is a one-time copy. Later login changes stay separate between the two browsers, and some
sites may still require you to sign in again.
On macOS, Safari is also available. Safari protects its cookies with Full Disk Access rather than
a keychain, so the import wizard asks you to grant it: **Open System Settings** takes you to the
right pane, and macOS may ask you to quit and reopen T3 Code before the grant applies. You can
revoke Full Disk Access after the import is done. Only Safari's primary profile is imported; cookies
kept by additional Safari profiles are not.
On macOS, Safari imports need Full Disk Access. Choose **Allow**, drag T3 Code into the
System Settings permission list, and turn access on. **Continue** becomes available when access
is detected. macOS may require you to quit and reopen T3 Code before the grant applies; reopen
the import wizard afterward. You can revoke Full Disk Access once the import is done.
On Windows, import supports Firefox and Helium profiles that use standard profile encryption.
Other Chromium-based browsers use app-bound encryption and cannot be imported. Partitioned cookies
+1
View File
@@ -40,6 +40,7 @@
"src/preload.ts!",
"src/preview-pick-preload.ts!",
"src/preview-pip-preload.ts!",
"src/mac-permission-preload.ts!",
"src/preview/Annotation.css!",
],
// The injected runtime resolves Playwright by string; release tooling runs
+1
View File
@@ -1301,6 +1301,7 @@ export interface DesktopBridge {
* lack it, and callers no-op when it is missing.
*/
openSystemSettings?: (pane: SystemSettingsPane) => Promise<boolean>;
checkSystemPermission?: (pane: SystemSettingsPane) => Promise<boolean>;
/**
* Probe this desktop machine for installed remote-capable editor CLIs
* (used for remote open-in-editor deep links). Optional: older desktop