@pi-chamber/web 0.8.2 → 0.9.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 (117) hide show
  1. package/README.md +22 -6
  2. package/bin/cli.js +16 -3
  3. package/bin/cli.test.js +62 -0
  4. package/bin/lib/DOCUMENTATION.md +6 -6
  5. package/bin/lib/cli-args.js +26 -7
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +6 -0
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-lifecycle.js +14 -0
  12. package/bin/lib/commands-logs.js +24 -5
  13. package/bin/lib/commands-serve.js +176 -4
  14. package/bin/lib/commands-tunnel.js +35 -0
  15. package/bin/lib/commands-update.js +107 -39
  16. package/bin/lib/commands-update.test.js +97 -1
  17. package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-DoEOH0hY.js} +1 -1
  18. package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-y9Ystuhv.js} +1 -1
  19. package/dist/assets/DiffView-ScM4XoqZ.js +18 -0
  20. package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-CjkhMFqJ.js} +3 -3
  21. package/dist/assets/GitView-Bqi6H8I-.js +8 -0
  22. package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
  23. package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
  24. package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-ClnfJJ2J.js} +1 -1
  25. package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
  26. package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
  27. package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
  28. package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
  29. package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-Cy9tmnMg.js} +1 -1
  30. package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
  31. package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
  32. package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-DJNcTQNp.js} +4 -4
  33. package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-DxgVLhi9.js} +1 -1
  34. package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
  35. package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
  36. package/dist/assets/gitStatusPredicates-CIFSGjJs.js +134 -0
  37. package/dist/assets/index-D2C3q2xD.js +8 -0
  38. package/dist/assets/index-DNoEeZ2U.css +1 -0
  39. package/dist/assets/{index-CMfiVUIr.js → index-DmNPBaSo.js} +1 -1
  40. package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-CrvpUauF.js} +1 -1
  41. package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-CKvhS32g.js} +1 -1
  42. package/dist/assets/{main-zZrKd3hZ.js → main-BFv8slLp.js} +2 -2
  43. package/dist/assets/main-CjM7g4Gq.js +135 -0
  44. package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-DKrraAqT.js} +1 -1
  45. package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-hQnLS5mt.js} +2 -2
  46. package/dist/assets/{mobile-VU_G_SgX.js → mobile-DuXOBGs_.js} +2 -2
  47. package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
  48. package/dist/assets/renderMobileApp-DofX2wjB.js +11 -0
  49. package/dist/assets/runtimeEndpointReset-BZeYg6eN.js +54 -0
  50. package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C7CBxDbh.js} +1 -1
  51. package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
  52. package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
  53. package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
  54. package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-BEoW7LlC.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
  56. package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
  57. package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
  58. package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
  59. package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
  60. package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
  61. package/dist/assets/{web-components-C9ENH49P.js → web-components-Dy-Tz_LJ.js} +3 -3
  62. package/dist/index.html +4 -4
  63. package/dist/mini-chat.html +3 -3
  64. package/dist/mobile.html +3 -3
  65. package/package.json +3 -4
  66. package/server/index.js +26 -7
  67. package/server/lib/client-auth/pairing.js +13 -2
  68. package/server/lib/client-auth/remote-clients.js +13 -2
  69. package/server/lib/fs/DOCUMENTATION.md +3 -1
  70. package/server/lib/fs/routes.test.js +74 -0
  71. package/server/lib/git/DOCUMENTATION.md +1 -1
  72. package/server/lib/git/identity-storage.js +10 -1
  73. package/server/lib/package-manager.js +1 -1
  74. package/server/lib/package-manager.test.js +11 -0
  75. package/server/lib/pi/archive-store.js +3 -2
  76. package/server/lib/pi/model-config-store.js +6 -2
  77. package/server/lib/pi/routes.js +11 -2
  78. package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
  79. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  80. package/server/lib/pi/session-daemon/session-daemon.js +226 -40
  81. package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
  82. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  83. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  84. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  85. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  86. package/server/lib/pi/session-folders-store.js +20 -2
  87. package/server/lib/pi/session-folders-store.test.js +17 -0
  88. package/server/lib/pi/settings-store.js +3 -2
  89. package/server/lib/pi/snippets-store.js +4 -1
  90. package/server/lib/pi/ui-settings-store.js +3 -2
  91. package/server/lib/server/cross-process-lock.js +112 -0
  92. package/server/lib/server/cross-process-lock.test.js +70 -0
  93. package/server/lib/server/server-profile.js +110 -0
  94. package/server/lib/server/server-profile.test.js +58 -0
  95. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  96. package/server/lib/server/tunnel-service.js +8 -1
  97. package/server/lib/stt/DOCUMENTATION.md +1 -1
  98. package/server/lib/stt/config-store.js +3 -2
  99. package/server/lib/terminal/DOCUMENTATION.md +3 -3
  100. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  101. package/server/lib/ui-auth/ui-auth.js +9 -2
  102. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  103. package/dist/assets/DiffView-Gh9wjthp.js +0 -18
  104. package/dist/assets/GitView-BmNCkkoC.js +0 -8
  105. package/dist/assets/JsonTreeView-CxXRXXzk.js +0 -1
  106. package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
  107. package/dist/assets/ToolOutputDialog-C_7vJLEq.js +0 -8
  108. package/dist/assets/computeVirtualFileMetrics-D0mQcleY.js +0 -3
  109. package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
  110. package/dist/assets/index-CzO3ooje.css +0 -1
  111. package/dist/assets/index-ivrh3jfy.js +0 -8
  112. package/dist/assets/main-BoVfUG73.js +0 -135
  113. package/dist/assets/renderElectronMiniChatApp-Bi1927c8.js +0 -2
  114. package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
  115. package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
  116. package/dist/assets/usePushVisibilityBeacon-zYd3ppNh.js +0 -10
  117. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
@@ -13,6 +13,13 @@ import { isNetworkExposedBindHost } from '../../server/lib/security/bind-host.js
13
13
  import {
14
14
  intro as clackIntro,
15
15
  outro as clackOutro,
16
+ cancel as clackCancel,
17
+ isCancel,
18
+ select,
19
+ text,
20
+ password as passwordPrompt,
21
+ confirm,
22
+ canPrompt,
16
23
  isJsonMode,
17
24
  isQuietMode,
18
25
  shouldRenderHumanOutput,
@@ -22,6 +29,145 @@ import {
22
29
  } from '../cli-output.js';
23
30
 
24
31
  const DAEMON_READY_TIMEOUT_MS = 30000;
32
+ const servePromptApi = { select, text, password: passwordPrompt, confirm, isCancel, cancel: clackCancel };
33
+
34
+ function hasExplicitServeConfiguration(options) {
35
+ return options.explicitPort === true
36
+ || options.lan === true
37
+ || typeof options.host === 'string'
38
+ || options.explicitUiPassword === true
39
+ || options.apiOnly === true
40
+ || options.foreground === true;
41
+ }
42
+
43
+ async function collectInteractiveServeOptions(options, prompts = servePromptApi) {
44
+ const ask = async (method, config) => {
45
+ const answer = await prompts[method](config);
46
+ if (prompts.isCancel(answer)) {
47
+ prompts.cancel('Server setup cancelled.');
48
+ return { cancelled: true };
49
+ }
50
+ return { answer };
51
+ };
52
+
53
+ const accessResult = await ask('select', {
54
+ message: 'Where should PiChamber be accessible?',
55
+ options: [
56
+ { value: 'local', label: 'This machine only', hint: 'recommended' },
57
+ { value: 'lan', label: 'Local network', hint: 'other devices on your LAN or Wi-Fi' },
58
+ { value: 'custom', label: 'Custom bind address' },
59
+ ],
60
+ initialValue: 'local',
61
+ });
62
+ if (accessResult.cancelled) return null;
63
+
64
+ let host = '127.0.0.1';
65
+ let lan = false;
66
+ if (accessResult.answer === 'lan') {
67
+ host = '0.0.0.0';
68
+ lan = true;
69
+ } else if (accessResult.answer === 'custom') {
70
+ const hostResult = await ask('text', {
71
+ message: 'Bind address',
72
+ initialValue: '127.0.0.1',
73
+ validate: (value) => String(value ?? '').trim() ? undefined : 'Enter a bind address.',
74
+ });
75
+ if (hostResult.cancelled) return null;
76
+ host = String(hostResult.answer).trim();
77
+ }
78
+
79
+ const portResult = await ask('text', {
80
+ message: 'Port',
81
+ initialValue: String(options.port),
82
+ validate: (value) => {
83
+ const normalized = String(value ?? '').trim();
84
+ if (!/^\d+$/.test(normalized)) return 'Enter a port from 0 to 65535.';
85
+ const port = Number(normalized);
86
+ return port >= 0 && port <= 65535 ? undefined : 'Enter a port from 0 to 65535.';
87
+ },
88
+ });
89
+ if (portResult.cancelled) return null;
90
+ const port = Number(String(portResult.answer).trim());
91
+
92
+ const networkExposed = accessResult.answer !== 'local';
93
+ const authResult = await ask('select', {
94
+ message: networkExposed ? 'Choose a required UI password' : 'Protect the UI with a password?',
95
+ options: [
96
+ { value: 'enter', label: 'Enter a password' },
97
+ { value: 'generate', label: 'Generate a secure password' },
98
+ ...(!networkExposed ? [{ value: 'none', label: 'No password', hint: 'local access only' }] : []),
99
+ ],
100
+ initialValue: networkExposed ? 'generate' : 'none',
101
+ });
102
+ if (authResult.cancelled) return null;
103
+
104
+ let uiPassword;
105
+ let explicitUiPassword = false;
106
+ if (authResult.answer === 'enter') {
107
+ const passwordResult = await ask('password', {
108
+ message: 'UI password',
109
+ validate: (value) => String(value ?? '').length ? undefined : 'Enter a password.',
110
+ });
111
+ if (passwordResult.cancelled) return null;
112
+ uiPassword = String(passwordResult.answer);
113
+ const confirmationResult = await ask('password', {
114
+ message: 'Confirm UI password',
115
+ validate: (value) => value === uiPassword ? undefined : 'Passwords do not match.',
116
+ });
117
+ if (confirmationResult.cancelled) return null;
118
+ explicitUiPassword = true;
119
+ } else if (authResult.answer === 'generate') {
120
+ uiPassword = '';
121
+ explicitUiPassword = true;
122
+ }
123
+
124
+ const contentResult = await ask('select', {
125
+ message: 'What should this server provide?',
126
+ options: [
127
+ { value: 'ui', label: 'Browser UI and API', hint: 'recommended' },
128
+ { value: 'api', label: 'API only', hint: 'for paired clients' },
129
+ ],
130
+ initialValue: 'ui',
131
+ });
132
+ if (contentResult.cancelled) return null;
133
+
134
+ const processResult = await ask('select', {
135
+ message: 'How should the server run?',
136
+ options: [
137
+ { value: 'daemon', label: 'In the background', hint: 'recommended' },
138
+ { value: 'foreground', label: 'In the foreground', hint: 'for process managers' },
139
+ ],
140
+ initialValue: 'daemon',
141
+ });
142
+ if (processResult.cancelled) return null;
143
+
144
+ logStatus('info', 'Review server', [
145
+ `Access: ${accessResult.answer === 'local' ? 'this machine only' : host}`,
146
+ `Port: ${port === 0 ? 'automatic' : port}`,
147
+ `Authentication: ${authResult.answer === 'none' ? 'disabled' : authResult.answer === 'generate' ? 'generated password' : 'enabled'}`,
148
+ `Content: ${contentResult.answer === 'api' ? 'API only' : 'browser UI and API'}`,
149
+ `Process: ${processResult.answer === 'foreground' ? 'foreground' : 'background'}`,
150
+ ].join('\n'));
151
+
152
+ const confirmResult = await ask('confirm', { message: 'Start this server?', initialValue: true });
153
+ if (confirmResult.cancelled) return null;
154
+ if (confirmResult.answer !== true) {
155
+ prompts.cancel('Server setup cancelled.');
156
+ return null;
157
+ }
158
+
159
+ return {
160
+ ...options,
161
+ host,
162
+ lan,
163
+ port,
164
+ explicitPort: true,
165
+ uiPassword,
166
+ explicitUiPassword,
167
+ apiOnly: contentResult.answer === 'api',
168
+ foreground: processResult.answer === 'foreground',
169
+ };
170
+ }
25
171
 
26
172
  function createServeCommand({
27
173
  serverPath,
@@ -31,6 +177,15 @@ function createServeCommand({
31
177
  setForegroundShutdown,
32
178
  }) {
33
179
  async function serveCommand(options) {
180
+ let usedInteractiveSetup = false;
181
+ if (options.offerInteractiveSetup === true && canPrompt(options) && !hasExplicitServeConfiguration(options)) {
182
+ clackIntro('PiChamber Server Setup');
183
+ const resolvedOptions = await collectInteractiveServeOptions(options);
184
+ if (!resolvedOptions) return;
185
+ options = resolvedOptions;
186
+ usedInteractiveSetup = true;
187
+ }
188
+
34
189
  const showOutput = shouldRenderHumanOutput(options);
35
190
  const jsonMessages = [];
36
191
  const emitNotice = (notice) => {
@@ -199,6 +354,9 @@ async function serveCommand(options) {
199
354
  });
200
355
 
201
356
  const resolvedPort = controller.getPort();
357
+ const resolvedProfileKey = typeof controller.getDaemonProfileKey === 'function'
358
+ ? controller.getDaemonProfileKey()
359
+ : null;
202
360
 
203
361
  // Write PID / instance files so status, stop, and restart can discover
204
362
  // this foreground instance the same way they discover daemon instances.
@@ -211,6 +369,7 @@ async function serveCommand(options) {
211
369
  launchMode: 'foreground',
212
370
  uiPassword: effectiveUiPassword,
213
371
  apiOnly: options.apiOnly === true,
372
+ ...(typeof resolvedProfileKey === 'string' && resolvedProfileKey.length > 0 ? { profileKey: resolvedProfileKey } : {}),
214
373
  }, emitNotice);
215
374
 
216
375
  if (isQuietMode(options)) {
@@ -221,6 +380,15 @@ async function serveCommand(options) {
221
380
  : `${resolvedPort}\n`
222
381
  );
223
382
  }
383
+ } else if (usedInteractiveSetup && showOutput && !options.suppressStartupSummary) {
384
+ logStatus('success', `port ${resolvedPort} (foreground)`);
385
+ if (autoGeneratedUiPassword) {
386
+ logStatus('success', 'UI password', effectiveUiPassword);
387
+ logStatus('warning', 'save this password', 'it is not shown again');
388
+ }
389
+ logStatus('info', `visit: ${buildLocalUrl(resolvedPort, '/')}`);
390
+ logStatus('info', `logs: pichamber logs -p ${resolvedPort}`);
391
+ clackOutro('server running; press Ctrl+C to stop');
224
392
  } else if (autoGeneratedUiPassword && showOutput && !options.suppressStartupSummary) {
225
393
  console.log(`Generated UI password: ${effectiveUiPassword}`);
226
394
  console.log('Save this password — it is not shown again.');
@@ -291,8 +459,9 @@ async function serveCommand(options) {
291
459
  serveSpin?.start(`Starting PiChamber on port ${targetPort === 0 ? 'auto' : targetPort}...`);
292
460
 
293
461
  let resolvedPort;
462
+ let resolvedProfileKey = null;
294
463
  try {
295
- resolvedPort = await new Promise((resolve, reject) => {
464
+ const ready = await new Promise((resolve, reject) => {
296
465
  let settled = false;
297
466
  const timeout = setTimeout(() => {
298
467
  if (settled) return;
@@ -305,7 +474,7 @@ async function serveCommand(options) {
305
474
  if (msg && msg.type === 'pichamber:ready' && typeof msg.port === 'number') {
306
475
  settled = true;
307
476
  clearTimeout(timeout);
308
- resolve(msg.port);
477
+ resolve(msg);
309
478
  }
310
479
  });
311
480
 
@@ -323,6 +492,8 @@ async function serveCommand(options) {
323
492
  reject(new Error(`PiChamber daemon exited before reporting ready${signal ? ` (${signal})` : ` (code ${code ?? 'unknown'})`}`));
324
493
  });
325
494
  });
495
+ resolvedPort = ready.port;
496
+ resolvedProfileKey = typeof ready.profileKey === 'string' && ready.profileKey.length > 0 ? ready.profileKey : null;
326
497
  } catch (error) {
327
498
  await terminateProcessTree(child.pid, { gracefulTimeoutMs: 1500, forceTimeoutMs: 1500 });
328
499
  throw error;
@@ -362,6 +533,7 @@ async function serveCommand(options) {
362
533
  launchMode: 'daemon',
363
534
  uiPassword: effectiveUiPassword,
364
535
  apiOnly: options.apiOnly === true,
536
+ ...(resolvedProfileKey ? { profileKey: resolvedProfileKey } : {}),
365
537
  }, emitNotice);
366
538
 
367
539
  const serveResult = {
@@ -399,7 +571,7 @@ async function serveCommand(options) {
399
571
  serveSpin?.clear();
400
572
 
401
573
  if (!options.suppressStartupSummary && showOutput) {
402
- clackIntro('PiChamber Started');
574
+ if (!usedInteractiveSetup) clackIntro('PiChamber Started');
403
575
  logStatus('success', `port ${serveResult.port} (PID: ${serveResult.pid})`);
404
576
  if (autoGeneratedUiPassword) {
405
577
  logStatus('success', 'UI password', effectiveUiPassword);
@@ -416,4 +588,4 @@ async function serveCommand(options) {
416
588
  return serveCommand;
417
589
  }
418
590
 
419
- export { createServeCommand };
591
+ export { createServeCommand, collectInteractiveServeOptions, hasExplicitServeConfiguration };
@@ -181,10 +181,15 @@ async function resolveTargetInstance({
181
181
  explicitPort: true,
182
182
  host: options.host,
183
183
  uiPassword: options.uiPassword,
184
+ explicitUiPassword: options.explicitUiPassword === true,
184
185
  apiOnly: options.apiOnly,
186
+ foreground: false,
187
+ json: false,
188
+ quiet: true,
185
189
  suppressUnsafePortWarning: true,
186
190
  suppressUiPasswordWarning: true,
187
191
  suppressStartupSummary: true,
192
+ suppressQuietOutput: true,
188
193
  });
189
194
  running = await discoverRunningInstances();
190
195
  const started = running.find((entry) => entry.port === options.port);
@@ -219,9 +224,13 @@ async function resolveTargetInstance({
219
224
  const startedPort = await serveCommand({
220
225
  ...options,
221
226
  explicitPort: false,
227
+ foreground: false,
228
+ json: false,
229
+ quiet: true,
222
230
  suppressUnsafePortWarning: true,
223
231
  suppressUiPasswordWarning: true,
224
232
  suppressStartupSummary: true,
233
+ suppressQuietOutput: true,
225
234
  });
226
235
  running = await discoverRunningInstances();
227
236
  const started = running.find((entry) => entry.port === startedPort) || getLatestInstance(running);
@@ -244,8 +253,13 @@ async function resolveTargetInstance({
244
253
  const startedPort = await serveCommand({
245
254
  ...options,
246
255
  explicitPort: false,
256
+ foreground: false,
257
+ json: false,
258
+ quiet: true,
247
259
  suppressUnsafePortWarning: true,
248
260
  suppressUiPasswordWarning: true,
261
+ suppressStartupSummary: true,
262
+ suppressQuietOutput: true,
249
263
  });
250
264
  running = await discoverRunningInstances();
251
265
  const started = running.find((entry) => entry.port === startedPort) || getLatestInstance(running);
@@ -1125,6 +1139,9 @@ async function tunnelCommand(options, subcommand, action, deps) {
1125
1139
  return;
1126
1140
  }
1127
1141
  case 'start': {
1142
+ const interactiveWizard = canPrompt(options)
1143
+ && !(typeof options.profile === 'string' && options.profile.trim().length > 0)
1144
+ && !(typeof options.mode === 'string' && options.mode.trim().length > 0);
1128
1145
  let provider = typeof options.provider === 'string' && options.provider.trim().length > 0
1129
1146
  ? options.provider.trim().toLowerCase()
1130
1147
  : '';
@@ -1474,6 +1491,24 @@ async function tunnelCommand(options, subcommand, action, deps) {
1474
1491
  }
1475
1492
  }
1476
1493
 
1494
+ if (interactiveWizard) {
1495
+ logStatus('info', 'Review tunnel', [
1496
+ `Provider: ${provider}`,
1497
+ `Mode: ${mode}`,
1498
+ `Target: ${options.explicitPort ? `port ${options.port}` : 'running or auto-started server'}`,
1499
+ `Hostname: ${hostname || 'ephemeral URL'}`,
1500
+ `Profile: ${selectedProfile?.name || 'none'}`,
1501
+ ].join('\n'));
1502
+ const approved = await clackConfirm({
1503
+ message: 'Start this tunnel?',
1504
+ initialValue: true,
1505
+ });
1506
+ if (clackIsCancel(approved) || approved !== true) {
1507
+ clackCancel('Tunnel start cancelled.');
1508
+ return;
1509
+ }
1510
+ }
1511
+
1477
1512
  const instance = await resolveTargetInstance({ options, serveCommand, allowAutoStart: true, rejectDesktopRuntime: true });
1478
1513
  if (instance?.autoStarted && shouldRenderHumanOutput(options)) {
1479
1514
  logStatus(
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs';
2
+ import { EXIT_CODE } from './cli-errors.js';
2
3
  import { requestServerShutdown } from './cli-http.js';
3
4
  import { discoverRunningInstances } from './cli-lifecycle.js';
4
5
  import {
@@ -13,6 +14,10 @@ import {
13
14
  import {
14
15
  intro as clackIntro,
15
16
  outro as clackOutro,
17
+ cancel as clackCancel,
18
+ confirm,
19
+ isCancel,
20
+ canPrompt,
16
21
  isJsonMode,
17
22
  isQuietMode,
18
23
  shouldRenderHumanOutput,
@@ -37,6 +42,9 @@ function createUpdateCommand({
37
42
  isInsideSystemdService = () => Boolean(process.env.INVOCATION_ID) || Boolean(process.env.PICHAMBER_SYSTEMD_UNIT),
38
43
  isUserStartupServiceActive = defaultIsUserStartupServiceActive,
39
44
  restartUserStartupService = defaultRestartUserStartupService,
45
+ discoverInstances = discoverRunningInstances,
46
+ requestShutdown = requestServerShutdown,
47
+ stopProcess = stopInstanceProcess,
40
48
  }) {
41
49
  return async function updateCommand(options = {}) {
42
50
  const showOutput = shouldRenderHumanOutput(options);
@@ -150,10 +158,33 @@ function createUpdateCommand({
150
158
  throw new Error(UNOWNED_INSTALL_MESSAGE);
151
159
  }
152
160
 
161
+ const latestVersion = updateInfo.version || 'latest';
162
+ const startupServiceActive = isUserStartupServiceActive();
163
+ const runningInstances = startupServiceActive ? [] : await discoverInstances();
164
+
165
+ if (canPrompt(options) && options.yes !== true) {
166
+ updateSpin?.clear();
167
+ logStatus('info', 'Review update', [
168
+ `Version: ${currentVersion} -> ${latestVersion}`,
169
+ `Package manager: ${pm}`,
170
+ startupServiceActive
171
+ ? 'Restart: startup service'
172
+ : `Restart: ${runningInstances.length} running instance(s)`,
173
+ ].join('\n'));
174
+ const approved = await confirm({
175
+ message: `Install PiChamber ${latestVersion}?`,
176
+ initialValue: true,
177
+ });
178
+ if (isCancel(approved) || approved !== true) {
179
+ clackCancel('Update cancelled.');
180
+ return;
181
+ }
182
+ }
183
+
153
184
  if (showOutput && !updateSpin) {
154
- logStatus('info', `updating ${updateInfo.currentVersion || currentVersion} -> ${updateInfo.version || 'latest'} with ${pm}`);
185
+ logStatus('info', `updating ${currentVersion} -> ${latestVersion} with ${pm}`);
155
186
  }
156
- updateSpin?.message(`Updating to ${updateInfo.version || 'latest'}...`);
187
+ updateSpin?.start(`Updating ${currentVersion} -> ${latestVersion}...`);
157
188
 
158
189
  const result = executeUpdate(pm, { silent: isJsonMode(options) || isQuietMode(options) });
159
190
  if (!result.success) {
@@ -164,10 +195,11 @@ function createUpdateCommand({
164
195
  throw new Error(`Update failed with exit code ${result.exitCode}`);
165
196
  }
166
197
 
167
- let restartedCount = 0;
198
+ const installedVersion = getCurrentVersion();
199
+ const restartResults = [];
168
200
  let startupServiceRestarted = false;
169
201
 
170
- if (isUserStartupServiceActive()) {
202
+ if (startupServiceActive) {
171
203
  updateSpin?.message('Restarting systemd user service...');
172
204
  try {
173
205
  restartUserStartupService();
@@ -181,60 +213,96 @@ function createUpdateCommand({
181
213
  }
182
214
  throw new Error(msg);
183
215
  }
184
- } else {
185
- const runningInstances = await discoverRunningInstances();
186
- if (runningInstances.length > 0) {
187
- updateSpin?.message(`Stopping ${runningInstances.length} running instance(s)...`);
188
- for (const instance of runningInstances) {
189
- try {
190
- const requested = await requestServerShutdown(instance.port, instance.host);
191
- await stopInstanceProcess(instance.pid, {
192
- shutdownWaitMs: requested ? 5000 : 0,
193
- gracefulTimeoutMs: 2500,
194
- forceTimeoutMs: 3000,
195
- });
196
- removePidFile(instance.pidFilePath);
197
- } catch {
198
- }
216
+ } else if (runningInstances.length > 0) {
217
+ updateSpin?.message(`Restarting ${runningInstances.length} running instance(s)...`);
218
+ for (const instance of runningInstances) {
219
+ const storedOptions = readInstanceOptions(instance.instanceFilePath) || { port: instance.port };
220
+ if (storedOptions.launchMode === 'foreground') {
221
+ restartResults.push({ port: instance.port, ok: false, reason: 'foreground-restart-required' });
222
+ continue;
199
223
  }
200
-
201
- updateSpin?.message(`Restarting ${runningInstances.length} instance(s)...`);
202
- for (const instance of runningInstances) {
203
- const storedOptions = readInstanceOptions(instance.instanceFilePath) || { port: instance.port };
204
- await serveCommand({
224
+ try {
225
+ const requested = await requestShutdown(instance.port, instance.host);
226
+ const stopped = await stopProcess(instance.pid, {
227
+ shutdownWaitMs: requested ? 5000 : 0,
228
+ gracefulTimeoutMs: 2500,
229
+ forceTimeoutMs: 3000,
230
+ });
231
+ if (!stopped) {
232
+ restartResults.push({ port: instance.port, ok: false, reason: 'stop-failed' });
233
+ continue;
234
+ }
235
+ removePidFile(instance.pidFilePath);
236
+ const restartedPort = await serveCommand({
205
237
  port: storedOptions.port || instance.port,
206
238
  host: storedOptions.host,
207
239
  explicitPort: true,
208
240
  uiPassword: storedOptions.uiPassword,
241
+ apiOnly: storedOptions.apiOnly === true,
209
242
  suppressStartupSummary: true,
210
243
  suppressUiPasswordWarning: true,
244
+ suppressQuietOutput: true,
211
245
  quiet: true,
212
246
  });
247
+ restartResults.push({ port: instance.port, restartedPort, ok: true });
248
+ } catch (error) {
249
+ restartResults.push({
250
+ port: instance.port,
251
+ ok: false,
252
+ reason: error instanceof Error ? error.message : String(error),
253
+ });
213
254
  }
214
- restartedCount = runningInstances.length;
215
255
  }
216
256
  }
217
257
 
218
- if (showOutput && !updateSpin) {
219
- logStatus('success', `updated to ${updateInfo.version || 'latest'}`);
258
+ const restartedCount = restartResults.filter((entry) => entry.ok).length;
259
+ const failedRestartCount = restartResults.length - restartedCount;
260
+ const versionVerified = latestVersion === 'latest' || installedVersion === latestVersion;
261
+ const messages = [];
262
+ if (!versionVerified) {
263
+ messages.push({
264
+ level: 'warning',
265
+ code: 'VERSION_MISMATCH',
266
+ message: `Package manager completed, but this install reports ${installedVersion} instead of ${latestVersion}.`,
267
+ });
220
268
  }
221
- updateSpin?.stop(`Updated to ${updateInfo.version || 'latest'}`);
222
- if (isJsonMode(options)) {
223
- printJson({
224
- currentVersion,
225
- latestVersion: updateInfo.version || 'latest',
226
- updated: true,
227
- packageManager: pm,
228
- restartedCount,
229
- startupServiceRestarted,
269
+ if (failedRestartCount > 0) {
270
+ messages.push({
271
+ level: 'warning',
272
+ code: 'RESTART_PARTIAL',
273
+ message: `${failedRestartCount} running instance(s) require manual restart.`,
230
274
  });
231
- return;
275
+ }
276
+
277
+ updateSpin?.clear();
278
+ const exitCode = messages.length > 0 ? EXIT_CODE.GENERAL_ERROR : EXIT_CODE.SUCCESS;
279
+ const resultPayload = {
280
+ status: messages.length > 0 ? 'warning' : 'ok',
281
+ previousVersion: currentVersion,
282
+ currentVersion: installedVersion,
283
+ latestVersion,
284
+ versionVerified,
285
+ updated: installedVersion !== currentVersion || versionVerified,
286
+ packageManager: pm,
287
+ restartedCount,
288
+ startupServiceRestarted,
289
+ restartResults,
290
+ messages,
291
+ };
292
+ if (isJsonMode(options)) {
293
+ printJson(resultPayload);
294
+ return { exitCode };
232
295
  }
233
296
  if (showOutput) {
234
- clackOutro('update complete');
297
+ logStatus(versionVerified ? 'success' : 'warning', `version ${currentVersion} -> ${installedVersion}`);
298
+ for (const message of messages) {
299
+ logStatus('warning', `[${message.code}]`, message.message);
300
+ }
301
+ clackOutro(messages.length > 0 ? 'update complete with warnings' : 'update complete');
235
302
  } else if (isQuietMode(options)) {
236
- process.stdout.write(`updated ${updateInfo.version || 'latest'}\n`);
303
+ process.stdout.write(`updated ${currentVersion} -> ${installedVersion} restarted:${restartedCount} failed:${failedRestartCount}\n`);
237
304
  }
305
+ return { exitCode };
238
306
  };
239
307
  }
240
308
 
@@ -23,6 +23,9 @@ async function withTempPiChamberDataDir(fn) {
23
23
 
24
24
  function createTestUpdateCommand(overrides = {}) {
25
25
  const executeUpdate = overrides.executeUpdate || vi.fn(() => ({ success: true, exitCode: 0 }));
26
+ const getCurrentVersion = overrides.getCurrentVersion || vi.fn()
27
+ .mockReturnValueOnce('1.0.0')
28
+ .mockReturnValue('9.9.9');
26
29
  const serveCommand = overrides.serveCommand || vi.fn();
27
30
  const restartUserStartupService = overrides.restartUserStartupService || vi.fn();
28
31
  const updateCommand = createUpdateCommand({
@@ -31,11 +34,14 @@ function createTestUpdateCommand(overrides = {}) {
31
34
  isInsideSystemdService: overrides.isInsideSystemdService || (() => false),
32
35
  isUserStartupServiceActive: overrides.isUserStartupServiceActive || (() => false),
33
36
  restartUserStartupService,
37
+ discoverInstances: overrides.discoverInstances,
38
+ requestShutdown: overrides.requestShutdown,
39
+ stopProcess: overrides.stopProcess,
34
40
  importFromFilePath: vi.fn(async () => ({
35
41
  checkForUpdates: overrides.checkForUpdates || vi.fn(async () => ({ available: true, version: '9.9.9' })),
36
42
  resolveTrustedUpdatePackageManager: overrides.resolveTrustedUpdatePackageManager || vi.fn(() => 'npm'),
37
43
  executeUpdate,
38
- getCurrentVersion: vi.fn(() => '1.0.0'),
44
+ getCurrentVersion,
39
45
  })),
40
46
  });
41
47
  return { updateCommand, executeUpdate, serveCommand, restartUserStartupService };
@@ -58,6 +64,96 @@ describe('update command', () => {
58
64
  });
59
65
  });
60
66
 
67
+ it('reports the version before and after a successful update', async () => {
68
+ await withTempPiChamberDataDir(async () => {
69
+ const output = [];
70
+ const originalWrite = process.stdout.write;
71
+ process.stdout.write = vi.fn((chunk) => {
72
+ output.push(String(chunk));
73
+ return true;
74
+ });
75
+ const { updateCommand } = createTestUpdateCommand();
76
+
77
+ try {
78
+ await updateCommand({ json: true });
79
+ expect(JSON.parse(output.join(''))).toMatchObject({
80
+ status: 'ok',
81
+ previousVersion: '1.0.0',
82
+ currentVersion: '9.9.9',
83
+ latestVersion: '9.9.9',
84
+ versionVerified: true,
85
+ updated: true,
86
+ });
87
+ } finally {
88
+ process.stdout.write = originalWrite;
89
+ }
90
+ });
91
+ });
92
+
93
+ it('reports a version mismatch as a warning', async () => {
94
+ await withTempPiChamberDataDir(async () => {
95
+ const output = [];
96
+ const originalWrite = process.stdout.write;
97
+ process.stdout.write = vi.fn((chunk) => {
98
+ output.push(String(chunk));
99
+ return true;
100
+ });
101
+ const { updateCommand } = createTestUpdateCommand({
102
+ getCurrentVersion: vi.fn().mockReturnValueOnce('1.0.0').mockReturnValue('1.0.0'),
103
+ });
104
+
105
+ try {
106
+ await updateCommand({ json: true });
107
+ expect(JSON.parse(output.join(''))).toMatchObject({
108
+ status: 'warning',
109
+ previousVersion: '1.0.0',
110
+ currentVersion: '1.0.0',
111
+ versionVerified: false,
112
+ });
113
+ } finally {
114
+ process.stdout.write = originalWrite;
115
+ }
116
+ });
117
+ });
118
+
119
+ it('reports partial instance restart failures without losing successful results', async () => {
120
+ await withTempPiChamberDataDir(async (dir) => {
121
+ const firstOptions = path.join(dir, 'first.json');
122
+ const secondOptions = path.join(dir, 'second.json');
123
+ fs.writeFileSync(firstOptions, JSON.stringify({ port: 3001, launchMode: 'daemon', apiOnly: true }));
124
+ fs.writeFileSync(secondOptions, JSON.stringify({ port: 3002, launchMode: 'daemon' }));
125
+ const output = [];
126
+ const originalWrite = process.stdout.write;
127
+ process.stdout.write = vi.fn((chunk) => {
128
+ output.push(String(chunk));
129
+ return true;
130
+ });
131
+ const { updateCommand, serveCommand } = createTestUpdateCommand({
132
+ discoverInstances: async () => [
133
+ { port: 3001, pid: 101, instanceFilePath: firstOptions, pidFilePath: path.join(dir, 'first.pid') },
134
+ { port: 3002, pid: 102, instanceFilePath: secondOptions, pidFilePath: path.join(dir, 'second.pid') },
135
+ ],
136
+ requestShutdown: async () => true,
137
+ stopProcess: async (pid) => pid === 101,
138
+ serveCommand: vi.fn(async (options) => options.port),
139
+ });
140
+
141
+ try {
142
+ const result = await updateCommand({ json: true });
143
+ const payload = JSON.parse(output.join(''));
144
+ expect(result).toMatchObject({ exitCode: 1 });
145
+ expect(payload).toMatchObject({ status: 'warning', restartedCount: 1 });
146
+ expect(payload.restartResults).toEqual([
147
+ expect.objectContaining({ port: 3001, restartedPort: 3001, ok: true }),
148
+ expect.objectContaining({ port: 3002, ok: false, reason: 'stop-failed' }),
149
+ ]);
150
+ expect(serveCommand).toHaveBeenCalledWith(expect.objectContaining({ port: 3001, apiOnly: true }));
151
+ } finally {
152
+ process.stdout.write = originalWrite;
153
+ }
154
+ });
155
+ });
156
+
61
157
  it('handles failed update execution safely without touching instances', async () => {
62
158
  await withTempPiChamberDataDir(async () => {
63
159
  const { updateCommand, executeUpdate, serveCommand, restartUserStartupService } = createTestUpdateCommand({
@@ -1 +1 @@
1
- import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{c as x}from"./index-ivrh3jfy.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
1
+ import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{c as x}from"./index-D2C3q2xD.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};