@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
|
@@ -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);
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import { t } from 'elysia';
|
|
10
10
|
import { createRouter } from '$shared/utils/ws-server';
|
|
11
|
-
import { messageQueries, sessionQueries,
|
|
11
|
+
import { messageQueries, sessionQueries, checkpointQueries } from '../../database/queries';
|
|
12
12
|
import { snapshotService } from '../../snapshot/snapshot-service';
|
|
13
13
|
import { streamManager } from '../../chat/stream-manager';
|
|
14
14
|
import { debug } from '$shared/utils/logger';
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from '../../snapshot/helpers';
|
|
23
23
|
import { ws } from '$backend/utils/ws';
|
|
24
24
|
import { requireSessionAccess } from '../access';
|
|
25
|
+
import { resolveSessionRoot } from '../../worktrees';
|
|
25
26
|
|
|
26
27
|
export const restoreHandler = createRouter()
|
|
27
28
|
/**
|
|
@@ -52,13 +53,9 @@ export const restoreHandler = createRouter()
|
|
|
52
53
|
|
|
53
54
|
debug.log('snapshot', `Checking restore conflicts for checkpoint ${messageId} in session ${sessionId}`);
|
|
54
55
|
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
if (session) {
|
|
59
|
-
const project = projectQueries.getById(session.project_id);
|
|
60
|
-
if (project) projectPath = project.path;
|
|
61
|
-
}
|
|
56
|
+
// Read file contents from the tree this session actually runs in —
|
|
57
|
+
// its worktree when it has one, the project otherwise.
|
|
58
|
+
const projectPath = resolveSessionRoot(sessionId)?.path || undefined;
|
|
62
59
|
|
|
63
60
|
// Build checkpoint path for branch-aware conflict detection
|
|
64
61
|
let targetPath: string[] | undefined;
|
|
@@ -147,10 +144,10 @@ export const restoreHandler = createRouter()
|
|
|
147
144
|
let filesRestored = 0;
|
|
148
145
|
let filesSkipped = 0;
|
|
149
146
|
|
|
150
|
-
const
|
|
151
|
-
if (
|
|
147
|
+
const sessionRoot = resolveSessionRoot(sessionId);
|
|
148
|
+
if (sessionRoot?.path) {
|
|
152
149
|
const result = await snapshotService.restoreSessionScoped(
|
|
153
|
-
|
|
150
|
+
sessionRoot.path,
|
|
154
151
|
sessionId,
|
|
155
152
|
null, // null = restore to initial (before all snapshots)
|
|
156
153
|
conflictResolutions
|
|
@@ -327,10 +324,10 @@ export const restoreHandler = createRouter()
|
|
|
327
324
|
let filesRestored = 0;
|
|
328
325
|
let filesSkipped = 0;
|
|
329
326
|
|
|
330
|
-
const
|
|
331
|
-
if (
|
|
327
|
+
const sessionRoot = resolveSessionRoot(sessionId);
|
|
328
|
+
if (sessionRoot?.path) {
|
|
332
329
|
const result = await snapshotService.restoreSessionScoped(
|
|
333
|
-
|
|
330
|
+
sessionRoot.path,
|
|
334
331
|
sessionId,
|
|
335
332
|
resolvedCheckpointId,
|
|
336
333
|
conflictResolutions,
|