@myrialabs/clopen 0.4.35 → 0.4.36
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.
- package/backend/artifacts/sync.test.ts +63 -0
- package/backend/artifacts/sync.ts +56 -3
- package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +1 -0
- package/backend/database/queries/session-queries.ts +50 -11
- package/backend/database/queries/worktree-queries.ts +148 -0
- package/backend/engine/adapters/opencode/server.ts +389 -83
- package/backend/engine/adapters/opencode/stream.ts +14 -14
- package/backend/engine/hot-reload.ts +25 -10
- package/backend/files/file-watcher.ts +35 -9
- package/backend/host/metrics.test.ts +110 -0
- package/backend/host/metrics.ts +235 -0
- package/backend/index.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
- package/backend/ports/attribute.test.ts +3 -2
- package/backend/ports/attribute.ts +5 -44
- package/backend/preview/browser/browser-pool.ts +81 -0
- package/backend/preview/browser/browser-preview-service.ts +142 -32
- package/backend/preview/browser/browser-tab-manager.ts +350 -113
- package/backend/preview/browser/types.ts +9 -0
- package/backend/projects/project-cleanup.integration.test.ts +1 -1
- package/backend/projects/project-cleanup.ts +7 -1
- package/backend/projects/shell-ownership.ts +65 -0
- package/backend/snapshot/snapshot-service.ts +6 -2
- package/backend/terminal/ptykit.ts +35 -6
- package/backend/utils/ws.ts +21 -1
- package/backend/worktrees/clone.ts +222 -0
- package/backend/worktrees/index.ts +29 -0
- package/backend/worktrees/merge.test.ts +93 -0
- package/backend/worktrees/merge.ts +232 -0
- package/backend/worktrees/paths.test.ts +60 -0
- package/backend/worktrees/paths.ts +60 -0
- package/backend/worktrees/resolve.ts +67 -0
- package/backend/worktrees/service.ts +315 -0
- package/backend/worktrees/tree.ts +59 -0
- package/backend/ws/access.ts +18 -0
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/chat/stream.ts +9 -2
- package/backend/ws/files/panel-state-scope.test.ts +102 -0
- package/backend/ws/files/path-access.test.ts +93 -1
- package/backend/ws/files/path-access.ts +54 -5
- package/backend/ws/files/read.ts +15 -10
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/state.ts +70 -8
- package/backend/ws/files/watch.ts +16 -14
- package/backend/ws/git/branch-name.ts +3 -3
- package/backend/ws/git/branch.ts +15 -15
- package/backend/ws/git/commit-message.ts +3 -3
- package/backend/ws/git/commit.ts +17 -17
- package/backend/ws/git/conflict.ts +10 -10
- package/backend/ws/git/diff.ts +9 -9
- package/backend/ws/git/ignored.ts +9 -9
- package/backend/ws/git/log.ts +3 -3
- package/backend/ws/git/remote.ts +43 -43
- package/backend/ws/git/staging.ts +16 -16
- package/backend/ws/git/status.ts +13 -13
- package/backend/ws/index.ts +4 -0
- package/backend/ws/preview/access.ts +11 -3
- package/backend/ws/projects/index.ts +5 -1
- package/backend/ws/projects/info.test.ts +54 -0
- package/backend/ws/projects/info.ts +398 -0
- package/backend/ws/sessions/crud.ts +21 -6
- package/backend/ws/snapshot/restore.ts +11 -14
- package/backend/ws/system/device-info.ts +62 -144
- package/backend/ws/worktrees/crud.ts +187 -0
- package/backend/ws/worktrees/index.ts +33 -0
- package/backend/ws/worktrees/transfer.ts +88 -0
- package/dist/assets/{index-B0iIhSO9.js → index-Bg-SUCFg.js} +1 -1
- package/dist/assets/{index-BRJqss6F.js → index-Cz4YpHVi.js} +1 -1
- package/dist/assets/main-9G7IpQpK.css +1 -0
- package/dist/assets/main-BofFsH8E.js +1085 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +26 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/workspace-scope.test.ts +80 -0
- package/shared/utils/workspace-scope.ts +57 -0
- package/shared/utils/ws-client.ts +25 -5
- package/shared/utils/ws-server.ts +19 -3
- package/dist/assets/main-Buko4D0t.css +0 -1
- package/dist/assets/main-C_iGUZyL.js +0 -1078
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
mapToolName,
|
|
43
43
|
TOOL_NAME_MAP,
|
|
44
44
|
} from './message-converter';
|
|
45
|
-
import { ensureClient, acquireServer, releaseServer,
|
|
45
|
+
import { ensureClient, acquireServer, releaseServer, getDefaultServer, type ServerInstance } from './server';
|
|
46
46
|
import { syncSkills } from '$backend/skills';
|
|
47
47
|
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
48
48
|
import { artifactFilter } from '$backend/profiles';
|
|
@@ -887,7 +887,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
887
887
|
// The pool hold is still held here on purpose — handing the server back
|
|
888
888
|
// first could let it be reaped out from under this very call.
|
|
889
889
|
for (const run of targets) {
|
|
890
|
-
const client = run.server?.client ??
|
|
890
|
+
const client = run.server?.client ?? getDefaultServer()?.client;
|
|
891
891
|
const { sessionId, projectPath } = run;
|
|
892
892
|
if (!client || !sessionId) continue;
|
|
893
893
|
try {
|
|
@@ -948,8 +948,8 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
948
948
|
* POST /question/{requestID}/reply to send user answers back to the OpenCode server.
|
|
949
949
|
*/
|
|
950
950
|
private replyToQuestion(run: OpenCodeRun | null, requestId: string, orderedAnswers: string[][]): void {
|
|
951
|
-
const
|
|
952
|
-
if (!
|
|
951
|
+
const server = run?.server ?? getDefaultServer();
|
|
952
|
+
if (!server) {
|
|
953
953
|
debug.warn('engine', 'replyToQuestion: Server URL not available');
|
|
954
954
|
return;
|
|
955
955
|
}
|
|
@@ -959,12 +959,12 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
959
959
|
// a shared "current server" would post this reply into the wrong one and
|
|
960
960
|
// leave the asking session waiting forever.
|
|
961
961
|
const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
|
|
962
|
-
const url = `${
|
|
962
|
+
const url = `${server.url}/question/${requestId}/reply${dirParam}`;
|
|
963
963
|
debug.log('engine', `Replying to question ${requestId}:`, orderedAnswers);
|
|
964
964
|
|
|
965
965
|
fetch(url, {
|
|
966
966
|
method: 'POST',
|
|
967
|
-
headers: { 'Content-Type': 'application/json' },
|
|
967
|
+
headers: { 'Content-Type': 'application/json', ...server.authHeaders },
|
|
968
968
|
body: JSON.stringify({ answers: orderedAnswers }),
|
|
969
969
|
}).then(async res => {
|
|
970
970
|
if (res.ok) {
|
|
@@ -986,15 +986,15 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
986
986
|
// still-running one when there is exactly one, else the shared client.
|
|
987
987
|
const running = this.runs.all();
|
|
988
988
|
const run = running.length === 1 ? running[0] : null;
|
|
989
|
-
const
|
|
990
|
-
if (!
|
|
989
|
+
const server = run?.server ?? getDefaultServer();
|
|
990
|
+
if (!server) {
|
|
991
991
|
debug.warn('engine', 'fetchAndReplyToQuestion: Server URL not available');
|
|
992
992
|
return;
|
|
993
993
|
}
|
|
994
994
|
|
|
995
995
|
try {
|
|
996
996
|
const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
|
|
997
|
-
const res = await fetch(`${
|
|
997
|
+
const res = await fetch(`${server.url}/question${dirParam}`, { headers: server.authHeaders });
|
|
998
998
|
if (!res.ok) {
|
|
999
999
|
debug.error('engine', `Failed to list pending questions: ${res.status}`);
|
|
1000
1000
|
return;
|
|
@@ -1029,14 +1029,14 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
1029
1029
|
* the v2 permission.reply method.
|
|
1030
1030
|
*/
|
|
1031
1031
|
private replyPermission(run: OpenCodeRun, permissionId: string, sessionId: string, response: 'once' | 'reject'): void {
|
|
1032
|
-
const
|
|
1033
|
-
if (!
|
|
1032
|
+
const server = run.server ?? getDefaultServer();
|
|
1033
|
+
if (!server) return;
|
|
1034
1034
|
const verb = response === 'reject' ? 'rejected' : 'approved';
|
|
1035
1035
|
|
|
1036
1036
|
// Try v2 endpoint first (/permission/{requestID}/reply), fall back to v1
|
|
1037
|
-
fetch(`${
|
|
1037
|
+
fetch(`${server.url}/permission/${permissionId}/reply`, {
|
|
1038
1038
|
method: 'POST',
|
|
1039
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1039
|
+
headers: { 'Content-Type': 'application/json', ...server.authHeaders },
|
|
1040
1040
|
body: JSON.stringify({ reply: response }),
|
|
1041
1041
|
}).then(res => {
|
|
1042
1042
|
if (res.ok) {
|
|
@@ -1044,7 +1044,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
1044
1044
|
return;
|
|
1045
1045
|
}
|
|
1046
1046
|
// v2 endpoint not available — try v1
|
|
1047
|
-
const client = run.server?.client ??
|
|
1047
|
+
const client = run.server?.client ?? getDefaultServer()?.client;
|
|
1048
1048
|
if (client) {
|
|
1049
1049
|
client.postSessionIdPermissionsPermissionId({
|
|
1050
1050
|
path: { id: sessionId, permissionID: permissionId },
|
|
@@ -34,6 +34,8 @@ import {
|
|
|
34
34
|
acquireServer,
|
|
35
35
|
pooledScopeKeys,
|
|
36
36
|
reconcileServerHolders,
|
|
37
|
+
revalidatePool,
|
|
38
|
+
setLiveStreamSource,
|
|
37
39
|
DEFAULT_SCOPE_KEY,
|
|
38
40
|
} from './adapters/opencode/server';
|
|
39
41
|
import { debug } from '$shared/utils/logger';
|
|
@@ -51,7 +53,6 @@ let started = false;
|
|
|
51
53
|
* talk to a server anyway.
|
|
52
54
|
*/
|
|
53
55
|
async function warmDefaultScope(): Promise<void> {
|
|
54
|
-
if (!pooledScopeKeys().includes(DEFAULT_SCOPE_KEY)) return;
|
|
55
56
|
try {
|
|
56
57
|
await acquireServer({});
|
|
57
58
|
debug.log('engine', 'Open Code default server re-warmed for the new config');
|
|
@@ -71,6 +72,10 @@ export function startEngineHotReload(): void {
|
|
|
71
72
|
if (started) return;
|
|
72
73
|
started = true;
|
|
73
74
|
|
|
75
|
+
// The pool sweeps itself on a timer; this is where it learns which holds are
|
|
76
|
+
// still backed by a running stream.
|
|
77
|
+
setLiveStreamSource(() => new Set(streamManager.getActiveStreams().map(s => s.streamId)));
|
|
78
|
+
|
|
74
79
|
onEngineConfigChanged(revision => {
|
|
75
80
|
// Holder bookkeeping is reconciled against the live stream set first, so
|
|
76
81
|
// "is anything running" and "is this server still needed" are answered from
|
|
@@ -83,16 +88,26 @@ export function startEngineHotReload(): void {
|
|
|
83
88
|
// that is mid-answer.
|
|
84
89
|
retireAllEngines();
|
|
85
90
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
'applying it to the next turn and draining the old server behind them'
|
|
91
|
-
);
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
91
|
+
// Read BEFORE revalidating: revalidation is what makes the outgoing default
|
|
92
|
+
// server reapable, so asking afterwards would report the scope as unused
|
|
93
|
+
// and skip the warm-up on exactly the change that needs it.
|
|
94
|
+
const defaultScopeInUse = pooledScopeKeys().includes(DEFAULT_SCOPE_KEY);
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
// Re-resolve every pooled scope's key, not just the default one. A Profile
|
|
97
|
+
// server is otherwise still its own scope's current key, so it is neither
|
|
98
|
+
// superseded nor idle and goes on serving the config — and the credentials —
|
|
99
|
+
// that were just replaced. Held servers are unaffected: they are pinned.
|
|
100
|
+
void revalidatePool().then(() => {
|
|
101
|
+
if (liveStreams.length > 0) {
|
|
102
|
+
debug.log(
|
|
103
|
+
'engine',
|
|
104
|
+
`Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
|
|
105
|
+
'applying it to the next turn and draining the old server behind them'
|
|
106
|
+
);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (defaultScopeInUse) return warmDefaultScope();
|
|
110
|
+
});
|
|
96
111
|
});
|
|
97
112
|
|
|
98
113
|
debug.log('engine', 'Engine hot-reload active');
|
|
@@ -33,6 +33,7 @@ import { stat, readdir } from 'node:fs/promises';
|
|
|
33
33
|
import { join, relative, normalize, sep } from 'node:path';
|
|
34
34
|
import { ws } from '$backend/utils/ws';
|
|
35
35
|
import { debug } from '$shared/utils/logger';
|
|
36
|
+
import { isScopeOfProject, scopeProjectId } from '$shared/utils/workspace-scope';
|
|
36
37
|
import { resolveGitDirs, type GitDirTarget } from '$backend/git/git-dirs';
|
|
37
38
|
import {
|
|
38
39
|
beginWatchedDiscovery,
|
|
@@ -413,7 +414,7 @@ class FileWatcherManager {
|
|
|
413
414
|
'file',
|
|
414
415
|
`Watch ceiling (${MAX_WATCHED_DIRS} dirs) reached for project ${pw.projectId}; deeper directories will not report changes`
|
|
415
416
|
);
|
|
416
|
-
ws.emit.project(pw.projectId, 'files:watch-error', {
|
|
417
|
+
ws.emit.project(scopeProjectId(pw.projectId), 'files:watch-error', {
|
|
417
418
|
projectId: pw.projectId,
|
|
418
419
|
error: `Project is too large to watch entirely (${MAX_WATCHED_DIRS}+ directories). Changes in deeply nested folders may not appear automatically.`
|
|
419
420
|
});
|
|
@@ -484,8 +485,15 @@ class FileWatcherManager {
|
|
|
484
485
|
* Recursively attach watchers to every non-ignored directory under `dir`.
|
|
485
486
|
* Ignored directories (node_modules, .git, build output, …) are never
|
|
486
487
|
* descended into — that pruning is what keeps the watch count survivable.
|
|
488
|
+
*
|
|
489
|
+
* `announceGitDirs` reports each pruned `.git` to git discovery. Set it when
|
|
490
|
+
* walking a directory that just APPEARED: everything inside it was created
|
|
491
|
+
* before this watcher had a handle on it, so a `git clone` or `git init` into
|
|
492
|
+
* a fresh nested path emits no event we can ever see. Pruning `.git` without
|
|
493
|
+
* announcing it therefore lost the sub-repo for the whole session. The
|
|
494
|
+
* initial walk leaves it off — `syncGitWatchers` already resolves the tree.
|
|
487
495
|
*/
|
|
488
|
-
private async watchSubtree(pw: ProjectWatcher, dir: string): Promise<void> {
|
|
496
|
+
private async watchSubtree(pw: ProjectWatcher, dir: string, announceGitDirs = false): Promise<void> {
|
|
489
497
|
if (pw.closed) return;
|
|
490
498
|
|
|
491
499
|
let entries;
|
|
@@ -501,7 +509,12 @@ class FileWatcherManager {
|
|
|
501
509
|
|
|
502
510
|
const childPath = join(dir, entry.name);
|
|
503
511
|
const relativePath = relative(pw.projectPath, childPath).replace(/\\/g, '/');
|
|
504
|
-
if (this.shouldIgnore(relativePath))
|
|
512
|
+
if (this.shouldIgnore(relativePath)) {
|
|
513
|
+
if (announceGitDirs && entry.name === '.git') {
|
|
514
|
+
this.routeGitEvent(pw, relativePath, childPath);
|
|
515
|
+
}
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
505
518
|
|
|
506
519
|
if (!this.watchDir(pw, childPath)) {
|
|
507
520
|
// Ceiling reached — stop descending entirely rather than watching an
|
|
@@ -509,7 +522,7 @@ class FileWatcherManager {
|
|
|
509
522
|
if (pw.truncated) return;
|
|
510
523
|
continue;
|
|
511
524
|
}
|
|
512
|
-
await this.watchSubtree(pw, childPath);
|
|
525
|
+
await this.watchSubtree(pw, childPath, announceGitDirs);
|
|
513
526
|
}
|
|
514
527
|
}
|
|
515
528
|
|
|
@@ -579,6 +592,17 @@ class FileWatcherManager {
|
|
|
579
592
|
this.stopWatching(projectId);
|
|
580
593
|
}
|
|
581
594
|
|
|
595
|
+
/**
|
|
596
|
+
* Release every workspace of a project — the main tree and each worktree.
|
|
597
|
+
* Watchers are keyed per workspace, so releasing the project id alone would
|
|
598
|
+
* leave a deleted project's worktree watchers running.
|
|
599
|
+
*/
|
|
600
|
+
releaseProjectScopes(projectId: string): void {
|
|
601
|
+
for (const key of [...this.watchers.keys(), ...this.viewers.keys()]) {
|
|
602
|
+
if (isScopeOfProject(key, projectId)) this.releaseProject(key);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
582
606
|
/**
|
|
583
607
|
* Check if a project is being watched
|
|
584
608
|
*/
|
|
@@ -653,7 +677,9 @@ class FileWatcherManager {
|
|
|
653
677
|
if (!USE_NATIVE_RECURSIVE_WATCH) {
|
|
654
678
|
if (isDirectory && changeType === 'created') {
|
|
655
679
|
if (this.watchDir(projectWatcher, fullPath)) {
|
|
656
|
-
|
|
680
|
+
// Announce pruned git dirs: this subtree existed before we could
|
|
681
|
+
// watch it, so anything already inside it emitted no event.
|
|
682
|
+
void this.watchSubtree(projectWatcher, fullPath, true);
|
|
657
683
|
}
|
|
658
684
|
} else if (changeType === 'deleted' && projectWatcher.dirWatchers.has(fullPath)) {
|
|
659
685
|
this.unwatchDir(projectWatcher, fullPath);
|
|
@@ -719,7 +745,7 @@ class FileWatcherManager {
|
|
|
719
745
|
projectWatcher.debounceTimer = null;
|
|
720
746
|
|
|
721
747
|
// Emit changes to users currently viewing the project
|
|
722
|
-
ws.emit.project(projectId, 'files:changed', {
|
|
748
|
+
ws.emit.project(scopeProjectId(projectId), 'files:changed', {
|
|
723
749
|
projectId,
|
|
724
750
|
changes,
|
|
725
751
|
timestamp: Date.now()
|
|
@@ -934,7 +960,7 @@ class FileWatcherManager {
|
|
|
934
960
|
projectWatcher.gitDebounceTimer = null;
|
|
935
961
|
const repoPaths = Array.from(projectWatcher.pendingGitRepos);
|
|
936
962
|
projectWatcher.pendingGitRepos.clear();
|
|
937
|
-
ws.emit.project(projectId, 'git:changed', {
|
|
963
|
+
ws.emit.project(scopeProjectId(projectId), 'git:changed', {
|
|
938
964
|
projectId,
|
|
939
965
|
repoPaths,
|
|
940
966
|
timestamp: Date.now()
|
|
@@ -971,7 +997,7 @@ class FileWatcherManager {
|
|
|
971
997
|
'file',
|
|
972
998
|
`Watcher for project ${projectId} faulted ${attempt} times; giving up on automatic restart`
|
|
973
999
|
);
|
|
974
|
-
ws.emit.project(projectId, 'files:watch-error', {
|
|
1000
|
+
ws.emit.project(scopeProjectId(projectId), 'files:watch-error', {
|
|
975
1001
|
projectId,
|
|
976
1002
|
error: 'File watching stopped after repeated failures. Refresh to retry.'
|
|
977
1003
|
});
|
|
@@ -1003,7 +1029,7 @@ class FileWatcherManager {
|
|
|
1003
1029
|
// reconcile — deliberately NOT via `files:changed`, which means "these
|
|
1004
1030
|
// specific paths changed" and made consumers tear down and rebuild live
|
|
1005
1031
|
// views (the open diff editor) on every restart.
|
|
1006
|
-
ws.emit.project(projectId, 'files:resync', {
|
|
1032
|
+
ws.emit.project(scopeProjectId(projectId), 'files:resync', {
|
|
1007
1033
|
projectId,
|
|
1008
1034
|
timestamp: Date.now()
|
|
1009
1035
|
});
|
|
@@ -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();
|