@openchamber/web 1.14.1 → 1.15.0

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 (87) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-4FWg9xMC.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-D_9BAjtv.js} +3 -3
  12. package/dist/assets/es-cjUissX4.js +15 -0
  13. package/dist/assets/fr-DqbXnTdK.js +13 -0
  14. package/dist/assets/index-Dg0nmvQU.css +1 -0
  15. package/dist/assets/index-ltrmNGAf.js +2 -0
  16. package/dist/assets/ja-Cetyq6Eg.js +15 -0
  17. package/dist/assets/ko-DtunWisP.js +15 -0
  18. package/dist/assets/main-BC0m8s1v.js +236 -0
  19. package/dist/assets/main-DzNa8r0N.js +2 -0
  20. package/dist/assets/miniChat-BRYDE-Se.js +2 -0
  21. package/dist/assets/mobile-C3QJVA97.js +2 -0
  22. package/dist/assets/pl-DctGLgve.js +15 -0
  23. package/dist/assets/pt-BR-CXPhf78S.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
  25. package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
  27. package/dist/assets/uk-Bdrc-kqF.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DzBg8hrC.js} +123 -119
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
  31. package/dist/assets/zh-TW-CoqiQING.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +130 -1
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/apns-runtime.js +9 -16
  41. package/server/lib/opencode/bootstrap-runtime.js +10 -0
  42. package/server/lib/opencode/core-routes.js +246 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/network-runtime.js +14 -1
  45. package/server/lib/opencode/network-runtime.test.js +29 -9
  46. package/server/lib/opencode/proxy.js +47 -6
  47. package/server/lib/opencode/settings-helpers.js +3 -0
  48. package/server/lib/opencode/settings-helpers.test.js +11 -0
  49. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  50. package/server/lib/package-manager.js +18 -5
  51. package/server/lib/relay/DOCUMENTATION.md +78 -0
  52. package/server/lib/relay/cross-compat.test.js +135 -0
  53. package/server/lib/relay/e2ee.js +341 -0
  54. package/server/lib/relay/e2ee.test.js +124 -0
  55. package/server/lib/relay/host-client.js +389 -0
  56. package/server/lib/relay/host-client.test.js +280 -0
  57. package/server/lib/relay/identity.js +73 -0
  58. package/server/lib/relay/identity.test.js +78 -0
  59. package/server/lib/relay/service.js +247 -0
  60. package/server/lib/relay/signing-key.js +50 -0
  61. package/server/lib/relay/tunnel-codec.js +373 -0
  62. package/server/lib/relay/tunnel-codec.test.js +58 -0
  63. package/server/lib/relay/tunnel-host.js +462 -0
  64. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  65. package/server/lib/ui-auth/ui-auth.js +10 -0
  66. package/server/opencode-proxy.test.js +38 -0
  67. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  68. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  69. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  70. package/dist/assets/es-bWcuDy_2.js +0 -15
  71. package/dist/assets/fr-DzRs3OzV.js +0 -13
  72. package/dist/assets/index-KnWk9fmM.css +0 -1
  73. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  74. package/dist/assets/ja-BqUX_UD3.js +0 -15
  75. package/dist/assets/ko-BQo10SNx.js +0 -15
  76. package/dist/assets/main-BDoqLlQB.js +0 -236
  77. package/dist/assets/main-DUGyTrDt.js +0 -2
  78. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  79. package/dist/assets/mobile-DnghtOCb.js +0 -2
  80. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  81. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  82. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  83. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  84. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  85. package/dist/assets/uk-C9k8SP8q.js +0 -15
  86. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  87. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
package/bin/cli.test.js CHANGED
@@ -204,6 +204,14 @@ describe('cli args', () => {
204
204
  expect(parsed.options.server).toBe('http://homebridge:3002');
205
205
  });
206
206
 
207
+ it('parses connect-url --relay flag', () => {
208
+ const parsed = parseArgs(['connect-url', '--relay', '--name', 'My laptop']);
209
+
210
+ expect(parsed.command).toBe('connect-url');
211
+ expect(parsed.options.relay).toBe(true);
212
+ expect(parsed.options.name).toBe('My laptop');
213
+ });
214
+
207
215
  it('parses connect-url api-only help', () => {
208
216
  const parsed = parseArgs(['connect-url', '--api-only', '--help']);
209
217
 
@@ -36,6 +36,9 @@ Command modules implement user-facing commands and preserve output contracts acr
36
36
  - `commands-connect-url.js`
37
37
  - Implements `openchamber connect-url`.
38
38
  - Finds or starts a local instance and prints the browser/connect URL according to the selected output mode.
39
+ - Emits a **pairing v2** link (`openchamber://connect?v=2&p=<base64url>`): it creates a one-time pairing session in the shared store (`client-pairing-sessions.json`) and encodes the pairing id + secret + transport candidates. The client redeems the secret over whichever candidate connects first (`/api/client-auth/pairing/redeem`). No standalone token is embedded — the QR itself is the single-use credential.
40
+ - The default form advertises the resolved server URL as a direct (lan/tunnel) candidate and folds in a relay candidate when the host relay is enabled, so one link works on-LAN and off-network.
41
+ - `--relay` builds a relay-only pairing link (the sole candidate is the relay transport), for sharing with a device that is not on the host's network — no server URL, no auto-start. The relay endpoint follows `OPENCHAMBER_RELAY_URL` / the stored setting / the default, matching the running host; the host must be running with the relay enabled to serve the redeem over the tunnel.
39
42
 
40
43
  - `commands-update.js`
41
44
  - Implements `openchamber update`.
@@ -264,6 +264,9 @@ function parseArgs(argv = process.argv.slice(2)) {
264
264
  }
265
265
  break;
266
266
  }
267
+ case 'relay':
268
+ options.relay = true;
269
+ break;
267
270
  case 'qr':
268
271
  options.qr = true;
269
272
  options.explicitQr = true;
@@ -384,6 +387,7 @@ OPTIONS:
384
387
  --hostname Alias for --host outside tunnel commands
385
388
  --lan Bind to 0.0.0.0 for LAN access
386
389
  --server <url> Public/server URL for connect-url links
390
+ --relay connect-url: also include the end-to-end-encrypted relay transport
387
391
  --ui-password Protect browser UI with single password
388
392
  --api-only Start API routes only, without serving browser UI assets
389
393
  --foreground Run server in foreground (use with systemd/process managers)
@@ -461,6 +465,11 @@ OPTIONS:
461
465
  --lan Bind to 0.0.0.0 for LAN access when starting
462
466
  --server <url> Public URL saved into the connection link
463
467
  --server-url <url> Alias for --server
468
+ --relay Also include the end-to-end-encrypted relay transport
469
+ so the link works away from the local network. The
470
+ device prefers the direct connection when reachable;
471
+ the instance brings the relay up on its own. Set
472
+ OPENCHAMBER_RELAY_URL to use a self-hosted relay.
464
473
  --name <label> Label saved with the remote client token
465
474
  --ui-password <value> Protect browser access when UI routes are enabled
466
475
  --api-only Start in headless/API-only mode when starting
@@ -473,6 +482,7 @@ EXAMPLES:
473
482
  openchamber connect-url --port 3000 --qr
474
483
  openchamber connect-url --port 3000 --api-only --lan --server http://workstation.local:3000 --qr
475
484
  openchamber connect-url --server https://openchamber.example.com --name Workstation
485
+ openchamber connect-url --relay --name "My laptop"
476
486
  `);
477
487
  }
478
488
 
@@ -13,6 +13,10 @@ import {
13
13
  import { discoverRunningInstances } from './cli-lifecycle.js';
14
14
  import { getInstanceFilePath, readInstanceOptions } from './cli-process.js';
15
15
  import { createRemoteClientAuthRuntime } from '../../server/lib/client-auth/remote-clients.js';
16
+ import { createClientPairingRuntime } from '../../server/lib/client-auth/pairing.js';
17
+ import { createRelayIdentityRuntime } from '../../server/lib/relay/identity.js';
18
+ import { DEFAULT_RELAY_URL } from '../../server/lib/relay/service.js';
19
+ import { bytesToBase64Url } from '../../server/lib/relay/e2ee.js';
16
20
  import {
17
21
  intro as clackIntro,
18
22
  outro as clackOutro,
@@ -24,6 +28,114 @@ import {
24
28
  } from '../cli-output.js';
25
29
 
26
30
  const REMOTE_CLIENTS_FILE_NAME = 'remote-clients.json';
31
+ const SETTINGS_FILE_NAME = 'settings.json';
32
+ const PAIRING_SESSIONS_FILE_NAME = 'client-pairing-sessions.json';
33
+
34
+ function isValidRelayUrl(value) {
35
+ if (typeof value !== 'string') return false;
36
+ try {
37
+ const url = new URL(value.trim());
38
+ return url.protocol === 'ws:' || url.protocol === 'wss:';
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ // Resolve the relay endpoint the same way the running host does (service.js):
45
+ // OPENCHAMBER_RELAY_URL env override, then the stored setting, then the default —
46
+ // so the pairing link points at the same relay the host connects out to.
47
+ function resolveRelayUrl(settings) {
48
+ const envUrl = process.env.OPENCHAMBER_RELAY_URL;
49
+ if (isValidRelayUrl(envUrl)) return envUrl.trim();
50
+ const stored = settings?.privateRelay?.relayUrl;
51
+ if (isValidRelayUrl(stored)) return stored.trim();
52
+ return DEFAULT_RELAY_URL;
53
+ }
54
+
55
+ // Minimal settings.json read/write for the relay identity runtime. It reads the
56
+ // whole object and writes it back with the relay keys added, so other settings
57
+ // are preserved. Enough for the CLI without wiring the full settings runtime.
58
+ function createSettingsAccessors() {
59
+ const settingsPath = path.join(getOpenChamberDataDir(), SETTINGS_FILE_NAME);
60
+ const readSettingsFromDiskMigrated = async () => {
61
+ try {
62
+ return JSON.parse(await fs.promises.readFile(settingsPath, 'utf8'));
63
+ } catch {
64
+ return {};
65
+ }
66
+ };
67
+ const writeSettingsToDisk = async (settings) => {
68
+ await fs.promises.mkdir(path.dirname(settingsPath), { recursive: true });
69
+ await fs.promises.writeFile(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
70
+ };
71
+ return { readSettingsFromDiskMigrated, writeSettingsToDisk };
72
+ }
73
+
74
+ // Resolves the instance's relay identity (serverId + encryption public key,
75
+ // generating it if the relay was never enabled) into a pairing-v2 relay
76
+ // candidate. Relay is a transport, not a separate link format: the candidate
77
+ // carries no token — the client redeems the one-time pairing secret over the
78
+ // E2EE tunnel like any other candidate. `enabled` reports whether the host relay
79
+ // is actually on (a relay candidate only connects when the host is relaying).
80
+ async function buildRelayPairingCandidate() {
81
+ const accessors = createSettingsAccessors();
82
+ const settings = await accessors.readSettingsFromDiskMigrated();
83
+ const relayUrl = resolveRelayUrl(settings);
84
+ const identityRuntime = createRelayIdentityRuntime({ crypto, ...accessors });
85
+ const identity = await identityRuntime.getRelayIdentity();
86
+ return {
87
+ enabled: settings?.privateRelay?.enabled === true,
88
+ relayUrl,
89
+ serverId: identity.serverId,
90
+ candidate: {
91
+ type: 'relay',
92
+ relayUrl,
93
+ serverId: identity.serverId,
94
+ hostEncPubJwk: identity.hostEncPubJwk,
95
+ priority: 30,
96
+ },
97
+ };
98
+ }
99
+
100
+ // Pairing runtime backed by the same on-disk store the running host reads, so a
101
+ // session created here is redeemable by the live server. createPairingSession
102
+ // only writes the store (no server needed to mint); redeem is served by the host.
103
+ function createCliPairingRuntime() {
104
+ const dataDir = getOpenChamberDataDir();
105
+ const remoteClientAuthRuntime = createRemoteClientAuthRuntime({
106
+ fsPromises: fs.promises,
107
+ path,
108
+ crypto,
109
+ storePath: path.join(dataDir, REMOTE_CLIENTS_FILE_NAME),
110
+ });
111
+ return createClientPairingRuntime({
112
+ fsPromises: fs.promises,
113
+ path,
114
+ crypto,
115
+ storePath: path.join(dataDir, PAIRING_SESSIONS_FILE_NAME),
116
+ remoteClientAuthRuntime,
117
+ });
118
+ }
119
+
120
+ // Mirror of encodePairingConnectionPayload in @openchamber/ui (the bin cannot
121
+ // import the UI package). Keep in sync: v2 payload → base64url(JSON) in the URL
122
+ // query, so the one-time secret rides the link, never the network.
123
+ function encodePairingConnectUrl(payload) {
124
+ const encoded = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)));
125
+ return `openchamber://connect?v=2&p=${encoded}`;
126
+ }
127
+
128
+ function buildPairingPayload({ pairing, label, candidates }) {
129
+ return {
130
+ v: 2,
131
+ pairingId: pairing.id,
132
+ secret: pairing.secret,
133
+ ...(label ? { label } : {}),
134
+ ...(pairing.fingerprint ? { fingerprint: pairing.fingerprint } : {}),
135
+ ...(pairing.expiresAt ? { expiresAt: pairing.expiresAt } : {}),
136
+ candidates,
137
+ };
138
+ }
27
139
 
28
140
  async function resolveConnectUrlServerUrl(options) {
29
141
  let hostOverride = options.host;
@@ -70,6 +182,15 @@ function isWildcardBindHost(host) {
70
182
  return host === '0.0.0.0' || host === '::' || host === '[::]';
71
183
  }
72
184
 
185
+ function isLoopbackServerUrl(serverUrl) {
186
+ try {
187
+ const hostname = new URL(serverUrl).hostname.replace(/^\[|\]$/g, '');
188
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1';
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+
73
194
  function normalizeServerUrlForConnection(value) {
74
195
  const trimmed = typeof value === 'string' ? value.trim() : '';
75
196
  if (!trimmed) return null;
@@ -91,15 +212,6 @@ function getOpenChamberDataDir() {
91
212
  : path.join(os.homedir(), '.config', 'openchamber');
92
213
  }
93
214
 
94
- function buildClientConnectionPayload({ serverUrl, token, label }) {
95
- const params = new URLSearchParams();
96
- params.set('v', '1');
97
- params.set('server', serverUrl.trim().replace(/\/+$/, ''));
98
- params.set('token', token.trim());
99
- if (label?.trim()) params.set('label', label.trim());
100
- return `openchamber://connect?${params.toString()}`;
101
- }
102
-
103
215
  async function displayTunnelQrCode(url) {
104
216
  try {
105
217
  const qrcode = await import('qrcode-terminal');
@@ -141,18 +253,35 @@ function createConnectUrlCommand({ serveCommand }) {
141
253
  ? { serverUrl: explicitServerUrl, source: 'explicit' }
142
254
  : await resolveConnectUrlServerUrl(options);
143
255
  const serverUrl = resolvedServerUrl.serverUrl;
144
- const label = options.name || `OpenChamber ${serverUrl}`;
145
- const runtime = createRemoteClientAuthRuntime({
146
- fsPromises: fs.promises,
147
- path,
148
- crypto,
149
- storePath: path.join(getOpenChamberDataDir(), REMOTE_CLIENTS_FILE_NAME),
150
- });
151
- const result = await runtime.createClient({ label });
152
- const connectUrl = buildClientConnectionPayload({ serverUrl, token: result.token, label });
256
+ const label = options.name || os.hostname();
257
+
258
+ // Direct candidate for the reachable server URL, plus the relay transport as
259
+ // a fallback candidate — one link that works both on the LAN and off-network.
260
+ // Candidate priorities make the client prefer the direct route and try the
261
+ // relay last, mirroring the UI's "Anywhere" pairing. `--relay` opts in even
262
+ // when the host relay is not up yet (the demand-driven lifecycle starts it);
263
+ // otherwise the relay rides along only when it is already enabled.
264
+ const candidates = [{ type: serverUrl.startsWith('https://') ? 'tunnel' : 'lan', url: serverUrl, priority: 10 }];
265
+ const relay = await buildRelayPairingCandidate();
266
+ if (options.relay || relay.enabled) candidates.push(relay.candidate);
267
+
268
+ const pairingRuntime = createCliPairingRuntime();
269
+ // Mark relay-carrying sessions like the server route does, so the host's
270
+ // demand-driven relay lifecycle keeps the relay up while the link is pending.
271
+ const usesRelay = candidates.some((candidate) => candidate.type === 'relay');
272
+ const { pairing } = await pairingRuntime.createPairingSession({ label, usesRelay });
273
+ const connectUrl = encodePairingConnectUrl(buildPairingPayload({ pairing, label, candidates }));
153
274
 
154
275
  if (isJsonMode(options)) {
155
- printJson({ serverUrl, connectUrl, token: result.token, client: result.client, autoStarted: serverState.autoStarted });
276
+ printJson({
277
+ serverUrl,
278
+ connectUrl,
279
+ pairingId: pairing.id,
280
+ fingerprint: pairing.fingerprint,
281
+ expiresAt: pairing.expiresAt,
282
+ candidates,
283
+ autoStarted: serverState.autoStarted,
284
+ });
156
285
  return;
157
286
  }
158
287
 
@@ -161,22 +290,40 @@ function createConnectUrlCommand({ serveCommand }) {
161
290
  return;
162
291
  }
163
292
 
164
- clackIntro('OpenChamber connect URL');
293
+ clackIntro('OpenChamber pairing link');
165
294
  if (serverState.autoStarted) {
166
295
  logStatus('success', `started OpenChamber on port ${options.port}`);
167
296
  }
168
297
  logStatus('success', connectUrl);
169
298
  clackLog.info(`Server URL: ${serverUrl}`);
299
+ if (options.relay || relay.enabled) {
300
+ clackLog.info(`Relay fallback: ${relay.relayUrl}`);
301
+ }
302
+ if (options.relay && !relay.enabled) {
303
+ logStatus('info', '[RELAY_STARTING]', 'Relay is not up yet. A running instance starts it within a minute; a stopped instance starts it on next launch.');
304
+ }
305
+ if (pairing.fingerprint) {
306
+ clackLog.info(`Fingerprint: ${pairing.fingerprint}`);
307
+ }
170
308
  if (resolvedServerUrl.source === 'lan-detected') {
171
309
  clackLog.info('Detected a LAN address because OpenChamber is bound to all interfaces. Use --server to override it.');
172
310
  } else if (resolvedServerUrl.source === 'loopback-fallback') {
173
311
  clackLog.warn('OpenChamber is bound to all interfaces, but no LAN address was detected. Use --server to provide a reachable URL.');
312
+ } else if (isLoopbackServerUrl(serverUrl)) {
313
+ // The direct candidate points at this machine only — other devices cannot
314
+ // use it. Say so instead of letting a "LAN" link silently not work (or a
315
+ // --relay link silently go relay-only).
316
+ if (options.relay) {
317
+ logStatus('warn', '[LAN_UNREACHABLE]', 'OpenChamber only listens on this machine, so devices will always connect through the relay. Restart with --lan to allow direct home-network connections.');
318
+ } else {
319
+ logStatus('warn', '[LAN_UNREACHABLE]', 'OpenChamber only listens on this machine, so other devices cannot use this link. Restart with --lan, or use --server to provide a reachable URL.');
320
+ }
174
321
  }
175
- clackLog.info('Copy this connection link into another OpenChamber client. The token is shown only once.');
322
+ clackLog.info('Scan or paste this link into another OpenChamber client. It is single-use and expires.');
176
323
  if (options.qr === true) {
177
324
  await displayTunnelQrCode(connectUrl);
178
325
  }
179
- clackOutro('connect URL generated');
326
+ clackOutro('pairing link generated');
180
327
  };
181
328
  }
182
329
 
@@ -1 +1 @@
1
- import{R as s,j as e}from"./vendor-.bun-C6iL44L9.js";import{u as c}from"./index-ZJTzZ0_U.js";import{c as j,d as b,I as a}from"./useAppFontEffects-BUUJYbAZ.js";import{D as y}from"./main-BDoqLlQB.js";import"./runtimeEndpointReset-By39StyB.js";import"./mobileLayoutPreference-Dio-WWkI.js";import"./SessionSwitcherDropdown-4FWg9xMC.js";function S(){const{t:n}=j(),{files:r}=b(),[t,x]=s.useState(null),[l,o]=s.useState(""),[p,m]=s.useState(!0),u=s.useRef(null),f=c(i=>i.pendingDiagramFile),d=s.useCallback(async i=>{m(!0),x(i);try{const g=await r?.readFile?.(i);g&&o(g.content)}catch{o("")}finally{m(!1)}},[r]);s.useEffect(()=>{if(!f)return;const i=c.getState().consumePendingDiagramFile();i&&d(i)},[d,f]);const h=s.useCallback(async()=>{const i=u.current?.getXml();t&&r?.writeFile&&i&&i!==l&&(await r.writeFile(t,i),o(i))},[t,r,l]),v=t?t.split("/").pop()||t:"";return t?p?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[e.jsx(a,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:v}),e.jsx("button",{type:"button",onClick:()=>{h()},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:n("filesView.diagram.saveDiagram"),children:e.jsx(a,{name:"save-3",className:"size-4"})}),e.jsx("button",{type:"button",onClick:()=>c.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:n("filesView.diagram.closeDiagramView"),children:e.jsx(a,{name:"close",className:"size-4"})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(y,{ref:u,xml:l,className:"h-full"})})]}):e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("div",{className:"typography-ui text-muted-foreground",children:n("filesView.editor.pickFileFromTree")})})}export{S as DiagramView};
1
+ import{R as s,j as e}from"./vendor-.bun-BE757pvp.js";import{u as c}from"./index-ltrmNGAf.js";import{c as j,d as b,I as a}from"./useAppFontEffects-DzBg8hrC.js";import{D as y}from"./main-BC0m8s1v.js";import"./runtimeEndpointReset-C42u8PvG.js";import"./mobileLayoutPreference-Dio-WWkI.js";import"./SessionSwitcherDropdown-DvoOalMY.js";function S(){const{t:n}=j(),{files:r}=b(),[t,x]=s.useState(null),[l,o]=s.useState(""),[p,m]=s.useState(!0),u=s.useRef(null),f=c(i=>i.pendingDiagramFile),d=s.useCallback(async i=>{m(!0),x(i);try{const g=await r?.readFile?.(i);g&&o(g.content)}catch{o("")}finally{m(!1)}},[r]);s.useEffect(()=>{if(!f)return;const i=c.getState().consumePendingDiagramFile();i&&d(i)},[d,f]);const h=s.useCallback(async()=>{const i=u.current?.getXml();t&&r?.writeFile&&i&&i!==l&&(await r.writeFile(t,i),o(i))},[t,r,l]),v=t?t.split("/").pop()||t:"";return t?p?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[e.jsx(a,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:v}),e.jsx("button",{type:"button",onClick:()=>{h()},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:n("filesView.diagram.saveDiagram"),children:e.jsx(a,{name:"save-3",className:"size-4"})}),e.jsx("button",{type:"button",onClick:()=>c.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:n("filesView.diagram.closeDiagramView"),children:e.jsx(a,{name:"close",className:"size-4"})})]}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(y,{ref:u,xml:l,className:"h-full"})})]}):e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("div",{className:"typography-ui text-muted-foreground",children:n("filesView.editor.pickFileFromTree")})})}export{S as DiagramView};
@@ -0,0 +1,11 @@
1
+ import{cf as Ke,cg as je,ch as de,ci as At,R as N,b as K,cj as Et,ck as kt,cl as vt,j as re}from"./vendor-.bun-BE757pvp.js";import{eP as Ct,eQ as St,eR as Lt,eS as Mt,eT as Ue,eU as Nt,eV as xt,y as pe,cW as Rt,cX as Tt,eW as _t,eX as Pt,d as Xe,e as Ze,eY as Ge,v as Ye,dA as It,A as Ce,c as Ft,eZ as $t,e_ as Ot,e$ as Dt,o as Wt,f0 as Se,f1 as qt,f2 as Bt,c8 as zt}from"./useAppFontEffects-DzBg8hrC.js";import{D as Ae,u as Y,t as Ht,v as Vt,h as Kt}from"./index-ltrmNGAf.js";const ee=t=>t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),jt=t=>/^\[[^\]]+\]:\s+\S+/m.test(t)||/^\[\^[^\]]+\]:\s+/m.test(t),Ut=t=>{const e=t.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(!e)return!1;const n=e[1];if(!n)return!1;const r=n[0],a=n.length,o=t.trimEnd().split(`
2
+ `).at(-1)?.trim()??"";return!new RegExp(`^[\\t ]{0,3}${r}{${a},}[\\t ]*$`).test(o)},te=t=>{try{return At(t,{linkMode:"text-only"})}catch{return t}},Xt=(t,e)=>{if(!e)return[{raw:t,src:t,mode:"full",highlight:!0}];if(jt(t))return[{raw:t,src:te(t),mode:"live",highlight:!0}];let n;try{n=Ke.lexer(t)}catch{return[{raw:t,src:te(t),mode:"live",highlight:!0}]}let r=-1;for(let o=n.length-1;o>=0;o-=1)if(n[o]?.type!=="space"){r=o;break}if(r<0)return[{raw:t,src:te(t),mode:"live",highlight:!0}];const a=[];for(let o=0;o<n.length;o+=1){const i=n[o];if(!i||i.type==="space")continue;const s=i.raw??"",c=o===r,l=i.type==="code"&&Ut(s);a.push({raw:s,src:l?s:te(s),mode:c?"live":"full",highlight:!l})}return a.length===0?[{raw:t,src:te(t),mode:"live",highlight:!0}]:a},Qe=(t,e,n)=>{try{return je.renderToString(t,{displayMode:n,throwOnError:!1})}catch{return e}},Zt={name:"inlineMath",level:"inline",start(t){const e=t.indexOf("\\(");return e<0?void 0:e},tokenizer(t){const e=/^\\\(([\s\S]+?)\\\)/.exec(t);if(e)return{type:"inlineMath",raw:e[0],text:e[1]??""}},renderer(t){const e=t;return Qe(e.text,e.raw,!1)}},Gt={name:"blockMath",level:"block",start(t){const e=t.indexOf("\\[");return e<0?void 0:e},tokenizer(t){const e=/^\\\[([\s\S]+?)\\\]/.exec(t);if(e)return{type:"blockMath",raw:e[0],text:e[1]??""}},renderer(t){const e=t;return Qe(e.text,e.raw,!0)}},Je=Ke.use({gfm:!0,breaks:!1,extensions:[Zt,Gt],renderer:{link({href:t,title:e,text:n}){const r=t??"",a=Ct(r);if(a)return`<a href="${ee(Lt(a))}" data-openchamber-agent-mention="true" class="text-primary hover:underline" target="_blank" rel="noopener noreferrer">${n}</a>`;const o=St(r);if(o)return`<a href="${ee(r)}" data-skill-name="${ee(o)}" class="text-primary hover:underline">${n}</a>`;const i=e?` title="${ee(e)}"`:"";return`<a href="${ee(r)}"${i} class="external-link" target="_blank" rel="noopener noreferrer">${n}</a>`}}}),Yt=t=>t.replace(/\$\$([\s\S]*?)\$\$/g,(e,n)=>{try{return je.renderToString(n,{displayMode:!0,throwOnError:!1})}catch{return`$$${n}$$`}}),et=t=>{if(t.indexOf("$")===-1)return t;const e=/(<(?:pre|code|kbd)[^>]*>[\s\S]*?<\/(?:pre|code|kbd)>)/gi;return t.split(e).map((n,r)=>r%2===1?n:Yt(n)).join("")},Qt=/<pre><code(?:\s+class="language-([^"]*)")?>([\s\S]*?)<\/code><\/pre>/g,Jt=1200,en=200,tn=(t,e)=>{let n=1;for(let r=0;r<t.length;r+=1)if(t.charCodeAt(r)===10&&++n>e)return!0;return!1},nn=t=>t.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&"),rn=async t=>{const e=[...t.matchAll(Qt)];if(e.length===0)return t;const n=Ae()?en:Jt;let r=t;for(const a of e){const[o,i,s]=a,c=(i||"text").toLowerCase();if(c==="mermaid")continue;const l=nn(s??"");if(tn(l,n)){r=r.replace(o,()=>o.replace("<pre",`<pre data-md-lang="${c}"`));continue}const d=await Mt(l,c);if(d){const u=d.replace(/^<pre/,`<pre data-md-lang="${c}"`);r=r.replace(o,()=>u)}}return r},on={USE_PROFILES:{html:!0,mathMl:!0,svg:!0},ADD_TAGS:["svg","path","g","rect","line","polygon","polyline","circle","ellipse","text","tspan","defs","marker"],ADD_ATTR:["d","viewBox","preserveAspectRatio","xmlns","target","fill","stroke","stroke-width","transform","points","x","y","x1","y1","x2","y2","cx","cy","r","rx","ry","style"],FORBID_TAGS:["script"],FORBID_CONTENTS:["script"]};let Le=!1;const an=()=>{Le||typeof window>"u"||!de.isSupported||(Le=!0,de.addHook("afterSanitizeAttributes",t=>{t instanceof HTMLAnchorElement&&t.target==="_blank"&&t.setAttribute("rel","noopener noreferrer")}))},tt=t=>de.isSupported?(an(),de.sanitize(t,on)):"",sn=240,G=new Map,cn=t=>{let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0).toString(36)},Me=(t,e)=>{if(G.delete(t),G.set(t,e),G.size<=sn)return;const n=G.keys().next().value;n&&G.delete(n)},ln=async t=>{const e=await Promise.resolve(Je.parse(t.src)),n=et(e),r=t.highlight?await rn(n):n;return tt(r)},dn=t=>{if(!t)return"";const e=Je.parse(t),n=et(e);return tt(n)},un=async(t,e,n)=>{if(!t)return[];const r=Xt(t,e);return Promise.all(r.map(async(a,o)=>{const i=cn(a.raw),s=`${i}:${a.mode}:${a.highlight?1:0}`,c=`${n}:${o}:${a.mode}`,l=G.get(c);if(l&&l.hash===i)return Me(c,l),{id:s,html:l.html};const d=await ln(a);return Me(c,{hash:i,html:d}),{id:s,html:d}}))},_=t=>Number.isFinite(t)&&t>0,Ne=t=>{if(typeof t=="number")return _(t)?t:null;if(typeof t!="string")return null;const e=t.trim().match(/^([+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?)(?:px)?$/);if(!e)return null;const n=Number(e[1]);return _(n)?n:null},he=(t,e,n)=>Math.min(n,Math.max(e,t)),mn=6,xe=1.25,fn=1.0015,pn=.5,hn=12,Re=3,gn=400,oe='[data-markdown="mermaid-block"]',B=t=>t.querySelector(oe)!==null,bn=t=>[t.x,t.y,t.width,t.height].map(e=>{const n=Number(e.toFixed(mn));return Object.is(n,-0)?"0":String(n)}).join(" "),wn=t=>{const e=t.viewBox?.trim().split(/[\s,]+/).map(a=>Number.parseFloat(a));if(e?.length===4){const[a,o,i,s]=e;if(Number.isFinite(a)&&Number.isFinite(o)&&_(i)&&_(s))return{x:a,y:o,width:i,height:s}}const n=Ne(t.width),r=Ne(t.height);return n===null||r===null?null:{x:0,y:0,width:n,height:r}},yn=t=>{let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0).toString(36)},An=t=>{const e=t.renderMode||"unknown",n=t.svgMarkup??"";if(!n){const r=[t.viewBox??"",t.width??"",t.height??""];return r.some(a=>a!=="")?`${e}:bounds:${r.join(":")}`:`${e}:no-svg`}return[e,yn(n)].join(":")},nt=(t,e)=>{if(!_(e.width)||!_(e.height))return t;const n=t.width/t.height,r=e.width/e.height;if(n>r){const o=t.width/r;return{x:t.x,y:t.y-(o-t.height)/2,width:t.width,height:o}}const a=t.height*r;return{x:t.x-(a-t.width)/2,y:t.y,width:a,height:t.height}},En=({currentBox:t,viewport:e,delta:n})=>!_(e.width)||!_(e.height)||!_(t.width)||!_(t.height)?t:{x:t.x-n.x/e.width*t.width,y:t.y-n.y/e.height*t.height,width:t.width,height:t.height},kn=(t,e)=>{const n=e.x-t.x,r=e.y-t.y;return n*n+r*r>Re*Re},vn=({currentBox:t,contentBox:e,viewport:n,pointer:r,zoomFactor:a,minScale:o,maxScale:i})=>{if(!_(n.width)||!_(n.height)||!_(a)||!_(t.width)||!_(t.height)||!_(e.width)||!_(e.height)||!_(o)||!_(i))return t;const s=Math.min(o,i),c=Math.max(o,i),l=nt(e,n),d=l.width/t.width,u=he(d*a,s,c),f=l.width/u,p=f/(t.width/t.height),g=he(r.x/n.width,0,1),k=he(r.y/n.height,0,1),v=t.x+g*t.width,A=t.y+k*t.height;return{x:v-g*f,y:A-k*p,width:f,height:p}},Ee=new WeakMap,Cn=t=>t instanceof HTMLElement?Ee.get(t)??null:null,Sn=t=>t.querySelector('[data-markdown="mermaid-viewport"]')??t.querySelector('[data-markdown="mermaid"]'),Te=t=>{const e=t.querySelector('[data-markdown="mermaid"] svg'),n=t.querySelector('[data-markdown="mermaid"]');return An({renderMode:t.getAttribute("data-mermaid-render"),svgMarkup:n?.getAttribute("data-md-original-svg")??e?.outerHTML??null,viewBox:e?.getAttribute("viewBox"),width:e?.getAttribute("width"),height:e?.getAttribute("height")})},ne=t=>{const e=t.getBoundingClientRect();return{width:e.width,height:e.height}},Ln=(t,e)=>{const n=e.getBoundingClientRect();return{x:t.clientX-n.left,y:t.clientY-n.top}},Mn=t=>t instanceof Element&&!!t.closest('button, a, [role="button"]'),Nn=t=>{const e=Sn(t),n=t.querySelector('[data-markdown="mermaid"] svg');if(!e||!n)return null;const r=wn({viewBox:n.getAttribute("viewBox"),width:n.getAttribute("width"),height:n.getAttribute("height")});if(!r)return null;let a=r,o=null,i=null,s=null,c=null;const l=m=>{a=m,n.setAttribute("viewBox",bn(m)),n.removeAttribute("width"),n.removeAttribute("height")},d=()=>{l(nt(r,ne(e)))},u=(m,L)=>{l(vn({currentBox:a,contentBox:r,viewport:ne(e),pointer:m,zoomFactor:L,minScale:pn,maxScale:hn}))},f=()=>{const m=ne(e);u({x:m.width/2,y:m.height/2},xe)},p=()=>{const m=ne(e);u({x:m.width/2,y:m.height/2},1/xe)},g=m=>{!m.ctrlKey&&!m.metaKey||(m.preventDefault(),m.stopPropagation(),u(Ln(m,e),Math.pow(fn,-m.deltaY)))},k=m=>{m.button!==0||Mn(m.target)||(o=m.pointerId,i={x:m.clientX,y:m.clientY},s=i,c!==null&&(window.clearTimeout(c),c=null),t.removeAttribute("data-mermaid-suppress-click"),e.setPointerCapture?.(m.pointerId),t.setAttribute("data-mermaid-panning","true"),m.preventDefault())},v=m=>{if(o!==m.pointerId||!s)return;const L={x:m.clientX,y:m.clientY};l(En({currentBox:a,viewport:ne(e),delta:{x:L.x-s.x,y:L.y-s.y}})),s=L,i&&kn(i,L)&&t.setAttribute("data-mermaid-suppress-click","true"),m.preventDefault()},A=m=>{o===m.pointerId&&(e.releasePointerCapture?.(m.pointerId),o=null,i=null,s=null,t.removeAttribute("data-mermaid-panning"),t.hasAttribute("data-mermaid-suppress-click")&&(c=window.setTimeout(()=>{t.removeAttribute("data-mermaid-suppress-click"),c=null},gn)))},S=()=>{d()};e.addEventListener("wheel",g,{passive:!1}),e.addEventListener("pointerdown",k),e.addEventListener("pointermove",v),e.addEventListener("pointerup",A),e.addEventListener("pointercancel",A),window.addEventListener("resize",S);const M=typeof ResizeObserver>"u"?null:new ResizeObserver(S);return M?.observe(e),d(),{zoomIn:f,zoomOut:p,fit:d,cleanup:()=>{e.removeEventListener("wheel",g),e.removeEventListener("pointerdown",k),e.removeEventListener("pointermove",v),e.removeEventListener("pointerup",A),e.removeEventListener("pointercancel",A),window.removeEventListener("resize",S),M?.disconnect(),c!==null&&window.clearTimeout(c),t.removeAttribute("data-mermaid-panning"),t.removeAttribute("data-mermaid-suppress-click"),Ee.delete(t)}}},xn=t=>{const e=new Map,n=new Map,r=()=>{for(const[o,i]of Array.from(e.entries())){const s=Te(o);(!t.contains(o)||s!==n.get(o))&&(i.cleanup(),e.delete(o),n.delete(o))}for(const o of Array.from(t.querySelectorAll(oe))){if(e.has(o)||o.querySelector('[data-markdown="mermaid"] svg')===null)continue;const i=Nn(o);i&&(e.set(o,i),n.set(o,Te(o)),Ee.set(o,i))}},a=()=>{for(const o of e.values())o.cleanup();e.clear(),n.clear()};return r(),{refresh:r,cleanup:a}},z=t=>`<svg class="remixicon size-3.5" viewBox="0 0 24 24" aria-hidden="true"><use href="#oc-${t}"></use></svg>`,ue={copy:z("file-copy"),check:z("check"),download:z("download"),zoomIn:z("add"),zoomOut:z("subtract"),fit:z("refresh"),textWrap:z("text-wrap")},rt="p-1 rounded hover:bg-interactive-hover/60 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--interactive-focus-ring)]",me=(t,e)=>{t.innerHTML=e},W=(t,e,n)=>{const r=document.createElement("button");return r.type="button",r.className=rt,r.setAttribute("data-md-action",n),r.setAttribute("title",e),r.setAttribute("aria-label",e),me(r,ue[t]),r},ot=(t,e,n)=>{const r=t.querySelector("[data-md-code-body]"),a=t.querySelector("pre"),o=t.querySelector("pre code"),i=t.querySelector('[data-md-action="toggle-code-wrap"]');if(t.setAttribute("data-code-wrap",e?"true":"false"),r?.classList.toggle("overflow-x-auto",!e),r?.classList.toggle("overflow-x-hidden",e),a?.classList.toggle("whitespace-pre-wrap",e),a?.classList.toggle("break-words",e),o?.classList.toggle("whitespace-pre-wrap",e),o?.classList.toggle("break-words",e),a&&(a.style.whiteSpace=e?"pre-wrap":"pre",a.style.overflowWrap=e?"anywhere":"normal"),o&&(o.style.whiteSpace=e?"pre-wrap":"pre",o.style.overflowWrap=e?"anywhere":"normal"),i){const s=e?n.disableCodeWrap:n.enableCodeWrap;i.setAttribute("title",s),i.setAttribute("aria-label",s),i.classList.toggle("text-foreground",e),i.classList.toggle("opacity-100",e),i.classList.toggle("text-muted-foreground",!e),i.classList.toggle("opacity-65",!e),i.setAttribute("aria-pressed",e?"true":"false")}},at=t=>{const e=document.createElement("div");e.setAttribute("data-md-code-line-numbers",""),e.setAttribute("aria-hidden","true"),e.className="min-w-8 shrink-0 select-none border-r border-border/50 pr-3 text-right font-mono text-[13px] text-muted-foreground/45";const n=t.textContent??"",r=Math.max(1,n.endsWith(`
3
+ `)?n.split(`
4
+ `).length-1:n.split(`
5
+ `).length);for(let a=1;a<=r;a+=1){const o=document.createElement("div");o.className="tabular-nums",o.textContent=String(a),e.appendChild(o)}return e},Rn=t=>{const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let r=n.nextNode();for(;r;)e.push(r),r=n.nextNode();return e},_e=(t,e)=>{let n=0;for(const a of t){const o=n+a.data.length;if(e<=o)return{node:a,offset:Math.max(0,e-n)};n=o}const r=t.at(-1);return r?{node:r,offset:r.data.length}:null},st=t=>{const e=t.querySelectorAll('[data-component="markdown-code"]');for(const n of Array.from(e)){const r=n.querySelector("pre code"),a=n.querySelector("[data-md-code-line-numbers]");if(!r||!a)continue;const o=Array.from(a.children),i=r.textContent??"",s=Rn(r),c=window.getComputedStyle(r),l=Number.parseFloat(c.lineHeight)||20;a.style.fontFamily=c.fontFamily,a.style.fontSize=c.fontSize,a.style.lineHeight=`${l}px`;let d=0;for(let u=0;u<o.length;u+=1){const f=i.indexOf(`
6
+ `,d),p=f===-1?i.length:f,g=o[u];if(!g)continue;const k=_e(s,d),v=_e(s,p);if(!k||!v||d===p)g.style.height=`${l}px`,g.style.lineHeight=`${l}px`;else{const A=document.createRange();A.setStart(k.node,k.offset),A.setEnd(v.node,v.offset);const S=[];for(const m of Array.from(A.getClientRects()))m.width===0&&m.height===0||S.some(L=>Math.abs(L-m.top)<2)||S.push(m.top);const M=Math.max(l,Math.max(1,S.length)*l);A.detach(),g.style.height=`${M}px`,g.style.lineHeight=`${l}px`}d=p+1}}},ke=t=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>st(t))})},Tn=(t,e,n)=>{const r=t.querySelectorAll('[data-component="markdown-code"]');for(const a of Array.from(r)){const o=a.querySelector("[data-md-code-body]"),i=a.querySelector("pre");o&&i&&!o.querySelector("[data-md-code-line-numbers]")&&(o.classList.add("flex","gap-3"),o.insertBefore(at(i),i)),ot(a,e,n)}ke(t)},Pe=(t,e,n,r)=>{me(t,ue.check),t.setAttribute("title",e),t.setAttribute("aria-label",e),window.setTimeout(()=>{me(t,ue[n]),t.setAttribute("title",r),t.setAttribute("aria-label",r)},2e3)},_n=t=>{const e=t.querySelectorAll(":not(pre) > code");for(const n of Array.from(e))n.getAttribute("data-markdown")!=="inline-code"&&n.setAttribute("data-markdown","inline-code")},Pn=(t,e)=>{const n=t.querySelectorAll("pre");for(const r of Array.from(n)){if(r.querySelector("code.language-mermaid"))continue;const a=r.parentElement;if(!a||a.closest('[data-component="markdown-code"]'))continue;const o=r.querySelector("code")?.className.match(/language-([\w+#.-]+)/)?.[1],i=r.getAttribute("data-md-lang")??o??"text",s=document.createElement("div");s.setAttribute("data-component","markdown-code"),s.className="my-4 group overflow-hidden rounded-2xl border border-border/80 bg-[var(--surface-elevated)]";const c=document.createElement("div");c.className="flex items-center justify-between border-b border-border/70 px-3 py-1.5";const l=document.createElement("span");l.className="font-mono text-[13px] text-muted-foreground",l.textContent=i;const d=W("copy",e.labels.copy,"copy-code"),u=W("textWrap",e.codeBlockLineWrap?e.labels.disableCodeWrap:e.labels.enableCodeWrap,"toggle-code-wrap");c.appendChild(l);const f=document.createElement("div");f.className="flex items-center gap-1",f.appendChild(u),f.appendChild(d),c.appendChild(f);const p=document.createElement("div");p.setAttribute("data-md-code-body",""),p.className=e.deferCodeLineNumberSync?"px-3 py-2.5 overflow-x-auto":"flex gap-3 px-3 py-2.5 overflow-x-auto",a.replaceChild(s,r),r.style.margin="0",r.style.background="transparent",r.classList.add("min-w-0","w-full","flex-1"),e.deferCodeLineNumberSync||p.appendChild(at(r)),p.appendChild(r),s.appendChild(c),s.appendChild(p),ot(s,e.codeBlockLineWrap,e.labels),e.deferCodeLineNumberSync||ke(s)}},Ie=t=>{const e=[],n=[],r=t.querySelectorAll("thead th");for(const o of Array.from(r))e.push((o.textContent??"").trim());const a=t.querySelectorAll("tbody tr");for(const o of Array.from(a)){const i=Array.from(o.querySelectorAll("td")).map(s=>(s.textContent??"").trim());i.length>0&&n.push(i)}return{headers:e,rows:n}},In=t=>/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t,Fe=({headers:t,rows:e})=>[t,...e].map(n=>n.map(In).join(",")).join(`
7
+ `),Fn=({headers:t,rows:e})=>[t,...e].map(n=>n.join(" ")).join(`
8
+ `),$e=({headers:t,rows:e})=>{const n=`| ${t.join(" | ")} |`,r=`| ${t.map(()=>"---").join(" | ")} |`,a=e.map(o=>`| ${o.join(" | ")} |`).join(`
9
+ `);return`${n}
10
+ ${r}
11
+ ${a}`},Oe=(t,e)=>{const n=document.createElement("div");n.className=`absolute top-full right-0 mt-1 hidden ${Rt}`,n.style.backgroundColor="var(--surface-elevated)",n.style.color="var(--surface-elevated-foreground)",n.setAttribute("data-md-menu",t);for(const r of e){const a=document.createElement("button");a.type="button",a.className=`w-full text-left ${Tt}`,a.setAttribute("data-md-action",`${t}-${r.key}`),a.textContent=r.label,n.appendChild(a)}return n},$n=(t,e)=>{const n=t.querySelectorAll("table");for(const r of Array.from(n)){if(r.closest('[data-markdown="table-wrapper"]'))continue;const o=document.createElement("div");o.className="group my-4 flex flex-col space-y-2",o.setAttribute("data-markdown","table-wrapper");const i=document.createElement("div");i.className="flex items-center justify-end gap-1";const s=document.createElement("div");s.className="relative",s.appendChild(W("copy",e.copyTable,"table-copy-toggle")),s.appendChild(Oe("table-copy",[{key:"csv",label:"CSV"},{key:"tsv",label:"TSV"},{key:"markdown",label:"Markdown"}]));const c=document.createElement("div");c.className="relative",c.appendChild(W("download",e.downloadTable,"table-download-toggle")),c.appendChild(Oe("table-download",[{key:"csv",label:"CSV"},{key:"markdown",label:"Markdown"}])),i.appendChild(s),i.appendChild(c);const l=document.createElement("div");l.className="overflow-x-auto rounded-lg border border-border/80 bg-[var(--surface-elevated)]";const d=r.parentElement;if(!d)continue;d.replaceChild(o,r),r.setAttribute("data-markdown","table"),r.classList.add("w-full","border-collapse","text-sm");for(const f of Array.from(r.querySelectorAll("tr")))f.classList.add("border-b","border-border/60");const u=r.querySelector("tbody tr:last-child");u?.classList.remove("border-b"),u?.classList.add("border-0");for(const f of Array.from(r.querySelectorAll("th")))f.classList.add("border-r","border-border/60","px-4","py-2.5","text-left","align-middle","font-semibold","text-foreground","last:border-r-0");for(const f of Array.from(r.querySelectorAll("td")))f.classList.add("border-r","border-border/60","px-4","py-2.5","align-middle","text-foreground/90","last:border-r-0");l.appendChild(r),o.appendChild(i),o.appendChild(l)}},On=(t,e)=>{const n=t.querySelectorAll("pre > code.language-mermaid");for(const r of Array.from(n)){const a=r.parentElement;if(!a)continue;const o=(r.textContent??"").replace(/\s+$/,""),i=e.renderMermaid(o),s=document.createElement("div");s.setAttribute("data-markdown","mermaid-block"),s.setAttribute("data-md-source",o),s.className="group relative";const c=document.createElement("div");c.setAttribute("data-markdown","mermaid-scroll");const l=document.createElement("div");if(l.setAttribute("data-markdown","mermaid-toolbar"),l.className="absolute top-1 right-2 flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity",i.svg){s.setAttribute("data-mermaid-render","svg");const u=document.createElement("div");u.setAttribute("data-markdown","mermaid-viewport");const f=document.createElement("div");if(f.setAttribute("data-markdown","mermaid"),f.setAttribute("data-md-original-svg",i.svg),f.innerHTML=i.svg,u.appendChild(f),c.appendChild(u),e.mermaidControls.showPanZoomControls&&(l.appendChild(W("zoomIn",e.labels.zoomInDiagram,"mermaid-zoom-in")),l.appendChild(W("zoomOut",e.labels.zoomOutDiagram,"mermaid-zoom-out")),l.appendChild(W("fit",e.labels.resetDiagramView,"mermaid-fit"))),e.mermaidControls.copy){const p=W("copy",e.labels.copyDiagram,"mermaid-copy");p.setAttribute("data-md-source",o),l.appendChild(p)}if(e.mermaidControls.download){const p=W("download",e.labels.downloadDiagram,"mermaid-download");p.setAttribute("data-md-svg","1"),l.appendChild(p)}}else{s.setAttribute("data-mermaid-render","ascii");const u=document.createElement("pre");if(u.setAttribute("data-markdown","mermaid-ascii"),u.textContent=i.ascii||o,c.appendChild(u),e.mermaidControls.copy){const f=W("copy",e.labels.copyDiagram,"mermaid-copy");f.setAttribute("data-md-source",i.ascii||o),l.appendChild(f)}}s.appendChild(c),s.appendChild(l);const d=a.parentElement;d&&d.replaceChild(s,a)}},Dn=(t,e)=>{const n=t.querySelectorAll("a[href]");for(const r of Array.from(n)){if(r.getAttribute("data-md-link-decorated")==="true"||r.getAttribute("data-openchamber-file-link")==="true")continue;const a=r.getAttribute("href")??"";if(!Ue(a))continue;r.setAttribute("data-md-link-decorated","true");const o=Nt(a);if(o){const i=document.createElement("span");i.className="mr-1 inline-flex size-[18px] items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)] align-middle";const s=document.createElement("img");s.src=o,s.alt="",s.setAttribute("aria-hidden","true"),s.loading="lazy",s.decoding="async",s.className="size-3.5 rounded-sm",s.addEventListener("error",()=>i.remove(),{once:!0}),i.appendChild(s),r.parentNode?.insertBefore(i,r)}if(e.onPreviewLoopback&&xt(a)){const i=document.createElement("button");i.type="button",i.className=`ml-1 align-middle ${rt}`,i.setAttribute("data-md-action","preview-loopback"),i.setAttribute("data-md-url",a),i.setAttribute("title",e.labels.previewTitle),i.setAttribute("aria-label",e.labels.previewLabel),me(i,ue.download),r.parentNode?.insertBefore(i,r.nextSibling)}}},De=(t,e)=>{_n(t),On(t,e),Pn(t,e),$n(t,e.labels),Dn(t,e)},We=(t,e,n)=>{const r=new Blob([e],{type:n}),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a)},ie=t=>{for(const e of Array.from(t.querySelectorAll("[data-md-menu]")))e.classList.add("hidden")},Wn=(t,e)=>{const n=r=>{const a=r.target;if(!(a instanceof Element))return;const o=a.closest("[data-md-action]");if(!o){ie(t);return}const i=o.getAttribute("data-md-action")??"";if(i==="copy-code"){const c=o.closest('[data-component="markdown-code"]')?.querySelector("code")?.textContent??"";c&&pe(c).then(()=>Pe(o,e.labels.copied,"copy",e.labels.copy));return}if(i==="toggle-code-wrap"){r.preventDefault(),e.onToggleCodeBlockLineWrap?.();return}if(i==="table-copy-toggle"||i==="table-download-toggle"){r.preventDefault();const s=o.parentElement?.querySelector("[data-md-menu]")??null,c=s?.classList.contains("hidden")??!1;ie(t),s&&c&&s.classList.remove("hidden");return}if(i.startsWith("table-copy-")){const s=i.replace("table-copy-",""),c=o.closest('[data-markdown="table-wrapper"]')?.querySelector("table");if(c instanceof HTMLTableElement){const l=Ie(c),d=s==="csv"?Fe(l):s==="tsv"?Fn(l):$e(l);pe(d)}ie(t);return}if(i.startsWith("table-download-")){const s=i.replace("table-download-",""),c=o.closest('[data-markdown="table-wrapper"]')?.querySelector("table");if(c instanceof HTMLTableElement){const l=Ie(c),d=s==="csv"?Fe(l):$e(l);We(s==="csv"?"table.csv":"table.md",d,s==="csv"?"text/csv":"text/markdown")}ie(t);return}if(i==="mermaid-copy"){const s=o.getAttribute("data-md-source")??"";s&&pe(s).then(()=>Pe(o,e.labels.copied,"copy",e.labels.copyDiagram));return}if(i==="mermaid-zoom-in"||i==="mermaid-zoom-out"||i==="mermaid-fit"){r.preventDefault();const s=o.closest('[data-markdown="mermaid-block"]'),c=Cn(s);i==="mermaid-zoom-in"?c?.zoomIn():i==="mermaid-zoom-out"?c?.zoomOut():c?.fit();return}if(i==="mermaid-download"){const s=o.closest('[data-markdown="mermaid-block"]')?.querySelector('[data-markdown="mermaid"]'),c=s?.getAttribute("data-md-original-svg")??s?.innerHTML??"";c&&We("diagram.svg",c,"image/svg+xml;charset=utf-8");return}if(i==="preview-loopback"){r.preventDefault();const s=o.getAttribute("data-md-url")??"";s&&e.onPreviewLoopback?.(s);return}};return t.addEventListener("click",n),()=>t.removeEventListener("click",n)},qn=new Set(["dockerfile","makefile","readme","license",".env",".gitignore",".npmrc"]),qe=Array.from(qn).map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),Bn=t=>Pt(t),zn=t=>_t(t),fe=t=>{let e=(t||"").trim();return e?((e.startsWith("`")&&e.endsWith("`")||e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e=e.replace(/[.,;!?]+$/g,""),e.endsWith(")")&&!e.includes("(")&&(e=e.slice(0,-1)),e.endsWith("]")&&!e.includes("[")&&(e=e.slice(0,-1)),e):""},ce=t=>{let e=fe(t);if(!e)return"";const n=e.indexOf(";");n>=0&&(e=e.slice(0,n)),e=e.replace(/#.*$/,"");const r=e.match(/^(.*\.[A-Za-z0-9_-]{1,16}):.*$/);r&&(e=r[1]??e);const a=qe.length>0?e.match(new RegExp(`^(.*(?:/|^)(${qe})):.*$`,"i")):null;return a&&(e=a[1]??e),fe(e)},it=t=>{const e=fe(t);if(!e)return null;const n=e.indexOf(";"),r=n>=0?fe(e.slice(0,n)):e;if(!r)return null;const a=r.match(/^(.*?):(\d+)-(\d+)$/);if(a){const c=ce(a[1]??""),l=Number.parseInt(a[2]??"",10),d=Number.parseInt(a[3]??"",10);return!c||!Number.isFinite(l)||!Number.isFinite(d)||d<l?null:{path:c,line:l,endLine:d}}const o=r.match(/^(.*)#L(\d+)(?:C(\d+))?$/i);if(o){const c=ce(o[1]??""),l=Number.parseInt(o[2]??"",10),d=o[3]?Number.parseInt(o[3],10):void 0;return!c||!Number.isFinite(l)?null:{path:c,line:l,column:Number.isFinite(d??Number.NaN)?d:void 0}}const i=r.match(/^(.*?):(\d+)(?::(\d+))?$/);if(i){const c=ce(i[1]??""),l=Number.parseInt(i[2]??"",10),d=i[3]?Number.parseInt(i[3],10):void 0;return!c||!Number.isFinite(l)?null:{path:c,line:l,column:Number.isFinite(d??Number.NaN)?d:void 0}}const s=ce(r);return s?{path:s}:null},ge=/(?:[A-Za-z]:[\\/])?[\w.\-/@+]*[\w\-/@+]\.[A-Za-z0-9]{1,8}(?::\d+(?:-\d+)?(?::\d+)?)?/g,ct=()=>{const t=K.c(4),e=It();let n;t[0]===Symbol.for("react.memo_cache_sentinel")?(n=Ce(!1),t[0]=n):n=t[0];const r=n;let a;t[1]===Symbol.for("react.memo_cache_sentinel")?(a=Ce(!0),t[1]=a):a=t[1];const o=a;let i;return t[2]!==e?.currentTheme?(i=e?.currentTheme??(typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?o:r),t[2]=e?.currentTheme,t[3]=i):i=t[3],i},lt=t=>{const e=K.c(4),{containerRef:n,enabled:r}=t;let a,o;e[0]!==n||e[1]!==r?(a=()=>{if(r===!1)return;const i=n.current;if(!i)return;const s=br;return i.addEventListener("click",s),()=>{i.removeEventListener("click",s)}},o=[n,r],e[0]=n,e[1]=r,e[2]=a,e[3]=o):(a=e[2],o=e[3]),N.useEffect(a,o)},J={download:!0,copy:!0,showPanZoomControls:!0},dt=!0,Hn=t=>{const e=t.match(/^(?:\uFEFF)?(---|\+\+\+)[^\S\r\n]*\r?\n[\s\S]*?\r?\n\1[^\S\r\n]*(?:\r?\n|$)/);return e?t.slice(e[0].length):t},Be='[data-openchamber-file-link="true"]',ut="data-openchamber-block-path-token",mt=`[${ut}]`,Q="data-openchamber-block-paths-scanned",Vn=2e5,Kn=4,jn=1e3,Un=200,Xn=80,Zn=40,ze=160,H=new Map;let le=0;const He=[],Gn=()=>Ae()?Un:jn,Yn=()=>Ae()?Zn:Xn,Qn=new Set(["dockerfile","makefile","readme","license",".env",".gitignore",".npmrc"]),ve=t=>Bn(t),Jn=t=>zn(t),er=(t,e)=>zt(t,e),tr=t=>{const e=t.split("/").filter(Boolean).pop()??"";return!e||e.endsWith(".")?!1:/\.[A-Za-z0-9_-]{1,16}$/.test(e)},ft=t=>{if(!t||t.startsWith("--")||t.includes("://")||/[<>]/.test(t)||/\s{2,}/.test(t))return!1;const e=ve(t),n=e.split("/").filter(Boolean).pop()??e;if(!n||n==="."||n==="..")return!1;const r=n.toLowerCase();return Qn.has(r)||r.startsWith(".")&&r.length>1?!0:tr(e)},pt=t=>{const e=it(t);return e?ft(e.path):!1},Ve=(t,e)=>{let n=0;for(const a of t){const o=n+a.data.length;if(e<=o)return{node:a,offset:Math.max(0,e-n)};n=o}const r=t.at(-1);return r?{node:r,offset:r.data.length}:null},nr=t=>{const e=t.querySelectorAll(mt);for(const r of Array.from(e))r.replaceWith(t.ownerDocument.createTextNode(r.textContent??""));const n=t.querySelectorAll(`code[${Q}]`);for(const r of Array.from(n))r.removeAttribute(Q),r.normalize()},be=t=>{if(t.tagName.toLowerCase()==="a"){const e=t.getAttribute("href")?.trim();if(e&&pt(e))return e}return(t.textContent||"").trim()},rr=t=>{const e=t.querySelectorAll("pre code");if(e.length===0)return;const n=t.ownerDocument;if(n)for(const r of Array.from(e)){if(r.getAttribute(Q)==="true")continue;if((r.textContent??"").length>Vn){r.setAttribute(Q,"true");continue}const a=n.createTreeWalker(r,NodeFilter.SHOW_TEXT),o=[];let i=a.nextNode();for(;i;)o.push(i),i=a.nextNode();const s=r.textContent??"";if(!s.includes(".")){r.setAttribute(Q,"true");continue}ge.lastIndex=0;const c=[];let l=ge.exec(s);for(;l;){const d=l[0];d&&pt(d)&&c.push({start:l.index,end:l.index+d.length,raw:d}),l=ge.exec(s)}for(const{start:d,end:u,raw:f}of c.reverse()){const p=Ve(o,d),g=Ve(o,u);if(!p||!g)continue;const k=n.createRange();k.setStart(p.node,p.offset),k.setEnd(g.node,g.offset);const v=n.createElement("span");v.setAttribute(ut,"true"),v.textContent=f,k.deleteContents(),k.insertNode(v)}r.setAttribute(Q,"true")}},we=(t,e)=>{const n=it(t);if(!n||!ft(n.path))return null;const r=Jn(n.path)?ve(n.path):er(e,n.path);return r?{...n,resolvedPath:r}:null},or=t=>{const e=ve(t);if(!e)return Promise.resolve(!1);const n=H.get(e);if(n)return H.delete(e),H.set(e,n),n;const r=new Promise(o=>{const i=()=>{le+=1,Kt(`/api/fs/stat?path=${encodeURIComponent(e)}&optional=true`,{method:"GET",cache:"no-store"}).then(async s=>{if(!s.ok){o(!1);return}const c=await s.json().catch(()=>null);o(c?.exists!==!1)}).catch(()=>o(!1)).finally(()=>{le=Math.max(0,le-1),He.shift()?.()})};if(le<Kn){i();return}He.push(i)}),a=Gn();for(;H.size>=a;){const o=H.keys().next().value;if(typeof o!="string")break;H.delete(o)}return H.set(e,r),r},ar=(t,e)=>t||Bt(t,e),ht=t=>{const e=K.c(7),{containerRef:n,effectiveDirectory:r,editor:a,preferRuntimeEditor:o,enabled:i}=t,s=N.useRef(null);let c,l;e[0]!==n||e[1]!==a||e[2]!==r||e[3]!==i||e[4]!==o?(c=()=>{const d=n.current;if(!d)return;let u=!1;const f=Yn(),p=i&&!Ot(),g=wr,k=()=>{const y=d.querySelectorAll(Be);for(const w of Array.from(y))g(w);nr(d)};if(!p){k();return}const v=y=>{const w=y;if(s.current!==null&&typeof window<"u"&&window.clearTimeout(s.current),typeof window>"u"){A();return}s.current=window.setTimeout(()=>{s.current=null,window.requestAnimationFrame(()=>{u||A()})},w)},A=()=>{p&&rr(d);const y=d.querySelectorAll(`[data-markdown="inline-code"], a, ${mt}`);let w=0;for(const h of Array.from(y)){const P=be(h),b=we(P,r);if(g(h),!b||w>=f)continue;w=w+1,(Ht()&&Vt()&&!Se(b.resolvedPath,r)?Promise.resolve(!0):or(b.resolvedPath)).then(R=>{if(u||!R||!d.contains(h))return;const F=be(h),$=we(F,r);!$||$.resolvedPath!==b.resolvedPath||(h.setAttribute("data-openchamber-file-link","true"),h.setAttribute("data-openchamber-file-ref",F),h.setAttribute("data-openchamber-file-path",$.resolvedPath),h.setAttribute("title","Open file"),h.tagName.toLowerCase()!=="a"&&(h.setAttribute("role","button"),h.setAttribute("tabindex","0")))})}},S=async y=>{const w=y.getAttribute("data-openchamber-file-ref")||be(y),h=we(w,r);if(!h)return;const P=ar(r,h.resolvedPath);if(o&&a){a.openFile(h.resolvedPath,Number.isFinite(h.line??Number.NaN)?Math.max(1,Math.trunc(h.line)):void 0,Number.isFinite(h.column??Number.NaN)?Math.max(1,Math.trunc(h.column)):void 0);return}Se(h.resolvedPath,r)||await qt(h.resolvedPath,r);const b=Y.getState();Number.isFinite(h.line??Number.NaN)?b.openContextFileAtLine(P,h.resolvedPath,Math.max(1,Math.trunc(h.line)),Number.isFinite(h.column??Number.NaN)?Math.max(1,Math.trunc(h.column)):1):b.openContextFile(P,h.resolvedPath)},M=y=>{const w=y.target;if(!(w instanceof Element))return;const h=w.closest(Be);h instanceof HTMLElement&&(y.preventDefault(),y.stopPropagation(),S(h))},m=y=>{if(y.key!=="Enter"&&y.key!==" ")return;const w=y.target;!(w instanceof HTMLElement)||w.getAttribute("data-openchamber-file-link")!=="true"||(y.preventDefault(),y.stopPropagation(),S(w))};v(ze);const L=new MutationObserver(()=>{v(ze)});return L.observe(d,{childList:!0,subtree:!0}),d.addEventListener("click",M),d.addEventListener("keydown",m),()=>{u=!0,s.current!==null&&typeof window<"u"&&window.clearTimeout(s.current),s.current=null,L.disconnect(),d.removeEventListener("click",M),d.removeEventListener("keydown",m)}},l=[n,a,r,o,i],e[0]=n,e[1]=a,e[2]=r,e[3]=i,e[4]=o,e[5]=c,e[6]=l):(c=e[5],l=e[6]),N.useEffect(c,l)},gt=t=>{const e=K.c(7),{containerRef:n,onShowPopup:r,enableFullscreen:a,enablePanZoom:o,allowMermaidWheelEvents:i}=t;let s,c;e[0]!==i||e[1]!==n||e[2]!==a||e[3]!==o||e[4]!==r?(s=()=>{const l=n.current;if(!l)return;const d=f=>{if(!a||!r)return;const p=f.target;if(!(p instanceof Element)||p.closest('button, a, [role="button"]'))return;const g=p.closest(oe);if(!g)return;if(g instanceof HTMLElement&&g.hasAttribute("data-mermaid-suppress-click")){g.removeAttribute("data-mermaid-suppress-click");return}const v=Array.from(l.querySelectorAll(oe)).indexOf(g);if(v<0)return;const A=g instanceof HTMLElement?g.getAttribute("data-md-source"):null;if(!A||A.trim().length===0)return;const S=`Diagram ${v+1}`;r({open:!0,title:S,content:"",metadata:{tool:"mermaid-preview",filename:S},mermaid:{url:`data:text/plain;charset=utf-8,${encodeURIComponent(A)}`,source:A,filename:S}})},u=f=>{if(i||(f.ctrlKey||f.metaKey)&&o)return;const p=f.target;!(p instanceof Element)||!p.closest(oe)||f.stopPropagation()};return l.addEventListener("click",d),l.addEventListener("wheel",u,{capture:!0,passive:!0}),()=>{l.removeEventListener("click",d),l.removeEventListener("wheel",u,!0)}},c=[i,n,a,o,r],e[0]=i,e[1]=n,e[2]=a,e[3]=o,e[4]=r,e[5]=s,e[6]=c):(s=e[5],c=e[6]),N.useEffect(s,c)},ye=64,sr=24,ir=ye/sr,cr=/[\s.,!?;:)\]]/,lr=t=>{const e=t<=12?2:t<=48?4:t<=96?8:Math.min(24,Math.ceil(t/8));return Math.max(1,Math.round(e*ir))},dr=(t,e)=>{const n=Math.min(t.length,e+lr(t.length-e));for(let r=n;r<Math.min(t.length,n+8);r+=1)if(cr.test(t[r]??""))return r+1;return n},ur=(t,e)=>{const[n,r]=N.useState(()=>e?0:t.length),a=N.useRef(n);return a.current=n,N.useEffect(()=>{if(!e||typeof window>"u"){r(t.length);return}a.current>t.length&&r(t.length);let o=null;const i=()=>{const s=Math.min(a.current,t.length);if(s>=t.length){o=null;return}r(dr(t,s)),o=window.setTimeout(i,ye)};return a.current<t.length&&(o=window.setTimeout(i,ye)),()=>{o!==null&&window.clearTimeout(o)}},[t,e]),e?t.slice(0,Math.min(n,t.length)):t},V=new Map,mr=100,fr=(t,e)=>{const n=V.get(t);if(n)return V.delete(t),V.set(t,n),n;const r=e();if(V.set(t,r),V.size>mr){const a=V.keys().next().value;a&&V.delete(a)}return r},pr=t=>({bg:t.colors.surface.elevated,fg:t.colors.surface.foreground,line:t.colors.interactive.border,accent:t.colors.primary.base,muted:t.colors.surface.mutedForeground,surface:t.colors.surface.muted,border:t.colors.interactive.border,transparent:!0,font:"system-ui, sans-serif"}),bt=(t,e,n,r=J)=>{const{t:a}=Ft(),o=N.useMemo(()=>({copy:a("markdownRenderer.code.actions.copyTitle"),copied:a("markdownRenderer.code.actions.copiedTitle"),enableCodeWrap:a("markdownRenderer.code.actions.enableWrapTitle"),disableCodeWrap:a("markdownRenderer.code.actions.disableWrapTitle"),copyTable:a("markdownRenderer.table.actions.copyTitle"),downloadTable:a("markdownRenderer.table.actions.downloadTitle"),copyDiagram:a("markdownRenderer.mermaid.actions.copySourceTitle"),downloadDiagram:a("markdownRenderer.mermaid.actions.downloadSvgTitle"),zoomInDiagram:a("markdownRenderer.mermaid.actions.zoomInTitle"),zoomOutDiagram:a("markdownRenderer.mermaid.actions.zoomOutTitle"),resetDiagramView:a("markdownRenderer.mermaid.actions.resetViewTitle"),previewLabel:a("terminalView.preview.open"),previewTitle:a("terminalView.preview.openTitle")}),[a]),i=Y(l=>l.codeBlockLineWrap),s=Y(l=>l.setCodeBlockLineWrap),c=N.useCallback(()=>{s(!Y.getState().codeBlockLineWrap)},[s]);return N.useMemo(()=>{const l=pr(t),d=Y.getState().mermaidRenderingMode,u=t.metadata?.id??"theme";return{labels:o,mermaidControls:r,codeBlockLineWrap:i,deferCodeLineNumberSync:e,onToggleCodeBlockLineWrap:c,renderMermaid:p=>fr(`${u}:${d}:${p}`,()=>{try{return d==="ascii"?{ascii:Et(p)}:{svg:kt(p,l)}}catch{return{}}}),onPreviewLoopback:n}},[t,o,r,i,e,c,n])},wt=t=>{const e=K.c(36),{containerRef:n,text:r,streaming:a,cacheKey:o,syntaxVars:i,ctx:s}=t;let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=[],e[0]=c):c=e[0],N.useEffect(yr,c);const l=N.useRef(null);let d;e[1]!==n?(d=()=>{const b=n.current;if(b){if(!l.current){if(!B(b))return;l.current=xn(b);return}l.current.refresh()}},e[1]=n,e[2]=d):d=e[2];const u=d;let f,p;e[3]!==n||e[4]!==s||e[5]!==u||e[6]!==r?(f=()=>{const b=n.current,E=b?.querySelector("[data-markdown-content]")??b;if(E&&r&&E.childNodes.length===0){const C=document.createElement("div");C.setAttribute("data-md-block",""),C.style.display="contents",C.innerHTML=dn(r),De(C,s),E.appendChild(C),B(C)&&u()}},p=[n,r,s,u],e[3]=n,e[4]=s,e[5]=u,e[6]=r,e[7]=f,e[8]=p):(f=e[7],p=e[8]),N.useLayoutEffect(f,p);let g,k;e[9]===Symbol.for("react.memo_cache_sentinel")?(g=()=>()=>{l.current?.cleanup(),l.current=null},k=[],e[9]=g,e[10]=k):(g=e[9],k=e[10]),N.useEffect(g,k);let v,A;e[11]!==o||e[12]!==n||e[13]!==s||e[14]!==u||e[15]!==a||e[16]!==r?(v=()=>{const b=n.current;if(!b)return;const E=b.querySelector("[data-markdown-content]")??b;let C=!0;return un(r,a,o).then(R=>{if(!C)return;const F=Array.from(E.children);R.forEach((x,I)=>{let T=F[I];if(T||(T=document.createElement("div"),T.setAttribute("data-md-block",""),T.style.display="contents",E.appendChild(T)),T.getAttribute("data-md-id")===x.id)return;const D=document.createElement("div");D.innerHTML=x.html,De(D,s);const j=B(T),q=B(D);vt(T,D,{childrenOnly:!0,onBeforeElUpdated:Ar}),T.setAttribute("data-md-id",x.id),(j||q||B(T))&&u()});const $=B(E);let O=!1;for(let x=F.length-1;x>=R.length;x=x-1,x){const I=F[x];I&&B(I)&&(O=!0),I?.remove()}(O||F.length>R.length&&$)&&u(),s.deferCodeLineNumberSync||ke(E)}),()=>{C=!1}},A=[n,r,a,o,s,u],e[11]=o,e[12]=n,e[13]=s,e[14]=u,e[15]=a,e[16]=r,e[17]=v,e[18]=A):(v=e[17],A=e[18]),N.useEffect(v,A);let S,M;e[19]!==n||e[20]!==s?(M=()=>{const b=n.current;if(b)return Wn(b,s)},S=[n,s],e[19]=n,e[20]=s,e[21]=S,e[22]=M):(S=e[21],M=e[22]),N.useEffect(M,S);let m,L;e[23]!==n||e[24]!==i?(m=()=>{const b=n.current,E=b?.querySelector("[data-markdown-content]")??b;if(E)for(const[C,R]of Object.entries(i))E.style.setProperty(C,R)},L=[n,i],e[23]=n,e[24]=i,e[25]=m,e[26]=L):(m=e[25],L=e[26]),N.useEffect(m,L);let y,w;e[27]!==n||e[28]!==s.codeBlockLineWrap||e[29]!==s.deferCodeLineNumberSync||e[30]!==s.labels?(y=()=>{const b=n.current,E=b?.querySelector("[data-markdown-content]")??b;E&&(s.deferCodeLineNumberSync||Tn(E,s.codeBlockLineWrap,s.labels))},w=[n,s.codeBlockLineWrap,s.deferCodeLineNumberSync,s.labels],e[27]=n,e[28]=s.codeBlockLineWrap,e[29]=s.deferCodeLineNumberSync,e[30]=s.labels,e[31]=y,e[32]=w):(y=e[31],w=e[32]),N.useEffect(y,w);let h,P;e[33]!==n?(h=()=>{const b=n.current,E=b?.querySelector("[data-markdown-content]")??b;if(!E||typeof ResizeObserver>"u")return;let C=null;const R=new ResizeObserver(()=>{C!==null&&window.cancelAnimationFrame(C),C=window.requestAnimationFrame(()=>{C=null,st(E)})});return R.observe(E),()=>{R.disconnect(),C!==null&&window.cancelAnimationFrame(C)}},P=[n],e[33]=n,e[34]=h,e[35]=P):(h=e[34],P=e[35]),N.useEffect(h,P)},yt=t=>t==="tool"?"markdown-content markdown-tool":t==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",hr=t=>{const e=K.c(32),{content:n,part:r,messageId:a,isAnimated:o,skipFadeIn:i,className:s,isStreaming:c,disableStreamAnimation:l,variant:d,onShowPopup:u,enableFileReferences:f}=t,p=o===void 0?!0:o,g=i===void 0?!1:i,k=c===void 0?!1:c,v=l===void 0?!1:l,A=d===void 0?"assistant":d,S=f===void 0?!0:f,M=ct(),{editor:m,runtime:L}=Xe(),y=N.useRef(null),w=Ze()??"",h=Y(Er);let P;e[0]!==w||e[1]!==h?(P=Z=>{w&&h(w,Z)},e[0]=w,e[1]=h,e[2]=P):P=e[2];const b=P,E=k&&!v,C=ur(n,E);let R;e[3]!==u?(R={containerRef:y,onShowPopup:u,enableFullscreen:dt,enablePanZoom:J.showPanZoomControls},e[3]=u,e[4]=R):R=e[4],gt(R);const F=S&&!k;let $;e[5]!==m||e[6]!==w||e[7]!==L.isVSCode||e[8]!==F?($={containerRef:y,effectiveDirectory:w,editor:m,preferRuntimeEditor:L.isVSCode,enabled:F},e[5]=m,e[6]=w,e[7]=L.isVSCode,e[8]=F,e[9]=$):$=e[9],ht($);let O;e[10]===Symbol.for("react.memo_cache_sentinel")?(O={containerRef:y},e[10]=O):O=e[10],lt(O);let x;e[11]!==M?(x=Ge(M),e[11]=M,e[12]=x):x=e[12];const I=x,T=bt(M,E,w?b:void 0,J),D=`markdown-${r?.id?`part-${r.id}`:`message-${a}`}`;let j;e[13]!==D||e[14]!==T||e[15]!==E||e[16]!==C||e[17]!==I?(j={containerRef:y,text:C,streaming:E,cacheKey:D,syntaxVars:I,ctx:T},e[13]=D,e[14]=T,e[15]=E,e[16]=C,e[17]=I,e[18]=j):j=e[18],wt(j);let q;e[19]!==s?(q=Ye("break-words w-full min-w-0",s),e[19]=s,e[20]=q):q=e[20];let U;e[21]!==A?(U=yt(A),e[21]=A,e[22]=U):U=e[22];let X;e[23]!==U?(X=re.jsx("div",{className:U,"data-markdown-content":!0}),e[23]=U,e[24]=X):X=e[24];let ae;e[25]!==q||e[26]!==X?(ae=re.jsx("div",{className:q,ref:y,children:X}),e[25]=q,e[26]=X,e[27]=ae):ae=e[27];const se=ae;if(p){let Z;return e[28]!==D||e[29]!==se||e[30]!==g?(Z=re.jsx(Dt,{skipAnimation:g,children:se},D),e[28]=D,e[29]=se,e[30]=g,e[31]=Z):Z=e[31],Z}return se},Sr=N.memo(hr,(t,e)=>t.content===e.content&&t.isStreaming===e.isStreaming&&t.disableStreamAnimation===e.disableStreamAnimation&&t.variant===e.variant&&t.isAnimated===e.isAnimated&&t.skipFadeIn===e.skipFadeIn&&t.className===e.className&&t.messageId===e.messageId&&t.onShowPopup===e.onShowPopup&&t.enableFileReferences===e.enableFileReferences&&t.part?.id===e.part?.id),gr=t=>{const e=K.c(30),{content:n,className:r,variant:a,disableLinkSafety:o,stripFrontmatter:i,onShowPopup:s,mermaidControls:c,allowMermaidWheelEvents:l,enableFileReferences:d}=t,u=a===void 0?"assistant":a,f=i===void 0?!1:i,p=c===void 0?J:c,g=l===void 0?!1:l,k=d===void 0?!0:d,{editor:v,runtime:A}=Xe(),S=ct(),M=N.useRef(null),m=Ze()??"";let L;e[0]!==n||e[1]!==f?(L=f?Hn(n):n,e[0]=n,e[1]=f,e[2]=L):L=e[2];const y=L;let w;e[3]!==g||e[4]!==p.showPanZoomControls||e[5]!==s?(w={containerRef:M,onShowPopup:s,enableFullscreen:dt,enablePanZoom:p.showPanZoomControls,allowMermaidWheelEvents:g},e[3]=g,e[4]=p.showPanZoomControls,e[5]=s,e[6]=w):w=e[6],gt(w);let h;e[7]!==v||e[8]!==m||e[9]!==k||e[10]!==A.isVSCode?(h={containerRef:M,effectiveDirectory:m,editor:v,preferRuntimeEditor:A.isVSCode,enabled:k},e[7]=v,e[8]=m,e[9]=k,e[10]=A.isVSCode,e[11]=h):h=e[11],ht(h);const P=!o;let b;e[12]!==P?(b={containerRef:M,enabled:P},e[12]=P,e[13]=b):b=e[13],lt(b);let E;e[14]!==S?(E=Ge(S),e[14]=S,e[15]=E):E=e[15];const C=E,R=bt(S,!1,void 0,p),F=`simple:${u}`;let $;e[16]!==R||e[17]!==y||e[18]!==C||e[19]!==F?($={containerRef:M,text:y,streaming:!1,cacheKey:F,syntaxVars:C,ctx:R},e[16]=R,e[17]=y,e[18]=C,e[19]=F,e[20]=$):$=e[20],wt($);let O;e[21]!==r?(O=Ye("break-words w-full min-w-0",r),e[21]=r,e[22]=O):O=e[22];let x;e[23]!==u?(x=yt(u),e[23]=u,e[24]=x):x=e[24];let I;e[25]!==x?(I=re.jsx("div",{className:x,"data-markdown-content":!0}),e[25]=x,e[26]=I):I=e[26];let T;return e[27]!==O||e[28]!==I?(T=re.jsx("div",{className:O,ref:M,children:I}),e[27]=O,e[28]=I,e[29]=T):T=e[29],T},Lr=N.memo(gr,(t,e)=>{const n=t.mermaidControls??J,r=e.mermaidControls??J;return t.content===e.content&&t.variant===e.variant&&t.className===e.className&&t.disableLinkSafety===e.disableLinkSafety&&t.stripFrontmatter===e.stripFrontmatter&&t.onShowPopup===e.onShowPopup&&n.download===r.download&&n.copy===r.copy&&n.showPanZoomControls===r.showPanZoomControls&&t.allowMermaidWheelEvents===e.allowMermaidWheelEvents&&t.enableFileReferences===e.enableFileReferences});function br(t){if(t.defaultPrevented||t.button!==0||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)return;const e=t.target;if(!(e instanceof Element))return;const n=e.closest("a[href]");if(!(n instanceof HTMLAnchorElement)||n.getAttribute("data-openchamber-file-link")==="true")return;const r=n.getAttribute("href")??"";Ue(r)&&(t.preventDefault(),t.stopPropagation(),Wt(r))}function wr(t){t.removeAttribute("data-openchamber-file-link"),t.removeAttribute("data-openchamber-file-ref"),t.removeAttribute("data-openchamber-file-path"),t.getAttribute("title")==="Open file"&&t.removeAttribute("title"),t.tagName.toLowerCase()!=="a"&&(t.removeAttribute("role"),t.removeAttribute("tabindex"))}function yr(){$t()}function Ar(t,e){return!t.isEqualNode(e)}function Er(t){return t.openContextPreview}export{Sr as MarkdownRenderer,Lr as SimpleMarkdownRenderer};
@@ -1 +1 @@
1
- import{b as N,R as _,j as n,bk as D,bi as C,bj as I,bg as M,be as S}from"./vendor-.bun-C6iL44L9.js";import{c as z,p as w,I as O}from"./useAppFontEffects-BUUJYbAZ.js";import{M as P}from"./main-BDoqLlQB.js";import"./index-ZJTzZ0_U.js";import"./runtimeEndpointReset-By39StyB.js";import"./mobileLayoutPreference-Dio-WWkI.js";import"./SessionSwitcherDropdown-4FWg9xMC.js";const G=R=>{const e=N.c(33),{open:y,onOpenChange:t,initialPrompt:j}=R,i=_.useId(),{t:o}=z(),k=B;let s;e[0]!==t?(s=v=>{!v&&k()||t(v)},e[0]=t,e[1]=s):s=e[1];let b;e[2]===Symbol.for("react.memo_cache_sentinel")?(b=n.jsx(D,{className:w("fixed inset-0 z-50 bg-black/50 dark:bg-black/75","transition-opacity duration-150 ease-out","data-[starting-style]:opacity-0 data-[ending-style]:opacity-0")}),e[2]=b):b=e[2];let g;e[3]===Symbol.for("react.memo_cache_sentinel")?(g=w("relative pointer-events-auto","w-[90vw] max-w-[720px] h-[680px] max-h-[85vh]","flex flex-col rounded-xl border shadow-none overflow-hidden origin-center","bg-background","transition-all duration-150 ease-out","data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]","data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]"),e[3]=g):g=e[3];let a;e[4]!==t?(a=()=>t(!1),e[4]=t,e[5]=a):a=e[5];let l;e[6]!==o?(l=o("multiRun.window.actions.closeAria"),e[6]=o,e[7]=l):l=e[7];let x;e[8]===Symbol.for("react.memo_cache_sentinel")?(x=n.jsx(O,{name:"close",className:"h-5 w-5"}),e[8]=x):x=e[8];let r;e[9]!==a||e[10]!==l?(r=n.jsx("div",{className:"absolute right-0.5 top-0.5 z-50",children:n.jsx("button",{type:"button",onClick:a,"aria-label":l,className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0.5 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:x})}),e[9]=a,e[10]=l,e[11]=r):r=e[11];let c;e[12]!==o?(c=o("multiRun.window.description"),e[12]=o,e[13]=c):c=e[13];let d;e[14]!==i||e[15]!==c?(d=n.jsx(C,{id:i,className:"sr-only",children:c}),e[14]=i,e[15]=c,e[16]=d):d=e[16];let u,m;e[17]!==t?(u=()=>t(!1),m=()=>t(!1),e[17]=t,e[18]=u,e[19]=m):(u=e[18],m=e[19]);let f;e[20]!==j||e[21]!==u||e[22]!==m?(f=n.jsx(P,{initialPrompt:j,onCreated:u,onCancel:m,isWindowed:!0}),e[20]=j,e[21]=u,e[22]=m,e[23]=f):f=e[23];let p;e[24]!==i||e[25]!==f||e[26]!==r||e[27]!==d?(p=n.jsxs(I,{children:[b,n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center pointer-events-none",children:n.jsxs(M,{"aria-describedby":i,className:g,children:[r,d,f]})})]}),e[24]=i,e[25]=f,e[26]=r,e[27]=d,e[28]=p):p=e[28];let h;return e[29]!==y||e[30]!==s||e[31]!==p?(h=n.jsx(S,{open:y,onOpenChange:s,children:p}),e[29]=y,e[30]=s,e[31]=p,e[32]=h):h=e[32],h};function B(){return typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"][data-open], [data-slot="select-content"][data-open]')}export{G as MultiRunWindow};
1
+ import{b as N,R as _,j as n,bl as D,bj as C,bk as I,bh as M,bf as S}from"./vendor-.bun-BE757pvp.js";import{c as z,v as w,I as O}from"./useAppFontEffects-DzBg8hrC.js";import{M as P}from"./main-BC0m8s1v.js";import"./index-ltrmNGAf.js";import"./runtimeEndpointReset-C42u8PvG.js";import"./mobileLayoutPreference-Dio-WWkI.js";import"./SessionSwitcherDropdown-DvoOalMY.js";const G=R=>{const e=N.c(33),{open:y,onOpenChange:t,initialPrompt:v}=R,i=_.useId(),{t:o}=z(),k=B;let s;e[0]!==t?(s=j=>{!j&&k()||t(j)},e[0]=t,e[1]=s):s=e[1];let b;e[2]===Symbol.for("react.memo_cache_sentinel")?(b=n.jsx(D,{className:w("fixed inset-0 z-50 bg-black/50 dark:bg-black/75","transition-opacity duration-150 ease-out","data-[starting-style]:opacity-0 data-[ending-style]:opacity-0")}),e[2]=b):b=e[2];let h;e[3]===Symbol.for("react.memo_cache_sentinel")?(h=w("relative pointer-events-auto","w-[90vw] max-w-[720px] h-[680px] max-h-[85vh]","flex flex-col rounded-xl border shadow-none overflow-hidden origin-center","bg-background","transition-all duration-150 ease-out","data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]","data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]"),e[3]=h):h=e[3];let a;e[4]!==t?(a=()=>t(!1),e[4]=t,e[5]=a):a=e[5];let l;e[6]!==o?(l=o("multiRun.window.actions.closeAria"),e[6]=o,e[7]=l):l=e[7];let x;e[8]===Symbol.for("react.memo_cache_sentinel")?(x=n.jsx(O,{name:"close",className:"h-5 w-5"}),e[8]=x):x=e[8];let r;e[9]!==a||e[10]!==l?(r=n.jsx("div",{className:"absolute right-0.5 top-0.5 z-50",children:n.jsx("button",{type:"button",onClick:a,"aria-label":l,className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0.5 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:x})}),e[9]=a,e[10]=l,e[11]=r):r=e[11];let c;e[12]!==o?(c=o("multiRun.window.description"),e[12]=o,e[13]=c):c=e[13];let d;e[14]!==i||e[15]!==c?(d=n.jsx(C,{id:i,className:"sr-only",children:c}),e[14]=i,e[15]=c,e[16]=d):d=e[16];let u,m;e[17]!==t?(u=()=>t(!1),m=()=>t(!1),e[17]=t,e[18]=u,e[19]=m):(u=e[18],m=e[19]);let f;e[20]!==v||e[21]!==u||e[22]!==m?(f=n.jsx(P,{initialPrompt:v,onCreated:u,onCancel:m,isWindowed:!0}),e[20]=v,e[21]=u,e[22]=m,e[23]=f):f=e[23];let p;e[24]!==i||e[25]!==f||e[26]!==r||e[27]!==d?(p=n.jsxs(I,{children:[b,n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center pointer-events-none",children:n.jsxs(M,{"aria-describedby":i,className:h,children:[r,d,f]})})]}),e[24]=i,e[25]=f,e[26]=r,e[27]=d,e[28]=p):p=e[28];let g;return e[29]!==y||e[30]!==s||e[31]!==p?(g=n.jsx(S,{open:y,onOpenChange:s,children:p}),e[29]=y,e[30]=s,e[31]=p,e[32]=g):g=e[32],g};function B(){return typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"][data-open], [data-slot="select-content"][data-open]')}export{G as MultiRunWindow};
@@ -0,0 +1 @@
1
+ import{r as I,j as t,R as a,b as z}from"./vendor-.bun-BE757pvp.js";import{af as me,aj as oe,E as Z,ae as ee,t as O,a9 as B,h as M,K as re,N as ae,q as le,H as J}from"./index-ltrmNGAf.js";import{c as V,B as U,w as W,y as ce,v as Q,I as T}from"./useAppFontEffects-DzBg8hrC.js";function pe(r){switch(r){case"ok":return null;case"auth":return"onboarding.remoteConnection.probe.authMessage";case"update-recommended":return"onboarding.remoteConnection.probe.updateRecommendedMessage";case"incompatible":return"onboarding.remoteConnection.probe.incompatibleMessage";case"wrong-service":return"onboarding.remoteConnection.probe.wrongServiceMessage";case"unreachable":return"onboarding.remoteConnection.probe.unreachableMessage";default:return null}}function Y(r){return r==="wrong-service"||r==="unreachable"||r==="incompatible"}function ie({onBack:r,showBackButton:e=!0,initialUrl:c="",initialLabel:n="",isRecoveryMode:o=!1,onConnect:b,onSwitchToLocal:i}){const{t:s}=V(),[h,y]=I.useState(c),[x,S]=I.useState(n),[N,f]=I.useState("idle"),[m,v]=I.useState(null),[R,C]=I.useState(""),j=me(h),p=j?.persistedUrl??null,w=I.useCallback(d=>{y(d.target.value),f("idle"),v(null),C("")},[]),g=I.useCallback(d=>{S(d.target.value)},[]),k=I.useCallback(async()=>{if(p){f("testing"),v(null),C("");try{const d=await oe(p);v(d),f(d.status==="ok"||d.status==="update-recommended"?"success":"error")}catch(d){C(d instanceof Error?d.message:s("onboarding.remoteConnection.errors.connectionTestFailed")),f("error")}}},[p,s]),K=I.useCallback(async()=>{if(!j)return;const d=j.persistedUrl;f("testing"),v(null),C("");try{const D=await oe(d);if(v(D),Y(D.status)){f("error");return}const F=await Z(),de=x.trim()||d,q=F.hosts.find($=>$.url===d),G=q?q.id:`host-${Date.now().toString(16)}`,te={id:G,label:de,url:d,apiUrl:d},ue=q?F.hosts.map($=>$.id===G?te:$):[...F.hosts,te];if(await ee({hosts:ue,defaultHostId:G,initialHostChoiceCompleted:!0}),b?.(),j.redeemUrl){window.location.assign(j.redeemUrl);return}O()&&await B()}catch(D){C(D instanceof Error?D.message:s("onboarding.remoteConnection.errors.failedToSaveConnection")),f("error")}},[j,x,b,s]),L=N==="testing",A=p!==null&&!L,E=p!==null&&!L&&!Y(m?.status??null),P=pe(m?.status??null),H=m?.status==="ok",u=m?.status==="update-recommended",_=m?.status==="auth",l=Y(m?.status??null);return t.jsx("div",{className:"flex flex-col items-center justify-center h-full p-8",children:t.jsxs("div",{className:"w-full max-w-md space-y-6",children:[e&&t.jsx("div",{className:"flex items-center",children:t.jsx(U,{variant:"ghost",onClick:r,className:"p-0 text-muted-foreground hover:text-foreground",children:s("onboarding.common.actions.back")})}),t.jsxs("div",{className:"space-y-2 text-center",children:[t.jsx("h1",{className:"typography-ui-header text-xl font-semibold text-foreground",children:s(o?"onboarding.remoteConnection.titleRecovery":"onboarding.remoteConnection.title")}),t.jsx("p",{className:"text-muted-foreground text-sm",children:s("onboarding.remoteConnection.description")})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{htmlFor:"remote-url",className:"text-sm text-foreground",children:s("onboarding.remoteConnection.field.serverAddress")}),t.jsx(W,{id:"remote-url",type:"url",value:h,onChange:w,placeholder:s("onboarding.remoteConnection.field.serverAddressPlaceholder"),disabled:L})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{htmlFor:"remote-label",className:"text-sm text-foreground",children:s("onboarding.remoteConnection.field.nameOptional")}),t.jsx(W,{id:"remote-label",type:"text",value:x,onChange:g,placeholder:s("onboarding.remoteConnection.field.namePlaceholder"),disabled:L})]})]}),m&&H&&t.jsx("div",{className:"rounded-lg border p-3 text-sm",style:{borderColor:"var(--status-success)",color:"var(--status-success)"},children:s("onboarding.remoteConnection.status.connectedSuccessfully",{latencyMs:m.latencyMs})}),m&&_&&t.jsx("div",{className:"rounded-lg border p-3 text-sm",style:{borderColor:"var(--status-warning)",color:"var(--status-warning)"},children:s("onboarding.remoteConnection.status.authWarning")}),m&&u&&t.jsx("div",{className:"rounded-lg border p-3 text-sm",style:{borderColor:"var(--status-warning)",color:"var(--status-warning)"},children:P?s(P):null}),m&&l&&t.jsxs("div",{className:"rounded-lg border p-3 text-sm space-y-3",style:{borderColor:"var(--status-error)",color:"var(--status-error)"},children:[t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold mb-1",children:s("onboarding.remoteConnection.status.connectionFailed")}),t.jsx("div",{className:"opacity-90",children:P?s(P):null})]}),t.jsx("div",{className:"text-xs opacity-80",children:m.status==="unreachable"?s("onboarding.remoteConnection.status.suggestionsUnreachable"):s("onboarding.remoteConnection.status.suggestionsWrongService")})]}),R&&t.jsx("div",{className:"rounded-lg border p-3 text-sm",style:{borderColor:"var(--status-error)",color:"var(--status-error)"},children:R}),t.jsxs("div",{className:"flex gap-3",children:[t.jsx(U,{variant:"outline",onClick:k,disabled:!A,children:s(L?"onboarding.remoteConnection.actions.testing":"onboarding.remoteConnection.actions.testConnection")}),t.jsx(U,{onClick:K,disabled:!E,children:s("onboarding.remoteConnection.actions.connectAndRestart")})]}),l&&t.jsxs("div",{className:"flex flex-col gap-2 pt-2 border-t border-border",children:[t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:s("onboarding.remoteConnection.actions.whatToDo")}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(U,{variant:"outline",size:"sm",onClick:r,className:"flex-1",children:s("onboarding.remoteConnection.actions.chooseDifferentServer")}),!o&&i&&t.jsx(U,{variant:"outline",size:"sm",onClick:i,className:"flex-1",children:s("onboarding.remoteConnection.actions.useLocalInstead")})]})]})]})})}const he="curl -fsSL https://opencode.ai/install | bash",fe="https://opencode.ai/docs",se=2500;function be(r){const e=z.c(5),{onCopy:c,copyTitle:n}=r;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=t.jsxs("code",{className:"flex-1 text-left overflow-x-auto whitespace-nowrap",children:[t.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),t.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),t.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),t.jsx("span",{className:"text-muted-foreground",children:" | "}),t.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e[0]=o):o=e[0];let b;e[1]===Symbol.for("react.memo_cache_sentinel")?(b=t.jsx(T,{name:"file-copy",className:"h-4 w-4"}),e[1]=b):b=e[1];let i;return e[2]!==n||e[3]!==c?(i=t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[o,t.jsx("button",{onClick:c,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors shrink-0",title:n,"aria-label":n,children:b})]}),e[2]=n,e[3]=c,e[4]=i):i=e[4],i}function xe({onCliAvailable:r}){const{t:e}=V(),[c,n]=a.useState(!1),[o,b]=a.useState(!1),[i,s]=a.useState(!1),[h,y]=a.useState(!1),[x,S]=a.useState(""),[N,f]=a.useState("unknown"),[m,v]=a.useState("local"),[R,C]=a.useState(!1),[j,p]=a.useState(!1);a.useEffect(()=>{b(O())},[]),a.useEffect(()=>{if(typeof navigator>"u"){f("unknown");return}const l=navigator.userAgent||"";/Windows/i.test(l)?f("windows"):/Macintosh|Mac OS X/i.test(l)?f("macos"):/Linux/i.test(l)?f("linux"):f("unknown")},[]),a.useEffect(()=>{let l=!1;return(async()=>{try{const d=await M("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!d.ok)return;const D=await d.json().catch(()=>null);if(!D||l)return;const F=typeof D.opencodeBinary=="string"?D.opencodeBinary.trim():"";F&&S(F)}catch{}})(),()=>{l=!0}},[]);const w=a.useCallback(async l=>{const d=l.target;d.closest(".app-region-no-drag")||d.closest("button, a, input, select, textarea, code, summary, details")||l.button===0&&o&&await re()},[o]),g=a.useCallback(async()=>{try{const l=await M("/health");if(!l.ok)return!1;const d=await l.json();return d.openCodeRunning===!0||d.isOpenCodeReady===!0}catch{return!1}},[]),k=a.useCallback(async l=>{if(!o)return;const d=await Z();await ee({...d,...l==="local"?{defaultHostId:"local"}:{},initialHostChoiceCompleted:!0})},[o]),K=a.useCallback(async()=>{o&&await k("local"),r?.()},[o,r,k]);a.useEffect(()=>{if(m!=="local")return;let l=!1,d=null;const D=async()=>{if(!l){try{const F=await g();if(l)return;if(F){await K();return}}catch{}l||(d=setTimeout(D,se))}};return d=setTimeout(D,se),()=>{l=!0,d&&clearTimeout(d)}},[m,g,K]);const L=a.useCallback(async()=>{y(!0);try{await g()&&await K()}finally{y(!1)}},[g,K]),A=a.useCallback(async()=>{if(!(typeof window>"u")&&o)try{const l=await ae();l.success&&l.path&&l.path.trim().length>0&&S(l.path.trim())}catch{}},[o]),E=a.useCallback(async()=>{s(!0);try{if(await le({opencodeBinary:x.trim()}),o){await k("local"),await B();return}await M("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>s(!1),1e3)}},[o,x,k]),P=a.useCallback(async()=>{const l=await ce(he);l.ok?(n(!0),setTimeout(()=>n(!1),2e3)):console.error("Failed to copy:",l.error)},[]),H=fe,u=N==="windows"?"C:\\Users\\you\\AppData\\Roaming\\npm\\opencode.cmd":N==="linux"?"/home/you/.bun/bin/opencode":"/Users/you/.bun/bin/opencode",_=!o||m==="local";return t.jsx("div",{className:"app-region-drag h-full flex items-center justify-center bg-transparent p-8 cursor-default select-none overflow-y-auto",onMouseDown:w,children:t.jsxs("div",{className:"w-full max-w-md space-y-7",children:[t.jsxs("header",{className:"text-center space-y-1.5",children:[t.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:e("onboarding.chooser.title")}),t.jsx("p",{className:"text-sm text-muted-foreground",children:e("onboarding.chooser.description")})]}),o&&t.jsxs("div",{className:"app-region-no-drag flex gap-1.5",children:[t.jsx("button",{type:"button",className:Q("flex-1 px-4 py-2 rounded-lg border transition-colors text-sm",m==="local"?"border-[var(--interactive-selection)] text-foreground bg-[var(--interactive-selection)]/10":"border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground"),onClick:()=>v("local"),children:e("onboarding.chooser.tabs.localInstall")}),t.jsx("button",{type:"button",className:Q("flex-1 px-4 py-2 rounded-lg border transition-colors text-sm",m==="remote"?"border-[var(--interactive-selection)] text-foreground bg-[var(--interactive-selection)]/10":"border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground"),onClick:()=>v("remote"),children:e("onboarding.chooser.tabs.connectRemote")})]}),o&&m==="remote"?t.jsx("div",{className:"app-region-no-drag",children:t.jsx(ie,{onBack:()=>v("local"),showBackButton:!1,onSwitchToLocal:()=>v("local")})}):null,_&&t.jsxs("div",{className:"space-y-4",children:[N==="windows"&&t.jsxs("div",{className:"rounded-lg border border-border bg-background/50 p-4",children:[t.jsx("div",{className:"text-sm text-foreground",children:e("onboarding.localSetup.windows.title")}),t.jsxs("ol",{className:"mt-2 list-decimal space-y-1 pl-5 text-sm text-muted-foreground",children:[t.jsx("li",{children:e("onboarding.localSetup.windows.stepRunInstallInWsl")}),t.jsx("li",{children:e("onboarding.localSetup.windows.stepSetBinaryPath")})]})]}),t.jsx("p",{className:"text-sm text-muted-foreground text-center leading-relaxed",children:e("onboarding.localSetup.intro")}),t.jsx("div",{className:"app-region-no-drag rounded-lg border border-border bg-background/60 backdrop-blur-sm px-4 py-3 font-mono text-sm",children:c?t.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--status-success)"},children:[t.jsx(T,{name:"check",className:"h-4 w-4"}),e("onboarding.common.status.copiedToClipboard")]}):t.jsx(be,{onCopy:P,copyTitle:e("onboarding.common.copyToClipboard")})}),t.jsxs("div",{className:"app-region-no-drag flex items-center justify-between",children:[t.jsxs("a",{href:H,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1",children:[e(N==="windows"?"onboarding.localSetup.docs.windows":"onboarding.localSetup.docs.default"),t.jsx(T,{name:"external-link",className:"h-3 w-3"})]}),t.jsx("button",{type:"button",onClick:L,disabled:h,className:"text-xs text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",children:e(h?"onboarding.localSetup.actions.checking":"onboarding.localSetup.actions.checkNow")})]}),t.jsxs("div",{className:"rounded-lg border px-4 py-3 flex items-center gap-3",style:{borderColor:"color-mix(in srgb, var(--primary-base) 20%, transparent)",backgroundColor:"color-mix(in srgb, var(--primary-base) 6%, transparent)"},role:"status","aria-live":"polite",children:[t.jsxs("span",{className:"relative inline-flex h-2.5 w-2.5 shrink-0","aria-hidden":!0,children:[t.jsx("span",{className:"absolute inset-0 rounded-full",style:{backgroundColor:"var(--primary-base)",animation:"pulse-opacity 1.6s ease-in-out infinite"}}),t.jsx("span",{className:"absolute inset-[-4px] rounded-full",style:{backgroundColor:"var(--primary-base)",animation:"pulse-opacity-dim 1.6s ease-in-out infinite",opacity:0}})]}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"text-sm text-foreground leading-tight",children:e("onboarding.localSetup.status.watching")}),t.jsx("div",{className:"text-xs text-muted-foreground leading-tight mt-0.5",children:e("onboarding.localSetup.status.autoContinue")})]})]}),t.jsxs("details",{className:"app-region-no-drag group rounded-lg border border-border/60 px-4 open:bg-background/40 transition-colors",open:R,onToggle:l=>C(l.currentTarget.open),children:[t.jsxs("summary",{className:"flex items-center justify-between cursor-pointer py-2.5 text-sm text-muted-foreground hover:text-foreground transition-colors list-none [&::-webkit-details-marker]:hidden",children:[t.jsx("span",{children:e("onboarding.localSetup.advanced.title")}),t.jsx(T,{name:"arrow-down-s",className:"h-4 w-4 transition-transform group-open:rotate-180"})]}),t.jsxs("div",{className:"pb-4 space-y-2",children:[t.jsxs("div",{className:"flex gap-2",children:[t.jsx(W,{value:x,onChange:l=>S(l.target.value),placeholder:u,disabled:i,className:"flex-1 font-mono text-xs"}),t.jsx(U,{type:"button",variant:"secondary",size:"sm",onClick:A,disabled:i||!o,children:e("onboarding.localSetup.actions.browse")}),t.jsx(U,{type:"button",size:"sm",onClick:E,disabled:i||!x.trim(),children:e("onboarding.localSetup.actions.apply")})]}),t.jsx("p",{className:"text-xs text-muted-foreground/70",children:e("onboarding.localSetup.helper.saveAndReload")})]})]}),t.jsxs("details",{className:"app-region-no-drag group rounded-lg border border-border/60 px-4 open:bg-background/40 transition-colors",open:j,onToggle:l=>p(l.currentTarget.open),children:[t.jsxs("summary",{className:"flex items-center justify-between cursor-pointer py-2.5 text-sm text-muted-foreground hover:text-foreground transition-colors list-none [&::-webkit-details-marker]:hidden",children:[t.jsx("span",{children:e("onboarding.localSetup.troubleshoot.title")}),t.jsx(T,{name:"arrow-down-s",className:"h-4 w-4 transition-transform group-open:rotate-180"})]}),t.jsx("ul",{className:"pb-4 space-y-1.5 text-xs text-muted-foreground list-disc pl-4",children:N==="windows"?t.jsx(t.Fragment,{children:t.jsx("li",{children:e("onboarding.localSetup.windows.hintDetectionFailed")})}):t.jsxs(t.Fragment,{children:[t.jsx("li",{children:e("onboarding.localSetup.hint.ensurePath")}),t.jsx("li",{children:e("onboarding.localSetup.hint.setEnv")}),t.jsx("li",{children:e("onboarding.localSetup.hint.missingRuntime")})]})})]})]})]})})}const ge="curl -fsSL https://opencode.ai/install | bash",ye="https://opencode.ai/docs";function ve(r){const e=z.c(5),{onCopy:c,copyTitle:n}=r;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=t.jsxs("code",{children:[t.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),t.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),t.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),t.jsx("span",{className:"text-muted-foreground",children:" | "}),t.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e[0]=o):o=e[0];let b;e[1]===Symbol.for("react.memo_cache_sentinel")?(b=t.jsx(T,{name:"file-copy",className:"h-4 w-4"}),e[1]=b):b=e[1];let i;return e[2]!==n||e[3]!==c?(i=t.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o,t.jsx("button",{onClick:c,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:n,children:b})]}),e[2]=n,e[3]=c,e[4]=i):i=e[4],i}const we=3e4;function je({onBack:r,onCliAvailable:e,isFromRecovery:c=!1,onSwitchToRemote:n}){const{t:o}=V(),[b,i]=a.useState(!1),[s,h]=a.useState(!1),[y,x]=a.useState(!1),[S,N]=a.useState(!1),[f,m]=a.useState(!1),[v,R]=a.useState(null),[C,j]=a.useState(""),[p,w]=a.useState("unknown");a.useEffect(()=>{const u=setTimeout(()=>h(!0),we);return()=>clearTimeout(u)},[]),a.useEffect(()=>{x(O())},[]),a.useEffect(()=>{if(typeof navigator>"u"){w("unknown");return}const u=navigator.userAgent||"";if(/Windows/i.test(u)){w("windows");return}if(/Macintosh|Mac OS X/i.test(u)){w("macos");return}if(/Linux/i.test(u)){w("linux");return}w("unknown")},[]),a.useEffect(()=>{let u=!1;return(async()=>{try{const _=await M("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!_.ok)return;const l=await _.json().catch(()=>null);if(!l||u)return;const d=typeof l.opencodeBinary=="string"?l.opencodeBinary.trim():"";d&&j(d)}catch{}})(),()=>{u=!0}},[]);const g=a.useCallback(async u=>{u.target.closest("button, a, input, select, textarea, code")||u.button===0&&y&&await re()},[y]),k=a.useCallback(async()=>{try{const u=await M("/health");if(!u.ok)return!1;const _=await u.json();return _.openCodeRunning===!0||_.isOpenCodeReady===!0}catch{return!1}},[]),K=a.useCallback(async()=>{if(!(typeof window>"u")&&y)try{const u=await ae();u.success&&u.path&&u.path.trim().length>0&&j(u.path.trim())}catch{}},[y]),L=a.useCallback(async()=>{N(!0);try{if(await le({opencodeBinary:C.trim()}),y){await B();return}await M("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>N(!1),1e3)}},[y,C]),A=a.useCallback(async()=>{const u=await ce(ge);u.ok?(i(!0),setTimeout(()=>i(!1),2e3)):console.error("Failed to copy:",u.error)},[]),E=a.useCallback(async()=>{m(!0),R(null);try{await k()?e?.():R(o("onboarding.localSetup.errors.cliNotReady"))}catch(u){R(u instanceof Error?u.message:o("onboarding.localSetup.errors.detectionFailed"))}finally{m(!1)}},[k,e,o]),P=ye,H=p==="windows"?"C:\\Users\\you\\AppData\\Roaming\\npm\\opencode.cmd":p==="linux"?"/home/you/.bun/bin/opencode":"/Users/you/.bun/bin/opencode";return t.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:g,children:[t.jsxs("div",{className:"w-full max-w-lg space-y-4 text-center",children:[t.jsx("div",{className:"flex items-center",children:t.jsx(U,{variant:"ghost",onClick:r,className:"p-0 text-muted-foreground hover:text-foreground",children:o("onboarding.common.actions.back")})}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:o("onboarding.localSetup.title")}),t.jsx("p",{className:"text-muted-foreground",children:o("onboarding.localSetup.description")})]}),p==="windows"&&t.jsxs("div",{className:"mx-auto max-w-2xl rounded-lg border border-border bg-background/50 p-4 text-left",children:[t.jsx("div",{className:"text-sm text-foreground",children:o("onboarding.localSetup.windows.title")}),t.jsxs("ol",{className:"mt-2 list-decimal space-y-1 pl-5 text-sm text-muted-foreground",children:[t.jsx("li",{children:o("onboarding.localSetup.windows.stepRunInstallInWsl")}),t.jsx("li",{children:o("onboarding.localSetup.windows.stepSetBinaryPath")})]})]}),t.jsx("div",{className:"flex justify-center",children:t.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:b?t.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[t.jsx(T,{name:"check",className:"h-4 w-4"}),o("onboarding.common.status.copiedToClipboard")]}):t.jsx(ve,{onCopy:A,copyTitle:o("onboarding.common.copyToClipboard")})})}),t.jsxs("a",{href:P,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 justify-center",children:[o(p==="windows"?"onboarding.localSetup.docs.windows":"onboarding.localSetup.docs.default"),t.jsx(T,{name:"external-link",className:"h-3 w-3"})]}),v&&t.jsx("div",{className:"mx-auto max-w-md rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive",children:v}),t.jsxs("div",{className:"space-y-3",children:[t.jsx(U,{type:"button",onClick:E,disabled:f,className:"w-full max-w-xs",size:"lg",children:o(f?"onboarding.localSetup.actions.checking":"onboarding.localSetup.actions.checkAndContinue")}),t.jsx("p",{className:"text-xs text-muted-foreground",children:o("onboarding.localSetup.helper.checkAndContinue")})]}),t.jsx("div",{className:"mx-auto w-full max-w-xl pt-4",children:t.jsxs("div",{className:"space-y-2",children:[t.jsx("div",{className:"text-sm text-muted-foreground",children:o("onboarding.localSetup.field.alreadyInstalled")}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(W,{value:C,onChange:u=>j(u.target.value),placeholder:H,disabled:S,className:"flex-1 font-mono text-xs"}),t.jsx(U,{type:"button",variant:"secondary",onClick:K,disabled:S||!y,children:o("onboarding.localSetup.actions.browse")}),t.jsx(U,{type:"button",onClick:L,disabled:S,children:o("onboarding.localSetup.actions.apply")})]}),t.jsx("div",{className:"text-xs text-muted-foreground/70",children:o("onboarding.localSetup.helper.saveAndReload")})]})}),c&&n&&t.jsxs("div",{className:"text-center pt-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:o("onboarding.localSetup.remotePreference")}),t.jsx(U,{variant:"link",onClick:n,children:o("onboarding.localSetup.actions.connectRemoteServer")})]})]}),s&&t.jsx("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:p==="windows"?t.jsx(t.Fragment,{children:t.jsx("p",{className:"text-sm text-muted-foreground/70",children:o("onboarding.localSetup.windows.hintDetectionFailed")})}):t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"text-sm text-muted-foreground/70",children:o("onboarding.localSetup.hint.ensurePath")}),t.jsx("p",{className:"text-sm text-muted-foreground/70",children:o("onboarding.localSetup.hint.setEnv")}),t.jsx("p",{className:"text-sm text-muted-foreground/70",children:o("onboarding.localSetup.hint.missingRuntime")})]})})]})}function X(r,e){if(r?.trim())return J(r.trim());if(e)return J(e)}function ke(r,e,c){switch(r){case"local-unavailable":return{title:"Local OpenCode Unavailable",description:"OpenCode CLI could not be started or is not installed. Install OpenCode or connect to a remote server instead.",titleKey:"onboarding.desktopRecovery.localUnavailable.title",descriptionKey:"onboarding.desktopRecovery.localUnavailable.description",iconKey:"local",showRetry:!0,retryLabel:"Retry Local",retryLabelKey:"onboarding.desktopRecovery.localUnavailable.retry",showUseLocal:!0,showUseRemote:!0,useLocalLabel:"Set Up Local",useLocalLabelKey:"onboarding.desktopRecovery.localUnavailable.useLocal",useRemoteLabel:"Use Remote",useRemoteLabelKey:"onboarding.desktopRecovery.common.useRemote"};case"remote-missing":return{title:"No Default Connection",description:"Your saved default connection could not be found. Choose how you want to connect.",titleKey:"onboarding.desktopRecovery.noDefaultConnection.title",descriptionKey:"onboarding.desktopRecovery.noDefaultConnection.description",iconKey:"local",showRetry:!1,showUseLocal:!0,showUseRemote:!0,useLocalLabel:"Use Local",useLocalLabelKey:"onboarding.desktopRecovery.common.useLocal",useRemoteLabel:"Use Remote",useRemoteLabelKey:"onboarding.desktopRecovery.common.useRemote"};case"remote-unreachable":{const n=X(e,c);return{title:"Remote Server Unreachable",description:`Could not connect to "${n||"the remote server"}". Check your network connection and verify the server address.`,titleKey:"onboarding.desktopRecovery.remoteUnreachable.title",descriptionKey:"onboarding.desktopRecovery.remoteUnreachable.description",descriptionParams:n?{host:n}:void 0,iconKey:"remote",showRetry:!0,retryLabel:"Retry Connection",retryLabelKey:"onboarding.desktopRecovery.remoteUnreachable.retry",showUseLocal:!0,showUseRemote:!0,useLocalLabel:"Use Local",useLocalLabelKey:"onboarding.desktopRecovery.common.useLocal",useRemoteLabel:"Use Remote",useRemoteLabelKey:"onboarding.desktopRecovery.common.useRemote"}}case"remote-wrong-service":{const n=X(e,c);return{title:"Incompatible Server",description:`The server at "${n||"unknown"}" is not running OpenChamber. Verify the address points to an OpenChamber server.`,titleKey:"onboarding.desktopRecovery.incompatibleServer.title",descriptionKey:"onboarding.desktopRecovery.incompatibleServer.description",descriptionParams:n?{host:n}:void 0,iconKey:"remote",showRetry:!1,showUseLocal:!0,showUseRemote:!0,useLocalLabel:"Use Local",useLocalLabelKey:"onboarding.desktopRecovery.common.useLocal",useRemoteLabel:"Use Remote",useRemoteLabelKey:"onboarding.desktopRecovery.common.useRemote"}}case"remote-incompatible":{const n=X(e,c);return{title:"Server Update Required",description:`The OpenChamber server at "${n||"unknown"}" is not compatible with this app version. Update OpenChamber on the server, then try again.`,titleKey:"onboarding.desktopRecovery.remoteIncompatible.title",descriptionKey:"onboarding.desktopRecovery.remoteIncompatible.description",descriptionParams:n?{host:n}:void 0,iconKey:"remote",showRetry:!0,retryLabel:"Retry Connection",retryLabelKey:"onboarding.desktopRecovery.remoteUnreachable.retry",showUseLocal:!0,showUseRemote:!0,useLocalLabel:"Use Local",useLocalLabelKey:"onboarding.desktopRecovery.common.useLocal",useRemoteLabel:"Use Remote",useRemoteLabelKey:"onboarding.desktopRecovery.common.useRemote"}}case"missing-default-host":return{title:"No Default Connection",description:"Your saved default connection could not be found. Choose how you want to connect.",titleKey:"onboarding.desktopRecovery.noDefaultConnection.title",descriptionKey:"onboarding.desktopRecovery.noDefaultConnection.description",iconKey:"local",showRetry:!1,showUseLocal:!0,showUseRemote:!0,useLocalLabel:"Use Local",useLocalLabelKey:"onboarding.desktopRecovery.common.useLocal",useRemoteLabel:"Use Remote",useRemoteLabelKey:"onboarding.desktopRecovery.common.useRemote"};default:{const n=r;throw new Error(`Unknown recovery variant: ${n}`)}}}function Ce(r){switch(r){case"local":return t.jsx(T,{name:"macbook",className:"h-8 w-8"});case"remote":return t.jsx(T,{name:"server",className:"h-8 w-8"})}}function Ne({variant:r,hostLabel:e,hostUrl:c,onRetry:n,onUseLocal:o,onUseRemote:b,isRetrying:i=!1}){const{t:s}=V(),h=ke(r,e,c),y=h.retryLabelKey??"onboarding.desktopRecovery.actions.retryConnection",x=a.useMemo(()=>{if(h.descriptionParams?.host)return h.descriptionParams;if(r==="remote-unreachable")return{host:s("onboarding.desktopRecovery.placeholders.remoteServer")};if(r==="remote-wrong-service"||r==="remote-incompatible")return{host:s("onboarding.desktopRecovery.placeholders.unknownServer")}},[h.descriptionParams,s,r]);return t.jsx("div",{className:"flex flex-col items-center justify-center h-full p-8",children:t.jsxs("div",{className:"w-full max-w-md space-y-6",children:[t.jsxs("div",{className:"flex flex-col items-center space-y-3 text-center",children:[t.jsx("div",{className:"p-3 rounded-full",style:{backgroundColor:"var(--status-warning)",opacity:.15},children:t.jsx("div",{style:{color:"var(--status-warning)"},children:Ce(h.iconKey)})}),t.jsx("h1",{className:"typography-ui-header text-xl font-semibold text-foreground",children:s(h.titleKey)}),t.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:s(h.descriptionKey,x)})]}),c&&(r==="remote-unreachable"||r==="remote-wrong-service"||r==="remote-incompatible")&&t.jsxs("div",{className:"rounded-lg border border-border bg-background/50 p-3",children:[t.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:s("onboarding.remoteConnection.field.serverAddress")}),t.jsx("div",{className:"font-mono text-sm text-foreground truncate",children:J(c)})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[h.showRetry&&n&&t.jsxs(U,{onClick:n,disabled:i,className:"w-full",children:[t.jsx(T,{name:"refresh",className:Q("h-4 w-4",i&&"animate-spin")}),s(i?"onboarding.desktopRecovery.actions.retrying":y)]}),t.jsxs("div",{className:"flex gap-2",children:[h.showUseLocal&&o&&t.jsxs(U,{variant:"outline",onClick:o,disabled:i,className:"flex-1",children:[t.jsx(T,{name:"macbook",className:"h-4 w-4"}),s(h.useLocalLabelKey)]}),h.showUseRemote&&b&&t.jsxs(U,{variant:"outline",onClick:b,disabled:i,className:"flex-1",children:[t.jsx(T,{name:"server",className:"h-4 w-4"}),s(h.useRemoteLabelKey)]})]})]})]})})}function ne(r,e){if(e==="use-remote")return{kind:"remote-form"};switch(r){case"local-unavailable":return{kind:"local-setup"};case"remote-unreachable":case"remote-incompatible":case"remote-wrong-service":case"remote-missing":case"missing-default-host":return{kind:"switch-default-to-local"};default:{const c=r;throw new Error(`Unhandled RecoveryVariant: ${c}`)}}}function Re(r){const e=z.c(27),{variant:c,hostUrl:n,hostLabel:o,onRetry:b,onChooseRemote:i,showRemoteForm:s,onCloseRemoteForm:h,onSwitchToLocalFromRemote:y,onEnterLocalSetup:x,isRetrying:S}=r,N=s===void 0?!1:s,f=S===void 0?!1:S,m=Se;let v;e[0]!==b?(v=async()=>{if(O()){await B();return}await M("/api/config/reload",{method:"POST"}),b?.()},e[0]=b,e[1]=v):v=e[1];const R=v;let C;e[2]!==x||e[3]!==c?(C=async()=>{if(ne(c,"use-local").kind==="local-setup"){x?.();return}if(await m("local"),O()){await B();return}window.location.reload()},e[2]=x,e[3]=c,e[4]=C):C=e[4];const j=C;let p;e[5]!==i||e[6]!==c?(p=()=>{ne(c,"use-remote").kind==="remote-form"&&i?.()},e[5]=i,e[6]=c,e[7]=p):p=e[7];const w=p;if(N){const k=c==="remote-wrong-service"?"":n||"",K=c==="remote-wrong-service"?"":o||"";let L;e[8]!==i||e[9]!==h?(L=h||(()=>i?.()),e[8]=i,e[9]=h,e[10]=L):L=e[10];let A;e[11]!==x||e[12]!==y?(A=y||(()=>{m("local").then(()=>{O()?B():x?.()})}),e[11]=x,e[12]=y,e[13]=A):A=e[13];let E;return e[14]!==K||e[15]!==k||e[16]!==L||e[17]!==A?(E=t.jsx(ie,{onBack:L,initialUrl:k,initialLabel:K,isRecoveryMode:!0,onSwitchToLocal:A}),e[14]=K,e[15]=k,e[16]=L,e[17]=A,e[18]=E):E=e[18],E}let g;return e[19]!==R||e[20]!==j||e[21]!==w||e[22]!==o||e[23]!==n||e[24]!==f||e[25]!==c?(g=t.jsx(Ne,{variant:c,hostLabel:o,hostUrl:n,onRetry:R,onUseLocal:j,onUseRemote:w,isRetrying:f}),e[19]=R,e[20]=j,e[21]=w,e[22]=o,e[23]=n,e[24]=f,e[25]=c,e[26]=g):g=e[26],g}async function Se(r){if(!O())return;const e=await Z();await ee({...e,...r==="local"?{defaultHostId:"local"}:{},initialHostChoiceCompleted:!0})}function Ke(r){const e=z.c(26),{onBack:c,onCliAvailable:n,mode:o,recoveryVariant:b,recoveryHostUrl:i,recoveryHostLabel:s,onEnterLocalSetup:h}=r,y=o===void 0?"first-launch":o,x=b===void 0?"missing-default-host":b,[S,N]=a.useState(!1),[f,m]=a.useState(!1);let v;e[0]===Symbol.for("react.memo_cache_sentinel")?(v=()=>{m(!1),N(!1)},e[0]=v):v=e[0];let R;e[1]!==y||e[2]!==s||e[3]!==i||e[4]!==x?(R=[y,x,i,s],e[1]=y,e[2]=s,e[3]=i,e[4]=x,e[5]=R):R=e[5],a.useEffect(v,R);const C=f?"local-setup":y;if(C==="recovery"){let p,w;e[6]===Symbol.for("react.memo_cache_sentinel")?(p=()=>N(!1),w=()=>{N(!1),m(!0)},e[6]=p,e[7]=w):(p=e[6],w=e[7]);let g;e[8]!==h?(g=()=>{m(!0),h?.()},e[8]=h,e[9]=g):g=e[9];let k;return e[10]!==s||e[11]!==i||e[12]!==x||e[13]!==S||e[14]!==g?(k=t.jsx(Re,{variant:x,hostUrl:i,hostLabel:s,showRemoteForm:S,onCloseRemoteForm:p,onSwitchToLocalFromRemote:w,onEnterLocalSetup:g}),e[10]=s,e[11]=i,e[12]=x,e[13]=S,e[14]=g,e[15]=k):k=e[15],k}if(C==="local-setup"){let p;e[16]!==c||e[17]!==f?(p=()=>{f?m(!1):c?.()},e[16]=c,e[17]=f,e[18]=p):p=e[18];let w;e[19]===Symbol.for("react.memo_cache_sentinel")?(w=()=>N(!0),e[19]=w):w=e[19];let g;return e[20]!==n||e[21]!==f||e[22]!==p?(g=t.jsx(je,{onBack:p,onCliAvailable:n,isFromRecovery:f,onSwitchToRemote:w}),e[20]=n,e[21]=f,e[22]=p,e[23]=g):g=e[23],g}let j;return e[24]!==n?(j=t.jsx(xe,{onCliAvailable:n}),e[24]=n,e[25]=j):j=e[25],j}export{Ke as OnboardingScreen};