Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(desktop): add a startup launch setting

tianma-ifa09205289258
diff --git a/apps/desktop/nsis/installer.nsh b/apps/desktop/nsis/installer.nsh
index 344024d7..99316eb5 100644
--- a/apps/desktop/nsis/installer.nsh
+++ b/apps/desktop/nsis/installer.nsh
@@ -8,4 +8,8 @@
!macro customUnInstall
DeleteRegKey HKCU "Software\Classes\*\shell\EdgeEver"
+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "EdgeEver"
+ ClearErrors
+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run" "EdgeEver"
+ ClearErrors
!macroend
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 7c908117..71b0c4d7 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -62,6 +62,11 @@ import { createAiDirectRuntime } from "./ai-direct.mjs";
import { createAcpPathStore, validateTrustedAcpPath } from "./acp-path-store.mjs";
import { createAcpHostRuntime, registerAcpIpc } from "./acp-host.mjs";
import { shouldQuitAfterAllWindowsClosed } from "./window-lifecycle.mjs";
+import {
+ commandLineOpensContent,
+ createLoginItemController,
+ shouldStartHidden,
+} from "./login-item.mjs";
import {
RENDERER_HIBERNATE_PREPARE_TIMEOUT_MS,
createRendererHibernateController,
@@ -372,8 +377,16 @@ const openDesktopDiagnosticIssue = async (details) => {
}));
};
+const revealMainWindow = () => {
+ if (!mainWindow || mainWindow.isDestroyed()) return false;
+ if (mainWindow.isVisible() && !mainWindow.isMinimized()) return true;
+ if (process.platform === "darwin") app.show();
+ return showWindow(mainWindow);
+};
+
const handleRendererProcessGone = async (details) => {
if (isQuitting || details.reason === "clean-exit" || rendererCrashDialogOpen) return;
+ revealMainWindow();
rendererCrashDialogOpen = true;
const isChinese = app.getLocale().toLowerCase().startsWith("zh");
try {
@@ -397,6 +410,7 @@ const handleRendererProcessGone = async (details) => {
const showRendererStartupFailure = async (details) => {
if (isQuitting || rendererStartupFailureDialogOpen || !mainWindow || mainWindow.isDestroyed()) return;
+ revealMainWindow();
rendererStartupFailureDialogOpen = true;
const isChinese = app.getLocale().toLowerCase().startsWith("zh");
const reason = String(details?.message || details?.errorDescription || details?.kind || "unknown").slice(0, 1000);
@@ -438,6 +452,7 @@ const clearRendererUnresponsiveTimer = () => {
const showRendererUnresponsive = async () => {
rendererUnresponsiveTimer = null;
if (isQuitting || rendererUnresponsiveDialogOpen || !mainWindow || mainWindow.isDestroyed()) return;
+ revealMainWindow();
rendererUnresponsiveDialogOpen = true;
const isChinese = app.getLocale().toLowerCase().startsWith("zh");
try {
@@ -462,6 +477,7 @@ const showRendererUnresponsive = async () => {
const showMainStartupFailure = async (error) => {
const message = String(error?.message || error).slice(0, 2000);
await writeDiagnostic("main.startup-failed", { message, stack: error?.stack });
+ revealMainWindow();
const isChinese = app.getLocale().toLowerCase().startsWith("zh");
const options = {
type: "error",
@@ -1490,7 +1506,7 @@ const desktopRendererEntryUrl = () => app.isPackaged && !process.env.EDGE_EVER_D
? (usePrivateAppProtocol ? DESKTOP_APP_ENTRY_URL : pathToFileURL(join(process.resourcesPath, "web/index.html")).href)
: webUrl;
-const createWindow = async () => {
+const createWindow = async ({ show = true } = {}) => {
const state = await readWindowState();
mainWindow = new BrowserWindow({
width: state.width,
@@ -1499,6 +1515,7 @@ const createWindow = async () => {
y: state.y,
minWidth: 960,
minHeight: 640,
+ show,
webPreferences: {
preload: join(currentDirectory, "../preload/index.cjs"),
contextIsolation: true,
@@ -1508,7 +1525,12 @@ const createWindow = async () => {
});
rendererReady = false;
armRendererStartupGuard();
- if (state.isMaximized) mainWindow.maximize();
+ if (show && state.isMaximized) mainWindow.maximize();
+ else if (state.isMaximized) {
+ mainWindow.once("show", () => {
+ if (!mainWindow?.isDestroyed()) mainWindow.maximize();
+ });
+ }
mainWindow.on("resize", () => void saveWindowState());
mainWindow.on("move", () => void saveWindowState());
mainWindow.on("close", (event) => {
@@ -1711,6 +1733,40 @@ const startApplication = async () => {
void writeDiagnostic("sidecar.ready", { scope: sidecarScopeKey });
createTray();
await loadGlobalShortcut();
+ const loginItems = createLoginItemController({
+ platform: process.platform,
+ packaged: app.isPackaged,
+ executablePath: app.getPath("exe"),
+ preferencePath: join(app.getPath("userData"), "login-item.json"),
+ readFile,
+ writeFile,
+ rename,
+ unlink,
+ getLoginItemSettings: (options) => app.getLoginItemSettings(options),
+ setLoginItemSettings: (settings) => app.setLoginItemSettings(settings),
+ });
+ let loginItemState = loginItems.current();
+ try {
+ loginItemState = await loginItems.reconcileAtStartup();
+ } catch (error) {
+ loginItemState = loginItems.current();
+ void writeDiagnostic("login-item.reconcile-failed", {
+ message: String(error?.message || error).slice(0, 500),
+ });
+ }
+ const startHidden = shouldStartHidden({
+ argv: process.argv,
+ wasOpenedAtLogin: loginItems.wasOpenedAtLogin(),
+ launchMode: loginItemState.launchMode,
+ opensContent: commandLineOpensContent(process.argv, { isAssociatedFile: isSupportedAssociatedFile }),
+ });
+ void writeDiagnostic("login-item.ready", {
+ supported: loginItemState.supported,
+ openAtLogin: loginItemState.openAtLogin,
+ launchMode: loginItemState.launchMode,
+ status: loginItemState.status,
+ startHidden,
+ });
ipcMain.on("desktop:local-data-reset-available-sync", (event) => {
event.returnValue = process.platform === "darwin" && app.isPackaged && !requestedUserDataDirectory;
@@ -1740,6 +1796,14 @@ const startApplication = async () => {
if (event.sender !== mainWindow?.webContents) return null;
return globalShortcutState();
});
+ ipcMain.handle("desktop:login-item", (event) => {
+ if (event.sender !== mainWindow?.webContents) return null;
+ return loginItems.current();
+ });
+ ipcMain.handle("desktop:set-login-item", (event, patch) => {
+ if (event.sender !== mainWindow?.webContents) return null;
+ return loginItems.update(patch);
+ });
ipcMain.handle("desktop:set-global-shortcut", (event, binding) => {
if (event.sender !== mainWindow?.webContents) return null;
return setGlobalShortcut(binding);
@@ -2184,7 +2248,7 @@ const startApplication = async () => {
]);
});
- await createWindow();
+ await createWindow({ show: !startHidden });
// Inspecting and ejecting mounted disk images invokes macOS command-line
// tools and may take several seconds. Keep that maintenance off the
// user-visible critical path so the first installed launch opens promptly.
diff --git a/apps/desktop/src/main/login-item.mjs b/apps/desktop/src/main/login-item.mjs
new file mode 100644
index 00000000..583607ca
--- /dev/null
+++ b/apps/desktop/src/main/login-item.mjs
@@ -0,0 +1,343 @@
+// Windows can disable a Run value from Task Manager without deleting it.
+// macOS login items cannot carry a start-hidden argument, so a tray launch is
+// decided from the saved mode when this process was opened at login.
+
+export const LOGIN_ITEM_NAME = "EdgeEver";
+export const START_HIDDEN_ARG = "--start-hidden";
+
+export const loginItemSupported = ({ platform, packaged }) =>
+ packaged === true && (platform === "win32" || platform === "darwin");
+
+export const normalizeLaunchMode = (value) => (value === "tray" ? "tray" : "window");
+
+export const parseLoginItemPreference = (raw) => {
+ let value = raw;
+ if (typeof raw === "string") {
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ value = null;
+ }
+ }
+ if (!value || typeof value !== "object") return { openAtLogin: false, launchMode: "window" };
+ return {
+ openAtLogin: value.openAtLogin === true,
+ launchMode: normalizeLaunchMode(value.launchMode),
+ };
+};
+
+export const loginItemArgs = (launchMode) => (
+ normalizeLaunchMode(launchMode) === "tray" ? [START_HIDDEN_ARG] : []
+);
+
+export const normalizeLoginItemArgs = (args, executablePath) => {
+ if (!Array.isArray(args)) return [];
+ const cleaned = [];
+ for (const arg of args) {
+ if (typeof arg !== "string") continue;
+ const stripped = arg.trim().replace(/^"(.*)"$/, "$1");
+ if (!stripped || stripped === "--" || stripped === executablePath) continue;
+ cleaned.push(stripped);
+ }
+ return cleaned;
+};
+
+const sameArgs = (left, right) => left.length === right.length && left.every((value, index) => value === right[index]);
+
+export const findWindowsLoginItem = (settings, { name, executablePath }) => {
+ const items = Array.isArray(settings?.launchItems) ? settings.launchItems : [];
+ return items.find((item) => item?.name === name)
+ ?? items.find((item) => item?.path === executablePath)
+ ?? null;
+};
+
+export const commandLineOpensContent = (argv, { isAssociatedFile } = {}) => {
+ if (!Array.isArray(argv)) return false;
+ for (let index = 0; index < argv.length; index += 1) {
+ const value = argv[index];
+ if (typeof value !== "string") continue;
+ if (value.startsWith("edgeever://")) return true;
+ if (value === "--share-file") {
+ const filePath = argv[index + 1];
+ if (typeof filePath === "string" && filePath.length > 0 && !filePath.startsWith("-")) return true;
+ }
+ if (!value.startsWith("-") && isAssociatedFile?.(value)) return true;
+ }
+ return false;
+};
+
+export const shouldStartHidden = ({
+ argv,
+ wasOpenedAtLogin = false,
+ launchMode = "window",
+ opensContent = false,
+} = {}) => {
+ if (opensContent) return false;
+ if (Array.isArray(argv) && argv.includes(START_HIDDEN_ARG)) return true;
+ return wasOpenedAtLogin === true && normalizeLaunchMode(launchMode) === "tray";
+};
+
+const unavailablePlan = () => ({
+ supported: false,
+ openAtLogin: false,
+ launchMode: "window",
+ action: "none",
+ status: "unavailable",
+});
+
+export const startupLoginItemPlan = ({
+ platform,
+ packaged,
+ saved,
+ os,
+ osReadable = true,
+ executablePath,
+}) => {
+ if (!loginItemSupported({ platform, packaged })) return unavailablePlan();
+ const launchMode = normalizeLaunchMode(saved?.launchMode);
+ const wanted = saved?.openAtLogin === true;
+ if (!osReadable) {
+ return {
+ supported: true,
+ openAtLogin: wanted,
+ launchMode,
+ action: "none",
+ status: wanted ? "enabled" : "disabled",
+ };
+ }
+
+ if (platform === "win32") {
+ const item = findWindowsLoginItem(os, { name: LOGIN_ITEM_NAME, executablePath });
+ if (!wanted) {
+ return {
+ supported: true,
+ openAtLogin: false,
+ launchMode,
+ action: item ? "remove" : "none",
+ status: "disabled",
+ };
+ }
+ if (item && item.enabled === false) {
+ return {
+ supported: true,
+ openAtLogin: false,
+ launchMode,
+ action: "persist-off",
+ status: "disabled-by-system",
+ };
+ }
+ const desiredArgs = loginItemArgs(launchMode);
+ const actualArgs = normalizeLoginItemArgs(item?.args, executablePath);
+ const current = Boolean(item)
+ && item.enabled === true
+ && item.path === executablePath
+ && sameArgs(actualArgs, desiredArgs);
+ return {
+ supported: true,
+ openAtLogin: true,
+ launchMode,
+ action: current ? "none" : "apply",
+ status: "enabled",
+ };
+ }
+
+ const status = os?.status;
+ const registered = os?.openAtLogin === true || status === "enabled" || status === "requires-approval";
+ if (!wanted) {
+ return {
+ supported: true,
+ openAtLogin: false,
+ launchMode,
+ action: registered ? "remove" : "none",
+ status: "disabled",
+ };
+ }
+ if (status === "not-found") {
+ return { supported: true, openAtLogin: true, launchMode, action: "apply", status: "not-found" };
+ }
+ if (!registered) {
+ return {
+ supported: true,
+ openAtLogin: false,
+ launchMode,
+ action: "persist-off",
+ status: "disabled-by-system",
+ };
+ }
+ return {
+ supported: true,
+ openAtLogin: true,
+ launchMode,
+ action: "none",
+ status: status === "requires-approval" ? "requires-approval" : "enabled",
+ };
+};
+
+export const loginItemUpdatePayload = ({ openAtLogin, launchMode, executablePath, platform }) => {
+ const enabled = openAtLogin === true;
+ const payload = { openAtLogin: enabled };
+ if (platform === "win32") {
+ payload.path = executablePath;
+ payload.name = LOGIN_ITEM_NAME;
+ payload.args = loginItemArgs(launchMode);
+ if (enabled) payload.enabled = true;
+ }
+ return payload;
+};
+
+export const publicLoginItemState = (plan) => ({
+ supported: plan.supported === true,
+ openAtLogin: plan.openAtLogin === true,
+ launchMode: normalizeLaunchMode(plan.launchMode),
+ status: plan.status || (plan.openAtLogin ? "enabled" : "disabled"),
+});
+
+export const normalizeLoginItemPatch = (current, patch) => {
+ if (!patch || typeof patch !== "object") return null;
+ const hasOpen = Object.hasOwn(patch, "openAtLogin");
+ const hasMode = Object.hasOwn(patch, "launchMode");
+ if (!hasOpen && !hasMode) return null;
+ if (hasOpen && typeof patch.openAtLogin !== "boolean") return null;
+ if (hasMode && patch.launchMode !== "window" && patch.launchMode !== "tray") return null;
+ return {
+ openAtLogin: hasOpen ? patch.openAtLogin : current.openAtLogin === true,
+ launchMode: hasMode ? patch.launchMode : normalizeLaunchMode(current.launchMode),
+ };
+};
+
+export const createLoginItemController = ({
+ platform,
+ packaged,
+ executablePath,
+ preferencePath,
+ readFile,
+ writeFile,
+ rename,
+ unlink,
+ getLoginItemSettings,
+ setLoginItemSettings,
+}) => {
+ let saved = { openAtLogin: false, launchMode: "window" };
+ let state = publicLoginItemState(unavailablePlan());
+ let openedAtLogin = false;
+ let chain = Promise.resolve();
+
+ const enqueue = (task) => {
+ const run = chain.then(task, task);
+ chain = run.then(() => {}, () => {});
+ return run;
+ };
+
+ const readOs = () => {
+ try {
+ const settings = platform === "win32"
+ ? getLoginItemSettings({ path: executablePath, args: loginItemArgs(saved.launchMode) })
+ : getLoginItemSettings();
+ return { ok: true, settings };
+ } catch {
+ return { ok: false, settings: null };
+ }
+ };
+
+ const persist = async (preference) => {
+ const temporaryPath = `${preferencePath}.tmp`;
+ await writeFile(temporaryPath, JSON.stringify(preference), { mode: 0o600 });
+ try {
+ await rename(temporaryPath, preferencePath);
+ } catch (error) {
+ await unlink(temporaryPath).catch(() => {});
+ throw error;
+ }
+ saved = preference;
+ };
+
+ const apply = (preference) => {
+ setLoginItemSettings(loginItemUpdatePayload({ ...preference, executablePath, platform }));
+ };
+
+ return {
+ reconcileAtStartup() {
+ return enqueue(async () => {
+ try {
+ saved = parseLoginItemPreference(await readFile(preferencePath, "utf8"));
+ } catch {
+ saved = { openAtLogin: false, launchMode: "window" };
+ }
+ if (platform === "darwin") {
+ try {
+ openedAtLogin = getLoginItemSettings().wasOpenedAtLogin === true;
+ } catch {
+ openedAtLogin = false;
+ }
+ }
+ const os = loginItemSupported({ platform, packaged }) ? readOs() : { ok: true, settings: null };
+ let plan = startupLoginItemPlan({
+ platform,
+ packaged,
+ saved,
+ os: os.settings,
+ osReadable: os.ok,
+ executablePath,
+ });
+ if (plan.action === "apply") apply({ openAtLogin: true, launchMode: plan.launchMode });
+ else if (plan.action === "remove") apply({ openAtLogin: false, launchMode: plan.launchMode });
+ else if (plan.action === "persist-off") plan = { ...plan, openAtLogin: false };
+ state = publicLoginItemState(plan);
+ if (plan.action === "persist-off") {
+ await persist({ openAtLogin: false, launchMode: plan.launchMode });
+ }
+ return state;
+ });
+ },
+ current() {
+ return state;
+ },
+ wasOpenedAtLogin() {
+ return openedAtLogin;
+ },
+ update(patch) {
+ return enqueue(async () => {
+ if (!state.supported) return state;
+ const next = normalizeLoginItemPatch(saved, patch);
+ if (!next) return { ...state, error: "invalid" };
+ try {
+ apply(next);
+ await persist(next);
+ } catch {
+ return { ...state, error: "saveFailed" };
+ }
+ const os = readOs();
+ let status = next.openAtLogin ? "enabled" : "disabled";
+ if (next.openAtLogin && platform === "darwin" && os.settings?.status === "requires-approval") {
+ status = "requires-approval";
+ }
+ if (next.openAtLogin && platform === "win32" && os.ok) {
+ const item = findWindowsLoginItem(os.settings, { name: LOGIN_ITEM_NAME, executablePath });
+ if (item && item.enabled === false) {
+ try {
+ apply({ openAtLogin: false, launchMode: next.launchMode });
+ await persist({ openAtLogin: false, launchMode: next.launchMode });
+ } catch {
+ saved = { openAtLogin: false, launchMode: next.launchMode };
+ }
+ state = {
+ supported: true,
+ openAtLogin: false,
+ launchMode: next.launchMode,
+ status: "disabled-by-system",
+ error: "saveFailed",
+ };
+ return state;
+ }
+ }
+ state = {
+ supported: true,
+ openAtLogin: next.openAtLogin,
+ launchMode: next.launchMode,
+ status,
+ };
+ return state;
+ });
+ },
+ };
+};
diff --git a/apps/desktop/src/main/login-item.test.mjs b/apps/desktop/src/main/login-item.test.mjs
new file mode 100644
index 00000000..162a8ecf
--- /dev/null
+++ b/apps/desktop/src/main/login-item.test.mjs
@@ -0,0 +1,321 @@
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, test } from "bun:test";
+import {
+ LOGIN_ITEM_NAME,
+ START_HIDDEN_ARG,
+ commandLineOpensContent,
+ createLoginItemController,
+ loginItemArgs,
+ loginItemSupported,
+ loginItemUpdatePayload,
+ normalizeLoginItemArgs,
+ normalizeLoginItemPatch,
+ parseLoginItemPreference,
+ shouldStartHidden,
+ startupLoginItemPlan,
+} from "./login-item.mjs";
+
+const exePath = "C:\\Users\\Example\\AppData\\Local\\Programs\\EdgeEver\\EdgeEver.exe";
+
+const windowsItem = (overrides = {}) => ({
+ name: LOGIN_ITEM_NAME,
+ path: exePath,
+ args: [],
+ enabled: true,
+ scope: "user",
+ ...overrides,
+});
+
+describe("login item support", () => {
+ test("is available only for a packaged Windows or macOS app", () => {
+ expect(loginItemSupported({ platform: "win32", packaged: true })).toBe(true);
+ expect(loginItemSupported({ platform: "darwin", packaged: true })).toBe(true);
+ expect(loginItemSupported({ platform: "linux", packaged: true })).toBe(false);
+ expect(loginItemSupported({ platform: "win32", packaged: false })).toBe(false);
+ });
+
+ test("keeps an unreadable preference turned off", () => {
+ expect(parseLoginItemPreference("{")).toEqual({ openAtLogin: false, launchMode: "window" });
+ expect(parseLoginItemPreference({ openAtLogin: true, launchMode: "tray" })).toEqual({
+ openAtLogin: true,
+ launchMode: "tray",
+ });
+ expect(parseLoginItemPreference({ openAtLogin: "yes", launchMode: "elsewhere" })).toEqual({
+ openAtLogin: false,
+ launchMode: "window",
+ });
+ });
+
+ test("rejects an empty or unknown settings change", () => {
+ const current = { openAtLogin: true, launchMode: "window" };
+ expect(normalizeLoginItemPatch(current, null)).toBeNull();
+ expect(normalizeLoginItemPatch(current, {})).toBeNull();
+ expect(normalizeLoginItemPatch(current, { launchMode: "background" })).toBeNull();
+ expect(normalizeLoginItemPatch(current, { openAtLogin: "yes" })).toBeNull();
+ expect(normalizeLoginItemPatch(current, { launchMode: "tray" })).toEqual({
+ openAtLogin: true,
+ launchMode: "tray",
+ });
+ });
+});
+
+describe("login item startup plan", () => {
+ test("writes a missing Windows entry and refreshes a stale path or argument", () => {
+ expect(startupLoginItemPlan({
+ platform: "win32",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "window" },
+ os: { launchItems: [] },
+ executablePath: exePath,
+ }).action).toBe("apply");
+
+ const stale = startupLoginItemPlan({
+ platform: "win32",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "tray" },
+ os: { launchItems: [windowsItem({ path: "C:\\Old\\EdgeEver.exe", args: [] })] },
+ executablePath: exePath,
+ });
+ expect(stale.action).toBe("apply");
+ expect(loginItemUpdatePayload({
+ openAtLogin: true,
+ launchMode: stale.launchMode,
+ executablePath: exePath,
+ platform: "win32",
+ })).toEqual({
+ openAtLogin: true,
+ path: exePath,
+ name: LOGIN_ITEM_NAME,
+ args: [START_HIDDEN_ARG],
+ enabled: true,
+ });
+ });
+
+ test("does not turn a Windows entry back on after Task Manager disables it", () => {
+ const plan = startupLoginItemPlan({
+ platform: "win32",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "tray" },
+ os: { launchItems: [windowsItem({ enabled: false, args: [START_HIDDEN_ARG] })] },
+ executablePath: exePath,
+ });
+ expect(plan).toMatchObject({ action: "persist-off", openAtLogin: false, status: "disabled-by-system" });
+ });
+
+ test("leaves a matching Windows entry untouched and removes one the user turned off", () => {
+ expect(startupLoginItemPlan({
+ platform: "win32",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "window" },
+ os: { launchItems: [windowsItem({ args: [exePath, "--"] })] },
+ executablePath: exePath,
+ }).action).toBe("none");
+ expect(normalizeLoginItemArgs([exePath, "--"], exePath)).toEqual([]);
+ expect(startupLoginItemPlan({
+ platform: "win32",
+ packaged: true,
+ saved: { openAtLogin: false, launchMode: "window" },
+ os: { launchItems: [windowsItem()] },
+ executablePath: exePath,
+ }).action).toBe("remove");
+ });
+
+ test("follows macOS login-item status without rewriting an approved entry", () => {
+ expect(startupLoginItemPlan({
+ platform: "darwin",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "tray" },
+ os: { openAtLogin: false, status: "not-registered" },
+ executablePath: "/Applications/EdgeEver.app/Contents/MacOS/EdgeEver",
+ })).toMatchObject({ action: "persist-off", openAtLogin: false });
+ expect(startupLoginItemPlan({
+ platform: "darwin",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "window" },
+ os: { openAtLogin: true, status: "requires-approval" },
+ executablePath: "/Applications/EdgeEver.app/Contents/MacOS/EdgeEver",
+ })).toMatchObject({ action: "none", status: "requires-approval", openAtLogin: true });
+ expect(startupLoginItemPlan({
+ platform: "darwin",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "window" },
+ os: { openAtLogin: false, status: "not-found" },
+ executablePath: "/Applications/EdgeEver.app/Contents/MacOS/EdgeEver",
+ }).action).toBe("apply");
+ expect(loginItemArgs("window")).toEqual([]);
+ expect(loginItemUpdatePayload({
+ openAtLogin: true,
+ launchMode: "tray",
+ executablePath: "/Applications/EdgeEver.app/Contents/MacOS/EdgeEver",
+ platform: "darwin",
+ })).toEqual({ openAtLogin: true });
+ });
+
+ test("keeps the saved choice when the system setting cannot be read", () => {
+ expect(startupLoginItemPlan({
+ platform: "win32",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "tray" },
+ os: null,
+ osReadable: false,
+ executablePath: exePath,
+ })).toMatchObject({ action: "none", openAtLogin: true, launchMode: "tray" });
+ expect(startupLoginItemPlan({
+ platform: "linux",
+ packaged: true,
+ saved: { openAtLogin: true, launchMode: "tray" },
+ os: null,
+ executablePath: "/app/EdgeEver.AppImage",
+ }).supported).toBe(false);
+ });
+});
+
+describe("hidden login launch", () => {
+ test("hides a tray login and shows a launch that opens a note", () => {
+ expect(shouldStartHidden({ argv: ["EdgeEver.exe", START_HIDDEN_ARG], launchMode: "tray" })).toBe(true);
+ expect(shouldStartHidden({
+ argv: ["EdgeEver.exe"],
+ wasOpenedAtLogin: true,
+ launchMode: "tray",
+ })).toBe(true);
+ expect(shouldStartHidden({
+ argv: ["EdgeEver.exe"],
+ wasOpenedAtLogin: true,
+ launchMode: "window",
+ })).toBe(false);
+ expect(shouldStartHidden({ argv: ["EdgeEver.exe"], launchMode: "tray" })).toBe(false);
+ expect(shouldStartHidden({
+ argv: ["EdgeEver.exe", START_HIDDEN_ARG, "--share-file", "D:\\Notes\\a.md"],
+ opensContent: commandLineOpensContent(
+ ["EdgeEver.exe", START_HIDDEN_ARG, "--share-file", "D:\\Notes\\a.md"],
+ { isAssociatedFile: (value) => value.endsWith(".md") },
+ ),
+ })).toBe(false);
+ expect(commandLineOpensContent(["EdgeEver.exe", "edgeever://memo/1"])).toBe(true);
+ expect(commandLineOpensContent(["EdgeEver.exe", "--share-file"])).toBe(false);
+ });
+});
+
+describe("login item controller", () => {
+ const createHarness = (platform) => {
+ const files = new Map();
+ let registry = null;
+ let openedAtLogin = false;
+ const calls = [];
+ const controller = createLoginItemController({
+ platform,
+ packaged: true,
+ executablePath: exePath,
+ preferencePath: "/user/login-item.json",
+ readFile: async (path) => {
+ if (!files.has(path)) throw new Error("missing");
+ return files.get(path);
+ },
+ writeFile: async (path, content) => { files.set(path, content); },
+ rename: async (from, to) => {
+ files.set(to, files.get(from));
+ files.delete(from);
+ },
+ unlink: async (path) => { files.delete(path); },
+ getLoginItemSettings: () => ({
+ openAtLogin: Boolean(registry),
+ wasOpenedAtLogin: openedAtLogin,
+ status: registry?.status ?? (registry ? "enabled" : "not-registered"),
+ launchItems: registry ? [registry] : [],
+ }),
+ setLoginItemSettings: (settings) => {
+ calls.push(settings);
+ if (!settings.openAtLogin) {
+ registry = null;
+ return;
+ }
+ registry = {
+ name: settings.name,
+ path: settings.path,
+ args: settings.args ?? [],
+ enabled: settings.enabled !== false,
+ status: "enabled",
+ };
+ },
+ });
+ return {
+ controller,
+ calls,
+ files,
+ setRegistry: (value) => { registry = value; },
+ setOpenedAtLogin: (value) => { openedAtLogin = value; },
+ };
+ };
+
+ test("repairs a packaged Windows login item from the saved preference", async () => {
+ const harness = createHarness("win32");
+ harness.files.set("/user/login-item.json", JSON.stringify({ openAtLogin: true, launchMode: "tray" }));
+ const state = await harness.controller.reconcileAtStartup();
+ expect(state).toMatchObject({ supported: true, openAtLogin: true, launchMode: "tray", status: "enabled" });
+ expect(harness.calls).toEqual([{
+ openAtLogin: true,
+ path: exePath,
+ name: LOGIN_ITEM_NAME,
+ args: [START_HIDDEN_ARG],
+ enabled: true,
+ }]);
+ });
+
+ test("remembers a system disable and a failed change", async () => {
+ const harness = createHarness("win32");
+ harness.files.set("/user/login-item.json", JSON.stringify({ openAtLogin: true, launchMode: "window" }));
+ harness.setRegistry(windowsItem({ enabled: false }));
+ const disabled = await harness.controller.reconcileAtStartup();
+ expect(disabled).toMatchObject({ openAtLogin: false, status: "disabled-by-system" });
+ expect(JSON.parse(harness.files.get("/user/login-item.json")).openAtLogin).toBe(false);
+ expect(harness.calls).toEqual([]);
+
+ harness.setRegistry(null);
+ const turnedOn = await harness.controller.update({ openAtLogin: true, launchMode: "window" });
+ expect(turnedOn).toMatchObject({ openAtLogin: true, status: "enabled" });
+ await expect(harness.controller.update({ launchMode: "background" })).resolves.toMatchObject({ error: "invalid" });
+ });
+
+ test("keeps macOS approval visible and hides only a login launch", async () => {
+ const harness = createHarness("darwin");
+ harness.files.set("/user/login-item.json", JSON.stringify({ openAtLogin: true, launchMode: "tray" }));
+ harness.setRegistry({ status: "requires-approval" });
+ harness.setOpenedAtLogin(true);
+ const state = await harness.controller.reconcileAtStartup();
+ expect(state).toMatchObject({ openAtLogin: true, launchMode: "tray", status: "requires-approval" });
+ expect(harness.calls).toEqual([]);
+ expect(harness.controller.wasOpenedAtLogin()).toBe(true);
+ expect(shouldStartHidden({
+ argv: ["EdgeEver"],
+ wasOpenedAtLogin: harness.controller.wasOpenedAtLogin(),
+ launchMode: state.launchMode,
+ })).toBe(true);
+ });
+});
+
+describe("desktop login item wiring", () => {
+ test("settings, startup, and uninstall share the same login item", () => {
+ const main = readFileSync(new URL("./index.mjs", import.meta.url), "utf8");
+ const preload = readFileSync(new URL("../preload/index.cjs", import.meta.url), "utf8");
+ const installer = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "..", "nsis", "installer.nsh"), "utf8");
+ const settings = readFileSync(new URL("../../../web/src/components/settings/LoginItemSettingsItem.tsx", import.meta.url), "utf8");
+ const preferences = readFileSync(new URL("../../../web/src/components/settings/PreferenceCard.tsx", import.meta.url), "utf8");
+
+ expect(main).toContain("createWindow({ show: !startHidden })");
+ expect(main).toContain("if (show && state.isMaximized) mainWindow.maximize();");
+ expect(main).toContain('ipcMain.handle("desktop:login-item"');
+ expect(main).toContain('ipcMain.handle("desktop:set-login-item"');
+ expect(main).toContain("revealMainWindow()");
+ expect(preload).toContain('loginItem: () => ipcRenderer.invoke("desktop:login-item")');
+ expect(preload).toContain('setLoginItem: (patch) => ipcRenderer.invoke("desktop:set-login-item", patch)');
+ expect(settings).toContain('t("settings.loginItem.title")');
+ expect(settings).toContain("bridge.loginItem()");
+ expect(settings).toContain("bridge.setLoginItem(patch)");
+ expect(preferences).toContain("<LoginItemSettingsItem />");
+ expect(installer).toContain("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
+ expect(installer).toContain("DeleteRegValue HKCU \"Software\\Microsoft\\Windows\\CurrentVersion\\Run\" \"EdgeEver\"");
+ expect(installer).toContain("DeleteRegValue HKCU \"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run\" \"EdgeEver\"");
+ });
+});
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index 1a85e74d..d949bb4c 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -32,6 +32,8 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
systemInfo: () => ipcRenderer.invoke("desktop:system-info"),
globalShortcut: () => ipcRenderer.invoke("desktop:global-shortcut"),
setGlobalShortcut: (binding) => ipcRenderer.invoke("desktop:set-global-shortcut", binding),
+ loginItem: () => ipcRenderer.invoke("desktop:login-item"),
+ setLoginItem: (patch) => ipcRenderer.invoke("desktop:set-login-item", patch),
captureGlobalShortcut: (capturing) => ipcRenderer.invoke("desktop:capture-global-shortcut", capturing),
setAccountScope: (accountId) => ipcRenderer.invoke("desktop:set-account-scope", accountId),
apiBaseUrl: ipcRenderer.sendSync("desktop:api-base-url-sync"),
diff --git a/apps/web/src/components/settings/LoginItemSettingsItem.tsx b/apps/web/src/components/settings/LoginItemSettingsItem.tsx
new file mode 100644
index 00000000..4df1bbdc
--- /dev/null
+++ b/apps/web/src/components/settings/LoginItemSettingsItem.tsx
@@ -0,0 +1,105 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Power } from "lucide-react";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { SETTINGS_ITEM_DESCRIPTION_CLASSNAME, SETTINGS_ITEM_TITLE_CLASSNAME } from "./settings-ui";
+
+type LoginItemLaunchMode = "window" | "tray";
+
+interface LoginItemState {
+ supported: boolean;
+ openAtLogin: boolean;
+ launchMode: LoginItemLaunchMode;
+ status: string;
+ error?: string;
+}
+
+export const LoginItemSettingsItem = () => {
+ const { t } = useTranslation();
+ const [state, setState] = useState<LoginItemState | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+
+ useEffect(() => {
+ const bridge = window.edgeeverDesktop;
+ if (!bridge?.loginItem) return undefined;
+ let cancelled = false;
+ void bridge.loginItem().then((next) => {
+ if (!cancelled && next) setState(next);
+ }).catch(() => {
+ if (!cancelled) setState(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ if (!state?.supported) return null;
+
+ const update = async (patch: { openAtLogin?: boolean; launchMode?: LoginItemLaunchMode }) => {
+ const bridge = window.edgeeverDesktop;
+ if (!bridge?.setLoginItem) return;
+ setBusy(true);
+ setError("");
+ try {
+ const next = await bridge.setLoginItem(patch);
+ if (next) setState(next);
+ setError(next?.error ? t("settings.loginItem.saveFailed") : "");
+ } catch {
+ setError(t("settings.loginItem.saveFailed"));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <>
+ <div className="flex min-h-16 flex-col items-start gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <Power className="h-4 w-4 shrink-0 text-slate-500" />
+ <div className="min-w-0">
+ <div className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.loginItem.title")}</div>
+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>
+ {state.status === "requires-approval"
+ ? t("settings.loginItem.requiresApproval")
+ : t("settings.loginItem.description")}
+ </p>
+ {error ? <p role="status" className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{error}</p> : null}
+ </div>
+ </div>
+ <div className="flex w-full shrink-0 justify-start sm:w-44 sm:justify-end">
+ <Switch
+ checked={state.openAtLogin}
+ disabled={busy}
+ onCheckedChange={(openAtLogin) => { void update({ openAtLogin }); }}
+ aria-label={t("settings.loginItem.aria")}
+ />
+ </div>
+ </div>
+ {state.openAtLogin ? (
+ <div className="flex min-h-16 flex-col items-start gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="h-4 w-4 shrink-0" />
+ <div className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.loginItem.launchModeLabel")}</div>
+ </div>
+ <div className="w-full shrink-0 sm:w-80">
+ <Select
+ value={state.launchMode}
+ disabled={busy}
+ onValueChange={(launchMode) => { void update({ launchMode: launchMode as LoginItemLaunchMode }); }}
+ >
+ <SelectTrigger aria-label={t("settings.loginItem.launchModeLabel")} className="h-9 bg-card">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="window">{t("settings.loginItem.launchModeWindow")}</SelectItem>
+ <SelectItem value="tray">{t("settings.loginItem.launchModeTray")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ ) : null}
+ </>
+ );
+};
diff --git a/apps/web/src/components/settings/PreferenceCard.tsx b/apps/web/src/components/settings/PreferenceCard.tsx
index 598cbdb6..90d1d818 100644
--- a/apps/web/src/components/settings/PreferenceCard.tsx
+++ b/apps/web/src/components/settings/PreferenceCard.tsx
@@ -56,6 +56,7 @@ import {
import { applyUiFontPreference, readUiFontPreference, writeUiFontPreference } from "@/lib/ui-font";
import { syncPublishedNoteBodyFont } from "@/lib/published-note-body-font";
import { useShowDescendantNotesPreference, writeShowDescendantNotesPreference } from "@/lib/descendant-notes-preference";
+import { LoginItemSettingsItem } from "./LoginItemSettingsItem";
import { PicGoSettingsItem } from "./PicGoSettingsItem";
import { NoteProseCssEditor } from "./NoteProseCssEditor";
import { NoteProseCssPreview } from "./NoteProseCssPreview";
@@ -354,6 +355,7 @@ export const PreferenceCard = ({
return (
<div className="grid gap-6">
<PreferenceSection title={t("settings.groups.interface")}>
+ <LoginItemSettingsItem />
<div className="flex min-h-16 flex-col items-start gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="flex min-w-0 items-center gap-3">
<Languages className="h-4 w-4 shrink-0 text-slate-500" />
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 5c14eee0..5455cec7 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -28,6 +28,14 @@ interface DesktopGlobalShortcutState {
error?: "invalid" | "unavailable" | "saveFailed";
}
+interface DesktopLoginItemState {
+ supported: boolean;
+ openAtLogin: boolean;
+ launchMode: "window" | "tray";
+ status: "disabled" | "enabled" | "requires-approval" | "disabled-by-system" | "unavailable";
+ error?: "invalid" | "saveFailed";
+}
+
interface EdgeEverDesktopBridge {
isAvailable: boolean;
canClearLocalData: boolean;
@@ -83,6 +91,8 @@ interface EdgeEverDesktopBridge {
}>;
globalShortcut(): Promise<DesktopGlobalShortcutState>;
setGlobalShortcut(binding: DesktopGlobalShortcutBinding | null): Promise<DesktopGlobalShortcutState>;
+ loginItem(): Promise<DesktopLoginItemState | null>;
+ setLoginItem(patch: { openAtLogin?: boolean; launchMode?: "window" | "tray" }): Promise<DesktopLoginItemState | null>;
captureGlobalShortcut(capturing: boolean): Promise<boolean>;
setAccountScope(accountId: string | null): Promise<{ ready: true; scope: string }>;
updateStatus(): Promise<DesktopUpdateStatus>;
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 33faa79d..9d2e5d76 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1024,6 +1024,16 @@ export const enUS = {
imageCompressionAria: "Compress note images",
showDescendantNotesTitle: "Show notes from sub-notebooks",
showDescendantNotesAria: "Show notes from sub-notebooks in parent notebooks",
+ loginItem: {
+ title: "Launch at startup",
+ aria: "Launch EdgeEver at startup",
+ description: "Open EdgeEver after this computer starts.",
+ launchModeLabel: "After startup",
+ launchModeWindow: "Open the main window",
+ launchModeTray: "Stay in the tray",
+ requiresApproval: "Allow EdgeEver in System Settings to finish turning this on.",
+ saveFailed: "Could not save this setting.",
+ },
spellcheckTitle: "Underline spelling mistakes",
spellcheckAria: "Underline possible spelling mistakes in the note editor",
aiSelectionMenuTitle: "Show AI assistant when text is selected",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index ef4137e2..75682a48 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -1013,6 +1013,16 @@ export const ja = {
imageCompressionAria: "ノート内の画像を圧縮する",
showDescendantNotesTitle: "サブノートブックのノートを表示",
showDescendantNotesAria: "親ノートブックにサブノートブックのノートを表示する",
+ loginItem: {
+ title: "起動後に開く",
+ aria: "パソコンの起動後に EdgeEver を開く",
+ description: "パソコンの起動後、EdgeEver を自動で開きます。",
+ launchModeLabel: "起動後",
+ launchModeWindow: "メインウィンドウを開く",
+ launchModeTray: "トレイに残す",
+ requiresApproval: "システム設定で EdgeEver の起動を許可すると、この設定が有効になります。",
+ saveFailed: "この設定を保存できませんでした。",
+ },
spellcheckTitle: "スペルミスに下線を表示",
spellcheckAria: "ノートエディタでスペルミスの可能性がある語に下線を表示する",
aiSelectionMenuTitle: "文字選択時に AI アシスタントを表示",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 211f10d7..fe9374ff 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -1013,6 +1013,16 @@ export const pl = {
imageCompressionAria: "Kompresuj obrazy w notatkach",
showDescendantNotesTitle: "Pokazuj notatki z podnotatników",
showDescendantNotesAria: "Pokazuj notatki z podnotatników w notatnikach nadrzędnych",
+ loginItem: {
+ title: "Uruchamiaj po włączeniu komputera",
+ aria: "Uruchamiaj EdgeEver po włączeniu komputera",
+ description: "Otwieraj EdgeEver po uruchomieniu komputera.",
+ launchModeLabel: "Po uruchomieniu",
+ launchModeWindow: "Otwórz główne okno",
+ launchModeTray: "Zostaw w zasobniku",
+ requiresApproval: "Zezwól EdgeEver w ustawieniach systemu, aby dokończyć włączanie.",
+ saveFailed: "Nie udało się zapisać tego ustawienia.",
+ },
spellcheckTitle: "Podkreślaj błędy pisowni",
spellcheckAria: "Podkreślaj możliwe błędy pisowni w edytorze notatek",
aiSelectionMenuTitle: "Pokazuj asystenta AI po zaznaczeniu tekstu",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 7270f696..08ea32ef 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -1024,6 +1024,16 @@ export const zhCN = {
imageCompressionAria: "是否压缩笔记内图片",
showDescendantNotesTitle: "父笔记本中显示子笔记本笔记",
showDescendantNotesAria: "是否在父笔记本中显示子笔记本中的笔记",
+ loginItem: {
+ title: "开机后启动",
+ aria: "开机后启动 EdgeEver",
+ description: "开机后自动打开 EdgeEver。",
+ launchModeLabel: "启动后",
+ launchModeWindow: "打开主窗口",
+ launchModeTray: "只在托盘运行",
+ requiresApproval: "还需要在系统设置里允许 EdgeEver 开机后启动。",
+ saveFailed: "无法保存这项设置。",
+ },
spellcheckTitle: "标记拼写错误",
spellcheckAria: "是否在笔记编辑器中用波浪线标记可能的拼写错误",
aiSelectionMenuTitle: "选中文字时显示 AI 助手",