Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 支持 Windows 和 macOS 登录时自动启动 (#4533)

DavidShenXD143e12cd38be
diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nsh
index a60dfbadc8..5e151a509a 100644
--- a/apps/desktop/resources/installer.nsh
+++ b/apps/desktop/resources/installer.nsh
@@ -65,7 +65,24 @@
System::Call 'shell32::SHChangeNotify(i 0x08000000, i 0, i 0, i 0)'
!macroend
+; Electron registers the per-user login item under the executable basename.
+; Upgrades invoke the old uninstaller too: preserve both registration and the
+; user's StartupApproved state. Only remove entries owned by this install path.
+!macro cindyRemoveLoginItemOnUninstall
+ ${IfNot} ${isUpdated}
+ Push $R0
+ ReadRegStr $R0 HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCT_FILENAME}"
+ ${If} $R0 == '"$INSTDIR\${APP_EXECUTABLE_FILENAME}"'
+ ${OrIf} $R0 == '$INSTDIR\${APP_EXECUTABLE_FILENAME}'
+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCT_FILENAME}"
+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run" "${PRODUCT_FILENAME}"
+ ${EndIf}
+ Pop $R0
+ ${EndIf}
+!macroend
+
!macro customUnInstall
+ !insertmacro cindyRemoveLoginItemOnUninstall
; 卸载时清理本产品自己的快捷方式(不碰并存的老 XDMaker / 另一区域安装)
Delete "$DESKTOP\${SHORTCUT_NAME}.lnk"
Delete "$SMPROGRAMS\${SHORTCUT_NAME}.lnk"
diff --git a/apps/desktop/scripts/test-login-item-uninstall.mjs b/apps/desktop/scripts/test-login-item-uninstall.mjs
new file mode 100644
index 0000000000..54063bd555
--- /dev/null
+++ b/apps/desktop/scripts/test-login-item-uninstall.mjs
@@ -0,0 +1,121 @@
+/**
+ * Windows-only NSIS integration check, outside the default unit tier.
+ * Runs the production macro against a unique scratch registry subtree, never
+ * real startup entries. Set CINDY_NSIS_BIN if makensis is not already cached.
+ * Usage: node apps/desktop/scripts/test-login-item-uninstall.mjs
+ */
+import assert from 'node:assert/strict';
+import console from 'node:console';
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import process from 'node:process';
+import { fileURLToPath, URL } from 'node:url';
+
+assert.equal(process.platform, 'win32', 'This integration check requires Windows and NSIS.');
+const cache = path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),
+ 'electron-builder', 'Cache', 'nsis');
+const compiler = process.env.CINDY_NSIS_BIN || (fs.existsSync(cache)
+ ? fs.readdirSync(cache).filter((name) => name.startsWith('nsis-')).sort().reverse()
+ .map((name) => path.join(cache, name, 'Bin', 'makensis.exe')).find(fs.existsSync)
+ : undefined);
+assert.ok(compiler && fs.existsSync(compiler), 'Set CINDY_NSIS_BIN to makensis.exe.');
+const installer = fs.readFileSync(fileURLToPath(new URL('../resources/installer.nsh', import.meta.url)), 'utf8');
+const start = installer.indexOf('!macro cindyRemoveLoginItemOnUninstall');
+assert.ok(start >= 0);
+const macro = installer.slice(start, installer.indexOf('!macroend', start) + '!macroend'.length);
+const uninstallStart = installer.indexOf('!macro customUnInstall');
+const uninstall = installer.slice(uninstallStart, installer.indexOf('!macroend', uninstallStart));
+assert.ok(uninstall.includes('!insertmacro cindyRemoveLoginItemOnUninstall'));
+const registryRoot = path.win32.join('Software', 'CindyLoginItemUninstallTest', randomUUID());
+const runKey = path.win32.join(registryRoot, 'Run');
+const approvedKey = path.win32.join(registryRoot, 'StartupApproved');
+const windowsKey = path.win32.join('Software', 'Microsoft', 'Windows', 'CurrentVersion');
+const isolatedMacro = macro
+ .replaceAll(path.win32.join(windowsKey, 'Run'), runKey)
+ .replaceAll(path.win32.join(windowsKey, 'Explorer', 'StartupApproved', 'Run'), approvedKey);
+assert.ok(!isolatedMacro.includes(windowsKey), 'All registry access must be isolated.');
+const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-uninstall-check-'));
+const script = path.join(root, 'check.nsi');
+const binary = path.join(root, 'check.exe');
+const result = path.join(root, 'result.txt');
+const newline = String.fromCharCode(10);
+const nsisNewline = '$' + String.fromCharCode(92) + 'r$' + String.fromCharCode(92) + 'n';
+const ownBare = path.win32.join('$INSTDIR', '${APP_EXECUTABLE_FILENAME}');
+const ownQuoted = '"' + ownBare + '"';
+const other = '"' + path.win32.join('C:', 'Another Install', '${APP_EXECUTABLE_FILENAME}') + '"';
+const cases = [
+ { name: 'uninstall-enabled', command: ownQuoted, approval: '2', remove: true },
+ { name: 'uninstall-disabled', command: ownQuoted, approval: '3', remove: true },
+ { name: 'uninstall-unquoted', command: ownBare, approval: '2', remove: true },
+ { name: 'upgrade-enabled', command: ownQuoted, approval: '2', updated: true },
+ { name: 'upgrade-disabled', command: ownQuoted, approval: '3', updated: true },
+ { name: 'other-install', command: other, approval: '2' },
+ { name: 'different-arguments', command: `${ownQuoted} --other`, approval: '2' },
+ { name: 'missing-entry', command: '', approval: '' },
+];
+
+try {
+ const lines = [
+ '!include "LogicLib.nsh"',
+ '!define PRODUCT_FILENAME "CindyTest"',
+ '!define APP_EXECUTABLE_FILENAME "${PRODUCT_FILENAME}.exe"',
+ '!define isUpdated `$updating == 1`',
+ 'Name "Cindy login item uninstall check"',
+ `OutFile "${binary}"`,
+ 'RequestExecutionLevel user', 'SilentInstall silent',
+ 'Var updating', 'Var failures', 'Var report',
+ isolatedMacro,
+ 'Section', 'SetRegView 64', 'StrCpy $failures 0',
+ `StrCpy $INSTDIR "${path.win32.join('C:', 'Program Files', 'Cindy Test')}"`,
+ `FileOpen $report "${result}" w`,
+ `WriteRegStr HKCU "${runKey}" "AnotherProduct" "keep"`,
+ `WriteRegStr HKCU "${approvedKey}" "AnotherProduct" "keep"`,
+ ];
+ for (const scenario of cases) {
+ lines.push(
+ `DeleteRegValue HKCU "${runKey}" "CindyTest"`,
+ `DeleteRegValue HKCU "${approvedKey}" "CindyTest"`,
+ `StrCpy $updating ${scenario.updated ? 1 : 0}`,
+ 'StrCpy $R0 "caller-register"',
+ );
+ if (scenario.command) lines.push(`WriteRegStr HKCU "${runKey}" "CindyTest" '${scenario.command}'`);
+ // Cleanup must preserve or delete the entire value regardless of type.
+ // DWORD markers let NSIS assert both enabled/disabled states with ReadRegStr.
+ if (scenario.approval) lines.push(`WriteRegDWORD HKCU "${approvedKey}" "CindyTest" ${scenario.approval}`);
+ lines.push(
+ '!insertmacro cindyRemoveLoginItemOnUninstall',
+ '${If} $R0 != "caller-register"', 'IntOp $failures $failures + 1', '${EndIf}',
+ `ReadRegStr $R1 HKCU "${runKey}" "CindyTest"`,
+ `ReadRegStr $R2 HKCU "${approvedKey}" "CindyTest"`,
+ `StrCpy $R3 '${scenario.remove ? '' : scenario.command}'`,
+ `StrCpy $R4 '${scenario.remove ? '' : scenario.approval}'`,
+ '${If} $R1 != $R3', 'IntOp $failures $failures + 1', '${EndIf}',
+ '${If} $R2 != $R4', 'IntOp $failures $failures + 1', '${EndIf}',
+ `FileWrite $report '${scenario.name}: failures=$failures${nsisNewline}'`,
+ );
+ }
+ lines.push(
+ `ReadRegStr $R1 HKCU "${runKey}" "AnotherProduct"`,
+ `ReadRegStr $R2 HKCU "${approvedKey}" "AnotherProduct"`,
+ '${If} $R1 != "keep"', '${OrIf} $R2 != "keep"',
+ 'IntOp $failures $failures + 1', '${EndIf}',
+ `DeleteRegKey HKCU "${registryRoot}"`,
+ 'FileClose $report', 'SetErrorLevel $failures', 'SectionEnd',
+ );
+ fs.writeFileSync(script, lines.join(newline), 'utf8');
+ const compiled = spawnSync(compiler, ['/V2', script], { encoding: 'utf8', windowsHide: true, timeout: 60_000 });
+ assert.ifError(compiled.error);
+ assert.equal(compiled.status, 0, compiled.stderr || compiled.stdout);
+ const executed = spawnSync(binary, [], { encoding: 'utf8', windowsHide: true, timeout: 60_000 });
+ if (fs.existsSync(result)) process.stdout.write(fs.readFileSync(result, 'utf8'));
+ assert.ifError(executed.error);
+ assert.equal(executed.status, 0, 'NSIS cleanup assertions failed');
+ console.log(`PASS ${cases.length} NSIS uninstall scenarios; scratch registry removed.`);
+} finally {
+ spawnSync('reg.exe', ['delete', `HKCU${String.fromCharCode(92)}${registryRoot}`, '/f', '/reg:64'], { windowsHide: true, stdio: 'ignore' });
+ assert.ok(root.startsWith(path.join(os.tmpdir(), 'cindy-uninstall-check-')));
+ fs.rmSync(root, { recursive: true, force: true });
+}
diff --git a/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts b/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts
index 391acc5fbc..1a41755c21 100644
--- a/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts
@@ -20,9 +20,13 @@ describe('Ghost account-boundary teardown ordering', () => {
const end = bootstrap.indexOf('\n}\n', start);
const body = bootstrap.slice(start, end);
- const interrupt = body.indexOf('interruptGhostCallsForAccountBoundary));');
- const wait = body.indexOf('waitForGhostMutations));');
- const suspend = body.indexOf('suspendAllGhosts);');
+ const interrupt = body.search(
+ /withAuthBoundaryTimeout\(\s*'interrupt Ghost calls',\s*interruptGhostCallsForAccountBoundary\s*,?\s*\)/,
+ );
+ const wait = body.search(
+ /withAuthBoundaryTimeout\(\s*'wait for Ghost mutations',\s*waitForGhostMutations\s*,?\s*\)/,
+ );
+ const suspend = body.search(/await run\(\s*'suspendAllGhosts',\s*suspendAllGhosts\s*,?\s*\)/);
expect(interrupt).toBeGreaterThan(-1);
expect(interrupt).toBeLessThan(wait);
diff --git a/apps/desktop/src/main/__tests__/loginItemIpc.test.ts b/apps/desktop/src/main/__tests__/loginItemIpc.test.ts
new file mode 100644
index 0000000000..1cd91c2bde
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/loginItemIpc.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ handle: vi.fn(), guard: vi.fn(), read: vi.fn(), set: vi.fn() }));
+vi.mock('electron', () => ({ app: {}, ipcMain: { handle: mocks.handle } }));
+vi.mock('../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: mocks.guard,
+}));
+vi.mock('../login-item-settings.js', () => ({
+ createLoginItemSettings: () => ({ read: mocks.read, set: mocks.set }),
+}));
+
+import { registerLoginItemIpc } from '../login-item-ipc.js';
+
+describe('login startup IPC authorization', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ registerLoginItemIpc();
+ });
+
+ it.each(['login-item:get', 'login-item:set'])(
+ 'rejects untrusted senders before OS access on %s',
+ (channel) => {
+ const handler = mocks.handle.mock.calls.find(([name]) => name === channel)![1];
+ mocks.guard.mockImplementation(() => {
+ throw new Error('[PERMISSION_DENIED]');
+ });
+ expect(() => handler({}, true)).toThrow('[PERMISSION_DENIED]');
+ expect(mocks.read).not.toHaveBeenCalled();
+ expect(mocks.set).not.toHaveBeenCalled();
+ },
+ );
+
+ it('passes the event through the guard and the uncoerced payload through validation', () => {
+ const event = {};
+ const handler = mocks.handle.mock.calls.find(([name]) => name === 'login-item:set')![1];
+ handler(event, 'false');
+ expect(mocks.guard).toHaveBeenCalledWith(event);
+ expect(mocks.set).toHaveBeenCalledWith('false');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/loginItemSettings.test.ts b/apps/desktop/src/main/__tests__/loginItemSettings.test.ts
new file mode 100644
index 0000000000..8cac1c8245
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/loginItemSettings.test.ts
@@ -0,0 +1,200 @@
+import type { App, LoginItemSettings, Settings } from 'electron';
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLoginItemSettings } from '../login-item-settings.js';
+
+function fixture(platform: NodeJS.Platform = 'win32', isPackaged = true, executable?: string) {
+ const execPath =
+ executable ?? (platform === 'win32'
+ ? path.win32.join('C:', 'Program Files', 'Cindy', 'Cindy.exe')
+ : '/Applications/Cindy.app/Contents/MacOS/Cindy');
+ let native: LoginItemSettings = {
+ openAtLogin: false,
+ openAsHidden: false,
+ wasOpenedAtLogin: false,
+ wasOpenedAsHidden: false,
+ restoreState: false,
+ status: 'not-registered',
+ executableWillLaunchAtLogin: false,
+ launchItems: [],
+ };
+ const app = {
+ isPackaged,
+ getLoginItemSettings: vi.fn((options: Parameters<App['getLoginItemSettings']>[0]) => {
+ if (platform !== 'win32') return native;
+ // Electron 41 parses the lookup as a command line, not as a raw path.
+ const lookup = options?.path ?? execPath;
+ const program = lookup.startsWith('"') ? lookup.split('"')[1] : lookup.split(' ')[0];
+ const launchItems = native.launchItems.filter(
+ (item) => item.path.toLowerCase() === program.toLowerCase(),
+ );
+ return {
+ ...native,
+ launchItems,
+ executableWillLaunchAtLogin: launchItems.some((item) => item.enabled),
+ };
+ }),
+ setLoginItemSettings: vi.fn((settings: Settings) => {
+ native = {
+ ...native,
+ // On Windows openAtLogin reads only the AppUserModelID entry, not Cindy.
+ openAtLogin: platform !== 'win32' && settings.openAtLogin === true,
+ executableWillLaunchAtLogin: settings.openAtLogin === true,
+ status: settings.openAtLogin ? 'enabled' : 'not-registered',
+ launchItems: settings.openAtLogin
+ ? [{ name: 'Cindy', path: execPath, args: [], scope: 'user', enabled: true }]
+ : [],
+ };
+ }),
+ };
+ return {
+ app,
+ execPath,
+ service: createLoginItemSettings({ app, platform, execPath }),
+ changeNative: (patch: Partial<LoginItemSettings>) => {
+ native = { ...native, ...patch };
+ },
+ };
+}
+
+describe('native login startup preference', () => {
+ it.each(['win32', 'darwin'] as const)(
+ 'defaults off on %s without writing on construction or read',
+ (platform) => {
+ const { service, app } = fixture(platform);
+ expect(service.read()).toEqual({ available: true, enabled: false, requiresApproval: false });
+ expect(app.setLoginItemSettings).not.toHaveBeenCalled();
+ },
+ );
+
+ it('registers and removes the stable Windows executable with matching arguments', () => {
+ const { service, app, execPath } = fixture();
+ expect(service.set(true).enabled).toBe(true);
+ expect(app.setLoginItemSettings).toHaveBeenLastCalledWith({
+ path: execPath,
+ args: [],
+ name: 'Cindy',
+ openAtLogin: true,
+ enabled: true,
+ });
+ expect(app.getLoginItemSettings).toHaveBeenLastCalledWith({ path: `"${execPath}"`, args: [] });
+ expect(service.set(false).enabled).toBe(false);
+ expect(app.setLoginItemSettings).toHaveBeenLastCalledWith({
+ path: execPath,
+ args: [],
+ name: 'Cindy',
+ openAtLogin: false,
+ enabled: false,
+ });
+ });
+
+ it.each([
+ path.win32.join('C:', 'Cindy', 'Cindy.exe'),
+ path.win32.join('C:', 'Program Files', 'Cindy', 'Cindy.exe'),
+ path.win32.join('C:', 'Users', 'Test User', 'AppData', 'Local', 'Cindy', 'Cindy.exe'),
+ ])('reads the named Windows entry independently of openAtLogin at %s', (execPath) => {
+ const { service, app } = fixture('win32', true, execPath);
+ expect(service.set(true).enabled).toBe(true);
+ expect(app.getLoginItemSettings({ path: `"${execPath}"` }).openAtLogin).toBe(false);
+ expect(service.read().enabled).toBe(true);
+ expect(service.set(false).enabled).toBe(false);
+ expect(service.read().enabled).toBe(false);
+ });
+
+ it('ignores other Windows entry names, scopes and arguments', () => {
+ const { service, execPath, changeNative } = fixture();
+ changeNative({
+ openAtLogin: true,
+ launchItems: [
+ { name: 'Other entry', path: execPath, args: [], scope: 'user', enabled: true },
+ { name: 'Cindy', path: execPath, args: [], scope: 'machine', enabled: true },
+ { name: 'Cindy', path: execPath, args: ['--other'], scope: 'user', enabled: true },
+ ],
+ });
+ expect(service.read().enabled).toBe(false);
+ });
+
+ it('uses the native main app login service on macOS', () => {
+ const { service, app } = fixture('darwin');
+ expect(service.set(true).enabled).toBe(true);
+ expect(app.setLoginItemSettings).toHaveBeenLastCalledWith({ openAtLogin: true });
+ expect(service.set(false).enabled).toBe(false);
+ expect(app.setLoginItemSettings).toHaveBeenLastCalledWith({ openAtLogin: false });
+ });
+
+ it('reflects Task Manager disabling our entry even if another entry launches the executable', () => {
+ const { service, app, execPath, changeNative } = fixture();
+ service.set(true);
+ changeNative({
+ executableWillLaunchAtLogin: true,
+ launchItems: [
+ { name: 'Cindy', path: execPath, args: [], scope: 'user', enabled: false },
+ { name: 'Other entry', path: execPath, args: ['--other'], scope: 'user', enabled: true },
+ ],
+ });
+ expect(service.read().enabled).toBe(false);
+ expect(app.setLoginItemSettings).toHaveBeenCalledTimes(1);
+ expect(service.set(true).enabled).toBe(true);
+ });
+
+ it('reflects removal in macOS System Settings without restoring the item', () => {
+ const { service, app, changeNative } = fixture('darwin');
+ service.set(true);
+ changeNative({ openAtLogin: false, status: 'not-registered' });
+ expect(service.read().enabled).toBe(false);
+ expect(app.setLoginItemSettings).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports pending macOS approval and allows cancelling it', () => {
+ const { service, app, changeNative } = fixture('darwin');
+ app.setLoginItemSettings.mockImplementationOnce(() => {
+ changeNative({ openAtLogin: false, status: 'requires-approval' });
+ });
+ expect(service.set(true)).toEqual({ available: true, enabled: false, requiresApproval: true });
+ expect(service.set(false).requiresApproval).toBe(false);
+ });
+
+ it.each([
+ ['win32', false],
+ ['darwin', false],
+ ['linux', true],
+ ] as const)(
+ 'rejects unsupported environment %s packaged=%s before OS access',
+ (platform, packaged) => {
+ const { service, app } = fixture(platform, packaged);
+ expect(service.read().available).toBe(false);
+ expect(() => service.set(true)).toThrow('[UNSUPPORTED_CAPABILITY]');
+ expect(app.getLoginItemSettings).not.toHaveBeenCalled();
+ expect(app.setLoginItemSettings).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([null, undefined, 1, 'true', {}, []])(
+ 'rejects non-boolean input %j before OS access',
+ (input) => {
+ const { service, app } = fixture();
+ expect(() => service.set(input)).toThrow('[INVALID_PARAMS]');
+ expect(app.getLoginItemSettings).not.toHaveBeenCalled();
+ expect(app.setLoginItemSettings).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports silent system refusal instead of claiming the setting was saved', () => {
+ const { service, app } = fixture();
+ app.setLoginItemSettings.mockImplementation(() => undefined);
+ expect(() => service.set(true)).toThrow('[PRECONDITION_FAILED]');
+ });
+
+ it('sanitizes native read and write errors', () => {
+ const { service, app } = fixture();
+ app.getLoginItemSettings.mockImplementationOnce(() => {
+ throw new Error('private path');
+ });
+ expect(() => service.read()).toThrow('[INTERNAL] Unable to read login startup settings');
+ app.setLoginItemSettings.mockImplementationOnce(() => {
+ throw new Error('private path');
+ });
+ expect(() => service.set(true)).toThrow('[INTERNAL] Unable to update login startup settings');
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index d81fc45c55..bba6b9daff 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,3 +1,4 @@
+import { registerLoginItemIpc } from './login-item-ipc.js';
import { retainProviderPresentationAfterAuthChange } from './maker-host/provider-presentation-store.js';
import { codexAccountState } from './maker-host/codex-account-auth.js';
import { syncSubscriptionAccountUsage } from './usage/subscriptionAccountUsage.js';
@@ -2449,6 +2450,7 @@ registerBrowserBackendIpc();
// ipcMain.handle 在 app ready 前注册也有效。
registerAppShortcutIpc();
registerAppearanceSettingsIpc();
+registerLoginItemIpc();
// ── 资源用量面板 IPC ─────────────────────────────────────────────────
// 订阅驱动采样(面板不开不采样),interval 已 unref 不拖退出;terminate 只认
diff --git a/apps/desktop/src/main/login-item-ipc.ts b/apps/desktop/src/main/login-item-ipc.ts
new file mode 100644
index 0000000000..e5d991f881
--- /dev/null
+++ b/apps/desktop/src/main/login-item-ipc.ts
@@ -0,0 +1,22 @@
+import { app, ipcMain } from 'electron';
+
+import { LOGIN_ITEM_GET_CHANNEL, LOGIN_ITEM_SET_CHANNEL } from '../shared/loginItem.js';
+import { createLoginItemSettings } from './login-item-settings.js';
+import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';
+
+/** Local app-content IPC only: system-wide settings are not device-link capabilities. */
+export function registerLoginItemIpc(): void {
+ const settings = createLoginItemSettings({
+ app,
+ platform: process.platform,
+ execPath: process.execPath,
+ });
+ ipcMain.handle(LOGIN_ITEM_GET_CHANNEL, (event) => {
+ assertTrustedAppRendererEvent(event);
+ return settings.read();
+ });
+ ipcMain.handle(LOGIN_ITEM_SET_CHANNEL, (event, enabled: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return settings.set(enabled);
+ });
+}
diff --git a/apps/desktop/src/main/login-item-settings.ts b/apps/desktop/src/main/login-item-settings.ts
new file mode 100644
index 0000000000..b7a2ded9b8
--- /dev/null
+++ b/apps/desktop/src/main/login-item-settings.ts
@@ -0,0 +1,89 @@
+import path from 'node:path';
+import type { App } from 'electron';
+
+import type { LoginItemState } from '../shared/loginItem.js';
+import { requireBoolean, throwIpcError } from './utils/ipcValidate.js';
+
+/** Injectable OS adapter: tests never register real login items. */
+interface LoginItemDependencies {
+ app: Pick<App, 'isPackaged' | 'getLoginItemSettings' | 'setLoginItemSettings'>;
+ platform: NodeJS.Platform;
+ execPath: string;
+}
+
+/**
+ * The OS owns this preference, including changes made in System Settings.
+ * No registration on startup, no mirrored defaults and no automatic re-enabling.
+ * Absence of our login item is the default (off); disabling removes that override.
+ * Windows NSIS installs use a stable executable path, not Squirrel's Update.exe.
+ */
+export function createLoginItemSettings({ app, platform, execPath }: LoginItemDependencies) {
+ const windows = platform === 'win32';
+ const name = path.win32.basename(execPath, '.exe');
+ const target = windows ? { path: execPath, args: [] as string[] } : {};
+ // Electron 41 parses the lookup path as a command line. Quote only the
+ // query; setLoginItemSettings already quotes the executable when writing.
+ const query = windows ? { path: `"${execPath}"`, args: [] as string[] } : {};
+
+ function read(): LoginItemState {
+ const unavailableReason =
+ platform !== 'win32' && platform !== 'darwin'
+ ? 'platform'
+ : !app.isPackaged
+ ? 'development'
+ : undefined;
+ if (unavailableReason) {
+ return { available: false, unavailableReason, enabled: false, requiresApproval: false };
+ }
+ try {
+ const settings = app.getLoginItemSettings(query);
+ // Windows openAtLogin reads the AppUserModelID entry, not our explicit
+ // name. launchItems includes StartupApproved and all entries for this
+ // executable, so match our own user entry and arguments here.
+ const enabled = windows
+ ? settings.launchItems.some(
+ (item) =>
+ item.name === name &&
+ item.scope === 'user' &&
+ item.args.length === 0 &&
+ item.enabled,
+ )
+ : settings.openAtLogin;
+ return {
+ available: true,
+ enabled,
+ requiresApproval: !windows && settings.status === 'requires-approval',
+ };
+ } catch {
+ throwIpcError('INTERNAL', 'Unable to read login startup settings');
+ }
+ }
+
+ function set(rawEnabled: unknown): LoginItemState {
+ const enabled = requireBoolean(rawEnabled, 'enabled');
+ if (!read().available) {
+ throwIpcError(
+ 'UNSUPPORTED_CAPABILITY',
+ 'Login startup requires an installed Windows or macOS app',
+ );
+ }
+ try {
+ app.setLoginItemSettings({
+ ...target,
+ openAtLogin: enabled,
+ ...(windows ? { name, enabled } : {}),
+ });
+ } catch {
+ throwIpcError('INTERNAL', 'Unable to update login startup settings');
+ }
+ const state = read();
+ if (
+ enabled ? !state.enabled && !state.requiresApproval : state.enabled || state.requiresApproval
+ ) {
+ throwIpcError('PRECONDITION_FAILED', 'The system did not apply the login startup setting');
+ }
+ return state;
+ }
+
+ return { read, set };
+}
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts
index 7fa27d385a..14149ec625 100644
--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts
@@ -164,8 +164,8 @@ describe('account provider readiness wiring', () => {
/handle\.isLive\(\)\s*&&\s*accountProviderReadinessBarrier\.isCurrentAdoptable\(\)/,
);
- expect(bootstrapSource).toContain(
- 'accountProviderReadinessArm.publish(userId, startProviderReadiness, resumeIncompleteDiscovery)',
+ expect(bootstrapSource).toMatch(
+ /accountProviderReadinessArm\.publish\(\s*userId,\s*startProviderReadiness,\s*resumeIncompleteDiscovery\s*,?\s*\)/,
);
expect(bootstrapSource).toContain('accountProviderReadinessArm.clear()');
expect(bootstrapSource).toContain('startPendingAccountProviderReadiness = null');
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f81fd4c977..c606e8b85a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,6 +1,11 @@
import { invokeOpenPath } from './openPath';
import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';
import type { RoutineInput } from '@cindy/maker-scheduler';
+import {
+ LOGIN_ITEM_GET_CHANNEL,
+ LOGIN_ITEM_SET_CHANNEL,
+ type LoginItemState,
+} from '../shared/loginItem';
import type { BotToolsetContext } from '../shared/botRemoteCapabilities';
import { contextBridge, ipcRenderer, webUtils } from 'electron';
import { DESKTOP_LOCAL, type RemoteDesktopApi } from '../shared/remoteDesktop';
@@ -1698,6 +1703,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
},
windowBehavior: {
+ getLoginItem: (): Promise<LoginItemState> => ipcRenderer.invoke(LOGIN_ITEM_GET_CHANNEL),
+ setLoginItem: (enabled: boolean): Promise<LoginItemState> =>
+ ipcRenderer.invoke(LOGIN_ITEM_SET_CHANNEL, enabled),
// 通知 main 落盘"首次点击是否吞掉"。仅落盘,不改变已创建窗口的行为——macOS
// acceptFirstMouse 是 BrowserWindow 构造参数,需要下次启动才读到新值。Windows
// 上此调用只是保持 userData 落盘和 renderer localStorage 一致,Windows JS
diff --git a/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts b/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts
index 86fe5dd7ec..d68583e0b5 100644
--- a/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts
+++ b/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts
@@ -57,11 +57,11 @@ describe('Windows Acrylic resize backing contract', () => {
});
it('keeps the root material attribute in sync with runtime material changes', () => {
- expect(bootstrapSource).toContain(
- 'win.webContents.send(\n WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,\n config.backgroundMaterial,\n )',
+ expect(bootstrapSource).toMatch(
+ /win\.webContents\.send\(\s*WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,\s*config\.backgroundMaterial\s*,?\s*\)/,
);
- expect(secondaryWindowsSource).toContain(
- 'win.webContents.send(\n WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,\n config.backgroundMaterial,\n )',
+ expect(secondaryWindowsSource).toMatch(
+ /win\.webContents\.send\(\s*WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,\s*config\.backgroundMaterial\s*,?\s*\)/,
);
expect(preloadSource).toContain(
'fanOutWindowBackdropMaterialChanged((material) => {\n if (typeof material === \'string\' && isWindowsBackdropMaterial(material))',
diff --git a/apps/desktop/src/renderer/__tests__/windowBehaviorSection.test.tsx b/apps/desktop/src/renderer/__tests__/windowBehaviorSection.test.tsx
index 73fedc8598..97b019662f 100644
--- a/apps/desktop/src/renderer/__tests__/windowBehaviorSection.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/windowBehaviorSection.test.tsx
@@ -1,9 +1,10 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { WindowBehaviorSection } from '@/components/settings/WindowBehaviorSection';
+import type { LoginItemState } from '../../shared/loginItem';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -18,6 +19,16 @@ vi.mock('@/hooks/useSwallowActivationClickSettings', () => ({
}));
function installWindowBehaviorApi(platform: 'darwin' | 'linux' | 'win32') {
+ const getLoginItem = vi.fn(async (): Promise<LoginItemState> => ({
+ available: true,
+ enabled: false,
+ requiresApproval: false,
+ }));
+ const setLoginItem = vi.fn(async (enabled: boolean): Promise<LoginItemState> => ({
+ available: true,
+ enabled,
+ requiresApproval: false,
+ }));
const getWindowsCloseBehavior = vi.fn(async () => 'tray' as const);
const setWindowsCloseBehavior = vi.fn(async (behavior: 'quit' | 'tray') => behavior);
const getLinuxCloseBehavior = vi.fn(async () => 'minimize' as const);
@@ -27,6 +38,8 @@ function installWindowBehaviorApi(platform: 'darwin' | 'linux' | 'win32') {
value: {
platform,
windowBehavior: {
+ getLoginItem,
+ setLoginItem,
getWindowsCloseBehavior,
setWindowsCloseBehavior,
getLinuxCloseBehavior,
@@ -35,6 +48,8 @@ function installWindowBehaviorApi(platform: 'darwin' | 'linux' | 'win32') {
} as unknown as Window['electronAPI'],
});
return {
+ getLoginItem,
+ setLoginItem,
getWindowsCloseBehavior,
setWindowsCloseBehavior,
getLinuxCloseBehavior,
@@ -48,6 +63,117 @@ afterEach(() => {
delete (window as Partial<Window>).electronAPI;
});
+describe('WindowBehaviorSection login startup', () => {
+ const label = 'settings.windowBehavior.loginItem.label';
+
+ it.each(['win32', 'darwin'] as const)(
+ 'starts off on %s and saves explicit on/off choices',
+ async (platform) => {
+ const api = installWindowBehaviorApi(platform);
+ render(<WindowBehaviorSection />);
+ const toggle = screen.getByRole('switch', { name: label });
+ await waitFor(() => expect(toggle.hasAttribute('disabled')).toBe(false));
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ expect(api.setLoginItem).not.toHaveBeenCalled();
+ fireEvent.click(toggle);
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('true'));
+ expect(api.setLoginItem).toHaveBeenLastCalledWith(true);
+ fireEvent.click(toggle);
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('false'));
+ expect(api.setLoginItem).toHaveBeenLastCalledWith(false);
+ },
+ );
+
+ it('does not expose or query login startup on Linux', async () => {
+ const api = installWindowBehaviorApi('linux');
+ render(<WindowBehaviorSection />);
+ expect(screen.queryByRole('switch', { name: label })).toBeNull();
+ expect(api.getLoginItem).not.toHaveBeenCalled();
+ await act(async () => {});
+ });
+
+ it('keeps the development-build control disabled without an installation hint', async () => {
+ const api = installWindowBehaviorApi('win32');
+ api.getLoginItem.mockResolvedValue({
+ available: false,
+ unavailableReason: 'development',
+ enabled: false,
+ requiresApproval: false,
+ });
+ render(<WindowBehaviorSection />);
+ await act(async () => {});
+ expect(screen.queryByText('settings.windowBehavior.loginItem.development')).toBeNull();
+ expect(screen.getByRole('switch', { name: label }).hasAttribute('disabled')).toBe(true);
+ });
+
+ it('shows pending macOS approval and lets the user cancel registration', async () => {
+ const api = installWindowBehaviorApi('darwin');
+ api.getLoginItem.mockResolvedValue({ available: true, enabled: false, requiresApproval: true });
+ render(<WindowBehaviorSection />);
+ await screen.findByText('settings.windowBehavior.loginItem.requiresApproval');
+ const toggle = screen.getByRole('switch', { name: label });
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ fireEvent.click(toggle);
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('false'));
+ expect(api.setLoginItem).toHaveBeenCalledWith(false);
+ });
+
+ it('reloads system changes when returning to the window', async () => {
+ const api = installWindowBehaviorApi('win32');
+ render(<WindowBehaviorSection />);
+ const toggle = screen.getByRole('switch', { name: label });
+ await waitFor(() => expect(toggle.hasAttribute('disabled')).toBe(false));
+ api.getLoginItem.mockResolvedValue({ available: true, enabled: true, requiresApproval: false });
+ fireEvent.focus(window);
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('true'));
+ });
+
+ it('shows read failure instead of presenting an editable default', async () => {
+ const api = installWindowBehaviorApi('win32');
+ api.getLoginItem.mockRejectedValue(new Error('unavailable'));
+ render(<WindowBehaviorSection />);
+ await screen.findByText('settings.windowBehavior.loginItem.loadFailed');
+ expect(screen.getByRole('switch', { name: label }).hasAttribute('disabled')).toBe(true);
+ });
+
+ it('re-reads actual state after a rejected save and lets the user retry', async () => {
+ const api = installWindowBehaviorApi('win32');
+ api.setLoginItem.mockRejectedValueOnce(new Error('[PRECONDITION_FAILED] refused'));
+ render(<WindowBehaviorSection />);
+ const toggle = screen.getByRole('switch', { name: label });
+ await waitFor(() => expect(toggle.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(toggle);
+ await screen.findByText('settings.windowBehavior.loginItem.notApplied');
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ expect(toggle.hasAttribute('disabled')).toBe(false);
+ expect(api.getLoginItem).toHaveBeenCalledTimes(2);
+ fireEvent.click(toggle);
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('true'));
+ });
+
+ it('locks the switch and ignores focus refreshes while saving', async () => {
+ const api = installWindowBehaviorApi('win32');
+ let finish!: (state: LoginItemState) => void;
+ api.setLoginItem.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ render(<WindowBehaviorSection />);
+ const toggle = screen.getByRole('switch', { name: label });
+ await waitFor(() => expect(toggle.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(toggle);
+ expect(toggle.hasAttribute('disabled')).toBe(true);
+ fireEvent.focus(window);
+ fireEvent.click(toggle);
+ expect(api.getLoginItem).toHaveBeenCalledTimes(1);
+ expect(api.setLoginItem).toHaveBeenCalledTimes(1);
+ await act(async () => finish({ available: true, enabled: true, requiresApproval: false }));
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ });
+});
+
describe('WindowBehaviorSection close behavior', () => {
it('shows minimize and quit on Linux and persists Linux choices', async () => {
const api = installWindowBehaviorApi('linux');
@@ -64,7 +190,9 @@ describe('WindowBehaviorSection close behavior', () => {
screen.queryByRole('radio', { name: 'settings.windowBehavior.closeBehavior.tray' }),
).toBeNull();
- fireEvent.click(screen.getByRole('radio', { name: 'settings.windowBehavior.closeBehavior.quit' }));
+ fireEvent.click(
+ screen.getByRole('radio', { name: 'settings.windowBehavior.closeBehavior.quit' }),
+ );
await waitFor(() => expect(api.setLinuxCloseBehavior).toHaveBeenCalledWith('quit'));
expect(api.setWindowsCloseBehavior).not.toHaveBeenCalled();
@@ -86,11 +214,12 @@ describe('WindowBehaviorSection close behavior', () => {
).toBeNull();
});
- it('keeps close behavior settings hidden on macOS', () => {
+ it('keeps close behavior settings hidden on macOS', async () => {
installWindowBehaviorApi('darwin');
render(<WindowBehaviorSection />);
expect(screen.queryByText('settings.windowBehavior.closeBehavior.label')).toBeNull();
+ await waitFor(() => expect(screen.getByRole('switch', { name: 'settings.windowBehavior.loginItem.label' }).hasAttribute('disabled')).toBe(false));
});
});
diff --git a/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx b/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx
index 192d6d0bf7..34a5c7fd53 100644
--- a/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx
@@ -1,7 +1,8 @@
/**
* WindowBehaviorSection — 「应用行为」section:本机相关的应用级开关。
*
- * 三项设置:
+ * 应用设置:
+ * - 登录电脑后自动启动:Windows / macOS 的系统登录启动项,默认不注册。
* 1. 「保持电脑唤醒」(keepAwake):main 用 powerSaveBlocker 防系统休眠、放行锁屏,
* 让后台 agent / 定时任务持续运行。跨平台生效(mac/win/linux),故常驻显示。
* 2. 「关闭主窗口时」:Windows 选择退出或收起到托盘,Linux 选择退出或最小化。
@@ -21,6 +22,7 @@ import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import { useSwallowActivationClickSettings } from '@/hooks/useSwallowActivationClickSettings';
import { useKeepAwakeSetting } from '@/hooks/useKeepAwakeSetting';
+import { useLoginItemSetting } from '@/hooks/useLoginItemSetting';
import {
isLinuxCloseBehavior,
isWindowsCloseBehavior,
@@ -38,6 +40,7 @@ function BehaviorCard({
checked,
onCheckedChange,
ariaLabel,
+ disabled,
}: {
label: string;
hint: string;
@@ -45,6 +48,7 @@ function BehaviorCard({
checked: boolean;
onCheckedChange: (next: boolean) => void;
ariaLabel: string;
+ disabled?: boolean;
}) {
return (
<div
@@ -67,7 +71,12 @@ function BehaviorCard({
{note}
</div>
- <Switch checked={checked} onCheckedChange={onCheckedChange} aria-label={ariaLabel} />
+ <Switch
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ aria-label={ariaLabel}
+ disabled={disabled}
+ />
</div>
);
}
@@ -75,6 +84,7 @@ function BehaviorCard({
export function WindowBehaviorSection() {
const { enabled, setEnabled } = useSwallowActivationClickSettings();
const { keepAwake, setKeepAwake } = useKeepAwakeSetting();
+ const loginItem = useLoginItemSetting();
const { t } = useTranslation();
// macOS 上 acceptFirstMouse 是 Cocoa 级参数、只在 BrowserWindow 构造时读一次,
// 用户切完开关下次启动才生效——单独渲染一行"需要重启应用"避免和主 hint 混在
@@ -136,6 +146,31 @@ export function WindowBehaviorSection() {
ariaLabel={t('settings.devices.keepAwake')}
/>
+ {loginItem.supported && (
+ <BehaviorCard
+ label={t('settings.windowBehavior.loginItem.label')}
+ hint={t('settings.windowBehavior.loginItem.hint')}
+ checked={Boolean(loginItem.state?.enabled || loginItem.state?.requiresApproval)}
+ disabled={!loginItem.state?.available || loginItem.busy}
+ onCheckedChange={(enabled) => void loginItem.setEnabled(enabled)}
+ ariaLabel={t('settings.windowBehavior.loginItem.label')}
+ note={
+ <div
+ className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)]"
+ aria-live="polite"
+ >
+ {loginItem.error ? (
+ <p role="alert">{t(`settings.windowBehavior.loginItem.${loginItem.error}`)}</p>
+ ) : loginItem.state?.requiresApproval ? (
+ <p>{t('settings.windowBehavior.loginItem.requiresApproval')}</p>
+ ) : loginItem.busy ? (
+ <p>{t('settings.windowBehavior.loginItem.loading')}</p>
+ ) : null}
+ </div>
+ }
+ />
+ )}
+
{(isWindows || isLinux) && (
<div
className={cn(
diff --git a/apps/desktop/src/renderer/hooks/useLoginItemSetting.ts b/apps/desktop/src/renderer/hooks/useLoginItemSetting.ts
new file mode 100644
index 0000000000..36730f97ba
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useLoginItemSetting.ts
@@ -0,0 +1,76 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type { LoginItemState } from '../../shared/loginItem';
+import { extractIpcError } from '@/utils/ipcError';
+
+/** Reads native state on mount/focus; serializes edits and discards stale reads. */
+export function useLoginItemSetting() {
+ const [state, setState] = useState<LoginItemState | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<'loadFailed' | 'saveFailed' | 'notApplied' | null>(null);
+ const mounted = useRef(false);
+ const generation = useRef(0);
+ const saving = useRef(false);
+ const platform = window.electronAPI?.platform;
+ const supported = platform === 'win32' || platform === 'darwin';
+
+ const refresh = useCallback(async () => {
+ if (saving.current) return;
+ const current = ++generation.current;
+ setBusy(true);
+ try {
+ const next = await window.electronAPI.windowBehavior.getLoginItem();
+ if (mounted.current && generation.current === current) {
+ setState(next);
+ setError(null);
+ }
+ } catch {
+ if (mounted.current && generation.current === current) {
+ setState(null);
+ setError('loadFailed');
+ }
+ } finally {
+ if (mounted.current && generation.current === current) setBusy(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ mounted.current = true;
+ if (supported) {
+ void refresh();
+ window.addEventListener('focus', refresh);
+ }
+ return () => {
+ mounted.current = false;
+ ++generation.current;
+ window.removeEventListener('focus', refresh);
+ };
+ }, [supported, refresh]);
+
+ const setEnabled = useCallback(async (enabled: boolean) => {
+ if (saving.current) return;
+ saving.current = true;
+ const current = ++generation.current;
+ setBusy(true);
+ setError(null);
+ try {
+ const next = await window.electronAPI.windowBehavior.setLoginItem(enabled);
+ if (mounted.current && generation.current === current) setState(next);
+ } catch (err) {
+ // Native writes may have partially applied. Re-read instead of presenting
+ // an optimistic value or blindly rolling back the system setting.
+ const next = await window.electronAPI.windowBehavior.getLoginItem().catch(() => null);
+ if (mounted.current && generation.current === current) {
+ setState(next);
+ setError(
+ extractIpcError(err)?.code === 'PRECONDITION_FAILED' ? 'notApplied' : 'saveFailed',
+ );
+ }
+ } finally {
+ saving.current = false;
+ if (mounted.current && generation.current === current) setBusy(false);
+ }
+ }, []);
+
+ return { state, busy, error, setEnabled, supported };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 897c6db94c..cb9fd4ab1b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -680,6 +680,15 @@
"wecomGroupClearFailed": "Could not remove the Webhook"
},
"windowBehavior": {
+ "loginItem": {
+ "label": "Start Cindy at Login",
+ "hint": "Open Cindy automatically when you sign in to your computer. Off by default.",
+ "requiresApproval": "Allow Cindy in Login Items in macOS System Settings to finish enabling startup.",
+ "loading": "Reading system settings…",
+ "loadFailed": "Could not read startup settings. Reopen this settings page to retry.",
+ "saveFailed": "Could not save startup settings. Retry or check your system startup items.",
+ "notApplied": "The system did not apply this setting. Check your system startup items and retry."
+ },
"title": "App Behavior",
"closeBehavior": {
"label": "When closing the main window",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 0c8641e4b8..97de973d15 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -680,6 +680,15 @@
"wecomGroupClearFailed": "Webhook を削除できませんでした"
},
"windowBehavior": {
+ "loginItem": {
+ "label": "ログイン時に Cindy を自動起動",
+ "hint": "パソコンへのログイン時に Cindy を自動的に開きます。初期設定ではオフです。",
+ "requiresApproval": "自動起動を有効にするには、macOS のシステム設定のログイン項目で Cindy を許可してください。",
+ "loading": "システム設定を読み込み中…",
+ "loadFailed": "起動設定を読み込めませんでした。この設定ページを開き直して再試行してください。",
+ "saveFailed": "起動設定を保存できませんでした。再試行するか、システムの起動項目を確認してください。",
+ "notApplied": "システムに設定が反映されませんでした。システムの起動項目を確認して再試行してください。"
+ },
"title": "アプリの動作",
"closeBehavior": {
"label": "メインウィンドウを閉じるとき",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 3dbd6faa7c..a42f03b810 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -680,6 +680,15 @@
"wecomGroupClearFailed": "Webhook을 삭제하지 못했습니다"
},
"windowBehavior": {
+ "loginItem": {
+ "label": "로그인 시 Cindy 자동 시작",
+ "hint": "컴퓨터에 로그인하면 Cindy를 자동으로 엽니다. 기본값은 꺼짐입니다.",
+ "requiresApproval": "자동 시작을 켜려면 macOS 시스템 설정의 로그인 항목에서 Cindy를 허용하세요.",
+ "loading": "시스템 설정을 읽는 중…",
+ "loadFailed": "시작 설정을 읽지 못했습니다. 이 설정 페이지를 다시 열어 재시도하세요.",
+ "saveFailed": "시작 설정을 저장하지 못했습니다. 다시 시도하거나 시스템 시작 항목을 확인하세요.",
+ "notApplied": "시스템에 설정이 적용되지 않았습니다. 시스템 시작 항목을 확인한 후 다시 시도하세요."
+ },
"title": "앱 동작",
"closeBehavior": {
"label": "기본 창을 닫을 때",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 82bb5eb439..7bc6b5e25d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -680,6 +680,15 @@
"wecomGroupClearFailed": "Webhook 移除失败"
},
"windowBehavior": {
+ "loginItem": {
+ "label": "登录电脑后自动启动 Cindy",
+ "hint": "登录系统后自动打开 Cindy,默认关闭",
+ "requiresApproval": "请在 macOS 系统设置的登录项中允许 Cindy,完成后此设置才会生效",
+ "loading": "正在读取系统设置…",
+ "loadFailed": "无法读取启动设置,请重新打开此设置页重试",
+ "saveFailed": "无法保存启动设置,请重试或检查系统启动项",
+ "notApplied": "系统未应用此设置,请检查系统启动项后重试"
+ },
"title": "应用行为",
"closeBehavior": {
"label": "关闭主窗口时",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c2df51a0bd..14708bc120 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -680,6 +680,15 @@
"wecomGroupClearFailed": "Webhook 移除失敗"
},
"windowBehavior": {
+ "loginItem": {
+ "label": "登入電腦後自動啟動 Cindy",
+ "hint": "登入系統後自動開啟 Cindy,預設關閉",
+ "requiresApproval": "請在 macOS 系統設定的登入項目中允許 Cindy,完成後此設定才會生效",
+ "loading": "正在讀取系統設定…",
+ "loadFailed": "無法讀取啟動設定,請重新開啟此設定頁重試",
+ "saveFailed": "無法儲存啟動設定,請重試或檢查系統啟動項目",
+ "notApplied": "系統未套用此設定,請檢查系統啟動項目後重試"
+ },
"title": "應用行為",
"closeBehavior": {
"label": "關閉主視窗時",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index eaa4e74bb4..435eb2e075 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1901,6 +1901,8 @@ interface ElectronAPI {
};
windowBehavior: {
+ getLoginItem: () => Promise<import('../shared/loginItem').LoginItemState>;
+ setLoginItem: (enabled: boolean) => Promise<import('../shared/loginItem').LoginItemState>;
setSwallowActivationClick: (enabled: boolean) => Promise<{ ok: true }>;
getWindowsCloseBehavior: () => Promise<'quit' | 'tray' | null>;
setWindowsCloseBehavior: (behavior: 'quit' | 'tray') => Promise<'quit' | 'tray'>;
diff --git a/apps/desktop/src/shared/loginItem.ts b/apps/desktop/src/shared/loginItem.ts
new file mode 100644
index 0000000000..0ab164301d
--- /dev/null
+++ b/apps/desktop/src/shared/loginItem.ts
@@ -0,0 +1,10 @@
+/** OS-owned login startup setting; only the local desktop may change it. */
+export interface LoginItemState {
+ available: boolean;
+ unavailableReason?: 'development' | 'platform';
+ enabled: boolean;
+ requiresApproval: boolean;
+}
+
+export const LOGIN_ITEM_GET_CHANNEL = 'login-item:get';
+export const LOGIN_ITEM_SET_CHANNEL = 'login-item:set';