@myrialabs/clopen 0.4.34 → 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/auth/permissions.ts +7 -0
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- 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.test.ts +105 -0
- package/backend/files/file-watcher.ts +80 -10
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/host/metrics.test.ts +110 -0
- package/backend/host/metrics.ts +235 -0
- package/backend/{ports → host}/runner.ts +19 -10
- package/backend/index.ts +16 -4
- package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
- package/backend/ports/attribute.test.ts +3 -2
- package/backend/ports/attribute.ts +6 -45
- package/backend/ports/kill.ts +1 -1
- package/backend/ports/monitor.ts +1 -1
- package/backend/ports/processes.ts +1 -1
- package/backend/ports/scan-host.ts +77 -8
- package/backend/ports/scan.test.ts +1 -1
- package/backend/ports/scan.ts +1 -1
- package/backend/ports/ssh-lineage.ts +1 -1
- 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/browser-video-capture.ts +84 -31
- 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/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- 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 +6 -4
- package/backend/ws/git/remote.ts +43 -43
- package/backend/ws/git/staging.ts +16 -16
- package/backend/ws/git/status.ts +47 -37
- package/backend/ws/index.ts +6 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- 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/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +70 -96
- 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-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
- package/dist/assets/{index-gGTMFUa8.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/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/database/schema.ts +26 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/port.ts +47 -9
- package/shared/utils/logger.ts +3 -0
- package/shared/utils/workspace-scope.test.ts +80 -0
- package/shared/utils/workspace-scope.ts +57 -0
- package/shared/utils/ws-client.ts +92 -17
- package/shared/utils/ws-server.ts +83 -16
- package/dist/assets/main-CYCMEbXB.css +0 -1
- package/dist/assets/main-ZCojSzvW.js +0 -1060
|
@@ -6,8 +6,29 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Thresholds:
|
|
8
8
|
* 50 messages/second → warning logged
|
|
9
|
-
* 100 messages/second → connection throttled (
|
|
10
|
-
* 200 messages/second → connection
|
|
9
|
+
* 100 messages/second → connection throttled (fire-and-forget events dropped)
|
|
10
|
+
* 200 messages/second → connection closed
|
|
11
|
+
*
|
|
12
|
+
* WHAT GETS SHED WHEN THROTTLING
|
|
13
|
+
*
|
|
14
|
+
* Throttling drops events, never request-response calls, and the asymmetry is
|
|
15
|
+
* the entire point. A busy Clopen tab is dominated by high-volume fire-and-
|
|
16
|
+
* forget traffic — preview pointer moves at ~30/s per viewer, terminal
|
|
17
|
+
* keystrokes, stream feedback — while the calls a panel actually waits on
|
|
18
|
+
* (`files:list-tree`, `git:status`, `engine:*-accounts-list`) are a trickle by
|
|
19
|
+
* comparison.
|
|
20
|
+
*
|
|
21
|
+
* Counting them in one bucket and dropping whatever arrived last meant the
|
|
22
|
+
* flood survived and the request died. That is backwards twice over: a dropped
|
|
23
|
+
* pointer move is invisible because the next one supersedes it a frame later,
|
|
24
|
+
* whereas a dropped request leaves a panel with no data and a user with no
|
|
25
|
+
* explanation. Worse, it was self-amplifying — a dropped request used to hang
|
|
26
|
+
* its caller until the client tore the socket down and every panel refetched at
|
|
27
|
+
* once, which is a bigger burst than the one that tripped the limiter.
|
|
28
|
+
*
|
|
29
|
+
* Abuse is still bounded, and by the threshold that was always the real one:
|
|
30
|
+
* a connection genuinely spamming the server crosses 200/s and gets closed
|
|
31
|
+
* regardless of what it is sending.
|
|
11
32
|
*/
|
|
12
33
|
|
|
13
34
|
import { debug } from '$shared/utils/logger';
|
|
@@ -59,7 +80,13 @@ export class MessageRateLimiter {
|
|
|
59
80
|
return state;
|
|
60
81
|
}
|
|
61
82
|
|
|
62
|
-
|
|
83
|
+
/**
|
|
84
|
+
* @param isRequest Whether `action` is a request-response route — i.e. a
|
|
85
|
+
* caller is blocked waiting for its reply. Such calls are counted like
|
|
86
|
+
* everything else but are never shed by throttling; see the note at the
|
|
87
|
+
* top of this file.
|
|
88
|
+
*/
|
|
89
|
+
checkRateLimit(conn: WSConnection, action: string, isRequest = false): boolean {
|
|
63
90
|
const state = this.getState(conn);
|
|
64
91
|
const now = Date.now();
|
|
65
92
|
const windowStart = now - this.config.windowMs;
|
|
@@ -91,6 +118,10 @@ export class MessageRateLimiter {
|
|
|
91
118
|
state.isWarning = false;
|
|
92
119
|
debug.warn('rate-limit', `Connection throttled: ${messagesPerSecond.toFixed(0)} msg/s on action ${action}`);
|
|
93
120
|
}
|
|
121
|
+
// Shed the flood, not the thing somebody is waiting on. Below the
|
|
122
|
+
// disconnect threshold a request is always answered; above it the
|
|
123
|
+
// connection is gone anyway.
|
|
124
|
+
if (isRequest) return true;
|
|
94
125
|
state.messagesDropped++;
|
|
95
126
|
return false;
|
|
96
127
|
}
|
|
@@ -12,6 +12,7 @@ import type { WSConnection } from '$shared/utils/ws-server';
|
|
|
12
12
|
import { ws } from '$backend/utils/ws';
|
|
13
13
|
import { requireCurrentProjectAccess, requireProjectAccess } from '../access';
|
|
14
14
|
import { browserPreviewServiceManager } from '../../preview/index';
|
|
15
|
+
import { makeScopeKey, scopeProjectId } from '$shared/utils/workspace-scope';
|
|
15
16
|
|
|
16
17
|
type PreviewService = ReturnType<typeof browserPreviewServiceManager.getService>;
|
|
17
18
|
type Tab = NonNullable<ReturnType<PreviewService['getActiveTab']>>;
|
|
@@ -24,7 +25,11 @@ export interface BrowserPreviewContext {
|
|
|
24
25
|
|
|
25
26
|
export function requireBrowserPreviewAccess(conn: WSConnection): BrowserPreviewContext {
|
|
26
27
|
const { userId, projectId } = requireCurrentProjectAccess(conn);
|
|
27
|
-
|
|
28
|
+
// Tabs are scoped to the tree being viewed, so a worktree's preview never
|
|
29
|
+
// shows the main project's pages.
|
|
30
|
+
const previewService = browserPreviewServiceManager.getService(
|
|
31
|
+
makeScopeKey(projectId, ws.getWorktreeId(conn))
|
|
32
|
+
);
|
|
28
33
|
return { userId, projectId, previewService };
|
|
29
34
|
}
|
|
30
35
|
|
|
@@ -38,11 +43,14 @@ export function requireBrowserPreviewAccess(conn: WSConnection): BrowserPreviewC
|
|
|
38
43
|
*/
|
|
39
44
|
export function requireBrowserPreviewAccessFor(
|
|
40
45
|
conn: WSConnection,
|
|
41
|
-
|
|
46
|
+
scopeKey: string
|
|
42
47
|
): BrowserPreviewContext {
|
|
48
|
+
// The caller passes a workspace scope key; membership is always decided on
|
|
49
|
+
// the project it belongs to.
|
|
50
|
+
const projectId = scopeProjectId(scopeKey);
|
|
43
51
|
requireProjectAccess(conn, projectId); // throws if the caller isn't a member
|
|
44
52
|
const userId = ws.getUserId(conn);
|
|
45
|
-
const previewService = browserPreviewServiceManager.getService(
|
|
53
|
+
const previewService = browserPreviewServiceManager.getService(scopeKey);
|
|
46
54
|
return { userId, projectId, previewService };
|
|
47
55
|
}
|
|
48
56
|
|
|
@@ -13,6 +13,7 @@ import { createRouter } from '$shared/utils/ws-server';
|
|
|
13
13
|
import { crudHandler } from './crud';
|
|
14
14
|
import { statusHandler } from './status';
|
|
15
15
|
import { presenceHandler } from './presence';
|
|
16
|
+
import { infoHandler } from './info';
|
|
16
17
|
|
|
17
18
|
export const projectsRouter = createRouter()
|
|
18
19
|
// CRUD Operations (HTTP)
|
|
@@ -22,4 +23,7 @@ export const projectsRouter = createRouter()
|
|
|
22
23
|
.merge(statusHandler)
|
|
23
24
|
|
|
24
25
|
// Presence Management (HTTP + Broadcast)
|
|
25
|
-
.merge(presenceHandler)
|
|
26
|
+
.merge(presenceHandler)
|
|
27
|
+
|
|
28
|
+
// Per-project resource info (storage + process-isolated CPU/RAM)
|
|
29
|
+
.merge(infoHandler);
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import type { PortEntry, PortOriginKind } from '$shared/types/ports';
|
|
3
|
+
import { groupPortsByProject } from './info';
|
|
4
|
+
|
|
5
|
+
function entry(port: number, kind: PortOriginKind, projectId?: string, publicUrl: string | null = null): PortEntry {
|
|
6
|
+
return {
|
|
7
|
+
key: `tcp:${port}`,
|
|
8
|
+
protocol: 'tcp',
|
|
9
|
+
port,
|
|
10
|
+
addresses: ['127.0.0.1'],
|
|
11
|
+
ipVersions: ['v4'],
|
|
12
|
+
pid: 1000 + port,
|
|
13
|
+
process: null,
|
|
14
|
+
workerPids: [],
|
|
15
|
+
origin: { kind, confidence: 'certain', label: 'Vite dev server', detail: null, projectId },
|
|
16
|
+
peers: [],
|
|
17
|
+
peerCount: 0,
|
|
18
|
+
publicUrl,
|
|
19
|
+
container: null,
|
|
20
|
+
canKill: true,
|
|
21
|
+
killBlockedReason: null
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('groupPortsByProject', () => {
|
|
26
|
+
it('keeps only ports a terminal session owns', () => {
|
|
27
|
+
const grouped = groupPortsByProject([
|
|
28
|
+
entry(5173, 'session', 'project-a'),
|
|
29
|
+
entry(8080, 'external'),
|
|
30
|
+
entry(6379, 'container', 'project-a')
|
|
31
|
+
]);
|
|
32
|
+
expect([...grouped.keys()]).toEqual(['project-a']);
|
|
33
|
+
expect(grouped.get('project-a')?.map((port) => port.port)).toEqual([5173]);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('drops a session port that names no project', () => {
|
|
37
|
+
expect(groupPortsByProject([entry(3000, 'session')]).size).toBe(0);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('separates ports belonging to different projects', () => {
|
|
41
|
+
const grouped = groupPortsByProject([
|
|
42
|
+
entry(5173, 'session', 'project-a'),
|
|
43
|
+
entry(3000, 'session', 'project-b'),
|
|
44
|
+
entry(4000, 'session', 'project-a')
|
|
45
|
+
]);
|
|
46
|
+
expect(grouped.get('project-a')?.map((port) => port.port)).toEqual([5173, 4000]);
|
|
47
|
+
expect(grouped.get('project-b')?.map((port) => port.port)).toEqual([3000]);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('carries the public URL through so a tunnelled port stays reachable', () => {
|
|
51
|
+
const grouped = groupPortsByProject([entry(5173, 'session', 'project-a', 'https://demo.trycloudflare.com')]);
|
|
52
|
+
expect(grouped.get('project-a')?.[0].publicUrl).toBe('https://demo.trycloudflare.com');
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Projects Info — what one project costs on this machine.
|
|
3
|
+
*
|
|
4
|
+
* Storage is a bounded walk of the project folder, nothing excluded. CPU and
|
|
5
|
+
* RAM come from the shared host probe in `backend/host/metrics.ts`, narrowed to
|
|
6
|
+
* the project's PTY shells and their descendants, so they sit on the same basis
|
|
7
|
+
* Settings → Device reports for the whole machine. Engine processes Clopen runs
|
|
8
|
+
* outside a terminal are not shells and do not appear here.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { t } from 'elysia';
|
|
12
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
15
|
+
import { projectQueries } from '../../database/queries';
|
|
16
|
+
import { requireProjectAccess } from '../access';
|
|
17
|
+
import { projectShellPids } from '../../projects/shell-ownership';
|
|
18
|
+
import { portMonitor } from '../../ports/monitor';
|
|
19
|
+
import { LOCAL_PORT_HOST, type PortEntry } from '$shared/types/ports';
|
|
20
|
+
import { debug } from '$shared/utils/logger';
|
|
21
|
+
import { collectProcessTree, getHostFacts, getProcessTable } from '../../host/metrics';
|
|
22
|
+
|
|
23
|
+
/** Ceiling on entries visited by one walk, so a monorepo cannot pin a core. */
|
|
24
|
+
const MAX_ENTRIES = 300_000;
|
|
25
|
+
/** Wall-clock ceiling — the backstop for slow disks and network mounts. */
|
|
26
|
+
const WALK_DEADLINE_MS = 15_000;
|
|
27
|
+
/** How many `stat` calls are in flight at once while walking one directory. */
|
|
28
|
+
const STAT_BATCH = 64;
|
|
29
|
+
/** A folder's size changes slowly; a poll should not re-walk it every tick. */
|
|
30
|
+
const STORAGE_CACHE_TTL_MS = 15_000;
|
|
31
|
+
/** An expensive walk earns a longer rest, so it is not repeated the moment its
|
|
32
|
+
* answer goes stale — otherwise one core stays busy while the panel is open. */
|
|
33
|
+
const STORAGE_TTL_PER_MS_SPENT = 4;
|
|
34
|
+
const STORAGE_CACHE_MAX_TTL_MS = 5 * 60_000;
|
|
35
|
+
/** A scan reads the socket table and the process list; the panel polls faster. */
|
|
36
|
+
const PORTS_CACHE_TTL_MS = 5_000;
|
|
37
|
+
|
|
38
|
+
// ── Storage ──────────────────────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
interface FolderStats {
|
|
41
|
+
sizeBytes: number;
|
|
42
|
+
fileCount: number;
|
|
43
|
+
dirCount: number;
|
|
44
|
+
truncated: boolean;
|
|
45
|
+
error?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const storageCache = new Map<string, { stats: FolderStats; at: number; ttl: number }>();
|
|
49
|
+
const storageInFlight = new Map<string, Promise<FolderStats>>();
|
|
50
|
+
|
|
51
|
+
/** Cached and single-flighted: a big walk outlives the poll interval, so a
|
|
52
|
+
* result-only cache would let every tick start another one. */
|
|
53
|
+
function getFolderStats(root: string): Promise<FolderStats> {
|
|
54
|
+
const cached = storageCache.get(root);
|
|
55
|
+
if (cached && Date.now() - cached.at < cached.ttl) {
|
|
56
|
+
return Promise.resolve(cached.stats);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const inFlight = storageInFlight.get(root);
|
|
60
|
+
if (inFlight) return inFlight;
|
|
61
|
+
|
|
62
|
+
const startedAt = Date.now();
|
|
63
|
+
const walk = walkFolder(root)
|
|
64
|
+
.catch((error): FolderStats => ({
|
|
65
|
+
sizeBytes: 0,
|
|
66
|
+
fileCount: 0,
|
|
67
|
+
dirCount: 0,
|
|
68
|
+
truncated: false,
|
|
69
|
+
error: error instanceof Error ? error.message : String(error)
|
|
70
|
+
}))
|
|
71
|
+
.then((stats) => {
|
|
72
|
+
const spent = Date.now() - startedAt;
|
|
73
|
+
const ttl = Math.min(
|
|
74
|
+
STORAGE_CACHE_MAX_TTL_MS,
|
|
75
|
+
Math.max(STORAGE_CACHE_TTL_MS, spent * STORAGE_TTL_PER_MS_SPENT)
|
|
76
|
+
);
|
|
77
|
+
storageCache.set(root, { stats, at: Date.now(), ttl });
|
|
78
|
+
storageInFlight.delete(root);
|
|
79
|
+
return stats;
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
storageInFlight.set(root, walk);
|
|
83
|
+
return walk;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function walkFolder(root: string): Promise<FolderStats> {
|
|
87
|
+
try {
|
|
88
|
+
const rootStat = await stat(root);
|
|
89
|
+
if (!rootStat.isDirectory()) {
|
|
90
|
+
return { sizeBytes: rootStat.size, fileCount: 1, dirCount: 0, truncated: false };
|
|
91
|
+
}
|
|
92
|
+
} catch (error) {
|
|
93
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
94
|
+
return { sizeBytes: 0, fileCount: 0, dirCount: 0, truncated: false, error: message };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const deadline = Date.now() + WALK_DEADLINE_MS;
|
|
98
|
+
const stack: string[] = [root];
|
|
99
|
+
let sizeBytes = 0;
|
|
100
|
+
let fileCount = 0;
|
|
101
|
+
let dirCount = 0;
|
|
102
|
+
let truncated = false;
|
|
103
|
+
|
|
104
|
+
while (stack.length > 0) {
|
|
105
|
+
if (fileCount + dirCount >= MAX_ENTRIES || Date.now() > deadline) {
|
|
106
|
+
truncated = true;
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const dir = stack.pop()!;
|
|
111
|
+
let entries: import('node:fs').Dirent[];
|
|
112
|
+
try {
|
|
113
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
114
|
+
} catch {
|
|
115
|
+
// Unreadable directory (permissions, vanished mid-walk) — skip it.
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const files: string[] = [];
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
if (fileCount + dirCount >= MAX_ENTRIES) {
|
|
122
|
+
truncated = true;
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
// Symlinks and Windows junctions: double-counted at best, a loop at worst.
|
|
126
|
+
if (entry.isSymbolicLink()) continue;
|
|
127
|
+
|
|
128
|
+
if (entry.isDirectory()) {
|
|
129
|
+
dirCount++;
|
|
130
|
+
stack.push(join(dir, entry.name));
|
|
131
|
+
} else if (entry.isFile()) {
|
|
132
|
+
fileCount++;
|
|
133
|
+
files.push(join(dir, entry.name));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// No platform reports sizes from a directory read, so one `stat` per file
|
|
138
|
+
// is unavoidable — but they need not be serialised.
|
|
139
|
+
for (let offset = 0; offset < files.length; offset += STAT_BATCH) {
|
|
140
|
+
const sizes = await Promise.all(
|
|
141
|
+
files.slice(offset, offset + STAT_BATCH).map((file) => stat(file).then((info) => info.size, () => 0))
|
|
142
|
+
);
|
|
143
|
+
for (const size of sizes) sizeBytes += size;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return { sizeBytes, fileCount, dirCount, truncated };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ── Per-project slice of the host process table ──────────────────────────────
|
|
151
|
+
|
|
152
|
+
interface ProjectProcess {
|
|
153
|
+
pid: number;
|
|
154
|
+
parentPid: number;
|
|
155
|
+
name: string;
|
|
156
|
+
cpuPercent: number | null;
|
|
157
|
+
memRssBytes: number;
|
|
158
|
+
command: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
interface ProcessStats {
|
|
162
|
+
status: 'running' | 'not_running';
|
|
163
|
+
cpuPercent: number | null;
|
|
164
|
+
memRssBytes: number | null;
|
|
165
|
+
memPercent: number | null;
|
|
166
|
+
processCount: number;
|
|
167
|
+
processes: ProjectProcess[];
|
|
168
|
+
rootPids: number[];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const IDLE: ProcessStats = {
|
|
172
|
+
status: 'not_running',
|
|
173
|
+
cpuPercent: 0,
|
|
174
|
+
memRssBytes: 0,
|
|
175
|
+
memPercent: 0,
|
|
176
|
+
processCount: 0,
|
|
177
|
+
processes: [],
|
|
178
|
+
rootPids: []
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
async function getProjectProcessStats(projectId: string, totalMemBytes: number): Promise<ProcessStats> {
|
|
182
|
+
const rootPids = projectShellPids(projectId);
|
|
183
|
+
|
|
184
|
+
// No shells means nothing is running, so zero is the truth here.
|
|
185
|
+
if (rootPids.length === 0) return IDLE;
|
|
186
|
+
|
|
187
|
+
const probe = await getProcessTable();
|
|
188
|
+
|
|
189
|
+
// Shells are alive but the host table is unreadable — unknown, not zero.
|
|
190
|
+
if (!probe || probe.list.length === 0) {
|
|
191
|
+
return {
|
|
192
|
+
status: 'running',
|
|
193
|
+
cpuPercent: null,
|
|
194
|
+
memRssBytes: null,
|
|
195
|
+
memPercent: null,
|
|
196
|
+
processCount: 0,
|
|
197
|
+
processes: [],
|
|
198
|
+
rootPids
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const tree = collectProcessTree(probe.list, rootPids);
|
|
203
|
+
const matched = probe.list.filter((entry) => tree.has(entry.pid));
|
|
204
|
+
|
|
205
|
+
if (matched.length === 0) {
|
|
206
|
+
return {
|
|
207
|
+
status: 'running',
|
|
208
|
+
cpuPercent: null,
|
|
209
|
+
memRssBytes: null,
|
|
210
|
+
memPercent: null,
|
|
211
|
+
processCount: 0,
|
|
212
|
+
processes: [],
|
|
213
|
+
rootPids
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const factor = probe.cpuFactor;
|
|
218
|
+
let cpuPercent = factor === null ? null : 0;
|
|
219
|
+
let memRssBytes = 0;
|
|
220
|
+
for (const entry of matched) {
|
|
221
|
+
if (cpuPercent !== null && factor !== null) cpuPercent += entry.cpu * factor;
|
|
222
|
+
memRssBytes += entry.memRss * 1024;
|
|
223
|
+
}
|
|
224
|
+
if (cpuPercent !== null) cpuPercent = Math.min(100, Math.max(0, cpuPercent));
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
status: 'running',
|
|
228
|
+
cpuPercent,
|
|
229
|
+
memRssBytes,
|
|
230
|
+
// Same installed-RAM figure Settings -> Device divides by.
|
|
231
|
+
memPercent: totalMemBytes > 0 ? (memRssBytes / totalMemBytes) * 100 : null,
|
|
232
|
+
processCount: matched.length,
|
|
233
|
+
processes: matched
|
|
234
|
+
.slice()
|
|
235
|
+
.sort((a, b) => b.cpu - a.cpu)
|
|
236
|
+
.slice(0, 20)
|
|
237
|
+
.map((entry) => ({
|
|
238
|
+
pid: entry.pid,
|
|
239
|
+
parentPid: entry.parentPid,
|
|
240
|
+
name: entry.name,
|
|
241
|
+
cpuPercent: factor === null ? null : Math.min(100, Math.max(0, entry.cpu * factor)),
|
|
242
|
+
memRssBytes: entry.memRss * 1024,
|
|
243
|
+
command: entry.command
|
|
244
|
+
})),
|
|
245
|
+
rootPids
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ── Ports ────────────────────────────────────────────────────────────────────
|
|
250
|
+
|
|
251
|
+
export interface ProjectPort {
|
|
252
|
+
port: number;
|
|
253
|
+
protocol: string;
|
|
254
|
+
label: string;
|
|
255
|
+
publicUrl: string | null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
let cachedPorts: { entries: Map<string, ProjectPort[]>; at: number } | null = null;
|
|
259
|
+
let inFlightPorts: Promise<Map<string, ProjectPort[]>> | null = null;
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Ports the local scan already attributed to a project, grouped by project id.
|
|
263
|
+
*
|
|
264
|
+
* The attribution is the port manager's, not a second guess: it climbs from the
|
|
265
|
+
* listening pid to a terminal session using the same shell roots this handler
|
|
266
|
+
* descends from. Ports a container publishes are the runtime's, not a shell's,
|
|
267
|
+
* so they carry no project and do not appear here.
|
|
268
|
+
*/
|
|
269
|
+
export function groupPortsByProject(entries: PortEntry[]): Map<string, ProjectPort[]> {
|
|
270
|
+
const byProject = new Map<string, ProjectPort[]>();
|
|
271
|
+
|
|
272
|
+
for (const entry of entries) {
|
|
273
|
+
const projectId = entry.origin.projectId;
|
|
274
|
+
// A container's published port belongs to the runtime, not to a shell.
|
|
275
|
+
if (entry.origin.kind !== 'session' || !projectId) continue;
|
|
276
|
+
const list = byProject.get(projectId) ?? [];
|
|
277
|
+
list.push({
|
|
278
|
+
port: entry.port,
|
|
279
|
+
protocol: entry.protocol,
|
|
280
|
+
label: entry.origin.label,
|
|
281
|
+
publicUrl: entry.publicUrl
|
|
282
|
+
});
|
|
283
|
+
byProject.set(projectId, list);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return byProject;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function scanProjectPorts(): Promise<Map<string, ProjectPort[]>> {
|
|
290
|
+
try {
|
|
291
|
+
const scan = await portMonitor.scanOnce(LOCAL_PORT_HOST);
|
|
292
|
+
return groupPortsByProject(scan.entries);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
// A panel that cannot list ports still reports storage and usage.
|
|
295
|
+
debug.warn('project', 'port scan failed for project info:', error);
|
|
296
|
+
return new Map();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Cached and single-flighted — one scan serves every open panel. */
|
|
301
|
+
function getProjectPorts(projectId: string): Promise<ProjectPort[]> {
|
|
302
|
+
const pick = (entries: Map<string, ProjectPort[]>) =>
|
|
303
|
+
(entries.get(projectId) ?? []).sort((left, right) => left.port - right.port);
|
|
304
|
+
|
|
305
|
+
if (cachedPorts && Date.now() - cachedPorts.at < PORTS_CACHE_TTL_MS) {
|
|
306
|
+
return Promise.resolve(pick(cachedPorts.entries));
|
|
307
|
+
}
|
|
308
|
+
if (inFlightPorts) return inFlightPorts.then(pick);
|
|
309
|
+
|
|
310
|
+
inFlightPorts = scanProjectPorts().then((entries) => {
|
|
311
|
+
cachedPorts = { entries, at: Date.now() };
|
|
312
|
+
inFlightPorts = null;
|
|
313
|
+
return entries;
|
|
314
|
+
});
|
|
315
|
+
return inFlightPorts.then(pick);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ── Handler ──────────────────────────────────────────────────────────────────
|
|
319
|
+
|
|
320
|
+
const nullableNumber = t.Union([t.Number(), t.Null()]);
|
|
321
|
+
|
|
322
|
+
export const infoHandler = createRouter().http(
|
|
323
|
+
'projects:info',
|
|
324
|
+
{
|
|
325
|
+
data: t.Object({
|
|
326
|
+
id: t.String({ minLength: 1 })
|
|
327
|
+
}),
|
|
328
|
+
response: t.Object({
|
|
329
|
+
project: t.Any(),
|
|
330
|
+
storage: t.Object({
|
|
331
|
+
sizeBytes: t.Number(),
|
|
332
|
+
fileCount: t.Number(),
|
|
333
|
+
dirCount: t.Number(),
|
|
334
|
+
truncated: t.Boolean(),
|
|
335
|
+
error: t.Optional(t.String())
|
|
336
|
+
}),
|
|
337
|
+
resources: t.Object({
|
|
338
|
+
status: t.Union([t.Literal('running'), t.Literal('not_running')]),
|
|
339
|
+
cpuPercent: nullableNumber,
|
|
340
|
+
memRssBytes: nullableNumber,
|
|
341
|
+
memPercent: nullableNumber,
|
|
342
|
+
processCount: t.Number(),
|
|
343
|
+
rootPids: t.Array(t.Number()),
|
|
344
|
+
processes: t.Array(
|
|
345
|
+
t.Object({
|
|
346
|
+
pid: t.Number(),
|
|
347
|
+
parentPid: t.Number(),
|
|
348
|
+
name: t.String(),
|
|
349
|
+
cpuPercent: nullableNumber,
|
|
350
|
+
memRssBytes: t.Number(),
|
|
351
|
+
command: t.String()
|
|
352
|
+
})
|
|
353
|
+
)
|
|
354
|
+
}),
|
|
355
|
+
ports: t.Array(
|
|
356
|
+
t.Object({
|
|
357
|
+
port: t.Number(),
|
|
358
|
+
protocol: t.String(),
|
|
359
|
+
label: t.String(),
|
|
360
|
+
publicUrl: t.Union([t.String(), t.Null()])
|
|
361
|
+
})
|
|
362
|
+
),
|
|
363
|
+
meta: t.Object({
|
|
364
|
+
platform: t.String(),
|
|
365
|
+
arch: t.String(),
|
|
366
|
+
logicalCores: t.Number()
|
|
367
|
+
})
|
|
368
|
+
})
|
|
369
|
+
},
|
|
370
|
+
async ({ data, conn }) => {
|
|
371
|
+
requireProjectAccess(conn, data.id);
|
|
372
|
+
const project = projectQueries.getById(data.id);
|
|
373
|
+
if (!project) {
|
|
374
|
+
throw new Error('Project not found');
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// Probed once per process, so only the first caller pays.
|
|
378
|
+
const facts = await getHostFacts();
|
|
379
|
+
|
|
380
|
+
const [storage, resources, ports] = await Promise.all([
|
|
381
|
+
getFolderStats(project.path),
|
|
382
|
+
getProjectProcessStats(data.id, facts.totalMemBytes),
|
|
383
|
+
getProjectPorts(data.id)
|
|
384
|
+
]);
|
|
385
|
+
|
|
386
|
+
return {
|
|
387
|
+
project,
|
|
388
|
+
storage,
|
|
389
|
+
resources,
|
|
390
|
+
ports,
|
|
391
|
+
meta: {
|
|
392
|
+
platform: facts.platform,
|
|
393
|
+
arch: facts.arch,
|
|
394
|
+
logicalCores: facts.logicalCores
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
);
|
|
@@ -14,7 +14,7 @@ import { t } from 'elysia';
|
|
|
14
14
|
import { createRouter } from '$shared/utils/ws-server';
|
|
15
15
|
import type { EngineType } from '$shared/types/unified';
|
|
16
16
|
import type { ChatSession } from '$shared/types/database/schema';
|
|
17
|
-
import { sessionQueries, messageQueries, projectQueries, snapshotQueries } from '../../database/queries';
|
|
17
|
+
import { sessionQueries, messageQueries, projectQueries, snapshotQueries, worktreeQueries } from '../../database/queries';
|
|
18
18
|
import { ws } from '$backend/utils/ws';
|
|
19
19
|
import { streamManager } from '../../chat/stream-manager';
|
|
20
20
|
import { snapshotService } from '../../snapshot/snapshot-service';
|
|
@@ -44,6 +44,8 @@ const sessionSchema = t.Object({
|
|
|
44
44
|
head_session_id: t.Optional(t.String()),
|
|
45
45
|
head_title: t.Optional(t.String()),
|
|
46
46
|
head_summary: t.Optional(t.String()),
|
|
47
|
+
// Isolation
|
|
48
|
+
worktree_id: t.Optional(t.Union([t.String(), t.Null()])),
|
|
47
49
|
// Activity tracking
|
|
48
50
|
sender_id: t.Optional(t.String()),
|
|
49
51
|
sender_name: t.Optional(t.String()),
|
|
@@ -78,9 +80,17 @@ function serializeSession(session: ChatSession) {
|
|
|
78
80
|
message_count: session.message_count ?? undefined,
|
|
79
81
|
user_count: session.user_count ?? undefined,
|
|
80
82
|
last_message_at: session.last_message_at ?? undefined,
|
|
83
|
+
worktree_id: session.worktree_id ?? null,
|
|
81
84
|
};
|
|
82
85
|
}
|
|
83
86
|
|
|
87
|
+
/** Validate a requested worktree belongs to this project; anything else is main. */
|
|
88
|
+
function resolveRequestedWorktree(projectId: string, worktreeId: string | null | undefined): string | null {
|
|
89
|
+
if (!worktreeId) return null;
|
|
90
|
+
const worktree = worktreeQueries.getById(worktreeId);
|
|
91
|
+
return worktree && worktree.project_id === projectId ? worktree.id : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
84
94
|
export const crudHandler = createRouter()
|
|
85
95
|
// List sessions (includes server-saved current session ID for refresh restore)
|
|
86
96
|
.http('sessions:list', {
|
|
@@ -125,7 +135,8 @@ export const crudHandler = createRouter()
|
|
|
125
135
|
.http('sessions:create', {
|
|
126
136
|
data: t.Object({
|
|
127
137
|
title: t.Optional(t.String()),
|
|
128
|
-
engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen'), t.Literal('pi'), t.Literal('cline'), t.Literal('cursor')]))
|
|
138
|
+
engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen'), t.Literal('pi'), t.Literal('cline'), t.Literal('cursor')])),
|
|
139
|
+
worktreeId: t.Optional(t.Union([t.String(), t.Null()]))
|
|
129
140
|
}),
|
|
130
141
|
response: sessionSchema
|
|
131
142
|
}, async ({ data, conn }) => {
|
|
@@ -136,7 +147,8 @@ export const crudHandler = createRouter()
|
|
|
136
147
|
project_id: projectId,
|
|
137
148
|
title: data.title || 'New Chat Session',
|
|
138
149
|
engine,
|
|
139
|
-
started_at: now
|
|
150
|
+
started_at: now,
|
|
151
|
+
worktree_id: resolveRequestedWorktree(projectId, data.worktreeId)
|
|
140
152
|
});
|
|
141
153
|
|
|
142
154
|
return serializeSession(session);
|
|
@@ -166,20 +178,23 @@ export const crudHandler = createRouter()
|
|
|
166
178
|
// Get or create shared session
|
|
167
179
|
.http('sessions:get-shared', {
|
|
168
180
|
data: t.Object({
|
|
169
|
-
forceNew: t.Optional(t.Boolean())
|
|
181
|
+
forceNew: t.Optional(t.Boolean()),
|
|
182
|
+
worktreeId: t.Optional(t.Union([t.String(), t.Null()]))
|
|
170
183
|
}),
|
|
171
184
|
response: sessionSchema
|
|
172
185
|
}, async ({ data, conn }) => {
|
|
173
186
|
const { projectId, project } = requireCurrentProjectAccess(conn);
|
|
187
|
+
const worktreeId = resolveRequestedWorktree(projectId, data.worktreeId);
|
|
174
188
|
|
|
175
189
|
// Check if an active session already exists BEFORE get-or-create
|
|
176
|
-
const existingActiveSession = (data.forceNew) ? null : sessionQueries.getActiveSessionForProject(projectId);
|
|
190
|
+
const existingActiveSession = (data.forceNew) ? null : sessionQueries.getActiveSessionForProject(projectId, worktreeId);
|
|
177
191
|
|
|
178
192
|
// Get or create shared session
|
|
179
193
|
const session = sessionQueries.getOrCreateSharedSession(
|
|
180
194
|
projectId,
|
|
181
195
|
project.name,
|
|
182
|
-
data.forceNew || false
|
|
196
|
+
data.forceNew || false,
|
|
197
|
+
worktreeId
|
|
183
198
|
);
|
|
184
199
|
|
|
185
200
|
const sessionResponse = serializeSession(session);
|