@pmate/cli 0.44.0 → 0.44.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -18275,6 +18275,7 @@ var import_node_child_process9 = require("child_process");
18275
18275
  var import_node_fs21 = require("fs");
18276
18276
  var import_node_os10 = require("os");
18277
18277
  var import_node_path26 = __toESM(require("path"));
18278
+ var import_sharp2 = __toESM(require("sharp"));
18278
18279
 
18279
18280
  // src/desktopRelease.ts
18280
18281
  init_sessionStore();
@@ -18335,6 +18336,11 @@ function readDesktopConfig(file, appId) {
18335
18336
  if (c.externalOrigins !== void 0 && !Array.isArray(c.externalOrigins)) throw new Error("externalOrigins must be an array");
18336
18337
  c.externalOrigins?.forEach(origin);
18337
18338
  if (c.notaryProfile !== void 0 && (typeof c.notaryProfile !== "string" || !c.notaryProfile.trim())) throw new Error("Invalid notaryProfile");
18339
+ if (c.tray !== void 0) {
18340
+ if (!c.tray || typeof c.tray !== "object" || typeof c.tray.icon !== "string" || !c.tray.icon.trim()) throw new Error("Invalid desktop tray icon");
18341
+ if (c.tray.platforms !== void 0 && (!Array.isArray(c.tray.platforms) || !c.tray.platforms.length || c.tray.platforms.some((value) => !["mac", "win"].includes(value)))) throw new Error("Invalid desktop tray platforms");
18342
+ if (c.tray.closeToTray !== void 0 && typeof c.tray.closeToTray !== "boolean") throw new Error("Invalid desktop closeToTray");
18343
+ }
18338
18344
  if ("web" in c) throw new Error("Remote desktop builds do not accept web build configuration; remove web");
18339
18345
  return c;
18340
18346
  }
@@ -18407,16 +18413,26 @@ async function runBuildCommand(command, cwd, env = process.env) {
18407
18413
  child.once("exit", (code, signal) => code === 0 ? resolve() : reject(new Error(`${command[0]} failed (${signal ?? code})`)));
18408
18414
  });
18409
18415
  }
18416
+ async function renderTrayIcons(source, output) {
18417
+ const idle = await (0, import_sharp2.default)(source).resize(36, 36, { fit: "contain" }).png().toBuffer();
18418
+ const gap = Buffer.from('<svg width="36" height="36" xmlns="http://www.w3.org/2000/svg"><circle cx="30" cy="6" r="7" fill="#000"/></svg>');
18419
+ const dot = Buffer.from('<svg width="36" height="36" xmlns="http://www.w3.org/2000/svg"><circle cx="30" cy="6" r="5" fill="#000"/></svg>');
18420
+ await (0, import_sharp2.default)(idle).toFile(import_node_path26.default.join(output, "trayTemplate.png"));
18421
+ await (0, import_sharp2.default)(idle).composite([{ input: gap, blend: "dest-out" }, { input: dot }]).png().toFile(import_node_path26.default.join(output, "trayUnreadTemplate.png"));
18422
+ }
18410
18423
  async function buildDesktop(args) {
18411
18424
  const { file, output } = resolveDesktopPaths(args);
18412
18425
  const c = readDesktopConfig(file, args.id);
18413
18426
  const base = import_node_path26.default.dirname(file);
18414
18427
  const icon = import_node_path26.default.resolve(base, c.icon);
18428
+ const tray = c.tray && (!c.tray.platforms || c.tray.platforms.includes(args.platform)) ? c.tray : void 0;
18429
+ const trayIcon = tray ? import_node_path26.default.resolve(base, tray.icon) : void 0;
18415
18430
  const env = desktopBuildEnvironment(c);
18416
18431
  if (!(0, import_node_fs21.existsSync)(icon) || !(0, import_node_fs21.statSync)(icon).isFile()) throw new Error(`Desktop icon not found: ${icon}`);
18432
+ if (trayIcon && (!(0, import_node_fs21.existsSync)(trayIcon) || !(0, import_node_fs21.statSync)(trayIcon).isFile())) throw new Error(`Desktop tray icon not found: ${trayIcon}`);
18417
18433
  if (!["mac", "win"].includes(args.platform) || !["arm64", "x64"].includes(args.arch)) throw new Error("Supported target: mac|win --arch arm64|x64");
18418
18434
  if (args.platform === "mac" && process.platform !== "darwin") throw new Error("macOS desktop packaging requires a macOS build host");
18419
- const plan = { config: file, notaryProfile: env.APPLE_KEYCHAIN_PROFILE, app: c.app, productName: c.productName, version: c.version, target: "electron", platform: args.platform, arch: args.arch, contentSource: "remote", origin: c.origin, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
18435
+ const plan = { config: file, notaryProfile: env.APPLE_KEYCHAIN_PROFILE, app: c.app, productName: c.productName, version: c.version, target: "electron", platform: args.platform, arch: args.arch, contentSource: "remote", origin: c.origin, tray: !!tray, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
18420
18436
  console.log(JSON.stringify({ phase: "plan", ...plan }, null, 2));
18421
18437
  if (args.dryRun) return;
18422
18438
  if (args.signed && args.platform === "mac") {
@@ -18429,7 +18445,8 @@ async function buildDesktop(args) {
18429
18445
  (0, import_node_fs21.mkdirSync)(appDir);
18430
18446
  const templateDir = import_node_path26.default.join(__dirname, "templates", "electron");
18431
18447
  (0, import_node_fs21.cpSync)(templateDir, appDir, { recursive: true });
18432
- (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(appDir, "desktop-config.json"), JSON.stringify({ app: c.app, productName: c.productName, origin: c.origin, authOrigins: c.authOrigins, externalOrigins: c.externalOrigins ?? [], bundleId: c.bundleId }));
18448
+ if (trayIcon) await renderTrayIcons(trayIcon, appDir);
18449
+ (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(appDir, "desktop-config.json"), JSON.stringify({ app: c.app, productName: c.productName, origin: c.origin, authOrigins: c.authOrigins, externalOrigins: c.externalOrigins ?? [], bundleId: c.bundleId, ...tray ? { tray: { closeToTray: tray.closeToTray !== false } } : {} }));
18433
18450
  (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(appDir, "package.json"), JSON.stringify({ name: c.bundleId.replace(/\./g, "-"), version: c.version, description: `${c.productName} desktop application`, author: "PMate", main: "main.cjs", dependencies: { "@pmate/chat-sdk": "0.11.7", "electron-updater": "6.8.3" } }));
18434
18451
  await runBuildCommand(["npm", "install", "--omit=dev", "--no-audit", "--no-fund"], appDir);
18435
18452
  const cache = import_node_path26.default.join((0, import_node_os10.homedir)(), ".cache", "pmate", "electron", `${ELECTRON_VERSION}-${BUILDER_VERSION}`);
@@ -0,0 +1,73 @@
1
+ const { execFile } = require('node:child_process')
2
+ const { existsSync, mkdirSync } = require('node:fs')
3
+ const { homedir } = require('node:os')
4
+ const path = require('node:path')
5
+ const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','runtime.checkEnvironment','runtime.install','runtime.status','scripts.run']
6
+ function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch } = {}) {
7
+ let identity, installation, progress = { phase: 'idle' }
8
+ const root = path.join(home, '.pmate', 'merry-runtime')
9
+ const run = execute || ((file, args, cwd) => new Promise((resolve, reject) => {
10
+ execFile(file, args, { cwd, timeout: 600000, maxBuffer: 1024 * 1024, env: { ...process.env, PATH: [path.join(home,'.bun/bin'),'/opt/homebrew/bin','/usr/local/bin',process.env.PATH].filter(Boolean).join(':'), GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
11
+ }))
12
+ const installed = async () => {
13
+ if(existsSync(path.join(root,'packages/pmate-agent-tools/src/cli.ts')))return true
14
+ try{await run('pmate-agent-tools',['plugin','--help']);return true}catch{return false}
15
+ }
16
+ const check = async () => {
17
+ const checks = [{ id:'macos', name:'macOS', ready:platform==='darwin', required:true }]
18
+ for (const name of ['git','node','bun','pnpm']) { let version; try { version=await run(name,['--version']) } catch {} checks.push({id:name,name,ready:!!version&&(name!=='node'||Number(version.replace(/^v/,'').split('.')[0])>=24),version,required:true}) }
19
+ return { supported:platform==='darwin', checks, installed:await installed() }
20
+ }
21
+ const api = async (route, method='GET', body) => {
22
+ if (!identity) throw new Error('请先登录梅丽号')
23
+ const response = await fetcher(`https://issue-api.pmate.chat${route}`, { method, headers: { authorization:`Bearer ${identity.token}`, 'x-pmate-app':identity.appId, 'content-type':'application/json' }, ...(body===undefined?{}:{body:JSON.stringify(body)}), signal:AbortSignal.timeout(30000) })
24
+ const value=await response.json()
25
+ if(!response.ok||!value.success)throw new Error(value.message||`Issues API 请求失败 (${response.status})`)
26
+ return value.data
27
+ }
28
+ const install = async () => {
29
+ if (installation) return installation
30
+ installation=(async()=>{
31
+ try {
32
+ const environment=await check()
33
+ if(!environment.supported)throw new Error('Runtime 目前仅支持 macOS')
34
+ const missing=environment.checks.filter(c=>!c.ready).map(c=>c.name)
35
+ if(missing.length)throw new Error(`请先安装 ${missing.join('、')},然后重新检测`)
36
+ if(environment.installed&&!existsSync(root)){progress={phase:'ready',message:'已检测到现有 Runtime'};return progress}
37
+ if(existsSync(root)&&!environment.installed)throw new Error('安装目录已存在但不完整,请检查后重试;不会覆盖现有文件')
38
+ if(!environment.installed){mkdirSync(path.dirname(root),{recursive:true,mode:0o700});progress={phase:'downloading',message:'正在获取 Runtime 源码'};await run('git',['clone','https://github.com/parrot-mate/pmate-agents.git',root])}
39
+ progress={phase:'installing',message:'正在安装依赖'}
40
+ await run('pnpm',['install','--frozen-lockfile','--ignore-scripts'],root)
41
+ progress={phase:'verifying',message:'正在验证 Runtime'}
42
+ await run('bun',['packages/pmate-agent-tools/src/cli.ts','plugin','--help'],root)
43
+ progress={phase:'ready',message:'Runtime 已安装'}
44
+ return progress
45
+ }catch(error){progress={phase:'error',error:error.message};throw error}finally{installation=undefined}
46
+ })()
47
+ return installation
48
+ }
49
+ const invoke = async (method,input) => {
50
+ if(!methods.includes(method))throw new Error('ELECTRON_METHOD_UNAVAILABLE')
51
+ if(method==='capabilities')return methods
52
+ if(method==='runtime.checkEnvironment')return check()
53
+ if(method==='runtime.status')return {...progress,installed:await installed()}
54
+ if(method==='runtime.install')return install()
55
+ if(method==='scripts.run') {if(input?.id!=='runtime.repair'||!input.args||Object.keys(input.args).length)throw new Error('未知安装操作');return install()}
56
+ if(method==='workspaces.list')return api('/v2/workspaces')
57
+ const {scope,id,config,expectedRevision}=input||{}
58
+ if(!scope||!['namespace','topic'].every(k=>typeof scope[k]==='string'&&/^[a-z0-9][a-z0-9_-]{0,127}$/.test(scope[k])))throw new Error('无效工作区')
59
+ const base=`/v2/topics/${encodeURIComponent(scope.namespace)}/${encodeURIComponent(scope.topic)}`
60
+ if(method==='agents.list')return api(base+'/vega-agents')
61
+ if(method==='plugins.list')return api(base+'/runtime-plugins')
62
+ if(typeof id!=='string'||!/^(?:[a-z][a-z0-9-]*:)?[a-z][a-z0-9-]*$/.test(id)||!config||typeof config!=='object'||Array.isArray(config))throw new Error('无效配置')
63
+ if(Object.hasOwn(config,'expectedRevision'))throw new Error('revision 必须单独指定')
64
+ if(method!=='agents.create'&&(!Number.isSafeInteger(expectedRevision)||expectedRevision<1))throw new Error('更新需要 revision')
65
+ if(method==='agents.create'&&expectedRevision!==undefined)throw new Error('创建不能指定 revision')
66
+ return api(base+(method==='plugins.configure'?'/runtime-plugins/':'/vega-agents/')+encodeURIComponent(id),'PUT',{...config,...(expectedRevision===undefined?{}:{expectedRevision})})
67
+ }
68
+ return { invoke, setIdentity(value) { identity=value ? {appId:value.appId,token:value.token} : undefined } }
69
+ }
70
+ function installAgentRuntime({ ipcMain, trusted, runtime }) {
71
+ ipcMain.handle('pmate:electron:invoke',(event,method,input)=>{if(!trusted(event))throw new Error('Untrusted Electron sender');return runtime.invoke(method,input)})
72
+ }
73
+ module.exports={createAgentRuntime,installAgentRuntime}
@@ -1,5 +1,5 @@
1
1
  const { createUpdateChecker, installUpdateHandlers } = require('./updates.cjs')
2
- const { app, BrowserWindow, session, shell, Menu, desktopCapturer, ipcMain, Notification, dialog } = require('electron')
2
+ const { app, BrowserWindow, session, shell, Menu, Tray, nativeImage, desktopCapturer, ipcMain, Notification, dialog } = require('electron')
3
3
  const path = require('node:path')
4
4
  const { installNotificationSettings } = require('./notification-settings.cjs')
5
5
  const { installMediaPermissions } = require('./media.cjs')
@@ -9,26 +9,37 @@ const { createRendererReach } = require('./reach-renderer.cjs')
9
9
  const { createDesktopCalls, supportsDesktopCalls } = require('./calls.cjs')
10
10
  const { installNavigationRestrictions } = require('./navigation.cjs')
11
11
  const { installDesktopApps } = require('./apps.cjs')
12
+ const { createDesktopTray } = require('./tray.cjs')
13
+ const { createAgentRuntime, installAgentRuntime } = require('./agent-runtime.cjs')
14
+ const agentRuntime = createAgentRuntime()
12
15
  const config = require('./desktop-config.json')
13
16
  app.setName(config.productName)
14
17
  if (process.platform === 'win32') app.setAppUserModelId(config.bundleId)
15
18
  // Stable across installer versions; separate from every other packaged PMate app.
16
19
  app.setPath('userData', path.join(app.getPath('appData'), config.bundleId))
17
20
  let mainWindow
18
- let desktopNotifications, desktopReach, desktopCalls, desktopApps
21
+ let desktopNotifications, desktopReach, desktopCalls, desktopApps, desktopTray
19
22
  function createWindow() {
20
- mainWindow = new BrowserWindow({ width: 1180, height: 820, minWidth: 380, minHeight: 540, title: config.productName, backgroundColor: '#f6f8fb', webPreferences: { additionalArguments: [`--pmate-app-version=${app.getVersion()}`, `--pmate-origin=${config.origin}`, `--pmate-desktop-calls=${supportsDesktopCalls(config.app)}`], preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:desktop', nodeIntegration: false, contextIsolation: true, sandbox: true, webSecurity: true } })
23
+ mainWindow = new BrowserWindow({ width: 1180, height: 820, minWidth: 380, minHeight: 540, title: config.productName, backgroundColor: '#f6f8fb', webPreferences: { additionalArguments: [`--pmate-app-version=${app.getVersion()}`, `--pmate-origin=${config.origin}`, `--pmate-desktop-calls=${supportsDesktopCalls(config.app)}`, `--pmate-desktop-tray=${!!config.tray}`], preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:desktop', nodeIntegration: false, contextIsolation: true, sandbox: true, webSecurity: true } })
21
24
  installNavigationRestrictions(mainWindow, config, url => shell.openExternal(url))
22
25
  mainWindow.webContents.on('did-start-navigation', (_event, _url, _inPlace, mainFrame) => { if (mainFrame) desktopNotifications?.clearContext() })
23
26
  mainWindow.webContents.on('did-fail-load', (_event, code, _description, url, mainFrame) => {
24
27
  if (mainFrame && code !== -3 && url !== `${config.origin}/_desktop/offline`) void mainWindow.loadURL(`${config.origin}/_desktop/offline`).catch(error => console.error("Offline page failed:", error.message))
25
28
  })
26
29
  void mainWindow.loadURL(config.origin).catch(error => console.error("Page load failed:", error.message))
30
+ mainWindow.on('close', event => { if (desktopTray?.shouldHideOnClose()) { event.preventDefault(); mainWindow.hide() } })
27
31
  mainWindow.on('closed', () => { mainWindow = null })
32
+ return mainWindow
33
+ }
34
+ function showMainWindow() {
35
+ if (!mainWindow) createWindow()
36
+ if (mainWindow.isMinimized()) mainWindow.restore()
37
+ mainWindow.show(); mainWindow.focus()
38
+ return mainWindow
28
39
  }
29
40
  if (!app.requestSingleInstanceLock()) app.quit()
30
41
  else {
31
- app.on('second-instance', () => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus() } })
42
+ app.on('second-instance', showMainWindow)
32
43
  app.whenReady().then(() => {
33
44
  const desktopSession = session.fromPartition('persist:desktop')
34
45
  desktopSession.protocol.handle('https', request => {
@@ -47,16 +58,17 @@ else {
47
58
  installNotificationSettings({ ipcMain, shell, origin: config.origin, getWindow: () => mainWindow })
48
59
  let updateController
49
60
  const checkForUpdates = createUpdateChecker({ app, dialog, shell, appId: config.app, getController: () => updateController })
61
+ if (config.tray) desktopTray = createDesktopTray({ Tray, Menu, nativeImage, iconPath: path.join(__dirname, 'trayTemplate.png'), unreadIconPath: path.join(__dirname, 'trayUnreadTemplate.png'),
62
+ productName: config.productName, getWindow: () => mainWindow, createWindow, checkForUpdates, quit: () => app.quit(), closeToTray: config.tray.closeToTray !== false })
50
63
  Menu.setApplicationMenu(Menu.buildFromTemplate([
51
64
  { role: 'appMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' },
52
65
  { label: config.productName, submenu: [{ label: '检查更新…', click: checkForUpdates }, { type: 'separator' }, { label: 'Back to app', click: () => { if (!mainWindow) createWindow(); else void mainWindow.loadURL(config.origin).catch(error => console.error("Page load failed:", error.message)) } }] },
53
66
  ]))
54
- desktopNotifications = createDesktopNotifications({ ipcMain, Notification, origin: config.origin, appId: config.app, getWindow: () => mainWindow, showWindow: () => {
55
- if (!mainWindow) createWindow()
56
- if (mainWindow.isMinimized()) mainWindow.restore()
57
- mainWindow.show(); mainWindow.focus()
58
- return mainWindow
59
- } })
67
+ desktopNotifications = createDesktopNotifications({ ipcMain, Notification, origin: config.origin, appId: config.app, getWindow: () => mainWindow, showWindow: showMainWindow })
68
+ if (desktopTray) ipcMain.handle('pmate:tray:unread', (event, count) => {
69
+ if (!desktopNotifications.trusted(event) || !Number.isSafeInteger(count) || count < 0 || count > 999999) throw new Error('Invalid tray unread count')
70
+ desktopTray.setUnread(count)
71
+ })
60
72
  desktopApps = installDesktopApps({ ipcMain, BrowserWindow, session: desktopSession, config, installNavigationRestrictions,
61
73
  openExternal: url => shell.openExternal(url), trusted: event => desktopNotifications.trusted(event) })
62
74
  updateController = installUpdateHandlers({ ipcMain, app, shell, appId: config.app, trusted: event => desktopNotifications.trusted(event), updater: require('electron-updater').autoUpdater, getWindow: () => mainWindow })
@@ -81,17 +93,21 @@ else {
81
93
  if (!desktopNotifications.trusted(event) || !desktopCalls) throw new Error('Untrusted call sender')
82
94
  desktopCalls.setPeople(people)
83
95
  })
84
- ipcMain.handle('pmate:reach:configure', (event, identity) => {
96
+ ipcMain.handle('pmate:reach:configure', async (event, identity) => {
85
97
  if (!desktopNotifications.trusted(event)) throw new Error('Untrusted reach sender')
86
- return desktopReach.configure(identity)
98
+ const result = await desktopReach.configure(identity)
99
+ agentRuntime.setIdentity(identity)
100
+ return result
87
101
  })
88
102
  ipcMain.handle('pmate:reach:stop', event => {
89
103
  if (!desktopNotifications.trusted(event)) throw new Error('Untrusted reach sender')
104
+ agentRuntime.setIdentity(null)
90
105
  desktopReach.stop(); desktopNotifications.reset()
91
106
  })
92
- app.on('before-quit', () => { desktopApps.close(); desktopReach.stop(); desktopNotifications.reset() })
107
+ app.on('before-quit', () => { desktopTray?.beginQuit(); desktopApps.close(); desktopReach.stop(); desktopNotifications.reset() })
108
+ app.on('will-quit', () => desktopTray?.destroy())
93
109
  createWindow()
94
- app.on('activate', () => { if (!mainWindow) createWindow() })
110
+ app.on('activate', showMainWindow)
95
111
  }).catch(error => { console.error('Desktop startup failed:', error.message); app.exit(1) })
96
- app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() })
112
+ app.on('window-all-closed', () => { if (!config.tray && process.platform !== 'darwin') app.quit() })
97
113
  }
@@ -1,7 +1,8 @@
1
1
  const { contextBridge, ipcRenderer } = require('electron')
2
2
  const origin = process.argv.find(value => value.startsWith('--pmate-origin='))?.slice('--pmate-origin='.length)
3
3
  if (process.isMainFrame && location.origin === origin) contextBridge.exposeInMainWorld('pmateDesktop', Object.freeze({
4
- runtime: Object.freeze({ platform: process.platform, appVersion: process.argv.find(value => value.startsWith('--pmate-app-version='))?.slice('--pmate-app-version='.length), electronVersion: process.versions.electron, bridgeVersion: '1.2.0', contentSource: 'remote' }),
4
+ runtime: Object.freeze({ platform: process.platform, appVersion: process.argv.find(value => value.startsWith('--pmate-app-version='))?.slice('--pmate-app-version='.length), electronVersion: process.versions.electron, bridgeVersion: '1.3.0', contentSource: 'remote' }),
5
+ electron: Object.freeze({ invoke: (method, input) => ipcRenderer.invoke('pmate:electron:invoke', method, input) }),
5
6
  updates: Object.freeze({
6
7
  check: () => ipcRenderer.invoke('pmate:update:check'),
7
8
  download: () => ipcRenderer.invoke('pmate:update:download'),
@@ -15,6 +16,9 @@ if (process.isMainFrame && location.origin === origin) contextBridge.exposeInMai
15
16
  apps: Object.freeze({
16
17
  open: url => ipcRenderer.invoke('pmate:app:open', url),
17
18
  }),
19
+ tray: process.argv.includes('--pmate-desktop-tray=true') ? Object.freeze({
20
+ setUnread: count => ipcRenderer.invoke('pmate:tray:unread', count),
21
+ }) : undefined,
18
22
  reach: Object.freeze({
19
23
  onEvent: handler => {
20
24
  const listener = (_event, value) => {
@@ -0,0 +1,49 @@
1
+ function createDesktopTray({ Tray, Menu, nativeImage, iconPath, unreadIconPath, productName, platform = process.platform, getWindow, createWindow, checkForUpdates, quit, closeToTray = true }) {
2
+ const load = path => {
3
+ const source = nativeImage.createFromPath(path)
4
+ if (source.isEmpty()) throw new Error(`Invalid tray icon: ${path}`)
5
+ const image = source.resize({ width: 18, height: 18, quality: 'best' })
6
+ if (platform === 'darwin') image.setTemplateImage(true)
7
+ return image
8
+ }
9
+ const icons = { idle: load(iconPath), unread: load(unreadIconPath) }
10
+ const tray = new Tray(icons.idle)
11
+ let quitting = false
12
+
13
+ const show = () => {
14
+ const window = getWindow() ?? createWindow()
15
+ if (window.isMinimized()) window.restore()
16
+ window.show()
17
+ window.focus()
18
+ return window
19
+ }
20
+ const hide = () => getWindow()?.hide()
21
+ const toggle = () => {
22
+ const window = getWindow()
23
+ if (window?.isVisible()) hide()
24
+ else show()
25
+ }
26
+ const menu = () => Menu.buildFromTemplate([
27
+ { label: `打开 ${productName}`, click: show },
28
+ { label: `隐藏 ${productName}`, enabled: !!getWindow()?.isVisible(), click: hide },
29
+ { type: 'separator' },
30
+ { label: '检查更新…', click: checkForUpdates },
31
+ { type: 'separator' },
32
+ { label: `退出 ${productName}`, click: () => { quitting = true; quit() } },
33
+ ])
34
+
35
+ tray.setToolTip(productName)
36
+ if (platform === 'darwin') tray.setIgnoreDoubleClickEvents(true)
37
+ tray.on('click', toggle)
38
+ tray.on('right-click', () => tray.popUpContextMenu(menu()))
39
+ return {
40
+ show,
41
+ hide,
42
+ setUnread(count) { tray.setImage(count > 0 ? icons.unread : icons.idle) },
43
+ shouldHideOnClose() { return closeToTray && !quitting },
44
+ beginQuit() { quitting = true },
45
+ destroy() { tray.destroy() },
46
+ }
47
+ }
48
+
49
+ module.exports = { createDesktopTray }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.44.0",
3
+ "version": "0.44.2",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {