@myrialabs/clopen 0.4.35 → 0.4.37

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 (91) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +1 -0
  6. package/backend/database/queries/session-queries.ts +50 -11
  7. package/backend/database/queries/worktree-queries.ts +148 -0
  8. package/backend/engine/adapters/opencode/server.ts +389 -83
  9. package/backend/engine/adapters/opencode/stream.ts +14 -14
  10. package/backend/engine/hot-reload.ts +25 -10
  11. package/backend/files/file-watcher.ts +35 -9
  12. package/backend/git/conflict-state.test.ts +396 -0
  13. package/backend/git/git-executor.ts +6 -0
  14. package/backend/git/git-parser.ts +144 -48
  15. package/backend/git/git-service.ts +727 -57
  16. package/backend/git/push-target.test.ts +264 -0
  17. package/backend/host/metrics.test.ts +110 -0
  18. package/backend/host/metrics.ts +235 -0
  19. package/backend/index.ts +5 -2
  20. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  21. package/backend/ports/attribute.test.ts +3 -2
  22. package/backend/ports/attribute.ts +5 -44
  23. package/backend/preview/browser/browser-pool.ts +81 -0
  24. package/backend/preview/browser/browser-preview-service.ts +142 -32
  25. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  26. package/backend/preview/browser/types.ts +9 -0
  27. package/backend/project/status-manager.ts +20 -0
  28. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  29. package/backend/projects/project-cleanup.ts +7 -1
  30. package/backend/projects/shell-ownership.ts +65 -0
  31. package/backend/snapshot/snapshot-service.ts +6 -2
  32. package/backend/terminal/ptykit.ts +35 -6
  33. package/backend/utils/ws.ts +21 -1
  34. package/backend/worktrees/clone.ts +222 -0
  35. package/backend/worktrees/index.ts +29 -0
  36. package/backend/worktrees/merge.test.ts +93 -0
  37. package/backend/worktrees/merge.ts +232 -0
  38. package/backend/worktrees/paths.test.ts +60 -0
  39. package/backend/worktrees/paths.ts +60 -0
  40. package/backend/worktrees/resolve.ts +67 -0
  41. package/backend/worktrees/service.ts +315 -0
  42. package/backend/worktrees/tree.ts +59 -0
  43. package/backend/ws/access.ts +18 -0
  44. package/backend/ws/artifacts/generate.ts +2 -2
  45. package/backend/ws/chat/stream.ts +9 -2
  46. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  47. package/backend/ws/files/path-access.test.ts +93 -1
  48. package/backend/ws/files/path-access.ts +54 -5
  49. package/backend/ws/files/read.ts +15 -10
  50. package/backend/ws/files/search.ts +7 -7
  51. package/backend/ws/files/state.ts +70 -8
  52. package/backend/ws/files/watch.ts +16 -14
  53. package/backend/ws/git/branch-name.ts +9 -8
  54. package/backend/ws/git/branch.ts +58 -16
  55. package/backend/ws/git/commit-message.ts +16 -13
  56. package/backend/ws/git/commit.ts +17 -17
  57. package/backend/ws/git/conflict.ts +116 -13
  58. package/backend/ws/git/diff-budget.test.ts +125 -0
  59. package/backend/ws/git/diff-budget.ts +220 -0
  60. package/backend/ws/git/diff.ts +9 -9
  61. package/backend/ws/git/ignored.ts +9 -9
  62. package/backend/ws/git/log.ts +28 -3
  63. package/backend/ws/git/remote.ts +118 -44
  64. package/backend/ws/git/staging.ts +16 -16
  65. package/backend/ws/git/status.ts +13 -13
  66. package/backend/ws/index.ts +4 -0
  67. package/backend/ws/preview/access.ts +11 -3
  68. package/backend/ws/projects/index.ts +5 -1
  69. package/backend/ws/projects/info.test.ts +54 -0
  70. package/backend/ws/projects/info.ts +398 -0
  71. package/backend/ws/sessions/crud.ts +21 -6
  72. package/backend/ws/snapshot/restore.ts +11 -14
  73. package/backend/ws/system/device-info.ts +62 -144
  74. package/backend/ws/worktrees/crud.ts +187 -0
  75. package/backend/ws/worktrees/index.ts +33 -0
  76. package/backend/ws/worktrees/transfer.ts +88 -0
  77. package/dist/assets/{index-BRJqss6F.js → index-Bik9TCBi.js} +1 -1
  78. package/dist/assets/{index-B0iIhSO9.js → index-sJmS_CCm.js} +1 -1
  79. package/dist/assets/main-DLqolBI2.css +1 -0
  80. package/dist/assets/main-Df1I3hnw.js +1096 -0
  81. package/dist/index.html +2 -2
  82. package/package.json +1 -1
  83. package/shared/types/database/schema.ts +26 -0
  84. package/shared/types/git.ts +123 -0
  85. package/shared/utils/logger.ts +1 -0
  86. package/shared/utils/workspace-scope.test.ts +80 -0
  87. package/shared/utils/workspace-scope.ts +57 -0
  88. package/shared/utils/ws-client.ts +25 -5
  89. package/shared/utils/ws-server.ts +19 -3
  90. package/dist/assets/main-Buko4D0t.css +0 -1
  91. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -0,0 +1,264 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { execGit } from './git-executor';
6
+ import { gitService } from './git-service';
7
+
8
+ /**
9
+ * Reviewing a pull request from a fork is the case that broke.
10
+ *
11
+ * `gh pr checkout` records the contributor's repository in
12
+ * `branch.<name>.remote` — often as a bare URL — and their branch name in
13
+ * `branch.<name>.merge`. The panel ignored both and ran
14
+ * `git push <selectedRemote> <localName> -u`, which pushed the review commits
15
+ * into the maintainer's own repository as a new branch and then rewrote the
16
+ * branch's remote so every later push went there too.
17
+ */
18
+
19
+ let workspace: string;
20
+ /** Bare repo standing in for the maintainer's repository. */
21
+ let upstream: string;
22
+ /** Bare repo standing in for the contributor's fork. */
23
+ let fork: string;
24
+ /** Working clone, with `origin` pointing at `upstream`. */
25
+ let work: string;
26
+
27
+ async function git(cwd: string, ...args: string[]) {
28
+ const result = await execGit(args, cwd);
29
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
30
+ return result.stdout;
31
+ }
32
+
33
+ async function branchesOf(bareRepo: string): Promise<string[]> {
34
+ const out = await git(bareRepo, 'for-each-ref', '--format=%(refname:short)', 'refs/heads/');
35
+ return out.split('\n').map(l => l.trim()).filter(Boolean).sort();
36
+ }
37
+
38
+ async function identify(repo: string) {
39
+ await git(repo, 'config', 'user.email', 'test@example.com');
40
+ await git(repo, 'config', 'user.name', 'Test');
41
+ await git(repo, 'config', 'commit.gpgsign', 'false');
42
+ }
43
+
44
+ beforeEach(async () => {
45
+ workspace = await mkdtemp(path.join(tmpdir(), 'clopen-push-'));
46
+ upstream = path.join(workspace, 'upstream.git');
47
+ fork = path.join(workspace, 'fork.git');
48
+ work = path.join(workspace, 'work');
49
+
50
+ await git(workspace, 'init', '--bare', '-b', 'main', upstream);
51
+
52
+ // Seed `main` in the upstream repo.
53
+ const seed = path.join(workspace, 'seed');
54
+ await git(workspace, 'clone', '-q', upstream, seed);
55
+ await identify(seed);
56
+ await writeFile(path.join(seed, 'a.txt'), 'a\n');
57
+ await git(seed, 'add', '-A');
58
+ await git(seed, 'commit', '-m', 'init');
59
+ await git(seed, 'push', 'origin', 'main');
60
+
61
+ // The fork starts as a copy of upstream and gains the contributor's branch.
62
+ await git(workspace, 'clone', '--bare', '-q', upstream, fork);
63
+ const forkWork = path.join(workspace, 'forkwork');
64
+ await git(workspace, 'clone', '-q', fork, forkWork);
65
+ await identify(forkWork);
66
+ await git(forkWork, 'checkout', '-b', 'their-branch');
67
+ await writeFile(path.join(forkWork, 'contrib.txt'), 'contribution\n');
68
+ await git(forkWork, 'add', '-A');
69
+ await git(forkWork, 'commit', '-m', 'contribution');
70
+ await git(forkWork, 'push', 'origin', 'their-branch');
71
+
72
+ // The maintainer's clone.
73
+ await git(workspace, 'clone', '-q', upstream, work);
74
+ await identify(work);
75
+ });
76
+
77
+ afterEach(async () => {
78
+ await rm(workspace, { recursive: true, force: true });
79
+ });
80
+
81
+ /** Reproduce what `gh pr checkout` leaves behind for a fork PR. */
82
+ async function checkoutForkPr(localName = 'their-branch') {
83
+ await git(work, 'fetch', fork, 'their-branch');
84
+ await git(work, 'checkout', '-b', localName, 'FETCH_HEAD');
85
+ await git(work, 'config', `branch.${localName}.remote`, fork);
86
+ await git(work, 'config', `branch.${localName}.merge`, 'refs/heads/their-branch');
87
+ }
88
+
89
+ describe('getPushTarget', () => {
90
+ test('reports no upstream for a fresh local branch', async () => {
91
+ await git(work, 'checkout', '-b', 'brand-new');
92
+ const target = await gitService.getPushTarget(work);
93
+ expect(target.branch).toBe('brand-new');
94
+ expect(target.hasUpstream).toBe(false);
95
+ });
96
+
97
+ test('reports the tracking branch of a normal clone', async () => {
98
+ const target = await gitService.getPushTarget(work);
99
+ expect(target.hasUpstream).toBe(true);
100
+ expect(target.remote).toBe('origin');
101
+ expect(target.remoteBranch).toBe('main');
102
+ expect(target.isUrl).toBe(false);
103
+ });
104
+
105
+ test('resolves a fork PR to the fork, not to origin', async () => {
106
+ await checkoutForkPr();
107
+
108
+ const target = await gitService.getPushTarget(work);
109
+ expect(target.hasUpstream).toBe(true);
110
+ expect(target.remote).toBe(fork);
111
+ expect(target.remoteBranch).toBe('their-branch');
112
+ expect(target.isUrl).toBe(true);
113
+ });
114
+
115
+ test('keeps the remote branch name when the local branch was renamed', async () => {
116
+ // gh renames the local branch when the name would collide.
117
+ await checkoutForkPr('contributor-their-branch');
118
+
119
+ const target = await gitService.getPushTarget(work);
120
+ expect(target.branch).toBe('contributor-their-branch');
121
+ expect(target.remoteBranch).toBe('their-branch');
122
+ });
123
+
124
+ test('honours branch.<name>.pushRemote over branch.<name>.remote', async () => {
125
+ await git(work, 'remote', 'add', 'fork', fork);
126
+ await git(work, 'config', 'branch.main.pushRemote', 'fork');
127
+
128
+ const target = await gitService.getPushTarget(work);
129
+ expect(target.remote).toBe('fork');
130
+ expect(target.isUrl).toBe(false);
131
+ });
132
+ });
133
+
134
+ describe('push — fork pull request under review', () => {
135
+ test('sends the review commit to the fork and leaves origin untouched', async () => {
136
+ await checkoutForkPr();
137
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
138
+ await git(work, 'add', '-A');
139
+ await git(work, 'commit', '-m', 'review fix');
140
+
141
+ // `remote` here is what the panel's dropdown would have supplied.
142
+ const result = await gitService.push(work, 'origin', 'their-branch');
143
+ expect(result.success).toBe(true);
144
+
145
+ // The fix landed on the contributor's branch...
146
+ const forkHead = await git(fork, 'log', '-1', '--format=%s', 'their-branch');
147
+ expect(forkHead.trim()).toBe('review fix');
148
+
149
+ // ...and the maintainer's repository gained nothing.
150
+ expect(await branchesOf(upstream)).toEqual(['main']);
151
+ });
152
+
153
+ test('does not rewrite the branch\'s configured remote', async () => {
154
+ await checkoutForkPr();
155
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
156
+ await git(work, 'add', '-A');
157
+ await git(work, 'commit', '-m', 'review fix');
158
+
159
+ await gitService.push(work, 'origin', 'their-branch');
160
+
161
+ // The old `-u` replaced this with "origin", so every later push — including
162
+ // a manual `git push` — silently went to the wrong repository.
163
+ const configured = (await git(work, 'config', '--get', 'branch.their-branch.remote')).trim();
164
+ expect(configured).toBe(fork);
165
+ const merge = (await git(work, 'config', '--get', 'branch.their-branch.merge')).trim();
166
+ expect(merge).toBe('refs/heads/their-branch');
167
+ });
168
+
169
+ test('force push targets the fork rather than origin', async () => {
170
+ await checkoutForkPr();
171
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
172
+ await git(work, 'add', '-A');
173
+ await git(work, 'commit', '-m', 'review fix');
174
+
175
+ const result = await gitService.pushAdvanced(work, 'force', 'origin', 'their-branch');
176
+ expect(result.success).toBe(true);
177
+
178
+ const forkHead = await git(fork, 'log', '-1', '--format=%s', 'their-branch');
179
+ expect(forkHead.trim()).toBe('review fix');
180
+ expect(await branchesOf(upstream)).toEqual(['main']);
181
+ });
182
+
183
+ test('explains why --force-with-lease cannot work against a URL upstream', async () => {
184
+ await checkoutForkPr();
185
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
186
+ await git(work, 'add', '-A');
187
+ await git(work, 'commit', '-m', 'review fix');
188
+
189
+ // There is no remote-tracking ref for the lease to compare against, so git
190
+ // refuses with a bare "stale info". Say what that means instead.
191
+ const result = await gitService.pushAdvanced(work, 'force-lease', 'origin', 'their-branch');
192
+ expect(result.success).toBe(false);
193
+ expect(result.message).toMatch(/remote-tracking ref/i);
194
+ expect(await branchesOf(upstream)).toEqual(['main']);
195
+ });
196
+ });
197
+
198
+ describe('push — branch with no upstream', () => {
199
+ test('still creates the branch on the chosen remote and records it', async () => {
200
+ await git(work, 'checkout', '-b', 'feature/new');
201
+ await writeFile(path.join(work, 'f.txt'), 'f\n');
202
+ await git(work, 'add', '-A');
203
+ await git(work, 'commit', '-m', 'new work');
204
+
205
+ const result = await gitService.push(work, 'origin', 'feature/new');
206
+ expect(result.success).toBe(true);
207
+ expect(await branchesOf(upstream)).toEqual(['feature/new', 'main']);
208
+
209
+ // `-u` is correct here: there was no upstream to overwrite.
210
+ const target = await gitService.getPushTarget(work);
211
+ expect(target.hasUpstream).toBe(true);
212
+ expect(target.remote).toBe('origin');
213
+ });
214
+ });
215
+
216
+ describe('getBranches', () => {
217
+ test('exposes the upstream of a normal tracking branch', async () => {
218
+ const info = await gitService.getBranches(work, 'origin');
219
+ expect(info.local.find(b => b.name === 'main')?.upstream).toBe('origin/main');
220
+ });
221
+
222
+ test('exposes a URL upstream that git itself cannot name', async () => {
223
+ await checkoutForkPr();
224
+ const info = await gitService.getBranches(work, 'origin');
225
+ const branch = info.local.find(b => b.name === 'their-branch');
226
+ expect(branch?.upstream).toBe(`${fork}/their-branch`);
227
+ });
228
+
229
+ test('counts ahead against the real upstream, not <selected remote>/<name>', async () => {
230
+ await git(work, 'checkout', '-b', 'renamed-locally', 'main');
231
+ await git(work, 'branch', '--set-upstream-to=origin/main', 'renamed-locally');
232
+ await writeFile(path.join(work, 'x.txt'), 'x\n');
233
+ await git(work, 'add', '-A');
234
+ await git(work, 'commit', '-m', 'local work');
235
+
236
+ // `origin/renamed-locally` does not exist; the old code compared against it
237
+ // and reported nothing to push.
238
+ const info = await gitService.getBranches(work, 'origin');
239
+ expect(info.ahead).toBe(1);
240
+ });
241
+ });
242
+
243
+ describe('setUpstream / unsetUpstream', () => {
244
+ test('repoints a branch at a different remote branch', async () => {
245
+ await git(work, 'checkout', '-b', 'wip', 'main');
246
+ await gitService.setUpstream(work, 'wip', 'origin', 'main');
247
+
248
+ const target = await gitService.getPushTarget(work, 'wip');
249
+ expect(target.remote).toBe('origin');
250
+ expect(target.remoteBranch).toBe('main');
251
+ });
252
+
253
+ test('clears tracking so the next push has to choose', async () => {
254
+ await gitService.unsetUpstream(work, 'main');
255
+ const target = await gitService.getPushTarget(work, 'main');
256
+ expect(target.hasUpstream).toBe(false);
257
+ });
258
+
259
+ test('reports a remote-tracking ref that does not exist', async () => {
260
+ await expect(gitService.setUpstream(work, 'main', 'origin', 'nope')).rejects.toThrow(
261
+ /could not set upstream/i
262
+ );
263
+ });
264
+ });
@@ -0,0 +1,110 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { collectProcessTree, cpuCapacityFactor, getHostFacts, withTimeout } from './metrics';
3
+
4
+ function proc(pid: number, parentPid: number) {
5
+ return { pid, parentPid };
6
+ }
7
+
8
+ describe('collectProcessTree', () => {
9
+ it('keeps the roots even when the table does not list them', () => {
10
+ expect([...collectProcessTree([], [42])]).toEqual([42]);
11
+ });
12
+
13
+ it('excludes processes outside the roots', () => {
14
+ const tree = collectProcessTree([proc(100, 1), proc(200, 1), proc(201, 200)], [200]);
15
+ expect([...tree].sort((a, b) => a - b)).toEqual([200, 201]);
16
+ });
17
+
18
+ it('reaches past the depth a bounded pass count would stop at', () => {
19
+ // shell → 15 nested children, listed child-before-parent so a
20
+ // repeated-pass matcher would only pick up one level per pass.
21
+ const list = [];
22
+ for (let depth = 15; depth >= 1; depth--) list.push(proc(1000 + depth, 1000 + depth - 1));
23
+ const tree = collectProcessTree(list, [1000]);
24
+ expect(tree.size).toBe(16);
25
+ expect(tree.has(1015)).toBe(true);
26
+ });
27
+
28
+ it('collects several roots at once', () => {
29
+ const list = [proc(11, 10), proc(21, 20), proc(31, 30)];
30
+ const tree = collectProcessTree(list, [10, 20]);
31
+ expect([...tree].sort((a, b) => a - b)).toEqual([10, 11, 20, 21]);
32
+ });
33
+
34
+ it('terminates on a parent cycle', () => {
35
+ const tree = collectProcessTree([proc(2, 1), proc(1, 2)], [1]);
36
+ expect([...tree].sort((a, b) => a - b)).toEqual([1, 2]);
37
+ });
38
+
39
+ it('ignores a process that claims to be its own parent', () => {
40
+ const tree = collectProcessTree([proc(5, 5), proc(6, 5)], [5]);
41
+ expect([...tree].sort((a, b) => a - b)).toEqual([5, 6]);
42
+ });
43
+ });
44
+
45
+ describe('cpuCapacityFactor', () => {
46
+ it('passes Linux through once a delta exists', () => {
47
+ expect(cpuCapacityFactor('linux', 8, 0.5, true)).toBe(1);
48
+ });
49
+
50
+ it('has no answer for Linux before the second sample', () => {
51
+ expect(cpuCapacityFactor('linux', 8, 0.5, false)).toBeNull();
52
+ });
53
+
54
+ it('divides the per-core macOS reading by the core count', () => {
55
+ expect(cpuCapacityFactor('darwin', 8, null, false)).toBe(1 / 8);
56
+ });
57
+
58
+ it('treats the BSDs like macOS', () => {
59
+ expect(cpuCapacityFactor('freebsd', 4, null, true)).toBe(1 / 4);
60
+ });
61
+
62
+ it('scales Windows by the machine busy fraction', () => {
63
+ expect(cpuCapacityFactor('win32', 8, 0.25, true)).toBe(0.25);
64
+ });
65
+
66
+ it('has no answer for Windows without a busy fraction', () => {
67
+ expect(cpuCapacityFactor('win32', 8, null, true)).toBeNull();
68
+ expect(cpuCapacityFactor('win32', 8, 0.25, false)).toBeNull();
69
+ });
70
+
71
+ it('refuses to divide by a missing core count', () => {
72
+ expect(cpuCapacityFactor('darwin', 0, null, true)).toBeNull();
73
+ });
74
+ });
75
+
76
+ describe('withTimeout', () => {
77
+ it('passes a value through when it beats the deadline', async () => {
78
+ expect(await withTimeout(Promise.resolve(7), 1000)).toBe(7);
79
+ });
80
+
81
+ it('resolves null on timeout when no fallback is given', async () => {
82
+ expect(await withTimeout(new Promise(() => {}), 10)).toBeNull();
83
+ });
84
+
85
+ it('resolves the fallback on timeout when one is given', async () => {
86
+ expect(await withTimeout(new Promise<number>(() => {}), 10, -1)).toBe(-1);
87
+ });
88
+
89
+ it('treats a rejection like a timeout rather than propagating it', async () => {
90
+ expect(await withTimeout(Promise.reject(new Error('nope')), 1000)).toBeNull();
91
+ });
92
+ });
93
+
94
+ describe('getHostFacts', () => {
95
+ it('probes once and hands every caller the same object', async () => {
96
+ const [a, b] = await Promise.all([getHostFacts(), getHostFacts()]);
97
+ expect(a).toBe(b);
98
+ });
99
+
100
+ it('always answers with a usable core count and installed RAM', async () => {
101
+ // Both are denominators: the core count normalises per-process CPU on
102
+ // macOS/BSD, and the RAM total is what "percent of host memory" divides
103
+ // by in Project Info. A zero from a failed probe would poison both.
104
+ const facts = await getHostFacts();
105
+ expect(facts.logicalCores).toBeGreaterThan(0);
106
+ expect(facts.totalMemBytes).toBeGreaterThan(0);
107
+ expect(facts.platform).toBeTruthy();
108
+ expect(facts.arch).toBeTruthy();
109
+ });
110
+ });
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Host metrics — hardware identity and the live process table.
3
+ *
4
+ * One module because Settings → Device and Project Info both ask, and their
5
+ * numbers only compare if measured the same way. `si.processes()` reports CPU
6
+ * against a different basis per platform (total capacity on Linux, one core on
7
+ * macOS/BSD, consumed CPU on Windows), so everything is normalised here to
8
+ * percent of machine capacity — the basis `si.currentLoad()` already uses.
9
+ */
10
+
11
+ import os from 'node:os';
12
+ import si from 'systeminformation';
13
+ import type { Systeminformation } from 'systeminformation';
14
+ import { debug } from '$shared/utils/logger';
15
+
16
+ /** Race a promise against a deadline. Without a fallback, a timeout gives null. */
17
+ export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null>;
18
+ export function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T>;
19
+ export function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T | null = null): Promise<T | null> {
20
+ let timer: ReturnType<typeof setTimeout> | undefined;
21
+ const timeout = new Promise<never>((_, reject) => {
22
+ timer = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
23
+ });
24
+ return Promise.race([promise, timeout])
25
+ .then((value) => {
26
+ clearTimeout(timer);
27
+ return value;
28
+ })
29
+ .catch(() => {
30
+ clearTimeout(timer);
31
+ return fallback;
32
+ });
33
+ }
34
+
35
+ // ── Static facts ─────────────────────────────────────────────────────────────
36
+
37
+ export interface HostFacts {
38
+ hostname: string;
39
+ platform: string;
40
+ distro: string;
41
+ release: string;
42
+ kernel: string;
43
+ arch: string;
44
+ isVirtual: boolean;
45
+ cpuBrand: string;
46
+ cpuManufacturer: string;
47
+ physicalCores: number;
48
+ logicalCores: number;
49
+ cpuSpeedGhz: number | null;
50
+ /** The single denominator behind every "percent of host memory" figure. */
51
+ totalMemBytes: number;
52
+ gpus: Array<{ model: string; vendor: string; vramMb: number | null }>;
53
+ }
54
+
55
+ let hostFactsPromise: Promise<HostFacts> | null = null;
56
+
57
+ /** Hardware identity, probed once per process. */
58
+ export function getHostFacts(): Promise<HostFacts> {
59
+ if (!hostFactsPromise) {
60
+ hostFactsPromise = probeHostFacts().catch((error) => {
61
+ // Don't cache a failed probe — let the next request retry.
62
+ hostFactsPromise = null;
63
+ throw error;
64
+ });
65
+ }
66
+ return hostFactsPromise;
67
+ }
68
+
69
+ async function probeHostFacts(): Promise<HostFacts> {
70
+ const [osInfo, cpu, system, graphics, memory] = await Promise.all([
71
+ withTimeout(si.osInfo(), 4000),
72
+ withTimeout(si.cpu(), 4000),
73
+ withTimeout(si.system(), 4000),
74
+ withTimeout(si.graphics(), 4000),
75
+ withTimeout(si.mem(), 4000)
76
+ ]);
77
+
78
+ return {
79
+ hostname: osInfo?.hostname || os.hostname(),
80
+ platform: osInfo?.platform || os.platform(),
81
+ distro: osInfo?.distro || '',
82
+ release: osInfo?.release || os.release(),
83
+ kernel: osInfo?.kernel || os.version(),
84
+ arch: osInfo?.arch || os.arch(),
85
+ isVirtual: Boolean(system?.virtual),
86
+ cpuBrand: cpu?.brand || '',
87
+ cpuManufacturer: cpu?.manufacturer || '',
88
+ physicalCores: cpu?.physicalCores || cpu?.cores || os.cpus().length,
89
+ logicalCores: cpu?.cores || os.cpus().length,
90
+ cpuSpeedGhz: typeof cpu?.speed === 'number' && cpu.speed > 0 ? cpu.speed : null,
91
+ totalMemBytes: typeof memory?.total === 'number' && memory.total > 0 ? memory.total : os.totalmem(),
92
+ gpus: (graphics?.controllers ?? []).map((controller) => ({
93
+ model: controller.model || 'Unknown GPU',
94
+ vendor: controller.vendor || 'Unknown',
95
+ vramMb: typeof controller.vram === 'number' && controller.vram > 0 ? controller.vram : null
96
+ }))
97
+ };
98
+ }
99
+
100
+ // ── Process table ────────────────────────────────────────────────────────────
101
+
102
+ /** Longer than the 500ms window `si` caches its own table for, so a hit here
103
+ * can never pair a stale table with a fresh `os.cpus()` snapshot. */
104
+ const PROCESS_CACHE_TTL_MS = 2_000;
105
+ /** `si.processes()` shells out — to PowerShell on Windows, which can hang. */
106
+ const PROCESS_PROBE_TIMEOUT_MS = 10_000;
107
+
108
+ export interface ProbedProcess {
109
+ pid: number;
110
+ parentPid: number;
111
+ name: string;
112
+ /** Raw `si` percentage — multiply by `cpuFactor` for a share of capacity. */
113
+ cpu: number;
114
+ /** `si` reports RSS in KB on every platform. */
115
+ memRss: number;
116
+ command: string;
117
+ }
118
+
119
+ export interface ProcessTable {
120
+ list: ProbedProcess[];
121
+ /** null when no honest conversion to a capacity share exists yet. */
122
+ cpuFactor: number | null;
123
+ }
124
+
125
+ let cachedTable: { table: ProcessTable | null; at: number } | null = null;
126
+ let inFlightTable: Promise<ProcessTable | null> | null = null;
127
+ let lastCpuTicks: { busy: number; total: number } | null = null;
128
+ let probeCount = 0;
129
+
130
+ function readCpuTicks(): { busy: number; total: number } {
131
+ let busy = 0;
132
+ let total = 0;
133
+ for (const core of os.cpus()) {
134
+ const active = core.times.user + core.times.nice + core.times.sys + core.times.irq;
135
+ busy += active;
136
+ total += active + core.times.idle;
137
+ }
138
+ return { busy, total };
139
+ }
140
+
141
+ /**
142
+ * Multiplier turning one `si` CPU percentage into a share of machine capacity.
143
+ * Linux is already capacity-relative; macOS/BSD count one core as 100%; Windows
144
+ * is relative to CPU the processes consumed, so it scales by the busy fraction.
145
+ */
146
+ export function cpuCapacityFactor(
147
+ platform: NodeJS.Platform,
148
+ logicalCores: number,
149
+ busyFraction: number | null,
150
+ hasDelta: boolean
151
+ ): number | null {
152
+ if (platform === 'linux') return hasDelta ? 1 : null;
153
+ if (platform === 'win32') return hasDelta && busyFraction !== null ? busyFraction : null;
154
+ return logicalCores > 0 ? 1 / logicalCores : null;
155
+ }
156
+
157
+ /**
158
+ * Every descendant of `roots`, via a parent → children index walked once.
159
+ * Exact at any depth, and `seen` guards the pid cycles Windows can report.
160
+ */
161
+ export function collectProcessTree(
162
+ list: Array<{ pid: number; parentPid: number }>,
163
+ roots: number[]
164
+ ): Set<number> {
165
+ const children = new Map<number, number[]>();
166
+ for (const entry of list) {
167
+ if (entry.parentPid === entry.pid) continue;
168
+ const siblings = children.get(entry.parentPid);
169
+ if (siblings) siblings.push(entry.pid);
170
+ else children.set(entry.parentPid, [entry.pid]);
171
+ }
172
+
173
+ const seen = new Set<number>(roots);
174
+ const queue = [...roots];
175
+ for (let head = 0; head < queue.length; head++) {
176
+ for (const child of children.get(queue[head]) ?? []) {
177
+ if (seen.has(child)) continue;
178
+ seen.add(child);
179
+ queue.push(child);
180
+ }
181
+ }
182
+
183
+ return seen;
184
+ }
185
+
186
+ async function probeProcessTable(): Promise<ProcessTable | null> {
187
+ // Sampled at the instant `si` takes its own sample, so both deltas span the
188
+ // same interval and the Windows conversion stays sound.
189
+ const ticks = readCpuTicks();
190
+ const previous = lastCpuTicks;
191
+ lastCpuTicks = ticks;
192
+
193
+ const totalDelta = previous ? ticks.total - previous.total : 0;
194
+ const busyFraction = previous && totalDelta > 0 ? (ticks.busy - previous.busy) / totalDelta : null;
195
+
196
+ const result = await withTimeout(si.processes(), PROCESS_PROBE_TIMEOUT_MS);
197
+ if (!result) {
198
+ // A timed-out probe still lands later and moves `si`'s delta base at a
199
+ // moment we no longer know, so drop our base rather than mismatch it.
200
+ debug.warn('host', 'si.processes() unavailable — reporting process metrics as unknown');
201
+ lastCpuTicks = null;
202
+ probeCount = 0;
203
+ return null;
204
+ }
205
+
206
+ probeCount++;
207
+
208
+ return {
209
+ list: (result.list ?? []).map((entry: Systeminformation.ProcessesProcessData) => ({
210
+ pid: entry.pid,
211
+ parentPid: entry.parentPid,
212
+ name: entry.name,
213
+ cpu: typeof entry.cpu === 'number' && Number.isFinite(entry.cpu) ? entry.cpu : 0,
214
+ memRss: typeof entry.memRss === 'number' && Number.isFinite(entry.memRss) ? entry.memRss : 0,
215
+ command: entry.command
216
+ })),
217
+ // Linux and Windows need a second sample before a delta exists.
218
+ cpuFactor: cpuCapacityFactor(process.platform, os.cpus().length, busyFraction, probeCount >= 2)
219
+ };
220
+ }
221
+
222
+ /** Cached and single-flighted: N panels polling in step cost one probe. */
223
+ export function getProcessTable(): Promise<ProcessTable | null> {
224
+ if (cachedTable && Date.now() - cachedTable.at < PROCESS_CACHE_TTL_MS) {
225
+ return Promise.resolve(cachedTable.table);
226
+ }
227
+ if (inFlightTable) return inFlightTable;
228
+
229
+ inFlightTable = probeProcessTable().then((table) => {
230
+ cachedTable = { table, at: Date.now() };
231
+ inFlightTable = null;
232
+ return table;
233
+ });
234
+ return inFlightTable;
235
+ }
package/backend/index.ts CHANGED
@@ -333,6 +333,11 @@ async function gracefulShutdown() {
333
333
  // and browser teardown below — otherwise the old process keeps those
334
334
  // sockets open long enough to overlap the new process ("too many clients").
335
335
  await connectionManager.closeAll();
336
+ // Engines next, because they own CHILD PROCESSES. Everything below is
337
+ // in-process cleanup that dies with us anyway, but an `opencode serve`
338
+ // we fail to kill outlives the restart holding its port and data-dir
339
+ // lock — and the 5s force-exit above used to fire before we got here.
340
+ await disposeAllEngines();
336
341
  // Same reasoning for SSH: stop the forwards' listeners and close every
337
342
  // transport so their remote sessions and bound ports are released now.
338
343
  await sshForwardManager.stopAll();
@@ -359,8 +364,6 @@ async function gracefulShutdown() {
359
364
  stopMemoryMaintenance();
360
365
  stopExtractionRunner();
361
366
  await flushEpisodicIngest();
362
- // Dispose all AI engines
363
- await disposeAllEngines();
364
367
  // Close database connection
365
368
  closeDatabase();
366
369
  debug.log('server', '✅ Graceful shutdown completed');
@@ -11,6 +11,8 @@
11
11
  import { browserMcpControl, browserPreviewServiceManager, type BrowserPreviewService } from '$backend/preview';
12
12
  import type { BrowserTab } from '$backend/preview/browser/types';
13
13
  import { projectContextService } from '$backend/mcp/internal/project-context';
14
+ import { sessionQueries } from '$backend/database/queries';
15
+ import { makeScopeKey } from '$shared/utils/workspace-scope';
14
16
  import { debug } from '$shared/utils/logger';
15
17
 
16
18
  /**
@@ -22,10 +24,10 @@ import { debug } from '$shared/utils/logger';
22
24
  * because acting on a guessed project is worth noticing in the logs.
23
25
  */
24
26
  export function getPreviewService(projectId?: string): BrowserPreviewService {
25
- if (projectId) return browserPreviewServiceManager.getService(projectId);
27
+ if (projectId) return browserPreviewServiceManager.getService(scopeForProject(projectId));
26
28
 
27
29
  const contextProjectId = projectContextService.getCurrentProjectId();
28
- if (contextProjectId) return browserPreviewServiceManager.getService(contextProjectId);
30
+ if (contextProjectId) return browserPreviewServiceManager.getService(scopeForProject(contextProjectId));
29
31
 
30
32
  const activeProjects = browserPreviewServiceManager.getActiveProjects();
31
33
  if (activeProjects.length > 0) {
@@ -36,6 +38,18 @@ export function getPreviewService(projectId?: string): BrowserPreviewService {
36
38
  throw new Error('No active browser preview service found. Project isolation requires projectId.');
37
39
  }
38
40
 
41
+ /**
42
+ * Workspace scope of the session driving this call, so an agent working in a
43
+ * worktree drives that worktree's browser rather than the main tree's.
44
+ */
45
+ function scopeForProject(projectId: string): string {
46
+ const chatSessionId = projectContextService.getCurrentChatSessionId();
47
+ const worktreeId = chatSessionId
48
+ ? sessionQueries.getById(chatSessionId)?.worktree_id ?? null
49
+ : null;
50
+ return makeScopeKey(projectId, worktreeId);
51
+ }
52
+
39
53
  /** The chat session driving this call — MCP control is scoped to it. */
40
54
  export function getChatSessionId(): string {
41
55
  const chatSessionId = projectContextService.getCurrentChatSessionId();