@openchamber/web 1.21.0 → 1.21.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 (135) hide show
  1. package/bin/cli.test.js +35 -0
  2. package/bin/lib/DOCUMENTATION.md +12 -0
  3. package/bin/lib/cli-settings-accessors.js +111 -0
  4. package/bin/lib/cli-settings-accessors.test.js +189 -0
  5. package/bin/lib/cli-startup.js +29 -9
  6. package/bin/lib/commands-connect-url.js +12 -14
  7. package/dist/assets/{CodeMirrorCommentWidgets-C2BopIs3.js → CodeMirrorCommentWidgets-BGj8TJxW.js} +1 -1
  8. package/dist/assets/CommitSection-DwGiXyjf.js +1 -0
  9. package/dist/assets/{DiffView-D5cvbEPb.js → DiffView-Db6bjVv1.js} +3 -3
  10. package/dist/assets/FilesView-DQOa7Lgz.js +17 -0
  11. package/dist/assets/GitView-CHzJxTi0.js +6 -0
  12. package/dist/assets/{JsonTreeView-osju7J70.js → JsonTreeView-CggOsLot.js} +1 -1
  13. package/dist/assets/MarkdownImageGallery-DoZpaHev.js +1 -0
  14. package/dist/assets/MarkdownRendererImpl-B5Y5xCOz.js +12 -0
  15. package/dist/assets/{OnboardingScreen-w2VG4fWY.js → OnboardingScreen-C98d69Fp.js} +1 -1
  16. package/dist/assets/{PatchDiff-Dan3mADn.js → PatchDiff-DJYMUiXA.js} +1 -1
  17. package/dist/assets/{PierreDiffViewer-CGoI2v0q.js → PierreDiffViewer-CY2bx_SB.js} +3 -3
  18. package/dist/assets/PlanView-PkiOY_9H.js +5 -0
  19. package/dist/assets/SettingsView-D-K3ELCM.js +28 -0
  20. package/dist/assets/{SettingsWindow-DXF-MTHG.js → SettingsWindow-oyOm2fHR.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-DrCa1JRk.js → ToolOutputDialog-lKyeQTPL.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-B_tfvlNF.js → ToolPartDiffPreview-C7kBQNAA.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-CN_BctrR.js → VirtualizedFileDiff-BP7ebDFF.js} +1 -1
  24. package/dist/assets/{WalkthroughView-D9Q4lr5x.js → WalkthroughView-MuJodAHD.js} +2 -2
  25. package/dist/assets/{computeVirtualFileMetrics-Gi1d5eU1.js → computeVirtualFileMetrics-CZ0xPeaT.js} +1 -1
  26. package/dist/assets/{contextPanelEmbeddedChat-CpzVNWAv.js → contextPanelEmbeddedChat-C9abMBTb.js} +1 -1
  27. package/dist/assets/de-CEoCz3j6.js +9 -0
  28. package/dist/assets/es-DwyXCqaL.js +15 -0
  29. package/dist/assets/{fr-5qJM0nFS.js → fr-CS7Csln9.js} +5 -5
  30. package/dist/assets/index-CUKcHnUA.css +1 -0
  31. package/dist/assets/{index-Brm3X9rs.js → index-CaPAjwXQ.js} +1 -1
  32. package/dist/assets/index-DIvDEKE-.js +7 -0
  33. package/dist/assets/{isDiffPlainText-pH9kAJQH.js → isDiffPlainText-ZBvDxhVB.js} +1 -1
  34. package/dist/assets/{isFilePlainText-CVKy_dgB.js → isFilePlainText-DiLRrkJr.js} +1 -1
  35. package/dist/assets/ja-vnwqLcx6.js +15 -0
  36. package/dist/assets/ko-CXuSfZv5.js +15 -0
  37. package/dist/assets/{main-vUCh0VB0.js → main-D5RWr6sJ.js} +2 -2
  38. package/dist/assets/main-DLlfDjQ_.js +926 -0
  39. package/dist/assets/{markdown-shiki.worker-CKGJ1J33.js → markdown-shiki.worker-D5fBU-lw.js} +5 -5
  40. package/dist/assets/markdownCore-CcTcLsQF.js +3 -0
  41. package/dist/assets/{miniChat-BlzGEYgE.js → miniChat-CqR3icsk.js} +2 -2
  42. package/dist/assets/{mobile-CkX6H-IT.js → mobile-RN_UTTlB.js} +2 -2
  43. package/dist/assets/{patchFileDiff-BCTsE43U.js → patchFileDiff-CjRR5ESs.js} +3 -3
  44. package/dist/assets/pl-BJxry0Mi.js +15 -0
  45. package/dist/assets/pt-BR-DxLmkhdv.js +15 -0
  46. package/dist/assets/{renderElectronMiniChatApp-CJYe_KOL.js → renderElectronMiniChatApp-1wC94fQK.js} +2 -2
  47. package/dist/assets/renderMobileApp-ltva2Plg.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-D6SmNZaP.js +15 -0
  49. package/dist/assets/{scheduledTasksApi-CAGPh_gZ.js → scheduledTasksApi-mjMDet_H.js} +1 -1
  50. package/dist/assets/{shikiHighlight-BgTPSITe.js → shikiHighlight-fGmFkxAM.js} +1 -1
  51. package/dist/assets/tr-5Mk_hQ2Q.js +6 -0
  52. package/dist/assets/uk-ClgQjmlw.js +15 -0
  53. package/dist/assets/{useAppFontEffects-Cll4gnsh.js → useAppFontEffects-KP8_yiGW.js} +143 -141
  54. package/dist/assets/{useInlineCommentController-DFFv0hae.js → useInlineCommentController-HIjtuhxD.js} +2 -2
  55. package/dist/assets/useRootScrollLock-BSiQ5F75.js +1 -0
  56. package/dist/assets/{vendor-base-ui-_6j2xOWl.js → vendor-base-ui-BeMD8X_w.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-language-data-DkQX2EBa.js → vendor-codemirror-language-data-DrTPkHl4.js} +2 -2
  58. package/dist/assets/{vendor-floating-ui-core-CXmKXOXc.js → vendor-floating-ui-core-PuGzNPnN.js} +1 -1
  59. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-BTvzWks8.js} +1 -1
  60. package/dist/assets/{vendor-floating-ui-react-dom-DKpLs02S.js → vendor-floating-ui-react-dom-DxYCWdHj.js} +1 -1
  61. package/dist/assets/{vendor-floating-ui-utils-BzXdqYpP.js → vendor-floating-ui-utils-D6FqdtJt.js} +1 -1
  62. package/dist/assets/vendor-linkify-it-DZCzzDkK.js +1 -0
  63. package/dist/assets/vendor-marked-linkify-it-CXI_LHIE.js +1 -0
  64. package/dist/assets/vendor-uc.micro-BAd0H0z4.js +1 -0
  65. package/dist/assets/{web-components-DLnGY4fs.js → web-components-DOXvU-tB.js} +1 -1
  66. package/dist/assets/zh-CN-Ba6y8H-i.js +15 -0
  67. package/dist/assets/zh-TW-Dv8yyhN1.js +15 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +3 -3
  70. package/dist/mobile.html +3 -3
  71. package/dist/site.webmanifest +1 -1
  72. package/dist/sw.js +1 -1
  73. package/package.json +2 -2
  74. package/public/site.webmanifest +1 -1
  75. package/server/index.js +2 -2
  76. package/server/lib/cloudflare-tunnel.js +1 -1
  77. package/server/lib/fs/DOCUMENTATION.md +1 -0
  78. package/server/lib/fs/routes.js +21 -0
  79. package/server/lib/fs/routes.test.js +89 -3
  80. package/server/lib/git/DOCUMENTATION.md +4 -3
  81. package/server/lib/git/service.js +128 -6
  82. package/server/lib/git/service.test.js +191 -1
  83. package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
  84. package/server/lib/markdown-image-grants/routes.js +3 -1
  85. package/server/lib/markdown-image-grants/routes.test.js +14 -0
  86. package/server/lib/openchamber-sessions/routes.js +4 -1
  87. package/server/lib/openchamber-sessions/routes.test.js +23 -0
  88. package/server/lib/opencode/env-runtime.js +17 -1
  89. package/server/lib/opencode/env-runtime.test.js +56 -0
  90. package/server/lib/opencode/lifecycle.js +48 -9
  91. package/server/lib/opencode/lifecycle.test.js +125 -1
  92. package/server/lib/opencode/managed-process-registry.d.ts +13 -0
  93. package/server/lib/opencode/managed-process-registry.js +213 -163
  94. package/server/lib/opencode/managed-process-registry.test.mjs +285 -0
  95. package/server/lib/opencode/project-directory-runtime.js +16 -11
  96. package/server/lib/opencode/project-directory-runtime.test.js +32 -12
  97. package/server/lib/opencode/pwa-manifest-routes.js +1 -1
  98. package/server/lib/opencode/routes-upgrade.test.js +96 -12
  99. package/server/lib/opencode/routes.js +53 -5
  100. package/server/lib/opencode/settings-helpers.js +3 -0
  101. package/server/lib/opencode/settings-helpers.test.js +10 -0
  102. package/server/lib/opencode/theme-runtime.js +1 -1
  103. package/server/lib/opencode/theme-runtime.test.js +129 -0
  104. package/server/lib/quota/DOCUMENTATION.md +19 -0
  105. package/server/lib/quota/providers/copilot.js +26 -10
  106. package/server/lib/quota/providers/copilot.test.js +78 -0
  107. package/server/lib/small-model/DOCUMENTATION.md +11 -5
  108. package/server/lib/small-model/call.js +64 -20
  109. package/server/lib/small-model/call.test.js +184 -2
  110. package/server/lib/tunnels/install-help.js +2 -2
  111. package/server/lib/tunnels/install-help.test.js +9 -0
  112. package/server/lib/walkthrough/languages.js +1 -0
  113. package/dist/assets/CommitSection-HJeMUAWb.js +0 -1
  114. package/dist/assets/FilesView-DPU8aNPL.js +0 -17
  115. package/dist/assets/GitView-Ct6xWrVH.js +0 -6
  116. package/dist/assets/MarkdownImageGallery-EujHSZ2M.js +0 -1
  117. package/dist/assets/MarkdownRendererImpl-CPzu4kIr.js +0 -12
  118. package/dist/assets/PlanView-Dgg-WTEc.js +0 -4
  119. package/dist/assets/SessionSwitcherDropdown-CJTrc8K7.js +0 -1
  120. package/dist/assets/SettingsView-D9yRuFZw.js +0 -28
  121. package/dist/assets/de-B_LdJwEM.js +0 -9
  122. package/dist/assets/es-CubfsAYV.js +0 -15
  123. package/dist/assets/index-BW82eK5v.css +0 -1
  124. package/dist/assets/index-rlLjZUM5.js +0 -7
  125. package/dist/assets/ja-DJYIBUlH.js +0 -15
  126. package/dist/assets/ko-DcUBkB7y.js +0 -15
  127. package/dist/assets/main-DLBxKIoX.js +0 -926
  128. package/dist/assets/markdownCore-DG6GHLF4.js +0 -3
  129. package/dist/assets/pl-rB6BLcio.js +0 -15
  130. package/dist/assets/pt-BR-DcwtlO-o.js +0 -15
  131. package/dist/assets/renderMobileApp-hQJTnr8B.js +0 -25
  132. package/dist/assets/runtimeEndpointReset-BDh7r8BL.js +0 -15
  133. package/dist/assets/uk-INZlFD9A.js +0 -15
  134. package/dist/assets/zh-CN-Dzda8xa1.js +0 -15
  135. package/dist/assets/zh-TW-Cwn3rNYZ.js +0 -15
@@ -2,11 +2,17 @@ import { EventEmitter } from 'node:events';
2
2
  import { afterEach, describe, expect, it, vi } from 'vitest';
3
3
 
4
4
  const spawnMock = vi.fn();
5
+ const spawnSyncMock = vi.fn();
5
6
  const recordStartupPerformanceMock = vi.fn();
6
7
 
7
8
  vi.mock('node:child_process', () => ({
8
9
  spawn: spawnMock,
9
- spawnSync: vi.fn(),
10
+ spawnSync: spawnSyncMock,
11
+ // `managed-process-registry.js` (imported transitively via lifecycle.js)
12
+ // calls `promisify(execFile)` at module load, so the mock must expose a
13
+ // function here. Lifecycle tests don't exercise the reaper path, so a plain
14
+ // stub is enough; the registry's best-effort writes are no-ops on errors.
15
+ execFile: vi.fn(),
10
16
  }));
11
17
  vi.mock('./startup-performance.js', () => ({
12
18
  recordStartupPerformance: recordStartupPerformanceMock,
@@ -20,6 +26,7 @@ const originalFetch = globalThis.fetch;
20
26
 
21
27
  afterEach(() => {
22
28
  spawnMock.mockReset();
29
+ spawnSyncMock.mockReset();
23
30
  recordStartupPerformanceMock.mockReset();
24
31
  globalThis.fetch = originalFetch;
25
32
  if (typeof originalOpencodeBinary === 'string') {
@@ -151,6 +158,56 @@ describe('OpenCode lifecycle', () => {
151
158
  expect(terminalEvents).toHaveLength(1);
152
159
  });
153
160
 
161
+ it('recovers an external OPENCODE_HOST connection using its configured endpoint', async () => {
162
+ const fetchMock = vi.fn(async () => ({
163
+ ok: true,
164
+ json: async () => ({ healthy: true }),
165
+ }));
166
+ globalThis.fetch = fetchMock;
167
+ const runtime = createRuntime({}, {
168
+ openCodePort: null,
169
+ openCodeBaseUrl: null,
170
+ isExternalOpenCode: true,
171
+ }, {
172
+ ENV_CONFIGURED_OPENCODE_PORT: null,
173
+ ENV_CONFIGURED_OPENCODE_HOST: { origin: 'http://seamus:4095', port: 4095 },
174
+ ENV_EFFECTIVE_PORT: 4095,
175
+ });
176
+
177
+ await runtime.restartOpenCode();
178
+
179
+ expect(fetchMock).toHaveBeenCalledWith(
180
+ 'http://seamus:4095/global/health',
181
+ expect.objectContaining({ method: 'GET' }),
182
+ );
183
+ expect(runtime.testState.openCodePort).toBe(4095);
184
+ expect(runtime.testState.openCodeBaseUrl).toBe('http://seamus:4095');
185
+ expect(runtime.testState.lastOpenCodeError).toBeNull();
186
+ });
187
+
188
+ it('retains the OPENCODE_HOST port after an external re-probe fails', async () => {
189
+ globalThis.fetch = vi.fn(async () => ({
190
+ ok: false,
191
+ json: async () => null,
192
+ }));
193
+ const runtime = createRuntime({}, {
194
+ openCodePort: 4095,
195
+ openCodeBaseUrl: 'http://seamus:4095',
196
+ isExternalOpenCode: true,
197
+ }, {
198
+ ENV_CONFIGURED_OPENCODE_PORT: null,
199
+ ENV_CONFIGURED_OPENCODE_HOST: { origin: 'http://seamus:4095', port: 4095 },
200
+ ENV_EFFECTIVE_PORT: 4095,
201
+ });
202
+
203
+ await expect(runtime.restartOpenCode()).rejects.toThrow(
204
+ 'External OpenCode server on port 4095 is not responding',
205
+ );
206
+
207
+ expect(runtime.testState.openCodePort).toBe(4095);
208
+ expect(runtime.testState.openCodeBaseUrl).toBe('http://seamus:4095');
209
+ });
210
+
154
211
  it('warms recently used directories after a successful bootstrap', async () => {
155
212
  const fetchMock = vi.fn(async () => ({
156
213
  ok: true,
@@ -791,3 +848,70 @@ describe('OpenCode lifecycle', () => {
791
848
  await server.close();
792
849
  });
793
850
  });
851
+
852
+ describe('killProcessOnPort on Windows', () => {
853
+ const originalPlatform = process.platform;
854
+
855
+ afterEach(() => {
856
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
857
+ });
858
+
859
+ const setPlatform = (platform) => {
860
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
861
+ };
862
+
863
+ it('force-kills the process listening on the target port via taskkill', () => {
864
+ setPlatform('win32');
865
+ const orphanPid = 54321;
866
+ spawnSyncMock.mockImplementation((cmd) => {
867
+ if (cmd === 'powershell') {
868
+ return { stdout: `${orphanPid}\r\n` };
869
+ }
870
+ return { stdout: '' };
871
+ });
872
+
873
+ const runtime = createRuntime();
874
+ runtime.killProcessOnPort(45678);
875
+
876
+ expect(spawnSyncMock).toHaveBeenCalledWith(
877
+ 'powershell',
878
+ expect.arrayContaining([expect.stringContaining('-LocalPort 45678')]),
879
+ expect.objectContaining({ windowsHide: true })
880
+ );
881
+ expect(spawnSyncMock).toHaveBeenCalledWith(
882
+ 'taskkill',
883
+ ['/PID', String(orphanPid), '/F'],
884
+ expect.objectContaining({ windowsHide: true })
885
+ );
886
+ });
887
+
888
+ it('never force-kills its own process id', () => {
889
+ setPlatform('win32');
890
+ spawnSyncMock.mockImplementation((cmd) => {
891
+ if (cmd === 'powershell') {
892
+ return { stdout: `${process.pid}\r\n` };
893
+ }
894
+ return { stdout: '' };
895
+ });
896
+
897
+ const runtime = createRuntime();
898
+ runtime.killProcessOnPort(45678);
899
+
900
+ expect(spawnSyncMock).not.toHaveBeenCalledWith('taskkill', expect.anything(), expect.anything());
901
+ });
902
+
903
+ it('does nothing when no process is listening on the target port', () => {
904
+ setPlatform('win32');
905
+ spawnSyncMock.mockImplementation((cmd) => {
906
+ if (cmd === 'powershell') {
907
+ return { stdout: '' };
908
+ }
909
+ return { stdout: '' };
910
+ });
911
+
912
+ const runtime = createRuntime();
913
+ runtime.killProcessOnPort(45678);
914
+
915
+ expect(spawnSyncMock).not.toHaveBeenCalledWith('taskkill', expect.anything(), expect.anything());
916
+ });
917
+ });
@@ -0,0 +1,13 @@
1
+ export function registerManagedProcess(entry: {
2
+ pid?: number;
3
+ ownerPid?: number;
4
+ port?: number | null;
5
+ binary?: string | null;
6
+ runtime?: string;
7
+ }): Promise<void>;
8
+
9
+ export function unregisterManagedProcess(pid?: number): Promise<void>;
10
+
11
+ export function reapOrphanedProcesses(options?: {
12
+ log?: (message: string) => void;
13
+ }): Promise<{ inspected: number; reaped: number }>;
@@ -32,13 +32,26 @@
32
32
  // been reparented to init/pid 1, or the recorded owner pid is dead. A
33
33
  // child still owned by a live instance is left untouched.
34
34
  //
35
+ // All filesystem and child-process operations here are ASYNCHRONOUS. The web
36
+ // server runs in-process inside the Electron main event loop (and other hosts),
37
+ // so any `spawnSync`/`*Sync` FS call blocks the single event loop — which also
38
+ // serves UI asset requests and realtime SSE traffic. The startup reaper can
39
+ // iterate several registry entries and, on Windows, each one spawns `tasklist`
40
+ // (100-500ms) and possibly `taskkill`; doing that synchronously stalls the
41
+ // whole process and is what caused the 1.13.3 `openchamber-ui://` lag
42
+ // regression (#1841). `execFile`/`fsp.*` keep the event loop responsive while
43
+ // the reaper waits on the kernel.
44
+ //
35
45
  // The VS Code extension cannot import this module (it does not bundle the web
36
46
  // package); it carries a parity implementation that reads/writes the SAME dir.
37
47
 
38
- import fs from 'node:fs';
48
+ import fsp from 'node:fs/promises';
39
49
  import os from 'node:os';
40
50
  import path from 'node:path';
41
- import { spawnSync } from 'node:child_process';
51
+ import { execFile } from 'node:child_process';
52
+ import { promisify } from 'node:util';
53
+
54
+ const defaultExecFileAsync = promisify(execFile);
42
55
 
43
56
  const resolveRegistryDir = () => {
44
57
  const override = process.env.OPENCHAMBER_MANAGED_PROCESS_REGISTRY;
@@ -48,67 +61,6 @@ const resolveRegistryDir = () => {
48
61
 
49
62
  const entryFilePath = (pid) => path.join(resolveRegistryDir(), `${pid}.json`);
50
63
 
51
- const writeEntryFile = (entry) => {
52
- const dir = resolveRegistryDir();
53
- try {
54
- fs.mkdirSync(dir, { recursive: true });
55
- const filePath = path.join(dir, `${entry.pid}.json`);
56
- const tmp = `${filePath}.tmp-${process.pid}`;
57
- fs.writeFileSync(tmp, JSON.stringify(entry, null, 2));
58
- fs.renameSync(tmp, filePath);
59
- } catch {
60
- // Best-effort: a failed registry write must never break spawn/shutdown.
61
- }
62
- };
63
-
64
- const readAllEntries = () => {
65
- const dir = resolveRegistryDir();
66
- let names = [];
67
- try {
68
- names = fs.readdirSync(dir).filter((name) => name.endsWith('.json'));
69
- } catch {
70
- return [];
71
- }
72
- const out = [];
73
- for (const name of names) {
74
- const filePath = path.join(dir, name);
75
- try {
76
- const entry = JSON.parse(fs.readFileSync(filePath, 'utf8'));
77
- if (entry && Number.isInteger(entry.pid)) {
78
- out.push({ entry, filePath });
79
- } else {
80
- fs.rmSync(filePath, { force: true });
81
- }
82
- } catch {
83
- // Corrupt/partial file — drop it.
84
- try { fs.rmSync(filePath, { force: true }); } catch {}
85
- }
86
- }
87
- return out;
88
- };
89
-
90
- /** Record an OpenCode process WE spawned so a future run can reap it if orphaned. */
91
- export const registerManagedProcess = ({ pid, ownerPid, port, binary, runtime } = {}) => {
92
- if (!Number.isInteger(pid)) return;
93
- writeEntryFile({
94
- pid,
95
- ownerPid: Number.isInteger(ownerPid) ? ownerPid : process.pid,
96
- port: Number.isInteger(port) ? port : null,
97
- binary: typeof binary === 'string' ? binary : null,
98
- runtime: typeof runtime === 'string' ? runtime : 'web',
99
- startedAt: new Date().toISOString(),
100
- });
101
- };
102
-
103
- /** Drop a pid from the registry (after we have killed/closed it ourselves). */
104
- export const unregisterManagedProcess = (pid) => {
105
- if (!Number.isInteger(pid)) return;
106
- try {
107
- fs.rmSync(entryFilePath(pid), { force: true });
108
- } catch {
109
- }
110
- };
111
-
112
64
  const isPidAlive = (pid) => {
113
65
  if (!Number.isInteger(pid)) return false;
114
66
  try {
@@ -122,38 +74,6 @@ const isPidAlive = (pid) => {
122
74
 
123
75
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
124
76
 
125
- // Returns { ppid, command } for a live pid on Unix, or null if it can't be read.
126
- const readUnixProcInfo = (pid) => {
127
- try {
128
- const result = spawnSync('ps', ['-p', String(pid), '-o', 'ppid=,command='], {
129
- encoding: 'utf8',
130
- timeout: 3000,
131
- windowsHide: true,
132
- });
133
- const line = (result.stdout || '').trim();
134
- if (!line) return null;
135
- const match = line.match(/^\s*(\d+)\s+(.*)$/);
136
- if (!match) return null;
137
- return { ppid: Number.parseInt(match[1], 10), command: match[2] };
138
- } catch {
139
- return null;
140
- }
141
- };
142
-
143
- // Windows image name for a pid (e.g. "opencode.exe"), or null.
144
- const readWindowsImageName = (pid) => {
145
- try {
146
- const result = spawnSync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {
147
- encoding: 'utf8',
148
- timeout: 3000,
149
- windowsHide: true,
150
- });
151
- return (result.stdout || '').trim() || null;
152
- } catch {
153
- return null;
154
- }
155
- };
156
-
157
77
  const commandIdentifiesOurServer = (command, entry) => {
158
78
  if (typeof command !== 'string') return false;
159
79
  const lower = command.toLowerCase();
@@ -164,88 +84,218 @@ const commandIdentifiesOurServer = (command, entry) => {
164
84
  return true;
165
85
  };
166
86
 
167
- const killOrphan = async (pid) => {
168
- if (process.platform === 'win32') {
87
+ /**
88
+ * Build the registry API over injectable filesystem and child-process
89
+ * dependencies. Production callers use the default instance exported below;
90
+ * tests pass their own `fs`/`execFileAsync` instead of mocking node builtins.
91
+ */
92
+ export const createManagedProcessRegistry = ({ fs = fsp, execFileAsync = defaultExecFileAsync } = {}) => {
93
+ const writeEntryFile = async (entry) => {
94
+ const dir = resolveRegistryDir();
169
95
  try {
170
- spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', timeout: 5000, windowsHide: true });
96
+ await fs.mkdir(dir, { recursive: true });
97
+ const filePath = path.join(dir, `${entry.pid}.json`);
98
+ const tmp = `${filePath}.tmp-${process.pid}`;
99
+ await fs.writeFile(tmp, JSON.stringify(entry, null, 2));
100
+ await fs.rename(tmp, filePath);
171
101
  } catch {
102
+ // Best-effort: a failed registry write must never break spawn/shutdown.
172
103
  }
173
- return;
174
- }
104
+ };
175
105
 
176
- const signalTree = (signal) => {
177
- try { process.kill(-pid, signal); } catch {}
178
- try { process.kill(pid, signal); } catch {}
106
+ const readAllEntries = async () => {
107
+ const dir = resolveRegistryDir();
108
+ let names = [];
109
+ try {
110
+ names = await fs.readdir(dir);
111
+ } catch {
112
+ return [];
113
+ }
114
+ const out = [];
115
+ for (const name of names.filter((value) => value.endsWith('.json'))) {
116
+ const filePath = path.join(dir, name);
117
+ try {
118
+ const entry = JSON.parse(await fs.readFile(filePath, 'utf8'));
119
+ if (entry && Number.isInteger(entry.pid)) {
120
+ out.push({ entry, filePath });
121
+ } else {
122
+ await fs.rm(filePath, { force: true });
123
+ }
124
+ } catch {
125
+ // Corrupt/partial file — drop it.
126
+ try {
127
+ await fs.rm(filePath, { force: true });
128
+ } catch {
129
+ // ignore
130
+ }
131
+ }
132
+ }
133
+ return out;
179
134
  };
180
135
 
181
- signalTree('SIGTERM');
182
- for (let waited = 0; waited < 1500 && isPidAlive(pid); waited += 150) {
183
- await sleep(150);
184
- }
185
- if (isPidAlive(pid)) {
186
- signalTree('SIGKILL');
187
- await sleep(300);
188
- }
189
- };
136
+ /** Record an OpenCode process WE spawned so a future run can reap it if orphaned. */
137
+ const registerManagedProcess = async ({ pid, ownerPid, port, binary, runtime } = {}) => {
138
+ if (!Number.isInteger(pid)) return;
139
+ await writeEntryFile({
140
+ pid,
141
+ ownerPid: Number.isInteger(ownerPid) ? ownerPid : process.pid,
142
+ port: Number.isInteger(port) ? port : null,
143
+ binary: typeof binary === 'string' ? binary : null,
144
+ runtime: typeof runtime === 'string' ? runtime : 'web',
145
+ startedAt: new Date().toISOString(),
146
+ });
147
+ };
190
148
 
191
- // Decide+act on a single registry entry. Returns true if it was reaped.
192
- const processEntry = async (entry, { log }) => {
193
- // Dead pid → nothing to do (caller drops the file).
194
- if (!isPidAlive(entry.pid)) return false;
195
-
196
- const ownerGone = Number.isInteger(entry.ownerPid) && !isPidAlive(entry.ownerPid);
197
-
198
- if (process.platform === 'win32') {
199
- const image = readWindowsImageName(entry.pid);
200
- const looksLikeOpencode = typeof image === 'string' && image.toLowerCase().includes('opencode');
201
- // Windows lacks reliable reparent-to-1 semantics (job objects usually kill
202
- // children with the parent), so we reap only when the owner is provably dead
203
- // AND the image still looks like opencode.
204
- if (looksLikeOpencode && ownerGone) {
205
- await killOrphan(entry.pid);
206
- log?.(`[lifecycle] reaped orphaned OpenCode pid ${entry.pid} (owner ${entry.ownerPid} gone)`);
207
- return true;
149
+ /** Drop a pid from the registry (after we have killed/closed it ourselves). */
150
+ const unregisterManagedProcess = async (pid) => {
151
+ if (!Number.isInteger(pid)) return;
152
+ try {
153
+ await fs.rm(entryFilePath(pid), { force: true });
154
+ } catch {
155
+ // Best-effort: dropping a missing file is not an error.
208
156
  }
209
- return false;
210
- }
157
+ };
211
158
 
212
- const info = readUnixProcInfo(entry.pid);
213
- // Can't verify identity (or it's not our server) → leave it alone.
214
- if (!info || !commandIdentifiesOurServer(info.command, entry)) return false;
159
+ // Returns { ppid, command } for a live pid on Unix, or null if it can't be read.
160
+ const readUnixProcInfo = async (pid) => {
161
+ try {
162
+ const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'ppid=,command='], {
163
+ encoding: 'utf8',
164
+ timeout: 3000,
165
+ windowsHide: true,
166
+ });
167
+ const line = (stdout || '').trim();
168
+ if (!line) return null;
169
+ const match = line.match(/^\s*(\d+)\s+(.*)$/);
170
+ if (!match) return null;
171
+ return { ppid: Number.parseInt(match[1], 10), command: match[2] };
172
+ } catch {
173
+ return null;
174
+ }
175
+ };
215
176
 
216
- const orphaned = info.ppid === 1 || ownerGone;
217
- if (!orphaned) return false; // still owned by a live instance
177
+ // Windows image name for a pid (e.g. "opencode.exe"), or null.
178
+ const readWindowsImageName = async (pid) => {
179
+ try {
180
+ const { stdout } = await execFileAsync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {
181
+ encoding: 'utf8',
182
+ timeout: 3000,
183
+ windowsHide: true,
184
+ });
185
+ return (stdout || '').trim() || null;
186
+ } catch {
187
+ return null;
188
+ }
189
+ };
218
190
 
219
- await killOrphan(entry.pid);
220
- log?.(`[lifecycle] reaped orphaned OpenCode pid ${entry.pid} (reparented/owner gone)`);
221
- return true;
222
- };
191
+ const killOrphan = async (pid) => {
192
+ if (process.platform === 'win32') {
193
+ try {
194
+ await execFileAsync('taskkill', ['/PID', String(pid), '/T', '/F'], {
195
+ stdio: 'ignore',
196
+ timeout: 5000,
197
+ windowsHide: true,
198
+ });
199
+ } catch {
200
+ // Best-effort: a failed kill is not fatal (startup reaper is a backstop).
201
+ }
202
+ return;
203
+ }
223
204
 
224
- /**
225
- * Kill any genuinely-orphaned OpenCode processes WE previously spawned, and
226
- * prune their registry files. Safe to call at startup before spawning a new
227
- * server. Returns { inspected, reaped }.
228
- */
229
- export const reapOrphanedProcesses = async ({ log } = {}) => {
230
- const records = readAllEntries();
231
- if (records.length === 0) return { inspected: 0, reaped: 0 };
205
+ const signalTree = (signal) => {
206
+ try {
207
+ process.kill(-pid, signal);
208
+ } catch {
209
+ // process group may already be gone
210
+ }
211
+ try {
212
+ process.kill(pid, signal);
213
+ } catch {
214
+ // pid may already be gone
215
+ }
216
+ };
232
217
 
233
- let reaped = 0;
234
- for (const { entry, filePath } of records) {
235
- let drop = false;
236
- try {
237
- const wasReaped = await processEntry(entry, { log });
238
- if (wasReaped) reaped += 1;
239
- // Drop the file when the process is gone (reaped now, or already dead);
240
- // keep it only while the process is still alive and owned by a live owner.
241
- drop = wasReaped || !isPidAlive(entry.pid);
242
- } catch (error) {
243
- log?.(`[lifecycle] reap check failed for pid ${entry.pid}: ${error?.message ?? error}`);
218
+ signalTree('SIGTERM');
219
+ for (let waited = 0; waited < 1500 && isPidAlive(pid); waited += 150) {
220
+ await sleep(150);
244
221
  }
245
- if (drop) {
246
- try { fs.rmSync(filePath, { force: true }); } catch {}
222
+ if (isPidAlive(pid)) {
223
+ signalTree('SIGKILL');
224
+ await sleep(300);
247
225
  }
248
- }
226
+ };
227
+
228
+ // Decide+act on a single registry entry. Returns true if it was reaped.
229
+ const processEntry = async (entry, { log }) => {
230
+ // Dead pid → nothing to do (caller drops the file).
231
+ if (!isPidAlive(entry.pid)) return false;
249
232
 
250
- return { inspected: records.length, reaped };
233
+ const ownerGone = Number.isInteger(entry.ownerPid) && !isPidAlive(entry.ownerPid);
234
+
235
+ if (process.platform === 'win32') {
236
+ const image = await readWindowsImageName(entry.pid);
237
+ const looksLikeOpencode = typeof image === 'string' && image.toLowerCase().includes('opencode');
238
+ // Windows lacks reliable reparent-to-1 semantics (job objects usually kill
239
+ // children with the parent), so we reap only when the owner is provably dead
240
+ // AND the image still looks like opencode.
241
+ if (looksLikeOpencode && ownerGone) {
242
+ await killOrphan(entry.pid);
243
+ log?.(`[lifecycle] reaped orphaned OpenCode pid ${entry.pid} (owner ${entry.ownerPid} gone)`);
244
+ return true;
245
+ }
246
+ return false;
247
+ }
248
+
249
+ const info = await readUnixProcInfo(entry.pid);
250
+ // Can't verify identity (or it's not our server) → leave it alone.
251
+ if (!info || !commandIdentifiesOurServer(info.command, entry)) return false;
252
+
253
+ const orphaned = info.ppid === 1 || ownerGone;
254
+ if (!orphaned) return false; // still owned by a live instance
255
+
256
+ await killOrphan(entry.pid);
257
+ log?.(`[lifecycle] reaped orphaned OpenCode pid ${entry.pid} (reparented/owner gone)`);
258
+ return true;
259
+ };
260
+
261
+ /**
262
+ * Kill any genuinely-orphaned OpenCode processes WE previously spawned, and
263
+ * prune their registry files. Safe to call at startup before spawning a new
264
+ * server. Returns { inspected, reaped }.
265
+ */
266
+ const reapOrphanedProcesses = async ({ log } = {}) => {
267
+ const records = await readAllEntries();
268
+ if (records.length === 0) return { inspected: 0, reaped: 0 };
269
+
270
+ let reaped = 0;
271
+ for (const { entry, filePath } of records) {
272
+ let drop = false;
273
+ try {
274
+ const wasReaped = await processEntry(entry, { log });
275
+ if (wasReaped) reaped += 1;
276
+ // Drop the file when the process is gone (reaped now, or already dead);
277
+ // keep it only while the process is still alive and owned by a live owner.
278
+ drop = wasReaped || !isPidAlive(entry.pid);
279
+ } catch (error) {
280
+ log?.(`[lifecycle] reap check failed for pid ${entry.pid}: ${error?.message ?? error}`);
281
+ }
282
+ if (drop) {
283
+ try {
284
+ await fs.rm(filePath, { force: true });
285
+ } catch {
286
+ // best-effort
287
+ }
288
+ }
289
+ }
290
+
291
+ return { inspected: records.length, reaped };
292
+ };
293
+
294
+ return { registerManagedProcess, unregisterManagedProcess, reapOrphanedProcesses };
251
295
  };
296
+
297
+ const defaultRegistry = createManagedProcessRegistry();
298
+
299
+ export const registerManagedProcess = defaultRegistry.registerManagedProcess;
300
+ export const unregisterManagedProcess = defaultRegistry.unregisterManagedProcess;
301
+ export const reapOrphanedProcesses = defaultRegistry.reapOrphanedProcesses;