@pi-chamber/web 0.9.0 → 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 (101) hide show
  1. package/README.md +22 -6
  2. package/bin/cli.js +11 -1
  3. package/bin/cli.test.js +18 -0
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +7 -3
  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-logs.js +22 -4
  12. package/bin/lib/commands-serve.js +10 -2
  13. package/bin/lib/commands-tunnel.js +14 -0
  14. package/bin/lib/commands-update.js +18 -14
  15. package/bin/lib/commands-update.test.js +2 -1
  16. package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DoEOH0hY.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-y9Ystuhv.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-ScM4XoqZ.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CjkhMFqJ.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Bqi6H8I-.js} +3 -3
  21. package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-ClnfJJ2J.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
  27. package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Cy9tmnMg.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-DJNcTQNp.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-DxgVLhi9.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-CIFSGjJs.js} +1 -1
  36. package/dist/assets/{index-yWgKW2Fx.js → index-D2C3q2xD.js} +4 -4
  37. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  38. package/dist/assets/{index-D1IaU-Q7.js → index-DmNPBaSo.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-CrvpUauF.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CKvhS32g.js} +1 -1
  41. package/dist/assets/{main-DhvLreEl.js → main-BFv8slLp.js} +2 -2
  42. package/dist/assets/{main-DcAMXRSi.js → main-CjM7g4Gq.js} +7 -7
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-DKrraAqT.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-hQnLS5mt.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-DuXOBGs_.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DofX2wjB.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-BZeYg6eN.js} +3 -3
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-C7CBxDbh.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-BEoW7LlC.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-Dy-Tz_LJ.js} +2 -2
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +3 -3
  60. package/server/index.js +26 -7
  61. package/server/lib/client-auth/pairing.js +13 -2
  62. package/server/lib/client-auth/remote-clients.js +13 -2
  63. package/server/lib/fs/DOCUMENTATION.md +3 -1
  64. package/server/lib/fs/routes.test.js +74 -0
  65. package/server/lib/git/DOCUMENTATION.md +1 -1
  66. package/server/lib/git/identity-storage.js +10 -1
  67. package/server/lib/package-manager.js +1 -1
  68. package/server/lib/package-manager.test.js +11 -0
  69. package/server/lib/pi/archive-store.js +3 -2
  70. package/server/lib/pi/model-config-store.js +6 -2
  71. package/server/lib/pi/routes.js +11 -2
  72. package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
  73. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  74. package/server/lib/pi/session-daemon/session-daemon.js +226 -40
  75. package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
  76. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  77. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  78. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  79. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  80. package/server/lib/pi/session-folders-store.js +20 -2
  81. package/server/lib/pi/session-folders-store.test.js +17 -0
  82. package/server/lib/pi/settings-store.js +3 -2
  83. package/server/lib/pi/snippets-store.js +4 -1
  84. package/server/lib/pi/ui-settings-store.js +3 -2
  85. package/server/lib/server/cross-process-lock.js +112 -0
  86. package/server/lib/server/cross-process-lock.test.js +70 -0
  87. package/server/lib/server/server-profile.js +110 -0
  88. package/server/lib/server/server-profile.test.js +58 -0
  89. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  90. package/server/lib/server/tunnel-service.js +8 -1
  91. package/server/lib/stt/config-store.js +3 -2
  92. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  93. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  94. package/server/lib/ui-auth/ui-auth.js +9 -2
  95. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  96. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  97. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  98. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  99. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  100. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  101. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
package/README.md CHANGED
@@ -5,20 +5,36 @@ PiChamber's web server and browser UI for the Pi coding-agent runtime.
5
5
  ## Run
6
6
 
7
7
  ```bash
8
- pichamber serve --port 3000
8
+ pichamber serve
9
9
  ```
10
10
 
11
- The server starts warming the local Pi session daemon as soon as HTTP is listening, serves the browser UI, and exposes authenticated Pi routes under `/api/pi/*`. HTTP readiness does not wait for Pi provider/model initialization; early Pi requests share the supervisor's in-flight startup.
11
+ In an interactive terminal, `pichamber serve` guides you through access, port,
12
+ authentication, browser UI versus API-only content, and background versus
13
+ foreground process mode. It shows a review before starting. The server starts
14
+ warming the local Pi session daemon as soon as HTTP is listening, serves the
15
+ browser UI, and exposes authenticated Pi routes under `/api/pi/*`. HTTP
16
+ readiness does not wait for Pi provider/model initialization; early Pi requests
17
+ share the supervisor's in-flight startup.
18
+
19
+ For scripts and non-interactive shells, pass the setup flags explicitly:
12
20
 
13
21
  ```bash
14
- pichamber serve --port 8080
15
- pichamber serve --lan --ui-password <password>
22
+ pichamber serve --port 3000 --ui-password <password>
23
+ pichamber serve --port 8080 --lan --ui-password <password>
24
+ pichamber serve --port 3000 --api-only --ui-password <password>
16
25
  pichamber connect-url --port 3000 --qr
17
- pichamber stop
26
+ pichamber stop --port 3000
18
27
  ```
19
28
 
29
+ `--quiet` and `--json` never prompt. Use `pichamber stop --force` when a broad
30
+ stop should skip confirmation, and `pichamber logs --no-follow` for a one-time
31
+ log tail. Use `pichamber update --yes` to update without the interactive review.
32
+
20
33
  Use `--api-only` for a host intended to be paired from a PiChamber desktop or mobile client. LAN-bound servers require a UI password unless the explicit unsafe-development override is set.
21
34
 
35
+ See the [CLI guide](../docs/content/docs/cli.mdx) for guided startup, updates,
36
+ tunnels, logs, pairing, and machine-readable output.
37
+
22
38
  ## Runtime contract
23
39
 
24
40
  - Pi session state and actions are served only through `/api/pi/*`.
@@ -27,7 +43,7 @@ Use `--api-only` for a host intended to be paired from a PiChamber desktop or mo
27
43
  - Final-only speech-to-text uses authenticated `/api/stt/*` routes and `/api/stt/ws`. Local model inference runs in a forked worker, while remote provider credentials remain in server configuration.
28
44
  - Browser and paired clients authenticate with UI sessions or scoped client credentials.
29
45
  - `connect-url` creates a one-time pairing link; credentials are not written to URLs or logs.
30
- - The server owns the Pi daemon lifecycle and stops its locally managed daemon during shutdown.
46
+ - The server owns its per-profile Pi daemon lifecycle (installed web, development web, and desktop use separate namespaces) and stops only its own daemon during shutdown.
31
47
 
32
48
  ## Development
33
49
 
package/bin/cli.js CHANGED
@@ -191,6 +191,13 @@ commands.update = createUpdateCommand({
191
191
  });
192
192
 
193
193
  async function main() {
194
+ // Seed output mode before parsing so syntax errors such as a missing option
195
+ // value still honor the strict --json contract.
196
+ const rawArgs = process.argv.slice(2);
197
+ activeCommandOptions = {
198
+ json: rawArgs.some((arg) => arg === '--json' || arg.startsWith('--json=')),
199
+ quiet: rawArgs.some((arg) => arg === '--quiet' || arg === '-q'),
200
+ };
194
201
  const parsed = parseArgs();
195
202
  const { command, explicitCommand, subcommand, tunnelAction, startupAction, options, removedFlagErrors, helpRequested, versionRequested } = parsed;
196
203
  if (command === 'serve' && explicitCommand) {
@@ -266,7 +273,10 @@ async function main() {
266
273
  process.exit(EXIT_CODE.USAGE_ERROR);
267
274
  }
268
275
 
269
- await commands[command](options);
276
+ const commandResult = await commands[command](options);
277
+ if (commandResult && Number.isInteger(commandResult.exitCode)) {
278
+ process.exitCode = commandResult.exitCode;
279
+ }
270
280
  }
271
281
 
272
282
  const isCliExecution = isModuleCliExecution(process.argv[1], import.meta.url, fs.realpathSync, 'pichamber');
package/bin/cli.test.js CHANGED
@@ -323,6 +323,11 @@ describe('cli args', () => {
323
323
  expect(parseArgs(['update', '-y']).options.yes).toBe(true);
324
324
  });
325
325
 
326
+ it('rejects invalid log line counts instead of silently using the default', () => {
327
+ expect(() => parseArgs(['logs', '--lines', 'not-a-number'])).toThrow(/Invalid lines value/);
328
+ expect(() => parseArgs(['logs', '--lines', '0'])).toThrow(/Invalid lines value/);
329
+ });
330
+
326
331
  it('supports --hostname as top-level bind alias', () => {
327
332
  const parsed = parseArgs(['serve', '--hostname', '0.0.0.0']);
328
333
 
@@ -485,6 +490,19 @@ describe('startup enable command helper', () => {
485
490
  });
486
491
 
487
492
  describe('version command', () => {
493
+ it('keeps JSON output strict when argument parsing fails', () => {
494
+ const result = spawnSync(process.execPath, [new URL('./cli.js', import.meta.url).pathname, '--json', '--port'], {
495
+ encoding: 'utf8',
496
+ });
497
+
498
+ expect(result.status).toBe(2);
499
+ expect(result.stderr).toBe('');
500
+ expect(JSON.parse(result.stdout)).toMatchObject({
501
+ status: 'error',
502
+ error: { message: 'Missing value for --port.' },
503
+ });
504
+ });
505
+
488
506
  it('prints the installed package version', () => {
489
507
  const packageJson = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
490
508
  const result = spawnSync(process.execPath, [new URL('./cli.js', import.meta.url).pathname, 'version'], {
@@ -9,10 +9,10 @@ This directory contains non-entrypoint PiChamber CLI implementation. `../cli.js`
9
9
  - `commands-status.js`: running-instance and tunnel status presentation.
10
10
  - `commands-logs.js`: log discovery, tailing, and follow behavior. Quiet mode emits raw log lines, while multi-instance output retains port prefixes.
11
11
  - `commands-startup.js`: native startup service management. Interactive `startup enable` walks through access, port, authentication, and confirmation when no setup flags are supplied. Flag-driven, non-TTY, `--quiet`, and `--json` runs remain non-interactive. The command stores serve flags (`--port`, `--lan`/`--host`, `--ui-password`, `--api-only`) in the native service. Re-running enable rewrites and restarts a systemd unit so the new settings take effect immediately. LAN binds require a UI password, matching `pichamber serve`.
12
- - `commands-connect-url.js`: authenticated direct/relay pairing links.
12
+ - `commands-connect-url.js`: authenticated direct/relay pairing links. Auto-started servers run silently inside the command; `--json` and non-TTY output contain only the requested machine-readable/link result, and QR art is interactive-terminal-only.
13
13
  - `pichamber version` and `pichamber --version`: print the installed package version; `--json` returns the same value as JSON.
14
- - `commands-update.js`: package update and restart coordination. Interactive updates review the old and target versions and restart impact before installation; `--yes` skips confirmation. Updates only a global install owned by the running CLI. Results distinguish the previous, installed, and latest versions and report partial restart failures. A Linux user systemd unit is restarted in place; the command does not spawn a replacement server on the same port.
15
- - `commands-tunnel.js`: tunnel lifecycle and profile management. Interactive tunnel setup ends with a review and confirmation; fully specified flag and profile runs remain direct.
14
+ - `commands-update.js`: package update and restart coordination. Interactive updates review the old and target versions and restart impact before installation; `--yes` skips confirmation. Updates only a global install owned by the running CLI. Package-manager output is suppressed for `--quiet`/`--json`; results distinguish the previous, installed, and latest versions and report partial restart failures with a non-zero CLI exit. A Linux user systemd unit is restarted in place; the command does not spawn a replacement server on the same port.
15
+ - `commands-tunnel.js`: tunnel lifecycle and profile management. Interactive tunnel setup ends with a review and confirmation; fully specified flag and profile runs remain direct. Auto-started servers never write nested output into the parent command's `--quiet` or `--json` result.
16
16
 
17
17
  ## Rules
18
18
 
@@ -361,10 +361,14 @@ function parseArgs(argv = process.argv.slice(2)) {
361
361
  case 'lines': {
362
362
  const { value, nextIndex } = consumeValue(i, inlineValue);
363
363
  i = nextIndex;
364
- const parsed = parseInt(value ?? '', 10);
365
- if (Number.isFinite(parsed) && parsed > 0) {
366
- options.lines = parsed;
364
+ if (typeof value !== 'string' || !/^\d+$/.test(value.trim())) {
365
+ throw new TunnelCliError('Invalid lines value. Provide a positive integer.', EXIT_CODE.USAGE_ERROR);
366
+ }
367
+ const parsed = Number(value);
368
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
369
+ throw new TunnelCliError('Invalid lines value. Provide a positive integer.', EXIT_CODE.USAGE_ERROR);
367
370
  }
371
+ options.lines = parsed;
368
372
  break;
369
373
  }
370
374
  case 'limit': {
@@ -236,6 +236,9 @@ async function discoverRunningInstances(options = {}) {
236
236
  launchMode,
237
237
  runtime: liveInfo.runtime,
238
238
  source: 'registry+probe',
239
+ profileKey: typeof storedOptions?.profileKey === 'string' && storedOptions.profileKey.length > 0
240
+ ? storedOptions.profileKey
241
+ : undefined,
239
242
  host: typeof confirmedHost === 'string' && confirmedHost.length > 0
240
243
  ? confirmedHost
241
244
  : (typeof storedOptions?.host === 'string' && storedOptions.host.length > 0 ? storedOptions.host : undefined),
@@ -56,6 +56,11 @@ function getLogFilePath(port) {
56
56
  return path.join(getLogsDir(), `pichamber-${port}.log`);
57
57
  }
58
58
 
59
+ function getDaemonLogFilePath(profileKey) {
60
+ if (typeof profileKey !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(profileKey)) return null;
61
+ return path.join(getLogsDir(), `pi-daemon-${profileKey}.log`);
62
+ }
63
+
59
64
  function getTunnelProfilesFilePath() {
60
65
  return path.join(getDataDir(), TUNNEL_PROFILES_FILE_NAME);
61
66
  }
@@ -120,6 +125,7 @@ export {
120
125
  readDesktopLocalClientTokenFromSettings,
121
126
  ensureLogsDir,
122
127
  getLogFilePath,
128
+ getDaemonLogFilePath,
123
129
  getTunnelProfilesFilePath,
124
130
  getLegacyCloudflareManagedRemoteFilePath,
125
131
  readLastManagedLocalConfigPath,
@@ -60,6 +60,7 @@ function writeInstanceOptions(instanceFilePath, options, onNotice) {
60
60
  uiPassword: typeof options.uiPassword === 'string' ? options.uiPassword : undefined,
61
61
  hasUiPassword: typeof options.uiPassword === 'string',
62
62
  apiOnly: options.apiOnly === true,
63
+ ...(typeof options.profileKey === 'string' && options.profileKey.length > 0 ? { profileKey: options.profileKey } : {}),
63
64
  startedAt: Number.isFinite(options.startedAt) ? options.startedAt : Date.now(),
64
65
  };
65
66
  fs.writeFileSync(instanceFilePath, JSON.stringify(toStore, null, 2), { mode: 0o600 });
@@ -111,18 +111,23 @@ function resolveToken(options) {
111
111
  }
112
112
 
113
113
  if (options.tokenStdin) {
114
- const fd = fs.openSync('/dev/stdin', 'r');
115
- try {
116
- const buf = Buffer.alloc(65536);
117
- const bytesRead = fs.readSync(fd, buf, 0, buf.length, null);
118
- const value = buf.slice(0, bytesRead).toString('utf8').trim();
119
- if (!value) {
120
- throw new Error('No token received from stdin.');
114
+ const chunks = [];
115
+ let totalBytes = 0;
116
+ const buffer = Buffer.alloc(8192);
117
+ while (true) {
118
+ const bytesRead = fs.readSync(0, buffer, 0, buffer.length, null);
119
+ if (bytesRead === 0) break;
120
+ totalBytes += bytesRead;
121
+ if (totalBytes > 65536) {
122
+ throw new Error('Token received from stdin is too large (max 65536 bytes).');
121
123
  }
122
- return value;
123
- } finally {
124
- fs.closeSync(fd);
124
+ chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
125
125
  }
126
+ const value = Buffer.concat(chunks).toString('utf8').trim();
127
+ if (!value) {
128
+ throw new Error('No token received from stdin.');
129
+ }
130
+ return value;
126
131
  }
127
132
 
128
133
  if (options.tokenFile) {
@@ -24,6 +24,7 @@ import {
24
24
  log as clackLog,
25
25
  isJsonMode,
26
26
  isQuietMode,
27
+ canPrompt,
27
28
  printJson,
28
29
  logStatus,
29
30
  } from '../cli-output.js';
@@ -238,8 +239,13 @@ function createConnectUrlCommand({ serveCommand }) {
238
239
  port: options.port,
239
240
  explicitPort: true,
240
241
  host: options.host,
242
+ lan: options.lan,
241
243
  uiPassword: options.uiPassword,
244
+ explicitUiPassword: options.explicitUiPassword === true,
242
245
  apiOnly: options.apiOnly,
246
+ foreground: false,
247
+ json: false,
248
+ quiet: true,
243
249
  suppressUnsafePortWarning: true,
244
250
  suppressUiPasswordWarning: true,
245
251
  suppressStartupSummary: true,
@@ -319,7 +325,9 @@ function createConnectUrlCommand({ serveCommand }) {
319
325
  }
320
326
  }
321
327
  clackLog.info('Scan or paste this link into another PiChamber client. It is single-use and expires.');
322
- if (options.qr === true) {
328
+ // QR art is terminal UI. Keep non-TTY stdout limited to the pairing link so
329
+ // agents can capture it even when they pass --qr defensively.
330
+ if (options.qr === true && canPrompt(options)) {
323
331
  await displayTunnelQrCode(connectUrl);
324
332
  }
325
333
  clackOutro('pairing link generated');
@@ -1,4 +1,4 @@
1
- import { getLogFilePath } from './cli-paths.js';
1
+ import { getDaemonLogFilePath, getLogFilePath } from './cli-paths.js';
2
2
  import { readTailLines, followFile } from './cli-log-files.js';
3
3
  import { discoverRunningInstances, getLatestInstance } from './cli-lifecycle.js';
4
4
  import {
@@ -45,10 +45,15 @@ async function logsCommand(options) {
45
45
  }
46
46
  const entries = targets.map((target) => {
47
47
  const logPath = getLogFilePath(target.port);
48
+ const daemonLogPath = getDaemonLogFilePath(target.profileKey);
48
49
  return {
49
50
  port: target.port,
50
51
  logPath,
51
52
  lines: readTailLines(logPath, options.lines),
53
+ ...(daemonLogPath ? {
54
+ daemonLogPath,
55
+ daemonLines: readTailLines(daemonLogPath, options.lines),
56
+ } : {}),
52
57
  };
53
58
  });
54
59
  printJson({ entries });
@@ -61,9 +66,12 @@ async function logsCommand(options) {
61
66
 
62
67
  for (const target of targets) {
63
68
  const logPath = getLogFilePath(target.port);
69
+ const daemonLogPath = getDaemonLogFilePath(target.profileKey);
64
70
  const lines = readTailLines(logPath, options.lines);
71
+ const daemonLines = daemonLogPath ? readTailLines(daemonLogPath, options.lines) : [];
65
72
  if (showFrames) {
66
73
  logStatus('info', `port ${target.port}`, logPath);
74
+ if (daemonLogPath) logStatus('info', 'Pi daemon', daemonLogPath);
67
75
  }
68
76
 
69
77
  for (const line of lines) {
@@ -73,6 +81,9 @@ async function logsCommand(options) {
73
81
  console.log(line);
74
82
  }
75
83
  }
84
+ for (const line of daemonLines) {
85
+ console.log(shouldPrefixLines ? `[${target.port} daemon] ${line}` : `[daemon] ${line}`);
86
+ }
76
87
  }
77
88
 
78
89
  if (showFrames) {
@@ -83,15 +94,22 @@ async function logsCommand(options) {
83
94
  return;
84
95
  }
85
96
 
86
- const unsubs = targets.map((target) => {
97
+ const unsubs = targets.flatMap((target) => {
87
98
  const logPath = getLogFilePath(target.port);
88
- return followFile(logPath, (line) => {
99
+ const daemonLogPath = getDaemonLogFilePath(target.profileKey);
100
+ const followers = [followFile(logPath, (line) => {
89
101
  if (shouldPrefixLines) {
90
102
  console.log(`[${target.port}] ${line}`);
91
103
  } else {
92
104
  console.log(line);
93
105
  }
94
- });
106
+ })];
107
+ if (daemonLogPath) {
108
+ followers.push(followFile(daemonLogPath, (line) => {
109
+ console.log(shouldPrefixLines ? `[${target.port} daemon] ${line}` : `[daemon] ${line}`);
110
+ }));
111
+ }
112
+ return followers;
95
113
  });
96
114
 
97
115
  await new Promise((resolve) => {
@@ -354,6 +354,9 @@ async function serveCommand(options) {
354
354
  });
355
355
 
356
356
  const resolvedPort = controller.getPort();
357
+ const resolvedProfileKey = typeof controller.getDaemonProfileKey === 'function'
358
+ ? controller.getDaemonProfileKey()
359
+ : null;
357
360
 
358
361
  // Write PID / instance files so status, stop, and restart can discover
359
362
  // this foreground instance the same way they discover daemon instances.
@@ -366,6 +369,7 @@ async function serveCommand(options) {
366
369
  launchMode: 'foreground',
367
370
  uiPassword: effectiveUiPassword,
368
371
  apiOnly: options.apiOnly === true,
372
+ ...(typeof resolvedProfileKey === 'string' && resolvedProfileKey.length > 0 ? { profileKey: resolvedProfileKey } : {}),
369
373
  }, emitNotice);
370
374
 
371
375
  if (isQuietMode(options)) {
@@ -455,8 +459,9 @@ async function serveCommand(options) {
455
459
  serveSpin?.start(`Starting PiChamber on port ${targetPort === 0 ? 'auto' : targetPort}...`);
456
460
 
457
461
  let resolvedPort;
462
+ let resolvedProfileKey = null;
458
463
  try {
459
- resolvedPort = await new Promise((resolve, reject) => {
464
+ const ready = await new Promise((resolve, reject) => {
460
465
  let settled = false;
461
466
  const timeout = setTimeout(() => {
462
467
  if (settled) return;
@@ -469,7 +474,7 @@ async function serveCommand(options) {
469
474
  if (msg && msg.type === 'pichamber:ready' && typeof msg.port === 'number') {
470
475
  settled = true;
471
476
  clearTimeout(timeout);
472
- resolve(msg.port);
477
+ resolve(msg);
473
478
  }
474
479
  });
475
480
 
@@ -487,6 +492,8 @@ async function serveCommand(options) {
487
492
  reject(new Error(`PiChamber daemon exited before reporting ready${signal ? ` (${signal})` : ` (code ${code ?? 'unknown'})`}`));
488
493
  });
489
494
  });
495
+ resolvedPort = ready.port;
496
+ resolvedProfileKey = typeof ready.profileKey === 'string' && ready.profileKey.length > 0 ? ready.profileKey : null;
490
497
  } catch (error) {
491
498
  await terminateProcessTree(child.pid, { gracefulTimeoutMs: 1500, forceTimeoutMs: 1500 });
492
499
  throw error;
@@ -526,6 +533,7 @@ async function serveCommand(options) {
526
533
  launchMode: 'daemon',
527
534
  uiPassword: effectiveUiPassword,
528
535
  apiOnly: options.apiOnly === true,
536
+ ...(resolvedProfileKey ? { profileKey: resolvedProfileKey } : {}),
529
537
  }, emitNotice);
530
538
 
531
539
  const serveResult = {
@@ -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);
@@ -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 {
@@ -274,21 +275,23 @@ function createUpdateCommand({
274
275
  }
275
276
 
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
+ };
277
292
  if (isJsonMode(options)) {
278
- printJson({
279
- status: messages.length > 0 ? 'warning' : 'ok',
280
- previousVersion: currentVersion,
281
- currentVersion: installedVersion,
282
- latestVersion,
283
- versionVerified,
284
- updated: installedVersion !== currentVersion || versionVerified,
285
- packageManager: pm,
286
- restartedCount,
287
- startupServiceRestarted,
288
- restartResults,
289
- messages,
290
- });
291
- return;
293
+ printJson(resultPayload);
294
+ return { exitCode };
292
295
  }
293
296
  if (showOutput) {
294
297
  logStatus(versionVerified ? 'success' : 'warning', `version ${currentVersion} -> ${installedVersion}`);
@@ -299,6 +302,7 @@ function createUpdateCommand({
299
302
  } else if (isQuietMode(options)) {
300
303
  process.stdout.write(`updated ${currentVersion} -> ${installedVersion} restarted:${restartedCount} failed:${failedRestartCount}\n`);
301
304
  }
305
+ return { exitCode };
302
306
  };
303
307
  }
304
308
 
@@ -139,8 +139,9 @@ describe('update command', () => {
139
139
  });
140
140
 
141
141
  try {
142
- await updateCommand({ json: true });
142
+ const result = await updateCommand({ json: true });
143
143
  const payload = JSON.parse(output.join(''));
144
+ expect(result).toMatchObject({ exitCode: 1 });
144
145
  expect(payload).toMatchObject({ status: 'warning', restartedCount: 1 });
145
146
  expect(payload.restartResults).toEqual([
146
147
  expect.objectContaining({ port: 3001, restartedPort: 3001, ok: true }),
@@ -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-yWgKW2Fx.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};
@@ -1 +1 @@
1
- import{R as r,j as t}from"./vendor-react-B5Z1Mdn3.js";import{u as a}from"./index-yWgKW2Fx.js";import{j as v,I as m}from"./useAppFontEffects-BgK55NDM.js";import{D as j}from"./DiagramEditor-CcbnMl1H.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-C_3mcJ01.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-BzeePAPn.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";import"./vendor-react-drawio-BYDptOsj.js";function Kt(){const{files:o}=v(),[e,d]=r.useState(null),[s,p]=r.useState(""),[x,n]=r.useState(!0),l=r.useRef(null),c=a(i=>i.pendingDiagramFile),u=r.useCallback(async i=>{n(!0),d(i);try{const f=await o?.readFile?.(i);f&&p(f.content)}catch{p("")}finally{n(!1)}},[o]);r.useEffect(()=>{if(!c)return;const i=a.getState().consumePendingDiagramFile();i&&u(i)},[u,c]);const g=r.useCallback(async()=>{const i=l.current?.getXml();e&&o?.writeFile&&i&&i!==s&&(await o.writeFile(e,i),p(i))},[e,o,s]),h=e?e.split("/").pop()||e:"";return e?x?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx(m,{name:"loader-4",className:"size-4 animate-spin"})}):t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[t.jsx(m,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:h}),t.jsx("button",{type:"button",onClick:()=>{g()},className:"size-6 flex items-center justify-center rounded-md text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Save diagram",children:t.jsx(m,{name:"save-3",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>a.getState().setActiveMainTab("chat"),className:"size-6 flex items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Close diagram view",children:t.jsx(m,{name:"close",className:"size-4"})})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(j,{ref:l,xml:s,className:"h-full"})})]}):t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("div",{className:"typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}export{Kt as DiagramView};
1
+ import{R as r,j as t}from"./vendor-react-B5Z1Mdn3.js";import{u as a}from"./index-D2C3q2xD.js";import{j as v,I as m}from"./useAppFontEffects-Cs0f1dKn.js";import{D as j}from"./DiagramEditor-DoEOH0hY.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-C7CBxDbh.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-B8Ac62S_.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";import"./vendor-react-drawio-BYDptOsj.js";function Kt(){const{files:o}=v(),[e,d]=r.useState(null),[s,p]=r.useState(""),[x,n]=r.useState(!0),l=r.useRef(null),c=a(i=>i.pendingDiagramFile),u=r.useCallback(async i=>{n(!0),d(i);try{const f=await o?.readFile?.(i);f&&p(f.content)}catch{p("")}finally{n(!1)}},[o]);r.useEffect(()=>{if(!c)return;const i=a.getState().consumePendingDiagramFile();i&&u(i)},[u,c]);const g=r.useCallback(async()=>{const i=l.current?.getXml();e&&o?.writeFile&&i&&i!==s&&(await o.writeFile(e,i),p(i))},[e,o,s]),h=e?e.split("/").pop()||e:"";return e?x?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx(m,{name:"loader-4",className:"size-4 animate-spin"})}):t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[t.jsx(m,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:h}),t.jsx("button",{type:"button",onClick:()=>{g()},className:"size-6 flex items-center justify-center rounded-md text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Save diagram",children:t.jsx(m,{name:"save-3",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>a.getState().setActiveMainTab("chat"),className:"size-6 flex items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Close diagram view",children:t.jsx(m,{name:"close",className:"size-4"})})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(j,{ref:l,xml:s,className:"h-full"})})]}):t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("div",{className:"typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}export{Kt as DiagramView};