@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.
Files changed (125) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/auth/permissions.ts +7 -0
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  20. package/backend/database/migrations/index.ts +7 -0
  21. package/backend/database/queries/index.ts +1 -0
  22. package/backend/database/queries/session-queries.ts +50 -11
  23. package/backend/database/queries/worktree-queries.ts +148 -0
  24. package/backend/engine/adapters/opencode/server.ts +389 -83
  25. package/backend/engine/adapters/opencode/stream.ts +14 -14
  26. package/backend/engine/hot-reload.ts +25 -10
  27. package/backend/files/file-watcher.test.ts +105 -0
  28. package/backend/files/file-watcher.ts +80 -10
  29. package/backend/git/git-service.test.ts +33 -0
  30. package/backend/git/git-service.ts +7 -3
  31. package/backend/git/nested-repos.test.ts +292 -1
  32. package/backend/git/nested-repos.ts +330 -17
  33. package/backend/host/metrics.test.ts +110 -0
  34. package/backend/host/metrics.ts +235 -0
  35. package/backend/{ports → host}/runner.ts +19 -10
  36. package/backend/index.ts +16 -4
  37. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  38. package/backend/ports/attribute.test.ts +3 -2
  39. package/backend/ports/attribute.ts +6 -45
  40. package/backend/ports/kill.ts +1 -1
  41. package/backend/ports/monitor.ts +1 -1
  42. package/backend/ports/processes.ts +1 -1
  43. package/backend/ports/scan-host.ts +77 -8
  44. package/backend/ports/scan.test.ts +1 -1
  45. package/backend/ports/scan.ts +1 -1
  46. package/backend/ports/ssh-lineage.ts +1 -1
  47. package/backend/preview/browser/browser-pool.ts +81 -0
  48. package/backend/preview/browser/browser-preview-service.ts +142 -32
  49. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  50. package/backend/preview/browser/browser-video-capture.ts +84 -31
  51. package/backend/preview/browser/types.ts +9 -0
  52. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  53. package/backend/projects/project-cleanup.ts +7 -1
  54. package/backend/projects/shell-ownership.ts +65 -0
  55. package/backend/snapshot/snapshot-service.ts +6 -2
  56. package/backend/terminal/ptykit.ts +35 -6
  57. package/backend/utils/ws.ts +21 -1
  58. package/backend/worktrees/clone.ts +222 -0
  59. package/backend/worktrees/index.ts +29 -0
  60. package/backend/worktrees/merge.test.ts +93 -0
  61. package/backend/worktrees/merge.ts +232 -0
  62. package/backend/worktrees/paths.test.ts +60 -0
  63. package/backend/worktrees/paths.ts +60 -0
  64. package/backend/worktrees/resolve.ts +67 -0
  65. package/backend/worktrees/service.ts +315 -0
  66. package/backend/worktrees/tree.ts +59 -0
  67. package/backend/ws/access.ts +18 -0
  68. package/backend/ws/artifacts/generate.ts +2 -2
  69. package/backend/ws/chat/stream.ts +9 -2
  70. package/backend/ws/containers/actions.ts +156 -0
  71. package/backend/ws/containers/index.ts +43 -0
  72. package/backend/ws/containers/list.ts +146 -0
  73. package/backend/ws/containers/logs.ts +43 -0
  74. package/backend/ws/containers/tunnel.ts +101 -0
  75. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  76. package/backend/ws/files/path-access.test.ts +93 -1
  77. package/backend/ws/files/path-access.ts +54 -5
  78. package/backend/ws/files/read.ts +15 -10
  79. package/backend/ws/files/search.ts +7 -7
  80. package/backend/ws/files/state.ts +70 -8
  81. package/backend/ws/files/watch.ts +16 -14
  82. package/backend/ws/git/branch-name.ts +3 -3
  83. package/backend/ws/git/branch.ts +15 -15
  84. package/backend/ws/git/commit-message.ts +3 -3
  85. package/backend/ws/git/commit.ts +17 -17
  86. package/backend/ws/git/conflict.ts +10 -10
  87. package/backend/ws/git/diff.ts +9 -9
  88. package/backend/ws/git/ignored.ts +9 -9
  89. package/backend/ws/git/log.ts +6 -4
  90. package/backend/ws/git/remote.ts +43 -43
  91. package/backend/ws/git/staging.ts +16 -16
  92. package/backend/ws/git/status.ts +47 -37
  93. package/backend/ws/index.ts +6 -0
  94. package/backend/ws/message-rate-limiter.test.ts +45 -0
  95. package/backend/ws/message-rate-limiter.ts +34 -3
  96. package/backend/ws/preview/access.ts +11 -3
  97. package/backend/ws/projects/index.ts +5 -1
  98. package/backend/ws/projects/info.test.ts +54 -0
  99. package/backend/ws/projects/info.ts +398 -0
  100. package/backend/ws/sessions/crud.ts +21 -6
  101. package/backend/ws/snapshot/restore.ts +11 -14
  102. package/backend/ws/ssh/connections.ts +8 -0
  103. package/backend/ws/system/device-info.ts +70 -96
  104. package/backend/ws/worktrees/crud.ts +187 -0
  105. package/backend/ws/worktrees/index.ts +33 -0
  106. package/backend/ws/worktrees/transfer.ts +88 -0
  107. package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
  108. package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
  109. package/dist/assets/main-9G7IpQpK.css +1 -0
  110. package/dist/assets/main-BofFsH8E.js +1085 -0
  111. package/dist/index.html +2 -2
  112. package/dist/manifest.json +9 -2
  113. package/package.json +1 -1
  114. package/shared/types/containers/container.ts +366 -0
  115. package/shared/types/containers/index.ts +5 -0
  116. package/shared/types/database/schema.ts +26 -0
  117. package/shared/types/host/index.ts +18 -0
  118. package/shared/types/ports/port.ts +47 -9
  119. package/shared/utils/logger.ts +3 -0
  120. package/shared/utils/workspace-scope.test.ts +80 -0
  121. package/shared/utils/workspace-scope.ts +57 -0
  122. package/shared/utils/ws-client.ts +92 -17
  123. package/shared/utils/ws-server.ts +83 -16
  124. package/dist/assets/main-CYCMEbXB.css +0 -1
  125. package/dist/assets/main-ZCojSzvW.js +0 -1060
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Resolving the working root of a chat session.
3
+ *
4
+ * Anything that runs on behalf of a session — the engine, snapshots, file
5
+ * reads — must use this rather than the path the client sent. The client's
6
+ * value is a view preference; the session's worktree is the fact, and letting
7
+ * the two disagree is how an isolated task ends up writing into the main tree.
8
+ */
9
+
10
+ import { existsSync } from 'fs';
11
+ import { projectQueries, sessionQueries, worktreeQueries } from '../database/queries';
12
+ import { debug } from '$shared/utils/logger';
13
+
14
+ export interface SessionRoot {
15
+ path: string;
16
+ projectId: string;
17
+ worktreeId: string | null;
18
+ worktreeName: string | null;
19
+ }
20
+
21
+ /**
22
+ * Root directory a worktree points at, or the project path when `worktreeId` is
23
+ * null. Falls back to the project when the worktree directory has vanished —
24
+ * a session must stay usable even if its worktree was deleted outside Clopen.
25
+ */
26
+ export function resolveWorktreeRoot(projectId: string, worktreeId: string | null): SessionRoot {
27
+ const project = projectQueries.getById(projectId);
28
+ const projectPath = project?.path ?? '';
29
+
30
+ if (!worktreeId) {
31
+ return { path: projectPath, projectId, worktreeId: null, worktreeName: null };
32
+ }
33
+
34
+ const worktree = worktreeQueries.getById(worktreeId);
35
+ if (!worktree || worktree.project_id !== projectId) {
36
+ return { path: projectPath, projectId, worktreeId: null, worktreeName: null };
37
+ }
38
+
39
+ if (!existsSync(worktree.path)) {
40
+ debug.warn('worktree', `Worktree directory missing, using main tree: ${worktree.path}`);
41
+ return { path: projectPath, projectId, worktreeId: null, worktreeName: null };
42
+ }
43
+
44
+ return {
45
+ path: worktree.path,
46
+ projectId,
47
+ worktreeId: worktree.id,
48
+ worktreeName: worktree.name
49
+ };
50
+ }
51
+
52
+ /** Working root for a session, or null when the session is unknown. */
53
+ export function resolveSessionRoot(sessionId: string): SessionRoot | null {
54
+ const session = sessionQueries.getById(sessionId);
55
+ if (!session) return null;
56
+ return resolveWorktreeRoot(session.project_id, session.worktree_id ?? null);
57
+ }
58
+
59
+ /**
60
+ * Working root for a session, preferring the session's own binding and falling
61
+ * back to the caller-supplied path when the session cannot be resolved.
62
+ */
63
+ export function resolveSessionPath(sessionId: string | undefined, fallbackPath: string): string {
64
+ if (!sessionId) return fallbackPath;
65
+ const root = resolveSessionRoot(sessionId);
66
+ return root?.path || fallbackPath;
67
+ }
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Worktree lifecycle: create, inspect, transfer, remove.
3
+ */
4
+
5
+ import fs from 'fs/promises';
6
+ import path from 'path';
7
+ import type { Worktree } from '$shared/types/database/schema';
8
+ import type { TreeMap } from '../snapshot/blob-store';
9
+ import { projectQueries, worktreeQueries } from '../database/queries';
10
+ import { fileWatcher } from '../files/file-watcher';
11
+ import { debug } from '$shared/utils/logger';
12
+ import { cleanupWorktreeSessions } from '../terminal/ptykit';
13
+ import { browserPreviewServiceManager } from '../preview';
14
+ import { makeScopeKey } from '$shared/utils/workspace-scope';
15
+ import { cloneTree } from './clone';
16
+ import {
17
+ applyMergePlan,
18
+ markAutoMergeable,
19
+ planMerge,
20
+ type MergeEntry,
21
+ type MergePlan,
22
+ type MergeResolution
23
+ } from './merge';
24
+ import { getProjectWorktreesDir, getWorktreePath, uniqueWorktreeSlug } from './paths';
25
+ import { hashTree, readBlobText } from './tree';
26
+
27
+ /** Worktree → main is `apply`; main → worktree is `sync`. */
28
+ export type TransferDirection = 'apply' | 'sync';
29
+
30
+ /** Conflict previews are truncated — the dialog shows a diff, not a whole file. */
31
+ const MAX_PREVIEW_BYTES = 256 * 1024;
32
+
33
+ export interface WorktreeChange {
34
+ path: string;
35
+ status: MergeEntry['status'];
36
+ conflict: boolean;
37
+ autoMergeable: boolean;
38
+ }
39
+
40
+ export interface WorktreeConflictPreview extends WorktreeChange {
41
+ sourceContent?: string;
42
+ targetContent?: string;
43
+ }
44
+
45
+ export interface TransferPreview {
46
+ direction: TransferDirection;
47
+ changes: WorktreeChange[];
48
+ conflicts: WorktreeConflictPreview[];
49
+ }
50
+
51
+ export interface TransferResult {
52
+ written: number;
53
+ deleted: number;
54
+ skipped: number;
55
+ failed: string[];
56
+ }
57
+
58
+ export interface WorktreeCreateResult {
59
+ worktree: Worktree;
60
+ fileCount: number;
61
+ carriedIgnoredFiles: boolean;
62
+ }
63
+
64
+ /**
65
+ * Clone the project into a new worktree.
66
+ *
67
+ * The base tree is hashed *after* the clone so the recorded merge base matches
68
+ * what the worktree actually starts from, and its blobs are stored so a
69
+ * three-way merge is still possible once both sides have moved on.
70
+ */
71
+ export async function createWorktree(input: {
72
+ projectId: string;
73
+ name: string;
74
+ createdBy?: string | null;
75
+ }): Promise<WorktreeCreateResult> {
76
+ const project = projectQueries.getById(input.projectId);
77
+ if (!project) throw new Error('Project not found');
78
+
79
+ const projectExists = await pathExists(project.path);
80
+ if (!projectExists) throw new Error(`Project path does not exist: ${project.path}`);
81
+
82
+ const takenSlugs = new Set(worktreeQueries.getByProjectId(input.projectId).map((row) => row.slug));
83
+ const slug = uniqueWorktreeSlug(input.name, takenSlugs);
84
+ const targetPath = getWorktreePath(input.projectId, slug);
85
+
86
+ if (await pathExists(targetPath)) {
87
+ // Left behind by a crashed create — the DB row is the source of truth.
88
+ await fs.rm(targetPath, { recursive: true, force: true });
89
+ }
90
+ await fs.mkdir(targetPath, { recursive: true });
91
+
92
+ let clone;
93
+ try {
94
+ clone = await cloneTree(project.path, targetPath);
95
+ } catch (error) {
96
+ await fs.rm(targetPath, { recursive: true, force: true }).catch(() => {});
97
+ throw error;
98
+ }
99
+
100
+ const baseTree = await hashTree(targetPath, true);
101
+
102
+ const worktree = worktreeQueries.create({
103
+ project_id: input.projectId,
104
+ name: input.name.trim() || slug,
105
+ slug,
106
+ path: targetPath,
107
+ clone_mode: clone.mode,
108
+ base_tree: baseTree,
109
+ created_by: input.createdBy ?? null
110
+ });
111
+
112
+ debug.log('worktree', `Created worktree "${worktree.name}" (${clone.mode}) at ${targetPath}`);
113
+ return { worktree, fileCount: clone.fileCount, carriedIgnoredFiles: clone.carriedIgnoredFiles };
114
+ }
115
+
116
+ /** Delete the worktree directory and its row. Sessions fall back to the main tree. */
117
+ export async function removeWorktree(worktreeId: string): Promise<void> {
118
+ const worktree = worktreeQueries.getById(worktreeId);
119
+ if (!worktree) return;
120
+
121
+ // Shells and browser tabs live in the worktree's own scope; without this they
122
+ // would outlive the directory they were opened in.
123
+ releaseWorkspaceScope(worktree.project_id, worktree.id);
124
+
125
+ await fs.rm(worktree.path, { recursive: true, force: true }).catch((error) => {
126
+ debug.warn('worktree', `Could not remove ${worktree.path}: ${error}`);
127
+ });
128
+ worktreeQueries.delete(worktreeId);
129
+ debug.log('worktree', `Removed worktree ${worktree.name}`);
130
+ }
131
+
132
+ /** Remove every worktree of a project — used when the project itself is deleted. */
133
+ export async function removeProjectWorktrees(projectId: string): Promise<void> {
134
+ for (const worktree of worktreeQueries.deleteByProjectId(projectId)) {
135
+ releaseWorkspaceScope(projectId, worktree.id);
136
+ }
137
+ await fs.rm(getProjectWorktreesDir(projectId), { recursive: true, force: true }).catch(() => {});
138
+ }
139
+
140
+ /** Tear down the per-workspace resources a worktree owns. */
141
+ function releaseWorkspaceScope(projectId: string, worktreeId: string): void {
142
+ const scopeKey = makeScopeKey(projectId, worktreeId);
143
+ try {
144
+ cleanupWorktreeSessions(projectId, worktreeId);
145
+ void browserPreviewServiceManager.removeService(scopeKey);
146
+ fileWatcher.releaseProject(scopeKey);
147
+ } catch (error) {
148
+ debug.warn('worktree', `Scope cleanup failed for ${scopeKey}: ${error}`);
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Disk actually occupied by a worktree, in kilobytes.
154
+ *
155
+ * `du` reports allocated blocks rather than apparent size, so a reflink clone
156
+ * correctly shows near-zero until its files are written to. Returns null where
157
+ * `du` is unavailable (Windows) rather than reporting a misleading number.
158
+ */
159
+ export async function getWorktreeDiskUsage(worktreePath: string): Promise<number | null> {
160
+ if (process.platform === 'win32') return null;
161
+
162
+ try {
163
+ const proc = Bun.spawn(['du', '-sk', worktreePath], { stdout: 'pipe', stderr: 'ignore' });
164
+ const output = await new Response(proc.stdout).text();
165
+ await proc.exited;
166
+ const kilobytes = Number.parseInt(output.trim().split(/\s+/)[0] ?? '', 10);
167
+ return Number.isFinite(kilobytes) ? kilobytes : null;
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ /** Resolve which trees are source and target for a direction. */
174
+ function resolveEnds(worktree: Worktree, direction: TransferDirection) {
175
+ const project = projectQueries.getById(worktree.project_id);
176
+ if (!project) throw new Error('Project not found');
177
+
178
+ return direction === 'apply'
179
+ ? { sourceRoot: worktree.path, targetRoot: project.path }
180
+ : { sourceRoot: project.path, targetRoot: worktree.path };
181
+ }
182
+
183
+ /** Build the plan for a transfer, hashing both live trees against the stored base. */
184
+ async function buildPlan(
185
+ worktree: Worktree,
186
+ direction: TransferDirection
187
+ ): Promise<{ plan: MergePlan; sourceRoot: string; targetRoot: string; baseTree: TreeMap }> {
188
+ const { sourceRoot, targetRoot } = resolveEnds(worktree, direction);
189
+ const baseTree = worktreeQueries.parseBaseTree(worktree);
190
+
191
+ const [sourceTree, targetTree] = await Promise.all([hashTree(sourceRoot), hashTree(targetRoot)]);
192
+
193
+ const plan = await markAutoMergeable(
194
+ planMerge(baseTree, sourceTree, targetTree),
195
+ sourceRoot,
196
+ targetRoot
197
+ );
198
+
199
+ return { plan, sourceRoot, targetRoot, baseTree };
200
+ }
201
+
202
+ /** What a transfer would do, including previews for every file needing a decision. */
203
+ export async function previewTransfer(
204
+ worktreeId: string,
205
+ direction: TransferDirection
206
+ ): Promise<TransferPreview> {
207
+ const worktree = requireWorktree(worktreeId);
208
+ const { plan, sourceRoot, targetRoot } = await buildPlan(worktree, direction);
209
+
210
+ const changes: WorktreeChange[] = plan.entries.map((entry) => ({
211
+ path: entry.path,
212
+ status: entry.status,
213
+ conflict: entry.conflict,
214
+ autoMergeable: entry.autoMergeable
215
+ }));
216
+
217
+ const conflicts: WorktreeConflictPreview[] = [];
218
+ for (const entry of plan.conflicts) {
219
+ conflicts.push({
220
+ path: entry.path,
221
+ status: entry.status,
222
+ conflict: true,
223
+ autoMergeable: entry.autoMergeable,
224
+ sourceContent: await previewContent(sourceRoot, entry.path, entry.sourceHash),
225
+ targetContent: await previewContent(targetRoot, entry.path, entry.targetHash)
226
+ });
227
+ }
228
+
229
+ return { direction, changes, conflicts };
230
+ }
231
+
232
+ /**
233
+ * Run the transfer, then re-base the worktree onto the main tree as it now
234
+ * stands. Without the re-base every later transfer would re-propose the same
235
+ * files, including the ones the user deliberately declined.
236
+ */
237
+ export async function executeTransfer(
238
+ worktreeId: string,
239
+ direction: TransferDirection,
240
+ resolutions: Record<string, MergeResolution>
241
+ ): Promise<TransferResult> {
242
+ const worktree = requireWorktree(worktreeId);
243
+ const { plan, sourceRoot, targetRoot } = await buildPlan(worktree, direction);
244
+
245
+ const applied = await applyMergePlan(plan, sourceRoot, targetRoot, resolutions);
246
+
247
+ const project = projectQueries.getById(worktree.project_id);
248
+ const newBase = project ? await hashTree(project.path, true) : null;
249
+
250
+ if (newBase) {
251
+ if (direction === 'apply') {
252
+ worktreeQueries.markApplied(worktreeId, newBase);
253
+ } else {
254
+ worktreeQueries.updateBaseTree(worktreeId, newBase);
255
+ }
256
+ }
257
+
258
+ debug.log(
259
+ 'worktree',
260
+ `Transfer ${direction} on ${worktree.name}: ${applied.written.length} written, ${applied.deleted.length} deleted, ${applied.skipped.length} skipped`
261
+ );
262
+
263
+ return {
264
+ written: applied.written.length,
265
+ deleted: applied.deleted.length,
266
+ skipped: applied.skipped.length,
267
+ failed: applied.failed
268
+ };
269
+ }
270
+
271
+ /** Count of files a worktree has diverged by, for the manager list. */
272
+ export async function countPendingChanges(worktreeId: string): Promise<number> {
273
+ const worktree = worktreeQueries.getById(worktreeId);
274
+ if (!worktree) return 0;
275
+
276
+ try {
277
+ const { plan } = await buildPlan(worktree, 'apply');
278
+ return plan.entries.length;
279
+ } catch {
280
+ return 0;
281
+ }
282
+ }
283
+
284
+ function requireWorktree(worktreeId: string): Worktree {
285
+ const worktree = worktreeQueries.getById(worktreeId);
286
+ if (!worktree) throw new Error('Worktree not found');
287
+ return worktree;
288
+ }
289
+
290
+ /** Current content of one side, falling back to the blob when the file is gone. */
291
+ async function previewContent(
292
+ root: string,
293
+ relativePath: string,
294
+ hash: string | null
295
+ ): Promise<string | undefined> {
296
+ if (hash === null) return undefined;
297
+
298
+ try {
299
+ const buffer = await fs.readFile(path.join(root, relativePath));
300
+ if (buffer.includes(0)) return '(binary file)';
301
+ return buffer.subarray(0, MAX_PREVIEW_BYTES).toString('utf-8');
302
+ } catch {
303
+ const text = await readBlobText(hash);
304
+ return text ?? undefined;
305
+ }
306
+ }
307
+
308
+ async function pathExists(target: string): Promise<boolean> {
309
+ try {
310
+ await fs.access(target);
311
+ return true;
312
+ } catch {
313
+ return false;
314
+ }
315
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Hashing a tree into the Checkpoints blob store.
3
+ *
4
+ * Worktree merges are three-way, so the base content has to outlive the tree it
5
+ * came from — the blobs are what make a merge base recoverable after both sides
6
+ * have moved on.
7
+ */
8
+
9
+ import fs from 'fs/promises';
10
+ import path from 'path';
11
+ import { blobStore, type TreeMap } from '../snapshot/blob-store';
12
+ import { getSnapshotFiles } from '../snapshot/gitignore';
13
+ import { debug } from '$shared/utils/logger';
14
+
15
+ /** Mirrors the snapshot service cap — larger files are never tracked. */
16
+ export const MAX_TRACKED_FILE_SIZE = 5 * 1024 * 1024;
17
+
18
+ /**
19
+ * Hash every snapshot-eligible file under `root`.
20
+ * When `storeBlobs` is set, contents are written to the blob store so they can
21
+ * be read back as a merge base later.
22
+ */
23
+ export async function hashTree(root: string, storeBlobs = false): Promise<TreeMap> {
24
+ if (storeBlobs) await blobStore.init();
25
+
26
+ const files = await getSnapshotFiles(root);
27
+ const tree: TreeMap = {};
28
+
29
+ for (const absolute of files) {
30
+ try {
31
+ const stat = await fs.stat(absolute);
32
+ if (stat.size > MAX_TRACKED_FILE_SIZE) continue;
33
+
34
+ const relativePath = path.relative(root, absolute).replace(/\\/g, '/');
35
+ const result = await blobStore.hashFile(relativePath, absolute);
36
+ tree[relativePath] = result.hash;
37
+
38
+ if (storeBlobs && !(await blobStore.hasBlob(result.hash))) {
39
+ const content = result.content ?? (await fs.readFile(absolute));
40
+ await blobStore.storeBlob(content);
41
+ }
42
+ } catch {
43
+ // Unreadable file — leave it out of the tree
44
+ }
45
+ }
46
+
47
+ debug.log('worktree', `Hashed ${Object.keys(tree).length} files under ${root}`);
48
+ return tree;
49
+ }
50
+
51
+ /** Read a blob back as text, or null when it is missing or not decodable. */
52
+ export async function readBlobText(hash: string): Promise<string | null> {
53
+ try {
54
+ const buffer = await blobStore.readBlob(hash);
55
+ return buffer.toString('utf-8');
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
@@ -2,6 +2,7 @@ import type { WSConnection } from '$shared/utils/ws-server';
2
2
  import type { Project, ChatSession, DatabaseMessage } from '$shared/types/database/schema';
3
3
  import { ws } from '$backend/utils/ws';
4
4
  import { projectQueries, sessionQueries, messageQueries } from '$backend/database/queries';
5
+ import { resolveWorktreeRoot } from '$backend/worktrees';
5
6
 
6
7
  export function requireProjectAccess(conn: WSConnection, projectId: string): Project {
7
8
  const userId = ws.getUserId(conn);
@@ -18,6 +19,23 @@ export function requireProjectAccess(conn: WSConnection, projectId: string): Pro
18
19
  return project;
19
20
  }
20
21
 
22
+ /**
23
+ * Project access plus the workspace root the connection is viewing.
24
+ *
25
+ * Anything that runs against a repository or a tree must use `root`: a worktree
26
+ * is its own checkout, and resolving to `project.path` silently ran every git
27
+ * command against the main tree instead.
28
+ */
29
+ export function requireProjectWorkspace(conn: WSConnection, projectId: string): {
30
+ project: Project;
31
+ root: string;
32
+ worktreeId: string | null;
33
+ } {
34
+ const project = requireProjectAccess(conn, projectId);
35
+ const resolved = resolveWorktreeRoot(projectId, ws.getWorktreeId(conn));
36
+ return { project, root: resolved.path || project.path, worktreeId: resolved.worktreeId };
37
+ }
38
+
21
39
  export function requireCurrentProjectAccess(conn: WSConnection): {
22
40
  userId: string;
23
41
  projectId: string;
@@ -14,7 +14,7 @@ import { createRouter } from '$shared/utils/ws-server';
14
14
  import { debug } from '$shared/utils/logger';
15
15
  import { generateArtifact, type GeneratableType } from '$backend/artifacts';
16
16
  import type { EngineType } from '$shared/types/unified';
17
- import { requireProjectAccess } from '../access';
17
+ import { requireProjectWorkspace } from '../access';
18
18
 
19
19
  export const artifactGenerateHandler = createRouter()
20
20
  .http('artifacts:generate', {
@@ -40,7 +40,7 @@ export const artifactGenerateHandler = createRouter()
40
40
 
41
41
  // Optional project only decides the engine process cwd; generation has no
42
42
  // project side effects. Falls back to the Clopen data dir when absent.
43
- const projectPath = data.projectId ? requireProjectAccess(conn, data.projectId).path : undefined;
43
+ const projectPath = data.projectId ? requireProjectWorkspace(conn, data.projectId).root : undefined;
44
44
 
45
45
  const fields = await generateArtifact(data.artifactType as GeneratableType, data.purpose, {
46
46
  engine: data.engine as EngineType,
@@ -17,6 +17,7 @@ import { ws } from '$backend/utils/ws';
17
17
  import { broadcastPresence } from '../projects/status';
18
18
  import { sessionQueries, messageQueries } from '../../database/queries';
19
19
  import { requireSessionAccess } from '../access';
20
+ import { resolveSessionPath } from '../../worktrees';
20
21
 
21
22
  /**
22
23
  * Broadcast presence + notify project members when a chat message may flip the
@@ -228,15 +229,21 @@ export const streamHandler = createRouter()
228
229
  requireSessionAccess(conn, data.chatSessionId);
229
230
  const projectId = ws.getProjectId(conn);
230
231
 
232
+ // The client's projectPath is a view preference; the session's worktree is
233
+ // the fact. Resolving server-side is what keeps an isolated session from
234
+ // writing into the main tree when the two disagree.
235
+ const workingRoot = resolveSessionPath(data.chatSessionId, data.projectPath);
236
+
231
237
  try {
232
238
  debug.log('chat', 'WS chat:stream received:', {
233
239
  chatSessionId: data.chatSessionId,
234
- projectId
240
+ projectId,
241
+ workingRoot
235
242
  });
236
243
 
237
244
  // Start background stream
238
245
  const streamId = await streamManager.startStream({
239
- projectPath: data.projectPath,
246
+ projectPath: workingRoot,
240
247
  projectId,
241
248
  prompt: data.prompt,
242
249
  chatSessionId: data.chatSessionId,
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Containers — changing something. Admin only, all of it.
3
+ *
4
+ * The routes are listed in ADMIN_ONLY_ROUTES; these handlers still check host
5
+ * access against the caller's real role rather than a hardcoded one, because a
6
+ * gate that trusts its caller is no gate at all.
7
+ *
8
+ * Stopping a container takes down whatever it serves, for everyone — the same
9
+ * reason stopping a port is admin-only — and removing an image or a volume
10
+ * takes down something nobody can bring back by pressing start.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import { LOCAL_HOST_ID } from '$shared/types/host';
16
+ import { removeResource, runContainerAction } from '../../containers/actions';
17
+ import { dismissPrune, pruneJobFor, startPrune } from '../../containers/prune-job';
18
+ import { requireHostAccess } from './list';
19
+ import { containerMonitor } from '../../containers/monitor';
20
+ import { sshConnectionQueries } from '../../database/queries';
21
+ import { ws } from '../../utils/ws';
22
+
23
+ function requireManageAccess(conn: Parameters<typeof ws.getUserId>[0], hostId: string): void {
24
+ if (hostId === LOCAL_HOST_ID) return;
25
+ sshConnectionQueries.ensureAccess(hostId, ws.getUserId(conn), ws.getRole(conn) === 'admin');
26
+ }
27
+
28
+ const ACTIONS = [
29
+ t.Literal('start'),
30
+ t.Literal('stop'),
31
+ t.Literal('restart'),
32
+ t.Literal('pause'),
33
+ t.Literal('unpause'),
34
+ t.Literal('remove'),
35
+ t.Literal('force-remove')
36
+ ];
37
+
38
+ const PRUNE_KINDS = [
39
+ t.Literal('containers'),
40
+ t.Literal('dangling-images'),
41
+ t.Literal('images'),
42
+ t.Literal('volumes'),
43
+ t.Literal('networks'),
44
+ t.Literal('build-cache')
45
+ ];
46
+
47
+ export const containersActionHandler = createRouter()
48
+ .http(
49
+ 'containers:action',
50
+ {
51
+ data: t.Object({
52
+ hostId: t.String({ minLength: 1 }),
53
+ containerId: t.String({ minLength: 12 }),
54
+ action: t.Union(ACTIONS)
55
+ }),
56
+ response: t.Any()
57
+ },
58
+ async ({ data, conn }) => {
59
+ requireManageAccess(conn, data.hostId);
60
+
61
+ // Re-read before acting rather than trusting the row the client clicked:
62
+ // a listing is a second or two old, and a container can be removed and
63
+ // its name reused in that time.
64
+ const container = await containerMonitor.findContainer(data.hostId, data.containerId);
65
+ if (!container) {
66
+ return { result: { ok: false, error: null }, gone: true };
67
+ }
68
+ if (!container.canManage) {
69
+ return {
70
+ result: { ok: false, error: `${container.name} cannot be changed from here right now.` },
71
+ gone: false
72
+ };
73
+ }
74
+
75
+ return {
76
+ result: await runContainerAction(data.hostId, data.containerId, data.action),
77
+ gone: false
78
+ };
79
+ }
80
+ )
81
+
82
+ /**
83
+ * Remove one image, volume or network.
84
+ *
85
+ * Containers go through `containers:action` instead, because removing one is
86
+ * part of its lifecycle and the confirmation has to know whether it is still
87
+ * running. Everything else has no lifecycle — it exists or it does not.
88
+ */
89
+ .http(
90
+ 'containers:remove',
91
+ {
92
+ data: t.Object({
93
+ hostId: t.String({ minLength: 1 }),
94
+ kind: t.Union([t.Literal('image'), t.Literal('volume'), t.Literal('network')]),
95
+ id: t.String({ minLength: 1 }),
96
+ force: t.Optional(t.Boolean())
97
+ }),
98
+ response: t.Any()
99
+ },
100
+ async ({ data, conn }) => {
101
+ requireManageAccess(conn, data.hostId);
102
+ return { result: await removeResource(data.hostId, data.kind, data.id, data.force === true) };
103
+ }
104
+ )
105
+
106
+ /**
107
+ * Clear up whatever is not in use.
108
+ *
109
+ * Takes a list rather than doing everything, because the kinds differ by what
110
+ * they cost to get back: a stopped container is nothing, an unused image is a
111
+ * pull or a build. The caller decides; each kind reports separately.
112
+ *
113
+ * Returns as soon as the sweep has started, not when it ends. A prune runs
114
+ * for minutes and belongs to the host rather than to the dialog that asked
115
+ * for it — the result arrives on `containers:prune-changed`.
116
+ */
117
+ .http(
118
+ 'containers:prune',
119
+ {
120
+ data: t.Object({
121
+ hostId: t.String({ minLength: 1 }),
122
+ kinds: t.Array(t.Union(PRUNE_KINDS), { minItems: 1, maxItems: 6 })
123
+ }),
124
+ response: t.Any()
125
+ },
126
+ async ({ data, conn }) => {
127
+ requireManageAccess(conn, data.hostId);
128
+ return { job: startPrune(data.hostId, data.kinds, ws.getUserId(conn)) };
129
+ }
130
+ )
131
+
132
+ /**
133
+ * The host's current sweep, or the last one nobody has acknowledged.
134
+ *
135
+ * What a dialog reads when it opens, so a sweep started before a refresh —
136
+ * or on another device — is still visible as the thing it is.
137
+ */
138
+ .http(
139
+ 'containers:prune-status',
140
+ { data: t.Object({ hostId: t.String({ minLength: 1 }) }), response: t.Any() },
141
+ async ({ data, conn }) => {
142
+ requireHostAccess(conn, data.hostId);
143
+ return { job: pruneJobFor(data.hostId, ws.getUserId(conn)) };
144
+ }
145
+ )
146
+
147
+ /** Acknowledge a finished sweep, so its report stops being offered. */
148
+ .http(
149
+ 'containers:prune-dismiss',
150
+ { data: t.Object({ hostId: t.String({ minLength: 1 }) }), response: t.Any() },
151
+ async ({ data, conn }) => {
152
+ requireManageAccess(conn, data.hostId);
153
+ dismissPrune(data.hostId);
154
+ return { ok: true };
155
+ }
156
+ );