mcp-ssh-manager 3.8.7 → 4.0.1

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.
Files changed (104) hide show
  1. package/.eslintignore +5 -0
  2. package/.gitattributes +5 -0
  3. package/CHANGELOG.md +371 -6
  4. package/CLAUDE.md +6 -0
  5. package/CODE_OF_CONDUCT.md +18 -0
  6. package/CONTRIBUTING.md +30 -0
  7. package/Formula/ssh-manager.rb +60 -0
  8. package/README.md +484 -964
  9. package/ROADMAP-V4.md +451 -0
  10. package/brand/README.md +43 -0
  11. package/brand/icon.svg +32 -0
  12. package/brand/mark.svg +18 -0
  13. package/brand/wordmark.svg +30 -0
  14. package/cli/app.js +230 -0
  15. package/cli/control.js +116 -0
  16. package/cli/lib/colors.sh +15 -0
  17. package/cli/lib/menu.sh +145 -96
  18. package/cli/portability.js +186 -0
  19. package/cli/ssh-manager +197 -91
  20. package/cli/ssh-manager.js +14 -0
  21. package/cli/style.js +17 -0
  22. package/cli/vault.js +411 -0
  23. package/desktop/ControlPlaneApp.swift +219 -0
  24. package/desktop/build.sh +58 -0
  25. package/desktop/electron/after-pack.cjs +39 -0
  26. package/desktop/electron/electron-builder.yml +148 -0
  27. package/desktop/electron/finalize-artifacts.mjs +83 -0
  28. package/desktop/electron/main.js +815 -0
  29. package/desktop/electron/package-lock.json +3656 -0
  30. package/desktop/electron/package.json +30 -0
  31. package/desktop/electron/prepare-engine.mjs +84 -0
  32. package/desktop/electron/resources/entitlements.mac.plist +22 -0
  33. package/desktop/electron/resources/icon.png +0 -0
  34. package/desktop/electron/resources/trayTemplate.png +0 -0
  35. package/desktop/electron/resources/trayTemplate@2x.png +0 -0
  36. package/desktop/electron/smoke-test.mjs +184 -0
  37. package/dist/ui/app.css +1 -0
  38. package/dist/ui/app.js +501 -0
  39. package/dist/ui/assets/Forum-Regular.woff2 +0 -0
  40. package/dist/ui/assets/JetBrainsMono-Bold.woff2 +0 -0
  41. package/dist/ui/assets/JetBrainsMono-Regular.woff2 +0 -0
  42. package/dist/ui/assets/Karla-Variable.woff2 +0 -0
  43. package/dist/ui/index.html +16 -0
  44. package/docs/DISTRIBUTION.md +136 -0
  45. package/docs/FINAL-TEST-V4.md +209 -0
  46. package/docs/MIGRATION.md +334 -0
  47. package/docs/TESTING-V4.md +119 -0
  48. package/docs/superpowers/specs/2026-10-08-desktop-from-npm-and-cli-design.md +187 -0
  49. package/docs/videos/control-plane.mp4 +0 -0
  50. package/package.json +61 -30
  51. package/scripts/build-interface.mjs +73 -0
  52. package/scripts/capture-screenshots.mjs +191 -0
  53. package/scripts/demo-env.mjs +461 -0
  54. package/scripts/frame-screenshots.py +176 -0
  55. package/scripts/macbook-mockup.py +296 -0
  56. package/scripts/make-tray-icon.py +61 -0
  57. package/scripts/preview-candidate.mjs +291 -0
  58. package/scripts/publish-desktop.mjs +46 -0
  59. package/scripts/record-demo.mjs +229 -0
  60. package/scripts/release-version.mjs +32 -0
  61. package/scripts/render-cli-menu.py +157 -0
  62. package/scripts/requirements-dev.in +12 -0
  63. package/scripts/requirements-dev.txt +424 -0
  64. package/scripts/run-ui-regression.mjs +48 -0
  65. package/scripts/setup-hooks.sh +7 -13
  66. package/scripts/smoke-desktop.mjs +80 -0
  67. package/scripts/test-drag-and-drop.mjs +114 -0
  68. package/scripts/test-first-run.mjs +5 -0
  69. package/scripts/test-import-ui.mjs +5 -0
  70. package/scripts/test-preferences-persist.mjs +5 -0
  71. package/scripts/test-upgrade-from-published.mjs +226 -0
  72. package/scripts/verify-mac-build.sh +153 -0
  73. package/scripts/verify-windows-build.ps1 +15 -0
  74. package/server.json +3 -3
  75. package/skills/README.md +42 -0
  76. package/skills/ssh-incident/SKILL.md +55 -0
  77. package/skills/ssh-operations/SKILL.md +62 -0
  78. package/skills/ssh-restricted/SKILL.md +57 -0
  79. package/src/agent-clients.js +482 -0
  80. package/src/approval.js +291 -0
  81. package/src/audit.js +11 -1
  82. package/src/command-log.js +162 -0
  83. package/src/config-loader.js +119 -4
  84. package/src/config-paths.js +101 -0
  85. package/src/control-plane.js +2730 -0
  86. package/src/desktop-install.js +747 -0
  87. package/src/index.js +179 -213
  88. package/src/live-stream.js +261 -0
  89. package/src/saved-commands.js +150 -0
  90. package/src/secret-store.js +573 -0
  91. package/src/server-aliases.js +8 -7
  92. package/src/server-config-manager.js +33 -7
  93. package/src/server-export.js +106 -0
  94. package/src/server-groups.js +82 -21
  95. package/src/server-import.js +477 -0
  96. package/src/shell-quote.js +9 -2
  97. package/src/ssh-connection.js +155 -0
  98. package/src/ssh-manager.js +186 -13
  99. package/src/tunnel-manager.js +79 -0
  100. package/src/vault-recovery.js +206 -0
  101. package/src/xlsx.js +322 -0
  102. package/docs/images/social-preview.png +0 -0
  103. package/docs/images/social-preview@2x.png +0 -0
  104. package/docs/images/ssh-manager-cli-menu.png +0 -0
@@ -0,0 +1,815 @@
1
+ /**
2
+ * The desktop application.
3
+ *
4
+ * ## Why the app *is* the control plane
5
+ *
6
+ * The obvious shape would be a window that launches `ssh-manager control` and
7
+ * points at it. That is what the earlier 104 KB Swift shell did, and it has one
8
+ * flaw that disqualifies it as a product: it needs Node and the npm package
9
+ * already installed. Somebody who downloads a `.dmg` has neither, and telling
10
+ * them to install Node first is telling them to use the CLI.
11
+ *
12
+ * So this process imports the control plane and runs it in-process. Electron
13
+ * already ships a Node runtime; using it means the app is genuinely
14
+ * self-contained, with no second process to supervise, no port handshake to get
15
+ * wrong, and no orphan left behind when the window is closed.
16
+ *
17
+ * ## What the window is
18
+ *
19
+ * A BrowserWindow on `http://127.0.0.1:<port>/?token=…` — the same interface
20
+ * `ssh-manager control` serves, byte for byte. There is deliberately no
21
+ * separate desktop UI: two implementations of the same screens is exactly the
22
+ * trap this project climbed out of when the single-file page was deleted.
23
+ */
24
+ import { app, BrowserWindow, dialog, Menu, nativeTheme, shell, Tray, nativeImage, Notification } from 'electron';
25
+ import fs from 'fs';
26
+ import os from 'os';
27
+ import path from 'path';
28
+ import { createRequire } from 'module';
29
+ // electron-updater is CommonJS: named imports do not resolve through the bridge.
30
+ import electronUpdater from 'electron-updater';
31
+ import { fileURLToPath, pathToFileURL } from 'url';
32
+
33
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
34
+
35
+ /**
36
+ * The engine lives two directories up in the repository, and inside
37
+ * `app.asar.unpacked` in a packaged build. Resolved rather than assumed,
38
+ * because getting it wrong produces a blank window and no clue why.
39
+ */
40
+ // The engine defaults its log and history to files beside its own source, which
41
+ // here is *inside the application bundle*. One file added there breaks the code
42
+ // signature — `codesign --verify` then reports a sealed resource as invalid and
43
+ // Gatekeeper refuses the app — and it happened: a single launch was enough.
44
+ // Set before the engine is imported, because the logger reads these once.
45
+ // Release smoke tests must not touch the machine's real Electron profile.
46
+ const smokeTest = process.argv.includes('--release-smoke-test');
47
+ const previewHome = process.env.SSH_MANAGER_PREVIEW_HOME;
48
+ if (previewHome) {
49
+ if (!path.isAbsolute(previewHome) || previewHome !== process.env.SSH_MANAGER_HOME) {
50
+ throw new Error('Candidate previews require matching absolute SSH_MANAGER_PREVIEW_HOME and SSH_MANAGER_HOME');
51
+ }
52
+ // A temporary vault alone does not isolate Chromium or native file dialogs.
53
+ // Set every profile path before ready; the launcher also supplies a fake OS
54
+ // home to the engine and local shell without changing the parent shell.
55
+ const paths = {
56
+ appData: 'app-data', userData: 'electron', sessionData: 'electron/session',
57
+ logs: 'logs', crashDumps: 'crashes', home: 'home', desktop: 'home/Desktop',
58
+ documents: 'home/Documents', downloads: 'home/Downloads',
59
+ };
60
+ for (const [name, relative] of Object.entries(paths)) {
61
+ const target = path.join(previewHome, relative);
62
+ fs.mkdirSync(target, { recursive: true });
63
+ app.setPath(name, target);
64
+ }
65
+ }
66
+ if (smokeTest) {
67
+ if (!process.env.SSH_MANAGER_HOME || !process.env.SSH_RELEASE_SMOKE_RESULT) {
68
+ throw new Error('Release smoke tests require an isolated SSH_MANAGER_HOME and result path');
69
+ }
70
+ app.setPath('userData', path.join(process.env.SSH_MANAGER_HOME, 'electron'));
71
+ }
72
+ const userData = app.getPath('userData');
73
+ // Electron does not create this until something asks it to, and the logger
74
+ // appends without making directories.
75
+ fs.mkdirSync(userData, { recursive: true });
76
+ process.env.SSH_LOG_FILE ||= path.join(userData, 'ssh-manager.log');
77
+ process.env.SSH_HISTORY_FILE ||= path.join(userData, 'command-history.json');
78
+
79
+ // node-pty is CommonJS with a native binding; `import` of a .node through the
80
+ // ESM bridge does not resolve. createRequire is the supported way in.
81
+ const require = createRequire(import.meta.url);
82
+
83
+ /**
84
+ * A shell on this machine, for the control plane to hand to the interface.
85
+ *
86
+ * This is the whole reason the desktop build differs from the npm one. A
87
+ * pseudo-terminal needs `forkpty`, a native module; the engine has none and is
88
+ * not going to grow one, because it installs on machines with no compiler.
89
+ * Here there is a toolchain, node-pty ships N-API prebuilds that Electron loads
90
+ * as they are, and the result is a real terminal — colours, `vim`, Ctrl-C and
91
+ * a window size that follows the pane.
92
+ *
93
+ * Returns null when the module is missing rather than throwing: a build without
94
+ * it is a build with no local shell, not a broken application. The interface
95
+ * asks the control plane whether one exists before offering it.
96
+ *
97
+ * @returns {import('../../src/control-plane.js').LocalShellFactory|null}
98
+ */
99
+ function localShellProvider() {
100
+ /** @type {typeof import('node-pty')} */
101
+ let pty;
102
+ try {
103
+ pty = require('node-pty');
104
+ } catch (error) {
105
+ console.error('No local shell in this build:', error.message);
106
+ return null;
107
+ }
108
+
109
+ return async ({ cols, rows, cwd }) => {
110
+ // The user's own login shell, because that is what "a terminal on this
111
+ // machine" means to them — their aliases, their prompt, their PATH.
112
+ const shellPath = process.platform === 'win32'
113
+ ? process.env.COMSPEC || 'powershell.exe'
114
+ : process.env.SHELL || (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash');
115
+
116
+ const env = { ...process.env, TERM: 'xterm-256color' };
117
+ // Electron sets this when it runs as a plain Node process; inherited by a
118
+ // shell it makes every `electron` the user runs behave as node instead.
119
+ delete env.ELECTRON_RUN_AS_NODE;
120
+
121
+ const term = pty.spawn(shellPath, [], {
122
+ name: 'xterm-256color',
123
+ cols,
124
+ rows,
125
+ cwd: cwd || os.homedir(),
126
+ env,
127
+ });
128
+
129
+ return {
130
+ shell: path.basename(shellPath),
131
+ onData: handler => term.onData(handler),
132
+ onExit: handler => term.onExit(() => handler()),
133
+ // node-pty writes strings. What arrives is the UTF-8 of exactly what the
134
+ // user typed, so decoding it back is lossless.
135
+ write: data => term.write(data.toString('utf8')),
136
+ resize: (nextCols, nextRows) => term.resize(nextCols, nextRows),
137
+ kill: () => term.kill(),
138
+ };
139
+ };
140
+ }
141
+
142
+ function engineRoot() {
143
+ return app.isPackaged
144
+ ? path.join(process.resourcesPath, 'engine')
145
+ : path.join(__dirname, '..', '..');
146
+ }
147
+
148
+ /**
149
+ * This application as Options → AI tools offers it to Claude Code, Claude
150
+ * Desktop or Codex: the binary that runs its engine. Looking in /Applications
151
+ * the way `ssh-manager control` does would miss a copy kept anywhere else.
152
+ */
153
+ function ownInstallation() {
154
+ if (!app.isPackaged) return undefined;
155
+ const installed = process.platform === 'darwin'
156
+ ? path.resolve(process.execPath, '..', '..', '..')
157
+ : process.platform === 'linux' && process.env.APPIMAGE ? process.env.APPIMAGE : process.execPath;
158
+ return { desktop: () => ({ supported: true, installed: true, path: installed, version: app.getVersion(), method: null }) };
159
+ }
160
+
161
+ /** @type {import('../../src/control-plane.js').ControlPlane|null} */
162
+ let plane = null;
163
+ /** @type {BrowserWindow|null} */
164
+ let mainWindow = null;
165
+ /** @type {Tray|null} Module-level, or it is garbage collected and vanishes. */
166
+ let tray = null;
167
+ /** What the menu was last built from, so it is only rebuilt when it changed. */
168
+ let trayState = '';
169
+ /** Requests already announced, so a queue that stays full is not announced twice. */
170
+ const announced = new Set();
171
+ /**
172
+ * What the updater is doing. Shown in the menu bar, and handed to the control
173
+ * plane so the window can show it too (Options → Updates, the sidebar), because
174
+ * an update that is only visible in a menu most people never open is not an
175
+ * update anyone ever installs.
176
+ * @type {{status: 'idle'|'checking'|'available'|'downloading'|'ready'|'error', version: string|null, percent: number, checkedAt: string|null, error: string|null}}
177
+ */
178
+ let update = { status: 'idle', version: null, percent: 0, checkedAt: null, error: null };
179
+ /** Whether the updater was started: a packaged build, and not a candidate preview. */
180
+ let updaterActive = false;
181
+ /** Who is told when `update` changes: the control plane, which tells the window. */
182
+ const updateListeners = new Set();
183
+
184
+ function updateSnapshot() {
185
+ return {
186
+ currentVersion: app.getVersion(),
187
+ status: update.status,
188
+ ...(update.version ? { version: update.version } : {}),
189
+ ...(update.status === 'downloading' || update.status === 'ready' ? { percent: update.percent } : {}),
190
+ ...(update.checkedAt ? { checkedAt: update.checkedAt } : {}),
191
+ ...(update.error ? { error: update.error } : {}),
192
+ // A preview build is offered newer previews as well as the stable release.
193
+ channel: app.getVersion().includes('-') ? 'preview' : 'stable',
194
+ };
195
+ }
196
+
197
+ /** What the control plane offers the window: see AppUpdates in control-plane.js. */
198
+ const appUpdates = {
199
+ snapshot: updateSnapshot,
200
+ check: async () => {
201
+ if (!updaterActive) throw new Error('Updates are turned off in this build');
202
+ await electronUpdater.autoUpdater.checkForUpdates();
203
+ },
204
+ download: async () => { await electronUpdater.autoUpdater.downloadUpdate(); },
205
+ install: () => electronUpdater.autoUpdater.quitAndInstall(),
206
+ subscribe: listener => {
207
+ updateListeners.add(listener);
208
+ return () => updateListeners.delete(listener);
209
+ },
210
+ };
211
+
212
+ async function startControlPlane() {
213
+ const root = engineRoot();
214
+ const { ControlPlane } = await import(pathToFileURL(path.join(root, 'src', 'control-plane.js')).href);
215
+ const { defaultSocketPath } = await import(pathToFileURL(path.join(root, 'src', 'approval.js')).href);
216
+
217
+ plane = new ControlPlane({
218
+ socketPath: defaultSocketPath(),
219
+ port: 0,
220
+ // Packaged, `dist/ui` sits next to the engine rather than in the source
221
+ // tree; the control plane resolves it relative to its own file, so nothing
222
+ // extra is needed here.
223
+ agents: ownInstallation(),
224
+ // Only a packaged build has a feed and a version to compare; a checkout run
225
+ // from source has nothing to update.
226
+ appUpdates: app.isPackaged ? appUpdates : null,
227
+ });
228
+ plane.setLocalShellProvider(localShellProvider());
229
+ return plane.start();
230
+ }
231
+
232
+ /**
233
+ * The colours the Windows and Linux window buttons are drawn in: the page's
234
+ * own ground and text, so the three buttons look like part of the header they
235
+ * sit on rather than a grey patch pasted over its corner. Follows the system
236
+ * theme, as the page does unless the user forced one in Options.
237
+ */
238
+ function titleBarOverlay() {
239
+ const dark = nativeTheme.shouldUseDarkColors;
240
+ return { color: dark ? '#121211' : '#fafaf7', symbolColor: dark ? '#edebe6' : '#1a1917', height: 48 };
241
+ }
242
+
243
+ function createWindow(url) {
244
+ const mac = process.platform === 'darwin';
245
+ mainWindow = new BrowserWindow({
246
+ width: 1280,
247
+ height: 840,
248
+ minWidth: 900,
249
+ minHeight: 600,
250
+ // The page's own ground, in whichever theme it will resolve to. A fixed
251
+ // light colour here flashes white for a beat before a dark page paints —
252
+ // the one moment of the launch anybody actually watches.
253
+ backgroundColor: nativeTheme.shouldUseDarkColors ? '#121211' : '#fafaf7',
254
+ // No title bar of the system's own on any platform. On macOS the three
255
+ // buttons float over the rail's top row; on Windows and Linux the system
256
+ // draws minimise, maximise and close over the right end of the page
257
+ // header (Window Controls Overlay), and the page reserves their width from
258
+ // the `env(titlebar-area-*)` CSS variables. Before 4.0 Windows and Linux
259
+ // kept a native title bar above a header that repeated what it said.
260
+ titleBarStyle: mac ? 'hiddenInset' : 'hidden',
261
+ ...(mac ? {} : { titleBarOverlay: titleBarOverlay() }),
262
+ // Centred in the rail's 48px top row: the buttons are 12px tall.
263
+ trafficLightPosition: { x: 18, y: 18 },
264
+ show: false,
265
+ webPreferences: {
266
+ // The page is served over HTTP by our own process and needs nothing from
267
+ // Electron: no preload, no node integration, context isolated. It talks
268
+ // to the control plane the same way a browser tab would.
269
+ nodeIntegration: false,
270
+ contextIsolation: true,
271
+ sandbox: true,
272
+ },
273
+ });
274
+
275
+ // Granted rather than prompted: an approval request that goes unseen is the
276
+ // one failure this whole feature exists to prevent, and a permission dialog
277
+ // for a window the user just opened themselves is noise. Only notifications —
278
+ // everything else is still refused.
279
+ mainWindow.webContents.session.setPermissionRequestHandler((_webContents, permission, callback) => {
280
+ callback(permission === 'notifications');
281
+ });
282
+
283
+ // Shown once painted rather than immediately: a window that appears empty and
284
+ // fills in a second later looks broken.
285
+ mainWindow.once('ready-to-show', () => mainWindow?.show());
286
+
287
+ // Anything that is not our own page opens in the real browser. The window
288
+ // holds a token that approves commands on production servers; a link in a
289
+ // file listing must not be able to navigate it somewhere else.
290
+ mainWindow.webContents.setWindowOpenHandler(({ url: target }) => {
291
+ void shell.openExternal(target);
292
+ return { action: 'deny' };
293
+ });
294
+ mainWindow.webContents.on('will-navigate', (event, target) => {
295
+ if (!target.startsWith(url.split('/?')[0])) {
296
+ event.preventDefault();
297
+ void shell.openExternal(target);
298
+ }
299
+ });
300
+
301
+ // The page has to reserve room for the window buttons, which a hidden title
302
+ // bar draws *over* the content. It cannot know that on its own — the same
303
+ // page is served to an ordinary browser tab, where there is nothing to avoid.
304
+ // `plain`, what this sent before 4.0, still means "a system title bar" to the
305
+ // page, so an older application showing a newer engine's page stays right.
306
+ const inset = mac ? 'macos' : 'overlay';
307
+ void mainWindow.loadURL(`${url}&shell=${inset}`);
308
+
309
+ if (!mac) {
310
+ const recolour = () => mainWindow?.setTitleBarOverlay(titleBarOverlay());
311
+ nativeTheme.on('updated', recolour);
312
+ mainWindow.on('closed', () => nativeTheme.removeListener('updated', recolour));
313
+ }
314
+ mainWindow.on('closed', () => { mainWindow = null; });
315
+ }
316
+
317
+ /** A menu with the shortcuts a terminal-adjacent app is expected to have. */
318
+ function buildMenu(url) {
319
+ const isMac = process.platform === 'darwin';
320
+ Menu.setApplicationMenu(Menu.buildFromTemplate([
321
+ ...(isMac ? [{ role: 'appMenu' }] : []),
322
+ {
323
+ label: 'File',
324
+ submenu: [
325
+ {
326
+ label: 'Open in browser',
327
+ accelerator: 'CmdOrCtrl+B',
328
+ // The tokenised URL is genuinely useful outside the app — a second
329
+ // screen, a different browser, devtools you are used to.
330
+ click: () => void shell.openExternal(url),
331
+ },
332
+ { type: 'separator' },
333
+ isMac ? { role: 'close' } : { role: 'quit' },
334
+ ],
335
+ },
336
+ { role: 'editMenu' },
337
+ {
338
+ label: 'View',
339
+ submenu: [
340
+ { role: 'reload' },
341
+ { role: 'forceReload' },
342
+ { role: 'toggleDevTools' },
343
+ { type: 'separator' },
344
+ { role: 'resetZoom' },
345
+ { role: 'zoomIn' },
346
+ { role: 'zoomOut' },
347
+ { type: 'separator' },
348
+ { role: 'togglefullscreen' },
349
+ ],
350
+ },
351
+ { role: 'windowMenu' },
352
+ {
353
+ role: 'help',
354
+ submenu: [{ label: 'Check for Updates…', click: () => void appUpdates.check().catch(() => { /* shown in Options → Updates */ }) }],
355
+ },
356
+ ]));
357
+ }
358
+
359
+ /**
360
+ * The menu-bar item.
361
+ *
362
+ * ## Why an app that already has a window needs one
363
+ *
364
+ * The window is where you *do* things. The menu bar is where you find out that
365
+ * there is something to do — which matters here more than in most apps, because
366
+ * the thing worth knowing is that an agent is blocked waiting for you, and you
367
+ * are by definition looking at something else when it happens. A notification
368
+ * says it once; the menu bar keeps saying it until you deal with it.
369
+ *
370
+ * The icon carries a count when something is waiting, so the answer to "is
371
+ * anything blocked on me?" costs a glance rather than a window switch.
372
+ *
373
+ * Everything shown here is read straight off the in-process control plane —
374
+ * `pending`, `terminals`, `streams`, the vault — because the app *is* the
375
+ * control plane. There is no IPC and nothing to keep in sync.
376
+ */
377
+ /**
378
+ * Native notifications, posted from the main process.
379
+ *
380
+ * The page can raise a Web Notification and does, in a browser tab. Inside the
381
+ * desktop app that is the wrong door: the notification is attributed to the
382
+ * renderer rather than the application, macOS has no authorisation on file for
383
+ * it, and on Windows it needs an AppUserModelID the renderer cannot set. In
384
+ * practice it silently does not appear, which for this feature is the worst
385
+ * possible failure — the whole promise is that you are told when an agent is
386
+ * blocked on you.
387
+ *
388
+ * So the desktop app posts them here instead, with the identity the installer
389
+ * registered, and the page stands down when it is running inside a shell.
390
+ *
391
+ * @param {any[]} pending - Requests currently waiting on a decision
392
+ */
393
+ function announce(pending) {
394
+ if (!Notification.isSupported()) return;
395
+
396
+ const waiting = new Set(pending.map(request => request.id));
397
+ for (const id of [...announced]) if (!waiting.has(id)) announced.delete(id);
398
+
399
+ for (const request of pending) {
400
+ if (announced.has(request.id)) continue;
401
+ announced.add(request.id);
402
+
403
+ const notification = new Notification({
404
+ title: request.destructive
405
+ ? `${request.server}: destructive command waiting`
406
+ : `${request.server}: waiting for your decision`,
407
+ body: String(request.command || request.tool || '').slice(0, 220),
408
+ // Destructive requests stay on screen. `rm -rf` on production and
409
+ // `systemctl status` are not the same interruption, and a banner that
410
+ // fades after four seconds is a banner that gets missed.
411
+ urgency: request.destructive ? 'critical' : 'normal',
412
+ timeoutType: request.destructive ? 'never' : 'default',
413
+ silent: false,
414
+ });
415
+ notification.on('click', () => {
416
+ if (mainWindow) {
417
+ if (mainWindow.isMinimized()) mainWindow.restore();
418
+ mainWindow.show();
419
+ mainWindow.focus();
420
+ } else if (plane) {
421
+ createWindow(plane.url);
422
+ }
423
+ });
424
+ notification.show();
425
+ }
426
+ }
427
+
428
+ function refreshTray() {
429
+ if (!tray || !plane) return;
430
+
431
+ // The map holds { request, settle, receivedAt }; the request is inside it.
432
+ // Reading the wrapper's fields directly is how this first shipped a menu
433
+ // saying "undefined ·" twice.
434
+ const pending = [...plane.pending.values()].map(entry => entry.request);
435
+ const shells = [...plane.terminals.values()];
436
+ const running = plane.streams.list().filter(s => s.code === null);
437
+ let servers = [];
438
+ try {
439
+ servers = plane.store.exists() ? plane.store.listServers() : [];
440
+ } catch {
441
+ // An unreadable vault is the interface's problem to report, not the tray's.
442
+ }
443
+
444
+ // Rebuilding a menu the user may have open is disruptive, and this runs on a
445
+ // timer, so only touch it when something actually moved.
446
+ const signature = JSON.stringify([
447
+ pending.map(r => r.id), shells.map(t => t.server),
448
+ running.map(s => s.id), servers, update.status, update.percent,
449
+ ]);
450
+ if (signature === trayState) return;
451
+ trayState = signature;
452
+
453
+ announce(pending);
454
+
455
+ const focus = () => {
456
+ if (mainWindow) {
457
+ if (mainWindow.isMinimized()) mainWindow.restore();
458
+ mainWindow.show();
459
+ mainWindow.focus();
460
+ } else if (plane) {
461
+ createWindow(plane.url);
462
+ }
463
+ };
464
+
465
+ /** A command short enough for a menu, with the end kept: that is where the path is. */
466
+ const brief = (text, max = 46) => {
467
+ const flat = String(text || '').replace(/\s+/g, ' ').trim();
468
+ return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
469
+ };
470
+
471
+ /** @type {Electron.MenuItemConstructorOptions[]} */
472
+ const template = [...updateMenuItems()];
473
+
474
+ if (pending.length) {
475
+ template.push({ label: `${pending.length} waiting for your decision`, enabled: false });
476
+ for (const request of pending.slice(0, 6)) {
477
+ template.push({
478
+ label: ` ${request.server} · ${brief(request.command)}`,
479
+ click: focus,
480
+ });
481
+ }
482
+ template.push({ type: 'separator' });
483
+ } else {
484
+ template.push({ label: 'Nothing is waiting', enabled: false });
485
+ template.push({ type: 'separator' });
486
+ }
487
+
488
+ if (shells.length || running.length) {
489
+ template.push({ label: 'Open right now', enabled: false });
490
+ for (const shell of shells.slice(0, 5)) {
491
+ template.push({ label: ` Shell on ${shell.server}`, click: focus });
492
+ }
493
+ for (const stream of running.slice(0, 5)) {
494
+ template.push({
495
+ label: ` ${stream.server} · ${brief(stream.command, 38)}`,
496
+ click: focus,
497
+ });
498
+ }
499
+ template.push({ type: 'separator' });
500
+ }
501
+
502
+ if (servers.length) {
503
+ template.push({
504
+ label: `Servers (${servers.length})`,
505
+ submenu: servers.slice(0, 12).map(name => ({ label: name, click: focus })),
506
+ });
507
+ template.push({ type: 'separator' });
508
+ }
509
+
510
+ template.push(
511
+ { label: 'Show SSH Manager', click: focus },
512
+ { label: 'Open in browser', click: () => plane && void shell.openExternal(plane.url) },
513
+ { type: 'separator' },
514
+ { label: 'Quit SSH Manager', click: () => app.quit() },
515
+ );
516
+
517
+ tray.setContextMenu(Menu.buildFromTemplate(template));
518
+ tray.setToolTip(pending.length
519
+ ? `SSH Manager — ${pending.length} waiting for your decision`
520
+ : 'SSH Manager');
521
+
522
+ // The count beside the icon, and on the dock. Only when it is not zero: a
523
+ // permanent "0" is a thing people learn to stop reading.
524
+ if (process.platform === 'darwin') {
525
+ tray.setTitle(pending.length ? ` ${pending.length}` : '');
526
+ app.dock?.setBadge(pending.length ? String(pending.length) : '');
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Updates, offered rather than applied.
532
+ *
533
+ * This application holds SSH connections and the approval socket an agent is
534
+ * blocked on. Downloading 120 MB on somebody's tethered connection because a
535
+ * release happened, or restarting under them while a transfer is running, are
536
+ * both worse than being a version behind for an afternoon.
537
+ *
538
+ * So: it checks, and says so — in the window (Options → Updates, and a mark on
539
+ * the sidebar), in the menu bar, and once per version in a notification.
540
+ * Downloading is a click. Installing happens when the application is closed
541
+ * anyway, or when you choose to restart — never in the middle of something.
542
+ */
543
+ function setupUpdater() {
544
+ // A candidate preview must keep the artifact the operator chose to test.
545
+ if (previewHome) return;
546
+ const { autoUpdater } = electronUpdater;
547
+ if (!app.isPackaged) return; // no feed, and no version to compare
548
+
549
+ autoUpdater.autoDownload = false;
550
+ autoUpdater.autoInstallOnAppQuit = true;
551
+ autoUpdater.logger = null;
552
+ updaterActive = true;
553
+
554
+ const move = (status, extra = {}) => {
555
+ update = { ...update, status, ...extra };
556
+ trayState = ''; // force the menu to rebuild
557
+ refreshTray();
558
+ const snapshot = updateSnapshot();
559
+ for (const listener of updateListeners) listener(snapshot);
560
+ };
561
+ const now = () => new Date().toISOString();
562
+
563
+ autoUpdater.on('checking-for-update', () => move('checking', { error: null }));
564
+ autoUpdater.on('update-available', info => {
565
+ move('available', { version: info.version, percent: 0, checkedAt: now(), error: null });
566
+ announceUpdate(info.version);
567
+ });
568
+ autoUpdater.on('update-not-available', () => move('idle', { version: null, checkedAt: now(), error: null }));
569
+ autoUpdater.on('download-progress', p => move('downloading', { percent: Math.round(p.percent) }));
570
+ autoUpdater.on('update-downloaded', info => move('ready', { version: info.version, percent: 100 }));
571
+ autoUpdater.on('error', error => {
572
+ // A failed background check is not worth an alert: the network is down, or
573
+ // GitHub is, and it will try again. The reason is kept for Options → Updates,
574
+ // where someone who asked to check can read it. A failed download goes back
575
+ // to "available", so it can be tried again.
576
+ const message = String(error?.message || error).split('\n')[0].slice(0, 200);
577
+ move(update.status === 'downloading' || update.status === 'ready' ? 'available' : 'idle', { checkedAt: now(), error: message });
578
+ });
579
+
580
+ const check = () => autoUpdater.checkForUpdates().catch(() => { /* see above */ });
581
+ setTimeout(check, 8000); // not during launch, when it would compete
582
+ const timer = setInterval(check, 6 * 60 * 60 * 1000);
583
+ timer.unref();
584
+ }
585
+
586
+ /**
587
+ * Say, once per version, that an update is on offer.
588
+ *
589
+ * The version is remembered on disk: a notification at every launch for an
590
+ * update somebody has already decided to leave for later is nagging, and
591
+ * the sidebar and the menu bar keep showing it anyway.
592
+ *
593
+ * @param {string} version
594
+ */
595
+ function announceUpdate(version) {
596
+ const marker = path.join(app.getPath('userData'), 'last-update-notice');
597
+ try {
598
+ if (fs.readFileSync(marker, 'utf8').trim() === version) return;
599
+ } catch { /* nothing recorded yet */ }
600
+ try { fs.writeFileSync(marker, `${version}\n`); } catch { /* it will say it again next time; harmless */ }
601
+ if (!Notification.isSupported()) return;
602
+ const notification = new Notification({
603
+ title: `SSH Manager ${version} is available`,
604
+ body: 'Open Options → Updates to download it. Nothing is installed until you restart.',
605
+ silent: true,
606
+ });
607
+ notification.on('click', () => {
608
+ if (mainWindow) {
609
+ if (mainWindow.isMinimized()) mainWindow.restore();
610
+ mainWindow.show();
611
+ mainWindow.focus();
612
+ } else if (plane) {
613
+ createWindow(plane.url);
614
+ }
615
+ });
616
+ notification.show();
617
+ }
618
+
619
+ /** The menu-bar entry for whatever the updater is up to, or nothing. */
620
+ function updateMenuItems() {
621
+ const { autoUpdater } = electronUpdater;
622
+ switch (update.status) {
623
+ case 'checking':
624
+ return [{ label: 'Checking for updates…', enabled: false }, { type: 'separator' }];
625
+ case 'available':
626
+ return [{
627
+ label: `Update to ${update.version}`,
628
+ click: () => autoUpdater.downloadUpdate().catch(() => { /* reported by the error handler */ }),
629
+ }, { type: 'separator' }];
630
+ case 'downloading':
631
+ return [{ label: `Downloading update… ${update.percent}%`, enabled: false },
632
+ { type: 'separator' }];
633
+ case 'ready':
634
+ return [{
635
+ label: `Restart to update to ${update.version}`,
636
+ click: () => autoUpdater.quitAndInstall(),
637
+ }, { type: 'separator' }];
638
+ default:
639
+ return updaterActive
640
+ ? [{ label: 'Check for Updates…', click: () => void appUpdates.check().catch(() => { /* shown in Options → Updates */ }) },
641
+ { type: 'separator' }]
642
+ : [];
643
+ }
644
+ }
645
+
646
+ function createTray() {
647
+ const iconPath = path.join(__dirname, 'resources', 'trayTemplate.png');
648
+ const icon = nativeImage.createFromPath(iconPath);
649
+ if (icon.isEmpty()) {
650
+ // A missing icon throws inside `new Tray` on macOS and would take the whole
651
+ // app down over a packaging mistake — which is exactly what happened: the
652
+ // first packaged build had no trayTemplate.png, because `resources` is
653
+ // buildResources and electron-builder leaves that out of the asar.
654
+ console.error(`No menu-bar icon at ${iconPath}; continuing without it.`);
655
+ return;
656
+ }
657
+ // macOS repaints template images for the current bar; without this the glyph
658
+ // is a black square on a dark menu bar.
659
+ icon.setTemplateImage(true);
660
+ tray = new Tray(icon);
661
+ tray.setToolTip('SSH Manager');
662
+ // Clicking the icon itself opens the menu on macOS; elsewhere it is expected
663
+ // to raise the window, and the menu is on right-click.
664
+ if (process.platform !== 'darwin') {
665
+ tray.on('click', () => {
666
+ if (mainWindow) mainWindow.show();
667
+ else if (plane) createWindow(plane.url);
668
+ });
669
+ }
670
+ refreshTray();
671
+ // Two seconds: fast enough that a blocked agent is visible almost at once,
672
+ // slow enough to be free. It reads four in-memory collections.
673
+ const timer = setInterval(refreshTray, 2000);
674
+ app.on('before-quit', () => clearInterval(timer));
675
+ }
676
+
677
+ // Windows ties a notification to an Application User Model ID. Without one,
678
+ // notifications from a packaged Electron app either do not appear at all or
679
+ // appear attributed to "electron.app.Electron" — and the approval feature is
680
+ // built on the assumption that the person is told when an agent is blocked.
681
+ // This must match `appId` in electron-builder.yml or the toast is orphaned.
682
+ if (process.platform === 'win32') app.setAppUserModelId('com.bvisible.ssh-manager');
683
+
684
+ /**
685
+ * Files dropped on the Dock icon.
686
+ *
687
+ * macOS delivers these as `open-file`, and it delivers them *early* — before
688
+ * `whenReady`, if somebody dropped a file on a cold icon and that is what
689
+ * launched the app. So they are collected here and flushed once there is
690
+ * something to flush them into; dropping the event on the floor because the
691
+ * window was not up yet is the classic way this feature half-works.
692
+ *
693
+ * What happens to them is the page's decision, not this process's: it knows
694
+ * which servers are open, which shells are running, and which remote directory
695
+ * is on screen. All that happens here is that it gets told.
696
+ */
697
+ const droppedFiles = [];
698
+
699
+ function flushDroppedFiles() {
700
+ if (!plane || droppedFiles.length === 0) return;
701
+ const paths = droppedFiles.splice(0, droppedFiles.length);
702
+ plane.announce({ type: 'dropped-files', paths });
703
+ if (mainWindow) {
704
+ if (mainWindow.isMinimized()) mainWindow.restore();
705
+ mainWindow.show();
706
+ mainWindow.focus();
707
+ }
708
+ }
709
+
710
+ app.on('open-file', (event, filePath) => {
711
+ event.preventDefault();
712
+ droppedFiles.push(filePath);
713
+ // Several files arrive as several events in quick succession; coalesce them
714
+ // so the page asks one question about five files rather than five questions.
715
+ setTimeout(flushDroppedFiles, 120);
716
+ });
717
+
718
+ // One copy at a time. A second launch — a double-click on the icon, or
719
+ // `ssh-manager app` on Windows and Linux, where opening an application starts
720
+ // another process — would bind the approval socket again and fight the first
721
+ // copy for it. It brings the running window forward instead. Not for a smoke
722
+ // test or a preview, which run beside a real copy on purpose, in a home of
723
+ // their own.
724
+ const soleCopy = smokeTest || previewHome || app.requestSingleInstanceLock();
725
+ if (!soleCopy) {
726
+ app.quit();
727
+ } else {
728
+ app.on('second-instance', () => {
729
+ if (mainWindow) {
730
+ if (mainWindow.isMinimized()) mainWindow.restore();
731
+ mainWindow.show();
732
+ mainWindow.focus();
733
+ } else if (plane) {
734
+ createWindow(plane.url);
735
+ }
736
+ });
737
+ }
738
+
739
+ app.whenReady().then(async () => {
740
+ if (!soleCopy) return;
741
+ try {
742
+ const { url } = await startControlPlane();
743
+ if (smokeTest) {
744
+ const { runSmokeTest } = await import('./smoke-test.mjs');
745
+ await runSmokeTest({ app, BrowserWindow, url, root: engineRoot(), localShellProvider });
746
+ app.quit();
747
+ return;
748
+ }
749
+ buildMenu(url);
750
+ createWindow(url);
751
+ createTray();
752
+ setupUpdater();
753
+ // Anything dropped before the window existed.
754
+ setTimeout(flushDroppedFiles, 500);
755
+ } catch (error) {
756
+ if (smokeTest) {
757
+ fs.writeFileSync(process.env.SSH_RELEASE_SMOKE_RESULT, JSON.stringify({ ok: false, error: error.message }));
758
+ app.exit(1);
759
+ return;
760
+ }
761
+ // A failure here means no interface at all, so it is a dialog rather than a
762
+ // line in a log nobody is reading — most often an over-long socket path or
763
+ // another copy already running.
764
+ // The hint has to match the failure. A packaged build once shipped without
765
+ // its dependencies and died on "Cannot find package 'dotenv'" — while this
766
+ // box confidently suggested another copy was running, which sent the reader
767
+ // looking in the wrong place entirely.
768
+ const guess = /Cannot find (package|module)/i.test(error.message)
769
+ ? 'The application is missing part of itself. This is a packaging fault, '
770
+ + 'not something you can fix here — please report it with this message.'
771
+ : error.code === 'EADDRINUSE' || /already running|EADDRINUSE/i.test(error.message)
772
+ ? 'Another copy is already running, or a stale socket is in the way.'
773
+ : 'The socket path may be too long for this system, or the port could '
774
+ + 'not be opened.';
775
+ dialog.showErrorBox('SSH Manager could not start', `${error.message}\n\n${guess}`);
776
+ app.quit();
777
+ }
778
+
779
+ app.on('activate', async () => {
780
+ if (BrowserWindow.getAllWindows().length === 0 && plane) {
781
+ createWindow(plane.url);
782
+ }
783
+ });
784
+ });
785
+
786
+ // On macOS, closing the window leaves the app in the menu bar. Everywhere else
787
+ // it quits.
788
+ //
789
+ // This used to quit on every platform, and the reason was sound at the time:
790
+ // leaving the control plane running with no window means a process holding SSH
791
+ // connections that nobody can see — and worse, holding the approval socket, so
792
+ // agents block on an interface that is not on screen.
793
+ //
794
+ // The tray is exactly the thing that was missing. It shows the connections, it
795
+ // shows what is waiting, and it carries a Quit. The invisible-process objection
796
+ // no longer applies, and quitting a menu-bar app because its window closed is
797
+ // not what a macOS user expects.
798
+ app.on('window-all-closed', () => {
799
+ if (process.platform !== 'darwin') app.quit();
800
+ });
801
+
802
+ app.on('before-quit', async event => {
803
+ if (tray) { tray.destroy(); tray = null; }
804
+ if (!plane) return;
805
+ event.preventDefault();
806
+ const closing = plane;
807
+ plane = null;
808
+ try {
809
+ await closing.stop();
810
+ } catch {
811
+ // Shutting down is best effort; failing to release a socket must not stop
812
+ // the app from exiting.
813
+ }
814
+ app.quit();
815
+ });