@pi-chamber/web 0.8.2 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +22 -6
  2. package/bin/cli.js +16 -3
  3. package/bin/cli.test.js +62 -0
  4. package/bin/lib/DOCUMENTATION.md +6 -6
  5. package/bin/lib/cli-args.js +26 -7
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +6 -0
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-lifecycle.js +14 -0
  12. package/bin/lib/commands-logs.js +24 -5
  13. package/bin/lib/commands-serve.js +176 -4
  14. package/bin/lib/commands-tunnel.js +35 -0
  15. package/bin/lib/commands-update.js +107 -39
  16. package/bin/lib/commands-update.test.js +97 -1
  17. package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-DoEOH0hY.js} +1 -1
  18. package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-y9Ystuhv.js} +1 -1
  19. package/dist/assets/DiffView-ScM4XoqZ.js +18 -0
  20. package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-CjkhMFqJ.js} +3 -3
  21. package/dist/assets/GitView-Bqi6H8I-.js +8 -0
  22. package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
  23. package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
  24. package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-ClnfJJ2J.js} +1 -1
  25. package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
  26. package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
  27. package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
  28. package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
  29. package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-Cy9tmnMg.js} +1 -1
  30. package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
  31. package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
  32. package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-DJNcTQNp.js} +4 -4
  33. package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-DxgVLhi9.js} +1 -1
  34. package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
  35. package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
  36. package/dist/assets/gitStatusPredicates-CIFSGjJs.js +134 -0
  37. package/dist/assets/index-D2C3q2xD.js +8 -0
  38. package/dist/assets/index-DNoEeZ2U.css +1 -0
  39. package/dist/assets/{index-CMfiVUIr.js → index-DmNPBaSo.js} +1 -1
  40. package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-CrvpUauF.js} +1 -1
  41. package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-CKvhS32g.js} +1 -1
  42. package/dist/assets/{main-zZrKd3hZ.js → main-BFv8slLp.js} +2 -2
  43. package/dist/assets/main-CjM7g4Gq.js +135 -0
  44. package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-DKrraAqT.js} +1 -1
  45. package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-hQnLS5mt.js} +2 -2
  46. package/dist/assets/{mobile-VU_G_SgX.js → mobile-DuXOBGs_.js} +2 -2
  47. package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
  48. package/dist/assets/renderMobileApp-DofX2wjB.js +11 -0
  49. package/dist/assets/runtimeEndpointReset-BZeYg6eN.js +54 -0
  50. package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C7CBxDbh.js} +1 -1
  51. package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
  52. package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
  53. package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
  54. package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-BEoW7LlC.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
  56. package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
  57. package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
  58. package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
  59. package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
  60. package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
  61. package/dist/assets/{web-components-C9ENH49P.js → web-components-Dy-Tz_LJ.js} +3 -3
  62. package/dist/index.html +4 -4
  63. package/dist/mini-chat.html +3 -3
  64. package/dist/mobile.html +3 -3
  65. package/package.json +3 -4
  66. package/server/index.js +26 -7
  67. package/server/lib/client-auth/pairing.js +13 -2
  68. package/server/lib/client-auth/remote-clients.js +13 -2
  69. package/server/lib/fs/DOCUMENTATION.md +3 -1
  70. package/server/lib/fs/routes.test.js +74 -0
  71. package/server/lib/git/DOCUMENTATION.md +1 -1
  72. package/server/lib/git/identity-storage.js +10 -1
  73. package/server/lib/package-manager.js +1 -1
  74. package/server/lib/package-manager.test.js +11 -0
  75. package/server/lib/pi/archive-store.js +3 -2
  76. package/server/lib/pi/model-config-store.js +6 -2
  77. package/server/lib/pi/routes.js +11 -2
  78. package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
  79. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  80. package/server/lib/pi/session-daemon/session-daemon.js +226 -40
  81. package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
  82. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  83. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  84. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  85. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  86. package/server/lib/pi/session-folders-store.js +20 -2
  87. package/server/lib/pi/session-folders-store.test.js +17 -0
  88. package/server/lib/pi/settings-store.js +3 -2
  89. package/server/lib/pi/snippets-store.js +4 -1
  90. package/server/lib/pi/ui-settings-store.js +3 -2
  91. package/server/lib/server/cross-process-lock.js +112 -0
  92. package/server/lib/server/cross-process-lock.test.js +70 -0
  93. package/server/lib/server/server-profile.js +110 -0
  94. package/server/lib/server/server-profile.test.js +58 -0
  95. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  96. package/server/lib/server/tunnel-service.js +8 -1
  97. package/server/lib/stt/DOCUMENTATION.md +1 -1
  98. package/server/lib/stt/config-store.js +3 -2
  99. package/server/lib/terminal/DOCUMENTATION.md +3 -3
  100. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  101. package/server/lib/ui-auth/ui-auth.js +9 -2
  102. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  103. package/dist/assets/DiffView-Gh9wjthp.js +0 -18
  104. package/dist/assets/GitView-BmNCkkoC.js +0 -8
  105. package/dist/assets/JsonTreeView-CxXRXXzk.js +0 -1
  106. package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
  107. package/dist/assets/ToolOutputDialog-C_7vJLEq.js +0 -8
  108. package/dist/assets/computeVirtualFileMetrics-D0mQcleY.js +0 -3
  109. package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
  110. package/dist/assets/index-CzO3ooje.css +0 -1
  111. package/dist/assets/index-ivrh3jfy.js +0 -8
  112. package/dist/assets/main-BoVfUG73.js +0 -135
  113. package/dist/assets/renderElectronMiniChatApp-Bi1927c8.js +0 -2
  114. package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
  115. package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
  116. package/dist/assets/usePushVisibilityBeacon-zYd3ppNh.js +0 -10
  117. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
@@ -0,0 +1,110 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+
3
+ const PROFILE_KEY_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
4
+ const MAX_EXPLICIT_LENGTH = 128;
5
+
6
+ export const isValidProfileKey = (value) => typeof value === 'string' && PROFILE_KEY_PATTERN.test(value);
7
+
8
+ const hashSeed = (seed) => createHash('sha256').update(seed).digest('hex').slice(0, 16);
9
+
10
+ const sanitizePortSegment = (port) => {
11
+ if (port === 0) return 'pauto';
12
+ if (Number.isInteger(port) && port > 0 && port <= 65535) return `p${port}`;
13
+ return '';
14
+ };
15
+
16
+ const resolveRuntime = ({ env = {}, runtime } = {}) => {
17
+ const fromEnv = typeof env.PICHAMBER_RUNTIME === 'string' ? env.PICHAMBER_RUNTIME.trim() : '';
18
+ if (fromEnv === 'desktop' || fromEnv === 'web') return fromEnv;
19
+ if (runtime === 'desktop' || runtime === 'web') return runtime;
20
+ return 'web';
21
+ };
22
+
23
+ const isDesktopDev = ({ env = {} } = {}) => {
24
+ const flag = typeof env.PICHAMBER_ELECTRON_DEV === 'string' ? env.PICHAMBER_ELECTRON_DEV.trim().toLowerCase() : '';
25
+ return flag === '1' || flag === 'true';
26
+ };
27
+
28
+ const isWebDev = ({ env = {} } = {}) => {
29
+ const kind = typeof env.PICHAMBER_SERVER_PROFILE_KIND === 'string' ? env.PICHAMBER_SERVER_PROFILE_KIND.trim().toLowerCase() : '';
30
+ if (kind === 'dev') return true;
31
+ const legacy = typeof env.PICHAMBER_DEV_SERVER === 'string' ? env.PICHAMBER_DEV_SERVER.trim().toLowerCase() : '';
32
+ return legacy === '1' || legacy === 'true';
33
+ };
34
+
35
+ /**
36
+ * Resolve the stable daemon profile for one PiChamber server.
37
+ *
38
+ * The profile key is stable across restarts of the same logical server and
39
+ * distinct across development, installed, desktop, and port-separated web
40
+ * servers. The server instance id is unique per launch and is used to prove
41
+ * which server currently owns a profile daemon.
42
+ */
43
+ export const resolveServerProfile = ({
44
+ env = process.env,
45
+ port,
46
+ runtime,
47
+ version,
48
+ serverInstanceId,
49
+ } = {}) => {
50
+ const safeEnv = env && typeof env === 'object' ? env : {};
51
+ const explicit = typeof safeEnv.PICHAMBER_SERVER_PROFILE === 'string'
52
+ ? safeEnv.PICHAMBER_SERVER_PROFILE.trim()
53
+ : '';
54
+ const effectiveRuntime = resolveRuntime({ env: safeEnv, runtime });
55
+ const development = effectiveRuntime === 'desktop'
56
+ ? isDesktopDev({ env: safeEnv })
57
+ : isWebDev({ env: safeEnv });
58
+ const instanceId = typeof serverInstanceId === 'string' && serverInstanceId.length > 0
59
+ ? serverInstanceId
60
+ : randomUUID();
61
+ const buildId = typeof version === 'string' && version.trim().length > 0 ? version.trim() : 'unknown';
62
+
63
+ if (explicit.length > 0) {
64
+ if (explicit.length > MAX_EXPLICIT_LENGTH) {
65
+ throw new Error('PICHAMBER_SERVER_PROFILE is too long.');
66
+ }
67
+ return {
68
+ profileKey: `custom-${hashSeed(`explicit:${explicit}`)}`,
69
+ profileLabel: explicit.slice(0, MAX_EXPLICIT_LENGTH),
70
+ serverInstanceId: instanceId,
71
+ runtime: effectiveRuntime,
72
+ source: 'custom',
73
+ development,
74
+ port: Number.isInteger(port) ? port : null,
75
+ buildId,
76
+ };
77
+ }
78
+
79
+ if (effectiveRuntime === 'desktop') {
80
+ const dev = development;
81
+ return {
82
+ profileKey: dev ? 'desktop-dev' : 'desktop',
83
+ profileLabel: dev ? 'desktop development' : 'desktop',
84
+ serverInstanceId: instanceId,
85
+ runtime: 'desktop',
86
+ source: dev ? 'desktop-dev' : 'desktop-installed',
87
+ development: dev,
88
+ port: Number.isInteger(port) ? port : null,
89
+ buildId,
90
+ };
91
+ }
92
+
93
+ const dev = development;
94
+ const portSegment = sanitizePortSegment(port);
95
+ const base = dev ? 'web-dev' : 'web';
96
+ const profileKey = portSegment ? `${base}-${portSegment}` : base;
97
+ const numericPort = Number.isInteger(port) ? port : null;
98
+ return {
99
+ profileKey,
100
+ profileLabel: numericPort === null
101
+ ? `${dev ? 'web development' : 'web'} server`
102
+ : `${dev ? 'web development' : 'web'} server on port ${numericPort}`,
103
+ serverInstanceId: instanceId,
104
+ runtime: 'web',
105
+ source: dev ? 'web-dev' : 'web-installed',
106
+ development: dev,
107
+ port: numericPort,
108
+ buildId,
109
+ };
110
+ };
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { isValidProfileKey, resolveServerProfile } from './server-profile.js';
4
+
5
+ describe('server profile', () => {
6
+ it('separates installed and development web servers on the same port', () => {
7
+ const installed = resolveServerProfile({ env: {}, port: 3000, runtime: 'web', version: '0.9.0' });
8
+ const dev = resolveServerProfile({
9
+ env: { PICHAMBER_SERVER_PROFILE_KIND: 'dev' },
10
+ port: 3000,
11
+ runtime: 'web',
12
+ version: '0.9.0',
13
+ });
14
+ expect(installed.profileKey).toBe('web-p3000');
15
+ expect(dev.profileKey).toBe('web-dev-p3000');
16
+ expect(installed.profileKey).not.toBe(dev.profileKey);
17
+ expect(installed.serverInstanceId).not.toBe(dev.serverInstanceId);
18
+ });
19
+
20
+ it('separates web servers on different ports', () => {
21
+ const a = resolveServerProfile({ env: {}, port: 3000 });
22
+ const b = resolveServerProfile({ env: {}, port: 3902 });
23
+ expect(a.profileKey).not.toBe(b.profileKey);
24
+ });
25
+
26
+ it('uses stable desktop profiles without ports', () => {
27
+ const installed = resolveServerProfile({ env: { PICHAMBER_RUNTIME: 'desktop' } });
28
+ const dev = resolveServerProfile({ env: { PICHAMBER_RUNTIME: 'desktop', PICHAMBER_ELECTRON_DEV: '1' } });
29
+ expect(installed.profileKey).toBe('desktop');
30
+ expect(dev.profileKey).toBe('desktop-dev');
31
+ });
32
+
33
+ it('hashes explicit profile overrides instead of using them as paths', () => {
34
+ const profile = resolveServerProfile({ env: { PICHAMBER_SERVER_PROFILE: '../../evil' }, port: 3000 });
35
+ expect(isValidProfileKey(profile.profileKey)).toBe(true);
36
+ expect(profile.profileKey).toMatch(/^custom-[0-9a-f]{16}$/);
37
+ expect(profile.profileKey).not.toContain('.');
38
+ });
39
+
40
+ it('preserves development replacement behavior for explicit profiles', () => {
41
+ const profile = resolveServerProfile({
42
+ env: {
43
+ PICHAMBER_SERVER_PROFILE: 'isolated-dev',
44
+ PICHAMBER_SERVER_PROFILE_KIND: 'dev',
45
+ },
46
+ port: 3000,
47
+ });
48
+ expect(profile.source).toBe('custom');
49
+ expect(profile.development).toBe(true);
50
+ });
51
+
52
+ it('keeps the profile key stable for one logical server across launches', () => {
53
+ const first = resolveServerProfile({ env: {}, port: 3000 });
54
+ const second = resolveServerProfile({ env: {}, port: 3000 });
55
+ expect(first.profileKey).toBe(second.profileKey);
56
+ expect(first.serverInstanceId).not.toBe(second.serverInstanceId);
57
+ });
58
+ });
@@ -1,6 +1,6 @@
1
1
  # Cloudflare Tunnel Service
2
2
 
3
- PiChamber exposes a PiChamber-hosted Cloudflare Tunnel that lets a browser or mobile client reach a private PiChamber server without opening inbound ports. The server dials outbound to Cloudflare with `cloudflared`; the public hostname then proxies to the local PiChamber HTTP endpoint.
3
+ PiChamber can manage a Cloudflare Tunnel that lets a browser or mobile client reach a private PiChamber server without opening inbound ports. The server dials outbound to Cloudflare with `cloudflared`; the public hostname then proxies to the local PiChamber HTTP endpoint.
4
4
 
5
5
  ## Modes
6
6
 
@@ -64,11 +64,10 @@ The PiChamber `pichamber.service` itself already supports both user (`~/.config/
64
64
  - `tunnel-service.test.js` covers validation (missing token/hostname, unsupported mode), status shape, secret redaction, and that `missing_dependency` is reported when `cloudflared` is absent.
65
65
  - Integration smoke against a real `cloudflared` binary is manual: install `cloudflared`, run `pichamber serve`, `curl /api/pichamber/tunnel/check`, start a quick tunnel, verify `status.url` appears and `curl -H "Host: $url-host"` reaches the server through the tunnel with `Authorization` still required.
66
66
 
67
- ## Cloudflare permissions for API-token flow
67
+ ## Cloudflare credentials
68
68
 
69
- If the operator wants PiChamber to create a tunnel automatically (rather than pasting a token), the Cloudflare API token needs:
70
-
71
- - `Zone:Read`, `DNS:Edit` on the zone that will host the hostname
72
- - `Account:Cloudflare Tunnel:Edit` (to create/list tunnels)
73
-
74
- PiChamber never asks for the Cloudflare account password. The manual token flow is the default; the API-token flow is an optional convenience that calls `https://api.cloudflare.com/client/v4/accounts/{accountId}/cfd_tunnel` with the scoped token. Secrets are still stored with `0600` and never returned in API responses.
69
+ PiChamber uses a manual Cloudflare tunnel token for `managed-remote` mode and
70
+ an existing `cloudflared` config for `managed-local` mode. It does not ask for a
71
+ Cloudflare account password and does not create tunnels through a Cloudflare
72
+ API-token wizard. Secrets are stored with `0600` and never returned in API
73
+ responses.
@@ -52,7 +52,14 @@ export const createTunnelService = ({
52
52
  const writeTokenStore = (token, hostname) => {
53
53
  try {
54
54
  fs.mkdirSync(path.dirname(tokenPath), { recursive: true, mode: 0o700 });
55
- fs.writeFileSync(tokenPath, JSON.stringify({ token, hostname }), { mode: 0o600 });
55
+ // Atomic replace so a concurrent server never reads a torn token.
56
+ const temporary = `${tokenPath}.tmp-${process.pid}-${Date.now()}`;
57
+ try {
58
+ fs.writeFileSync(temporary, JSON.stringify({ token, hostname }), { mode: 0o600 });
59
+ fs.renameSync(temporary, tokenPath);
60
+ } catch {
61
+ try { fs.rmSync(temporary, { force: true }); } catch {}
62
+ }
56
63
  } catch {}
57
64
  };
58
65
 
@@ -19,7 +19,7 @@ This module owns final-only composer dictation for web, Electron, hosted mobile,
19
19
  - `DELETE /api/stt/models/:modelId`
20
20
  - `WS /api/stt/ws`
21
21
 
22
- All routes use the existing `/api` authentication middleware. The WebSocket path is in both the URL-token and private-relay allowlists. Shared UI opens it through `openRuntimeWebSocket` after minting URL auth.
22
+ All routes use the existing `/api` authentication middleware. The WebSocket path is in both the URL-token and private-relay allowlists. Shared UI opens it through `openRuntimeWebSocket` with the token returned by that connection's URL-auth mint. A failed older connection cannot clear a newer shared token.
23
23
 
24
24
  Remote URL and API-key values live in `<PiChamber data>/stt/config.json` with owner-only permissions where the platform supports them. Status responses redact API keys. WebSocket start frames carry only a stored provider configuration ID. They never accept a URL or credential.
25
25
 
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
 
5
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
5
6
  import { DEFAULT_LOCAL_STT_MODEL, isLocalSttModelId } from './local/model-catalog.js';
6
7
 
7
8
  const DEFAULT_CONFIG = Object.freeze({ enabled: false, providerConfigId: 'local', language: '', localModelId: DEFAULT_LOCAL_STT_MODEL, providers: [] });
@@ -51,7 +52,7 @@ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rena
51
52
  catch (error) { if (error?.code === 'ENOENT') return { ...DEFAULT_CONFIG, providers: [] }; throw new Error('STT configuration is invalid'); }
52
53
  };
53
54
  const write = async (changes) => {
54
- const operation = mutation.then(async () => {
55
+ const operation = mutation.then(() => withCrossProcessLock(`${file}.lock`, async () => {
55
56
  const current = await read();
56
57
  let providers = current.providers;
57
58
  if (changes?.remoteProvider) {
@@ -73,7 +74,7 @@ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rena
73
74
  await fs.rm(temporary, { force: true }).catch(() => {});
74
75
  throw error;
75
76
  }
76
- });
77
+ }));
77
78
  mutation = operation.catch(() => {});
78
79
  return operation;
79
80
  };
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Ownership
4
4
 
5
- `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron uses this same runtime in-process; VS Code returns an explicit unsupported error.
5
+ `runtime.js` owns terminal identity, PTY processes, status, ordered output, bounded scrollback, WebSocket attachments, and lifecycle routes. `shells.js` discovers executable shell families and resolves the persisted shell ID without accepting command strings or arguments. Clients own tab arrangement and choose stable terminal IDs. Electron, hosted mobile, and Capacitor clients use this same server runtime through the shared authenticated transport.
6
6
 
7
7
  ## Protocol
8
8
 
@@ -10,7 +10,7 @@
10
10
 
11
11
  - `attach` registers a connection for one terminal. One socket may attach to many terminals.
12
12
  - Every attach and reconnect begins with an authoritative `snapshot` containing bounded history and the current sequence.
13
- - A current socket that closes or errors before its initial `open` invalidates its URL-scoped auth token before retrying, so retries mint a fresh token instead of backing off against a rejected upgrade. Hidden or offline clients wait 60 seconds and wake promptly on visibility/online recovery.
13
+ - A current socket that closes or errors before its initial `open` invalidates only the URL-scoped auth token used for that connection before retrying. A stale failure cannot clear a newer shared token minted for terminal, dictation, or events. Hidden or offline clients wait 60 seconds and wake promptly on visibility/online recovery.
14
14
  - `output`, `exit`, and `restarted` carry monotonically increasing per-terminal sequences. Output carries raw live bytes plus replay-safe bytes with terminal query exchanges removed.
15
15
  - Attach registers before capturing the snapshot, buffers concurrent events, drops events represented by the snapshot sequence, then enters live delivery.
16
16
  - `write` always includes the terminal ID; sockets never have mutable single-terminal binding state.
@@ -24,7 +24,7 @@ HTTP remains the authenticated command plane for create, resize, appearance upda
24
24
  - IDs are client-provided or generated with `randomUUID()`.
25
25
  - Concurrent creates for one ID are single-flight only when working directory and shell preference match. Existing IDs cannot be reused for another working directory.
26
26
  - Dimensions are bounded to 1-1000 columns and 1-500 rows; input is capped at 64 KiB.
27
- - A client may create before its renderer has mounted. It derives an initial size from the container and font metrics (falling back to 80x24 when unavailable), then sends a resize once Ghostty reports its final dimensions. This allows shell startup and renderer initialization to overlap.
27
+ - A client may create before its renderer has mounted. It derives an initial size from the container and font metrics (falling back to 80x24 when unavailable), then sends a resize once the renderer reports its final dimensions. This allows shell startup and renderer initialization to overlap.
28
28
  - PTY children explicitly clear `NODE_CHANNEL_FD`; daemon IPC descriptors are host-private and invalid after PTY descriptor cleanup.
29
29
  - PTY children also strip AppImage `ARGV0` (and other host-private shell vars such as `ELECTRON_RUN_AS_NODE`, `BASH_ENV`, `ENV`, `BASH_XTRACEFD`). An exported `ARGV0` makes zsh rewrite argv[0] for every external command, which breaks Python venv detection and other argv[0]/$0 consumers while leaving `/proc/self/exe` correct. On Linux, PTY spawn is wrapped with `env -u ARGV0` because `bun-pty` merges the native OS environ and would otherwise reintroduce `ARGV0` after a JS-only delete.
30
30
  - `GET /api/terminal/shells` reports shell IDs available on the active server using the same augmented PATH provided to spawned PTYs, plus whether each executable has a supported login-mode argument. `auto` preserves environment/platform fallback order; an explicit unavailable shell fails creation instead of silently running a different shell. Login mode is opt-in and uses only built-in arguments for known shells. Preference changes affect new sessions and explicit restarts, not running PTYs.
@@ -1,32 +1,52 @@
1
- # Tunnels Module Documentation
1
+ # Tunnels module documentation
2
2
 
3
3
  ## Purpose
4
+
4
5
  This module contains the shared tunnel support surface for PiChamber: provider
5
- capability metadata, tunnel types/normalization helpers, cross-platform
6
+ capability metadata, tunnel types and normalization helpers, cross-platform
6
7
  executable discovery, and dependency install-help metadata.
7
8
 
8
- The tunnel start implementation lives in
9
- `packages/web/server/lib/cloudflare-tunnel.js`; CLI orchestration lives in
10
- `packages/web/bin/lib/commands-tunnel.js`.
9
+ The Cloudflare provider implementation lives in
10
+ `packages/web/server/lib/cloudflare-tunnel.js`. The server-owned lifecycle is
11
+ `packages/web/server/lib/server/tunnel-service.js`, and CLI orchestration lives
12
+ in `packages/web/bin/lib/commands-tunnel.js`.
11
13
 
12
- > Wiring note: the previous service orchestration entrypoint
13
- > (`tunnels/index.js`, `createTunnelService`) was removed as dead code — no
14
- > runtime entrypoint registered tunnel routes or started a tunnel service.
15
- > The remaining files are consumed by the CLI capability surface and by the
16
- > Cloudflare tunnel provider implementation, not by a tunnel orchestration runtime.
14
+ `startWebUiServer` creates the tunnel service and registers its authenticated
15
+ routes. Tunnel startup is intentionally separate from `pichamber serve` startup:
16
+ use `pichamber tunnel start` after the server is running.
17
17
 
18
18
  ## Entrypoints and structure
19
- - `packages/web/server/lib/tunnels/executable-search.js`: cross-platform executable discovery, including Windows Store app aliases. Consumed by the tunnel providers and `packages/web/server/lib/workspace/host.js`.
20
- - `packages/web/server/lib/tunnels/install-help.js`: provider/platform install command metadata (`getTunnelDependencyInstallInfo`) for missing tunnel dependencies.
21
- - `packages/web/server/lib/tunnels/types.js`: shared tunnel provider, mode, and intent constants plus the shared `TunnelServiceError` class.
19
+
20
+ - `executable-search.js` discovers provider executables across platforms,
21
+ including Windows Store app aliases. The workspace host and tunnel providers
22
+ use it.
23
+ - `install-help.js` provides provider and platform install guidance for missing
24
+ dependencies.
25
+ - `types.js` defines provider, mode, intent, and `TunnelServiceError` values.
26
+ - `../cloudflare-tunnel.js` starts Cloudflare Quick, Managed Remote, and Managed
27
+ Local children and reports their public hostname.
28
+ - `../server/tunnel-service.js` owns one active child, token storage, public URL
29
+ state, and tunnel-auth registration.
22
30
 
23
31
  ## Public exports
32
+
24
33
  - `install-help.js` → `getTunnelDependencyInstallInfo(provider, platform)`
25
- - `executable-search.js` → `getExecutableSearchDirectories`, `createExecutableSearchEnv`, `findExecutableOnPath`, `resolveExecutableLaunchTarget`
26
- - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`, `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`, `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`, `TunnelServiceError`
34
+ - `executable-search.js` → `getExecutableSearchDirectories`,
35
+ `createExecutableSearchEnv`, `findExecutableOnPath`,
36
+ `resolveExecutableLaunchTarget`
37
+ - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`,
38
+ `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`,
39
+ `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`,
40
+ `TunnelServiceError`
27
41
 
28
42
  ## Consumers
29
- - `packages/web/bin/lib/cli-tunnel-capabilities.js`: provider capability metadata for CLI tunnel commands (Cloudflare only).
30
- - `packages/web/server/lib/cloudflare-tunnel.js`: executable discovery, install-help metadata, and provider constants.
31
- - `packages/web/server/lib/workspace/host.js`: executable discovery.
32
43
 
44
+ - `packages/web/bin/lib/cli-tunnel-capabilities.js` provides Cloudflare
45
+ capability metadata to the CLI.
46
+ - `packages/web/bin/lib/commands-tunnel.js` validates flags, presents prompts,
47
+ and calls the server lifecycle routes.
48
+ - `packages/web/server/index.js` creates the tunnel service and registers the
49
+ authenticated routes.
50
+ - `packages/ui/src/components/sections/pichamber/tunnel/` renders status,
51
+ setup, profiles, and one-time connect links.
52
+ - `packages/electron/main.mjs` reads tunnel status for native quit-risk UI.
@@ -369,8 +369,15 @@ function getOrCreateJwtSecret() {
369
369
  const secret = crypto.randomBytes(32).toString('hex');
370
370
  try {
371
371
  fs.mkdirSync(PICHAMBER_DATA_DIR, { recursive: true });
372
- fs.writeFileSync(JWT_SECRET_FILE, secret, { mode: 0o600 });
373
- console.log('[JWT] Generated and persisted new secret to', JWT_SECRET_FILE);
372
+ // Exclusive create: a concurrent server creating its first secret at the
373
+ // same instant re-reads the winner instead of overwriting it.
374
+ try {
375
+ fs.writeFileSync(JWT_SECRET_FILE, secret, { mode: 0o600, flag: 'wx' });
376
+ console.log('[JWT] Generated and persisted new secret to', JWT_SECRET_FILE);
377
+ } catch (error) {
378
+ if (error?.code !== 'EEXIST') throw error;
379
+ return new TextEncoder().encode(fs.readFileSync(JWT_SECRET_FILE, 'utf8').trim());
380
+ }
374
381
  } catch (e) {
375
382
  console.warn('[JWT] Failed to persist secret:', e.message);
376
383
  }
@@ -126,7 +126,15 @@ export const createUiPasskeys = ({
126
126
 
127
127
  const persistStore = (store) => {
128
128
  ensureStoreDirectory();
129
- fs.writeFileSync(storeFile, JSON.stringify(store, null, 2));
129
+ // Atomic replace so a concurrent server never reads a torn store.
130
+ const temporary = `${storeFile}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
131
+ try {
132
+ fs.writeFileSync(temporary, JSON.stringify(store, null, 2), { mode: 0o600 });
133
+ fs.renameSync(temporary, storeFile);
134
+ } catch (error) {
135
+ try { fs.rmSync(temporary, { force: true }); } catch {}
136
+ throw error;
137
+ }
130
138
  };
131
139
 
132
140
  const createEmptyStore = () => ({
@@ -1,18 +0,0 @@
1
- import{R as i,j as e}from"./vendor-react-B5Z1Mdn3.js";import{c as J,u as Q,w as Qe,n as Be}from"./index-ivrh3jfy.js";import{b3 as Ft,D as Nt,a as vt,I as U,b as Ct,b4 as Lt,b5 as Ne,a$ as Dt,aa as kt,ao as Ye,b6 as Je,aP as Rt,p as ve,U as Ce,j as Ze,Q as ne,t as et,aS as tt,aA as Et,b7 as At,b8 as Tt,aB as Mt,b9 as It,ba as $t,bb as Pt,bc as _t,k as Bt,bd as Wt,be as Ot,E as zt,F as Gt,G as Ht}from"./useAppFontEffects-8ZU-TTIW.js";import{d as nt,P as Ut,i as We,a as Oe,b as Vt}from"./gitStatusPredicates-DBGDfr1K.js";import{p as Kt}from"./VirtualizedFileDiff-DrxkW2WQ.js";import{v as qt,g as Xt}from"./contextFileOpenGuard-BRc5Z0g-.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-CBaS2Ank.js";import"./vendor-dnd-kit-core-CP8ck10N.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-B-Icjoj4.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-B_0wrsbo.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";import"./web-components-C9ENH49P.js";import"./computeVirtualFileMetrics-D0mQcleY.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-yJ9XpNMI.js";import"./vendor-pierre-theming-Dgp7B_O4.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./runtimeEndpointReset-DImT35Ug.js";import"./SessionUnreadDot-BxtTkvHB.js";import"./permissionStore-iKN1K2_x.js";import"./appThemeRegistry-gegrE2dq.js";import"./registerCustomTheme-DmolaWWZ.js";import"./isDiffPlainText-MmBA1REG.js";import"./vendor-diff-C3JhlQdm.js";function Qt(s,n=10){const t=[];let r;for(const l of s.split(`
2
- `)){const p=l.match(Ft);if(p!=null){r!=null&&(r.hunkLines.length>0&&(De(r,n,"trailing"),Ae(r,t)),r=void 0);const d=parseInt(p[3]),x=parseInt(p[1]),h=parseInt(p[4]??"1"),c=parseInt(p[2]??"1");isNaN(d)||isNaN(x)||isNaN(h)||isNaN(c)?t.push(l):r={additionStart:d,deletionStart:x,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(r==null){t.push(l);continue}if(l.startsWith(" "))r.contextLines.push(l);else if(l!==""){if(r.hunkLines.length>0&&r.contextLines.length>n*2){const d=r.contextLines.length-n*2,x=r.contextLines.slice(-n);De(r,n,"trailing");const{additionCount:h,deletionCount:c}=r;Ae(r,t),r={additionStart:r.additionStart+h+d,deletionStart:r.deletionStart+c+d,deletionCount:0,additionCount:0,contextLines:x,hunkLines:[]}}De(r,n,r.hunkLines.length===0?"leading":"before-change"),r.hunkLines.push(l),l.startsWith("+")?r.additionCount+=1:l.startsWith("-")&&(r.deletionCount+=1)}}r!=null&&r.hunkLines.length>0&&(De(r,n,"trailing"),Ae(r,t));const a=t.join(`
3
- `);return s.endsWith(`
4
- `)?`${a}
5
- `:a}function De(s,n,t){if(t==="leading"&&s.contextLines.length>n){const r=s.contextLines.length-n;s.contextLines.splice(0,r),s.additionStart+=r,s.deletionStart+=r}return t==="trailing"&&s.contextLines.length>n&&(s.contextLines.length=n),s.contextLines.length>0&&(s.hunkLines.push(...s.contextLines),s.additionCount+=s.contextLines.length,s.deletionCount+=s.contextLines.length,s.contextLines.length=0),s}function Ae(s,n){n.push(`@@ -${ze(s.deletionStart,s.deletionCount)} +${ze(s.additionStart,s.additionCount)} @@`),n.push(...s.hunkLines)}function ze(s,n){return n===1?`${s}`:`${s},${n}`}const Yt=i.memo(function({scope:n,isGitRepo:t,branchAvailable:r,allCount:a,workingCount:l,stagedCount:p,turnCount:d,branchCount:x,onScopeChange:h}){const[c,f]=i.useState(!1),b=n==="all"?a:n==="staged"?p:n==="turn"?d:n==="branch"?x:l,L=n==="staged"?"Staged":n==="turn"?"Last turn":n==="branch"?"Branch":n==="all"?"All":"Changed";return e.jsxs(Nt,{open:c,onOpenChange:f,children:[e.jsx(vt,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":"Select change mode",children:[e.jsxs("span",{className:"whitespace-nowrap",children:[L,e.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",b]})]}),e.jsx(U,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"})]})}),e.jsx(Ct,{align:"start",className:"w-40",children:e.jsxs(Lt,{value:n,onValueChange:u=>{(u==="all"||u==="working"||u==="staged"||u==="turn"||u==="branch")&&(h?.(u),f(!1))},children:[t!==!1?e.jsx(Ne,{value:"all",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"All"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:a})]})}):null,t!==!1?e.jsx(Ne,{value:"working",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Changed"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:l})]})}):null,t!==!1?e.jsx(Ne,{value:"staged",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Staged"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:p})]})}):null,e.jsx(Ne,{value:"turn",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Last turn"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:d})]})}),r?e.jsx(Ne,{value:"branch",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Branch"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:x})]})}):null]})})]})}),Jt=64,Zt=3,ae=new Map,en=(s,n,t=Zt)=>{const r=`${s}\0${t}\0${n}`,a=ae.get(r);if(a)return ae.delete(r),ae.set(r,a),a;const l=nn(n),p=l?Dt(Qt(n,t),{oldFile:{name:s,contents:l.before},newFile:{name:s,contents:l.after}})??He(s):kt(tn(s,n))[0]?.files[0]??He(s);for(ae.set(r,p);ae.size>Jt;){const d=ae.keys().next().value;if(!d)break;ae.delete(d)}return p},tn=(s,n)=>!n.trim()||n.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(n)?n:`Index: ${s}
6
- ===================================================================
7
- --- ${s}
8
- +++ ${s}
9
- ${n}`,nn=s=>{if(!s.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(s))return;const n=[...s.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(n.length!==1)return;const t=n[0],r=Number.parseInt(t[1]??"",10),a=Number.parseInt(t[2]??"",10);if(r>1||a>1||!Number.isFinite(r)||!Number.isFinite(a))return;const l=(t.index??0)+t[0].length,p=s.slice(l),d=[],x=[];let h;for(const c of p.split(/\r?\n/)){if(c.startsWith("diff --git ")||c.startsWith("@@ "))break;if(c.startsWith("\\")){if(h==="-"||h===" "){const f=d.at(-1);f&&(f.newline=!1)}if(h==="+"||h===" "){const f=x.at(-1);f&&(f.newline=!1)}continue}if(c.startsWith("-")){d.push({text:c.slice(1),newline:!0}),h="-";continue}if(c.startsWith("+")){x.push({text:c.slice(1),newline:!0}),h="+";continue}c.startsWith(" ")&&(d.push({text:c.slice(1),newline:!0}),x.push({text:c.slice(1),newline:!0}),h=" ")}return{before:Ge(d),after:Ge(x)}},Ge=s=>s.map(n=>n.text+(n.newline?`
10
- `:"")).join(""),He=s=>Kt({name:s,contents:""},{name:s,contents:""}),sn=s=>/^Binary files .+ differ$/m.test(s)||/^GIT binary patch$/m.test(s),Me=(s,n,t)=>sn(n)?{original:"",modified:"",isBinary:!0,patch:n,contextMode:t}:{original:"",modified:"",patch:n,fileDiff:en(s,n),contextMode:t},st=(s,n,t)=>{const r=s??0,a=n??0;return!r&&!a?null:e.jsxs("span",{className:J("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",t?.className),children:[r?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",r]}):null,a?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a]}):null]})},rn=i.memo(function({changedFiles:n,selectedFile:t,onSelectFile:r}){return n.length===0?null:e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:n.map(a=>{const l=nt(a),p=t===a.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>r(a.path),className:J("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",p?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[e.jsx(Je,{filePath:a.path,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:l.color},title:l.description,"aria-label":l.description,children:l.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:a.path,children:a.path}),st(a.insertions,a.deletions)]})},a.path)})})})}),on=i.memo(function(){return e.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Content of this file cannot be viewed."})})}),an=i.memo(function({filePath:n,diff:t,renderSideBySide:r}){const a=t.original.length>0,l=t.modified.length>0,p=r?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",d=r?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:p,children:[a&&e.jsxs("div",{className:d,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:t.original,alt:`Original: ${n}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),l&&e.jsxs("div",{className:d,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a?"Modified":"New"}),e.jsx("img",{src:t.modified,alt:`Modified: ${n}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),ln=i.memo(function({filePath:n,diff:t,renderSideBySide:r,wrapLines:a}){const l=i.useMemo(()=>Rt(n)||"text",[n]);return t.isBinary?e.jsx(on,{}):ve(n)?e.jsx(an,{filePath:n,diff:t,renderSideBySide:r}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(Ut,{original:t.original,modified:t.modified,fileDiff:t.fileDiff,language:l,fileName:n,renderSideBySide:r,wrapLines:a,layout:"inline"})})}),Te=({label:s,icon:n,loading:t,disabled:r,tone:a,onClick:l})=>e.jsx(Ce,{variant:"ghost",size:"sm",className:J("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",a==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",a==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]"),disabled:r,title:s,"aria-label":s,onClick:p=>{p.stopPropagation(),l()},children:t?e.jsx(U,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(U,{name:n,className:n==="add"?"size-4":"size-3.5"})}),cn=i.memo(function({filePath:n,staged:t,busyAction:r,disabled:a,onAction:l}){return e.jsx("div",{className:"flex items-center gap-0.5 rounded-full border border-[var(--interactive-border)]/45 bg-[var(--surface-background)]/95 px-1 py-0.5 shadow-sm backdrop-blur-md",children:t?e.jsx(Te,{label:`Unstage ${n}`,icon:"arrow-go-back",loading:r==="unstage",disabled:a,onClick:()=>l("unstage")}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{label:`Revert changes in ${n}`,icon:"arrow-go-back",loading:r==="discard",disabled:a,tone:"failure",onClick:()=>l("discard")}),e.jsx(Te,{label:`Stage ${n}`,icon:"add",loading:r==="stage",disabled:a,tone:"success",onClick:()=>l("stage")})]})})}),rt=3,un=1e6,dn=15e3,Ue=500,fn=i.memo(function({directory:n,file:t,layout:r,wrapLines:a,isSelected:l,isExpanded:p,isMounted:d,onSelect:x,onExpandedChange:h,registerSectionRef:c,showOpenInEditorAction:f=!1,isOpeningInEditor:b=!1,onOpenInEditor:L,staged:u=!1,showFileActions:C=!0,loadFullFiles:g=!1,initialDiffData:R=null}){const{git:I}=Ze(),k=ne(i.useCallback(m=>m.directories.get(n)?.diffCache.get(t.path)??null,[n,t.path])),V=ne(m=>m.setDiff),E=ne(m=>m.fetchStatus),y=Q(m=>m.setDiffFileLayout),[w,j]=i.useState(0),[A,F]=i.useState(null),[q,N]=i.useState(!1),[_,B]=i.useState(null),[Z,se]=i.useState(!1),[P,le]=i.useState(null),[T,ee]=i.useState(null),W=i.useRef(null),ce=i.useRef(null),O=i.useMemo(()=>nt(t),[t]),re=r==="side-by-side",Y=g?"full":"patch",te=`${t.index}:${t.working_dir}:${t.insertions}:${t.deletions}`,z=i.useMemo(()=>R||(u?T:P||(k?{original:k.original,modified:k.modified,isBinary:k.isBinary,contextMode:"full"}:null)),[k,R,P,u,T]),ue=z?.contextMode===Y,ye=i.useCallback(m=>{ce.current=m,c(t.path,m)},[t.path,c]),de=i.useCallback(m=>{h(t.path,m)},[t.path,h]),fe=i.useCallback(()=>{x(t.path)},[t.path,x]);i.useEffect(()=>{u?ee(null):le(null),F(null),W.current=null},[te,u]),i.useEffect(()=>{if(!p||!d)return;if(!n||R||z&&ue){W.current=null,N(!1);return}const m=`${n}::${t.path}::${u?"staged":"unstaged"}::${te}::${Y}::${w}`;if(W.current===m)return;W.current=m,F(null),N(!0);let D=!1;const $=Qe(),je=g?un:rt,me=ve(t.path)?I.getGitFileDiff(n,{path:t.path,staged:u}):I.getGitDiff(n,{path:t.path,staged:u,contextLines:je}),ie=dn,ke=new Promise((K,G)=>{setTimeout(()=>G(new Error(`Timed out after ${ie}ms`)),ie)});return Promise.race([me,ke]).then(K=>{if(!D){if("diff"in K){const G=Me(t.path,K.diff,Y);u?ee(G):le(G)}else{const G={original:K.original??"",modified:K.modified??"",isBinary:K.isBinary,contextMode:"full"};u?ee(G):V(n,t.path,G,$)}N(!1)}}).catch(K=>{if(D)return;const G=K instanceof Error?K.message:String(K);F(G),N(!1)}),()=>{D=!0,W.current===m&&(W.current=null)}},[Y,z,ue,w,n,t.path,te,I,R,p,d,g,V,u]);const pe=i.useCallback(()=>{de(!p),fe()},[de,fe,p]),we=i.useCallback(async m=>{if(!(!n||_!==null)){B(m);try{m==="stage"?await I.stageGitFile(n,t.path):m==="unstage"?await I.unstageGitFile(n,t.path):await I.revertGitFile(n,t.path,{scope:"working"}),j(D=>D+1),await E(n,I)}catch(D){const $=m==="unstage"?"Failed to unstage changes":m==="stage"?"Failed to stage changes":"Failed to revert changes";et.error(D instanceof Error?D.message:$)}finally{B(D=>D===m?null:D)}}},[n,E,t.path,_,I]);return e.jsxs("div",{ref:ye,className:J("scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0"),children:[e.jsx("div",{className:J("z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80","sticky top-0"),children:e.jsxs("div",{role:"button",tabIndex:0,onClick:pe,onKeyDown:m=>{m.target===m.currentTarget&&(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),pe())},className:J("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",l?"bg-[var(--interactive-selection)]/35":null),children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:p?e.jsx(U,{name:"arrow-down-s",className:"size-4"}):e.jsx(U,{name:"arrow-right-s",className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:O.color},title:O.description,"aria-label":O.description,children:O.code}),e.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:t.path,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Je,{filePath:t.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const m=t.path.lastIndexOf("/");if(m===-1)return e.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:t.path});const D=t.path.slice(0,m),$=t.path.slice(m+1);return e.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[e.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:D}),e.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("span",{className:"text-foreground",children:$})]})]})})()]})})]}),e.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[st(t.insertions,t.deletions),f&&L?e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:"Open this file in editor at change",onClick:m=>{m.stopPropagation(),L(t.path,z)},disabled:b,children:b?e.jsx(U,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(U,{name:"edit",className:"size-3.5"})}):null,e.jsx(tt,{mode:re?"side-by-side":"unified",onModeChange:m=>{const D=m==="side-by-side"?"side-by-side":"inline";y(t.path,D)},className:"opacity-70"})]})]})}),p&&e.jsxs("div",{className:"relative overflow-hidden bg-background",children:[!d&&!A?e.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,A?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:A}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>j(m=>m+1),children:"Retry"})]}):null,d&&q&&!z&&!A?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading diff..."]}):null,d&&z&&!Z&&t.insertions+t.deletions>Ue?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:`Large diff (${t.insertions+t.deletions} changed lines)`}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Rendering may be slow. You can still view the diff by clicking below."}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>se(!0),children:"Render anyway"})]}):null,d&&z&&(Z||t.insertions+t.deletions<=Ue)?e.jsxs(e.Fragment,{children:[e.jsx(ln,{filePath:t.path,diff:z,renderSideBySide:re,wrapLines:a}),C?e.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:e.jsx("div",{className:"pointer-events-auto",children:e.jsx(cn,{filePath:t.path,staged:u,busyAction:_,disabled:_!==null,onAction:we})})}):null]}):null]})]})}),pn=1100,Ve=300,mn=s=>s<=6?s:s<=12?6:s<=25?4:2,hn=(s,n)=>Et(s,n),Ke=(s,n)=>{const t=s.split(`
11
- `),r=n.split(`
12
- `),a=Math.min(t.length,r.length);for(let l=0;l<a;l+=1)if(t[l]!==r[l])return l+1;return r.length>t.length?t.length+1:t.length>r.length?Math.max(1,r.length):1},gn=s=>Array.isArray(s)?s.filter(n=>!n||typeof n!="object"?!1:typeof n.file=="string"):[],xn=s=>s.split(/^diff --git /m).slice(1).flatMap(t=>{const[r=""]=t.split(`
13
- `,1),a=r.lastIndexOf(" b/");if(a<=2)return[];const l=r.slice(2,a),p=r.slice(a+3).trim(),d=`diff --git ${t}`,x=d.includes(`
14
- new file mode `)?"added":d.includes(`
15
- deleted file mode `)?"deleted":d.includes(`
16
- rename from `)?"renamed":"modified";let h=0,c=0;for(const f of d.split(`
17
- `))f.startsWith("+")&&!f.startsWith("+++")&&(h+=1),f.startsWith("-")&&!f.startsWith("---")&&(c+=1);return[{file:x==="deleted"?l:p,status:x,additions:h,deletions:c,patch:d}]}),bn=s=>s==="added"?"A":s==="deleted"?"D":"M";function yn({activeDiffScope:s,effectiveDirectory:n,branchBase:t,branchHead:r,git:a,sessionMessageRecords:l}){const[p,d]=i.useState([]),[x,h]=i.useState(null),[c,f]=i.useState(!1),b=i.useMemo(()=>{const C=At(l,{showTextJustificationActivity:!1,showTurnChangedFiles:!0,mergeHiddenUserTurns:!0});for(let g=C.turns.length-1;g>=0;g-=1){const R=C.turns[g];if(!R)continue;const I=R.activityParts.map(E=>E.part).filter(E=>E.type==="tool"),k=Tt(I);if(k.length>0)return k.map(E=>({file:E.path,status:"modified",additions:E.additions,deletions:E.deletions,patch:E.patch}));const V=gn(R.userMessage.info?.summary?.diffs);if(V.length>0)return V}return[]},[l]);i.useEffect(()=>{if(s!=="branch"||!n||!t||!r||!a.getGitRangeDiff){d([]),h(null),f(!1);return}let C=!1;return f(!0),h(null),a.getGitRangeDiff(n,{base:t,head:r,contextLines:rt}).then(g=>{C||(d(xn(g.diff??"")),f(!1))}).catch(g=>{C||(d([]),f(!1),h(g instanceof Error?g.message:String(g)))}),()=>{C=!0}},[s,t,r,n,a]);const L=i.useMemo(()=>{const C=new Map;for(const g of b)if(g.file){if(typeof g.patch=="string"){C.set(g.file,Me(g.file,g.patch,"patch"));continue}C.set(g.file,{original:g.before??"",modified:g.after??"",contextMode:"full"})}return C},[b]),u=i.useMemo(()=>{const C=new Map;for(const g of p)!g.file||typeof g.patch!="string"||C.set(g.file,Me(g.file,g.patch,"patch"));return C},[p]);return{branchDiffs:p,branchDiffError:x,branchDiffLoading:c,lastTurnDiffs:b,lastTurnDiffData:L,branchDiffData:u}}const qe=(s,n)=>{if(n.length===0)return null;let t=null,r=null;for(const l of n)l.top<=s?(!t||l.top>t.top)&&(t=l):(!r||l.top<r.top)&&(r=l);const a=t??r;return a?{path:a.path,topOffset:a.top-s}:null},wn=(s,n,t,r)=>Math.min(Math.max(0,r),Math.max(0,s+t-n));function jn({pinSelectedFileHeaderToTopOnNavigate:s,scrollRequestNonce:n,changedFiles:t,expandedFiles:r,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const p=i.useRef(null),d=i.useRef(new Map),[x,h]=i.useState(null),c=i.useRef(null),f=i.useRef(null),b=i.useRef(!1),L=i.useRef(null),u=i.useRef(null),C=i.useRef(null),g=i.useCallback(()=>{const y=p.current;if(!y)return null;const w=y.getBoundingClientRect().top,j=[];for(const[A,F]of d.current)F&&j.push({path:A,top:F.getBoundingClientRect().top});return qe(w,j)},[]),R=i.useCallback(()=>{c.current=null,b.current=!1,h(null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null)},[]),I=i.useCallback(()=>{L.current=null;const y=p.current;if(!y)return;const w=y.getBoundingClientRect(),j=w.top-Ve,A=w.bottom+Ve,F={},q=[];for(const[N,_]of d.current){if(!_)continue;const B=_.getBoundingClientRect();q.push({path:N,top:B.top}),r.has(N)&&(B.bottom<j||B.top>A||(F[N]=!0))}u.current=qe(w.top,q),a(N=>{let _=!1;const B=new Set(N);for(const Z of Object.keys(F))B.has(Z)||(B.add(Z),_=!0);return _?B:N})},[r,a]),k=i.useCallback(()=>{typeof window>"u"||L.current===null&&(L.current=window.requestAnimationFrame(I))},[I]);i.useEffect(()=>{const y=p.current;if(y)return k(),y.addEventListener("scroll",k,{passive:!0}),window.addEventListener("resize",k),()=>{y.removeEventListener("scroll",k),window.removeEventListener("resize",k),L.current!==null&&(window.cancelAnimationFrame(L.current),L.current=null)}},[t,r,k]),i.useLayoutEffect(()=>{const y=C.current;if(!y)return;C.current=null;const w=p.current,j=d.current.get(y.path);if(!w||!j)return;const A=w.getBoundingClientRect().top,F=j.getBoundingClientRect().top-A;w.scrollTop=wn(w.scrollTop,y.topOffset,F,w.scrollHeight-w.clientHeight),u.current=y},[l]);const V=i.useCallback((y,w)=>{const j=d.current;w?j.set(y,w):j.delete(y),k()},[k]),E=i.useCallback(y=>{const w=d.current.get(y),j=p.current;if(!w||!j)return!1;const A=w.getBoundingClientRect().top-j.getBoundingClientRect().top;return j.scrollTo({top:j.scrollTop+A,behavior:"auto"}),!0},[]);return i.useEffect(()=>{if(!c.current)return;let w=0;const j=20;let A=!1;const F=(N=!0)=>{A||(A=!0,c.current=null,b.current=!1,N&&h(null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null))},q=()=>{if(A){f.current=null;return}const N=c.current;if(!N){F(),f.current=null;return}if(!E(N)){w+=1,w<j?f.current=window.requestAnimationFrame(q):(F(),f.current=null);return}if(s&&b.current){h(N),F(!1);return}F()};return f.current=window.requestAnimationFrame(q),()=>{A=!0,f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null)}},[s,n,E]),{diffScrollRef:p,fileSectionRefs:d,pinnedStackedTarget:x,pendingScrollTargetRef:c,shouldPinAfterAlignRef:b,pendingScrollAnchorRestoreRef:C,lastScrollAnchorRef:u,captureScrollAnchor:g,cancelPendingScrollAlignment:R,queueVisibleStackedFilesSync:k,registerSectionRef:V,scrollToFile:E}}const Xe=s=>{if(!s)return null;const n=s.split(`
18
- `);let t=null;for(const r of n){const a=r.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(a){const l=Number.parseInt(a[1]??"",10);t=Number.isFinite(l)&&l>=1?l:null;continue}if(t!==null){if(r.startsWith(" ")){t+=1;continue}if(r.startsWith("+"))return t;if(r.startsWith("-"))return Math.max(1,t)}}return null};function Sn({effectiveDirectory:s,activeDiffStaged:n,git:t,files:r,setDiff:a,openContextFileAtLine:l}){const[p,d]=i.useState(null),x=i.useCallback(async(h,c)=>{if(!s||!h)return;d(h);const f=Qe();try{let b=null;if(c?.patch&&!c.isBinary&&!ve(h)?b=Xe(c.patch):c&&c.contextMode==="full"&&!c.isBinary&&!ve(h)&&(b=Ke(c.original,c.modified)),b===null)try{const R=await t.getGitDiff(s,{path:h,staged:n,contextLines:3});b=Xe(R.diff)}catch{b=null}let L=c;if(b===null||!L){const R=await t.getGitFileDiff(s,{path:h,staged:n});L={original:R.original??"",modified:R.modified??"",isBinary:R.isBinary},n||a(s,h,L,f??void 0)}const u=b??(L.isBinary||ve(h)?1:Ke(L.original,L.modified)),C=hn(s,h),g=await qt(r,C,{directory:s});if(!g.ok){et.error(Xt(g.reason));return}l(s,C,u,1)}finally{d(b=>b===h?null:b)}},[n,s,r,t,l,a]);return{openingEditorFilePath:p,openFileInEditorAtChange:x}}function Fn(s){const{hideStackedFileSidebar:n=!1,stackedDefaultCollapsedAll:t=!1,pinSelectedFileHeaderToTopOnNavigate:r=!1,diffScope:a="all",branchBase:l=null,branchHead:p=null,targetFilePath:d=null}=s,{git:x,files:h}=Ze(),c=Mt(),{screenWidth:f,isMobile:b}=It(),L=$t(c??null),u=Pt(c??null),C=_t(c??null),g=ne(o=>o.setActiveDirectory),R=ne(o=>o.ensureStatus),I=ne(o=>o.fetchStatus),k=ne(o=>o.clearDiffCache),V=ne(o=>o.setDiff),[E,y]=i.useState(null),[w,j]=i.useState(!1),[A,F]=i.useState(()=>new Set),[q,N]=i.useState(()=>new Set),[_,B]=i.useState(!1),[Z,se]=i.useState(0),[P,le]=i.useState(()=>new Map),[T,ee]=i.useState(a);i.useEffect(()=>{ee(a)},[a]);const W=Q(o=>o.pendingDiffFile),ce=Q(o=>o.pendingDiffStaged),O=Q(o=>o.pendingDiffScope),re=Q(o=>o.setPendingDiffFile),Y=Q(o=>o.diffLayoutPreference),te=Q(o=>o.diffFileLayout),z=Q(o=>o.setDiffFileLayout),ue=Q(o=>o.diffWrapLines),ye=Q(o=>o.setDiffWrapLines),de=Q(o=>o.openContextFileAtLine),fe=Bt(o=>o.currentSessionId),pe=Wt(fe??""),we=ue,m=T==="staged"?!0:T==="working"?!1:null,D=m??w,$=b||f<=768,je=!n&&!$&&f>=1024,me=i.useRef(null),{branchDiffs:ie,branchDiffError:ke,branchDiffLoading:K,lastTurnDiffs:G,lastTurnDiffData:it,branchDiffData:ot}=yn({activeDiffScope:T,effectiveDirectory:c,branchBase:l,branchHead:p,git:x,sessionMessageRecords:pe}),H=i.useMemo(()=>{if(T==="turn"||T==="branch")return(T==="branch"?ie:G).map(M=>({path:M.file??"",index:"",working_dir:bn(M.status),insertions:M.additions??0,deletions:M.deletions??0,isNew:M.status==="added"})).filter(M=>M.path).sort((M,X)=>M.path.localeCompare(X.path));if(!u?.files)return[];const o=u.diffStats??{},v=T==="staged"?We:T==="working"?Oe:()=>!0;return u.files.filter(v).map(S=>({...S,insertions:o[S.path]?.insertions??0,deletions:o[S.path]?.deletions??0,isNew:Vt(S)})).sort((S,M)=>S.path.localeCompare(M.path))},[T,ie,G,u]),at=i.useMemo(()=>u?.files?u.files.filter(Oe).length:0,[u]),lt=i.useMemo(()=>u?.files?u.files.filter(We).length:0,[u]),ct=G.length,ut=u?.files?.length??0,dt=ie.length,{diffScrollRef:ft,pinnedStackedTarget:pt,pendingScrollTargetRef:he,shouldPinAfterAlignRef:ge,pendingScrollAnchorRestoreRef:Ie,lastScrollAnchorRef:$e,captureScrollAnchor:Pe,cancelPendingScrollAlignment:xe,queueVisibleStackedFilesSync:Le,registerSectionRef:mt,scrollToFile:_e}=jn({pinSelectedFileHeaderToTopOnNavigate:r,scrollRequestNonce:Z,changedFiles:H,expandedFiles:A,setMountedStackedFiles:N,fileDiffRefreshNonce:P}),be=i.useCallback(o=>{F(v=>{if(v.has(o))return v;const S=new Set(v);return S.add(o),S})},[]),Re=i.useMemo(()=>H.map(o=>o.path).join("\0"),[H]);i.useEffect(()=>{const o=Re?Re.split("\0"):[],v=new Set(o),S=`${c??""}:${T}:${t?"collapsed":"default"}`,M=me.current!==S;me.current=S,F(X=>{if(M){const oe=t?0:mn(o.length);return new Set(o.slice(0,oe))}let Se=!1;const Fe=new Set;for(const oe of X){if(!v.has(oe)){Se=!0;continue}Fe.add(oe)}return Se?Fe:X}),N(X=>{if(M)return new Set;let Se=!1;const Fe=new Set;for(const oe of X){if(!v.has(oe)){Se=!0;continue}Fe.add(oe)}return Se?Fe:X})},[T,Re,c,N,t]);const Ee=i.useCallback(o=>{const v=te[o.path];if(v)return v;if(Y==="inline")return"inline";if(Y==="side-by-side")return"side-by-side";const S=f<pn;return o.isNew||S?"inline":"side-by-side"},[te,Y,f]),ht=i.useMemo(()=>H.length===0?null:H.every(o=>Ee(o)==="side-by-side")?"side-by-side":"inline",[H,Ee]);i.useEffect(()=>{c&&(g(c),R(c,x))},[c,g,R,x]),i.useEffect(()=>{if(c)return Ot.onGitRefreshHint(o=>{Be(o.directory)===Be(c)&&(o.paths?.length&&(Ie.current=Pe()??$e.current,k(c,o.paths),le(v=>{const S=new Map(v);for(const M of o.paths??[])S.set(M,(S.get(M)??0)+1);return S})),I(c,x,{silent:!0}))})},[Pe,k,c,I,x,$e,Ie]),i.useEffect(()=>{T!=="all"&&!O||W&&(O&&ee(O),y(W),j(O==="staged"||!O&&ce),re(null),ge.current=!0,he.current=W,be(W),se(o=>o+1))},[T,be,W,O,ce,he,re,ge]),i.useEffect(()=>{if(T==="all")return;const o=d?.trim();o&&(y(o),j(T==="staged"),ge.current=!0,he.current=o,be(o),se(v=>v+1))},[T,be,he,ge,d]),i.useEffect(()=>{if(!E)return;H.some(v=>v.path===E)||(y(null),j(!1))},[H,E]);const gt=i.useCallback((o,v)=>{xe(),F(S=>{const M=S.has(o);if(v===M)return S;const X=new Set(S);return v?X.add(o):X.delete(o),X}),v||N(S=>{if(!S.has(o))return S;const M=new Set(S);return M.delete(o),M}),Le()},[xe,Le,N]),xt=i.useCallback(()=>{xe(),F(o=>o.size>0?new Set:new Set(H.map(v=>v.path))),N(new Set),Le()},[xe,H,Le,N]),bt=i.useCallback(o=>{},[]),yt=i.useCallback(o=>{xe(),y(o),j(!1),ge.current=!0,he.current=o,be(o),se(v=>v+1),_e(o)},[xe,be,he,_e,ge]),wt=i.useCallback(o=>{const v=o==="side-by-side"?"side-by-side":"inline";H.forEach(S=>{z(S.path,v)})},[H,z]),{openingEditorFilePath:jt,openFileInEditorAtChange:St}=Sn({effectiveDirectory:c,activeDiffStaged:D,git:x,files:h,setDiff:V,openContextFileAtLine:de});return{git:x,files:h,effectiveDirectory:c,screenWidth:f,isMobile:b,isGitRepo:L,status:u,isLoadingStatus:C,activeDiffScope:T,setActiveDiffScope:ee,branchDiffs:ie,branchDiffError:ke,branchDiffLoading:K,diffWrapLines:we,setDiffWrapLines:ye,forcedStaged:m,displayFileStaged:w,displayFile:E,pinnedStackedTarget:pt,expandedFiles:A,mountedStackedFiles:q,loadFullFiles:_,setLoadFullFiles:B,fileDiffRefreshNonce:P,showFileSidebar:je,diffScrollRef:ft,lastTurnDiffData:it,branchDiffData:ot,changedFiles:H,workingFileCount:at,stagedFileCount:lt,turnFileCount:ct,allFileCount:ut,branchFileCount:dt,currentLayoutForAllFiles:ht,openingEditorFilePath:jt,registerSectionRef:mt,handleStackedEntryExpandedChange:gt,handleExpandOrCollapseAll:xt,handleSelectFile:bt,handleSelectFileAndScroll:yt,handleHeaderLayoutChange:wt,openFileInEditorAtChange:St,getLayoutForFile:Ee}}const Er=({hideStackedFileSidebar:s=!1,stackedDefaultCollapsedAll:n=!1,pinSelectedFileHeaderToTopOnNavigate:t=!1,showOpenInEditorAction:r=!1,diffScope:a="all",onDiffScopeChange:l,branchBase:p=null,branchHead:d=null,targetFilePath:x=null,flushContent:h=!1})=>{const{effectiveDirectory:c,isGitRepo:f,status:b,isLoadingStatus:L,activeDiffScope:u,setActiveDiffScope:C,branchDiffError:g,branchDiffLoading:R,diffWrapLines:I,setDiffWrapLines:k,forcedStaged:V,displayFileStaged:E,displayFile:y,pinnedStackedTarget:w,expandedFiles:j,mountedStackedFiles:A,loadFullFiles:F,setLoadFullFiles:q,fileDiffRefreshNonce:N,showFileSidebar:_,diffScrollRef:B,lastTurnDiffData:Z,branchDiffData:se,changedFiles:P,workingFileCount:le,stagedFileCount:T,turnFileCount:ee,allFileCount:W,branchFileCount:ce,currentLayoutForAllFiles:O,openingEditorFilePath:re,registerSectionRef:Y,handleStackedEntryExpandedChange:te,handleExpandOrCollapseAll:z,handleSelectFile:ue,handleSelectFileAndScroll:ye,handleHeaderLayoutChange:de,openFileInEditorAtChange:fe,getLayoutForFile:pe}=Fn({hideStackedFileSidebar:s,stackedDefaultCollapsedAll:n,pinSelectedFileHeaderToTopOnNavigate:t,diffScope:a,branchBase:p,branchHead:d,targetFilePath:x}),we=()=>{if(!c)return null;const D=$=>V!==null?V:E&&$===y;return e.jsxs("div",{className:J("flex min-w-0 flex-1 min-h-0 h-full",h?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[_&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:P.length})]}),e.jsx(rn,{changedFiles:P,selectedFile:null,onSelectFile:ye})]}),e.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:e.jsx(Ye,{ref:B,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:e.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:P.map($=>e.jsx(fn,{directory:c,file:$,layout:pe($),wrapLines:I,isSelected:!1,isExpanded:j.has($.path),isMounted:A.has($.path)||$.path===w,onSelect:ue,onExpandedChange:te,registerSectionRef:Y,showOpenInEditorAction:r&&u!=="turn"&&u!=="branch",isOpeningInEditor:re===$.path,onOpenInEditor:(je,me)=>{fe(je,me)},staged:D($.path),showFileActions:u!=="turn"&&u!=="branch",loadFullFiles:F,initialDiffData:u==="turn"?Z.get($.path)??null:u==="branch"?se.get($.path)??null:null},`${$.path}:${N.get($.path)??0}`))})})})]})},m=()=>c?u!=="turn"&&L&&!b?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):u!=="turn"&&u!=="branch"&&f===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):u==="branch"&&R?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):u==="branch"&&g?e.jsx("div",{className:"flex flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground",children:`Failed to load branch changes: ${g}`}):P.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:u==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):we():e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(f!==!1||u==="turn")&&(u==="all"||u==="working"||u==="staged"||u==="turn"||u==="branch")?e.jsx(Yt,{scope:u,isGitRepo:f,branchAvailable:!!(p&&d),allCount:W,workingCount:le,stagedCount:T,turnCount:ee,branchCount:ce,onScopeChange:D=>{C(D),l?.(D)}}):e.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:L&&!b?"Loading changes...":P.length===1?`${P.length} file changed`:`${P.length} files changed`})}),P.length>0&&e.jsxs(Ce,{variant:"ghost",size:"sm",onClick:z,className:J("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:j.size>0?"Collapse all":"Expand all",children:[e.jsx(U,{name:"expand-up-down",className:"size-4"}),e.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:j.size>0?"Collapse all":"Expand all"})]}),P.length>0&&u!=="turn"&&u!=="branch"&&e.jsxs(zt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>q(D=>!D),"aria-pressed":F,"aria-label":F?"Unload full files":"Load full files",className:J("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",F&&"bg-interactive-selection text-interactive-selection-foreground"),children:e.jsx(U,{name:"file-download",className:"size-4"})})}),e.jsx(Ht,{children:e.jsx("p",{children:F?"Unload full files":"Load full files"})})]}),P.length>0&&e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>k(!I),className:J("h-5 w-5 p-0 transition-opacity",I?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:I?"Disable line wrap":"Enable line wrap",children:e.jsx(U,{name:"text-wrap",className:"size-4"})}),O&&e.jsx(tt,{mode:O==="side-by-side"?"side-by-side":"unified",onModeChange:de})]}),m()]})};export{Er as DiffView};