@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.
Files changed (82) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +1 -0
  6. package/backend/database/queries/session-queries.ts +50 -11
  7. package/backend/database/queries/worktree-queries.ts +148 -0
  8. package/backend/engine/adapters/opencode/server.ts +389 -83
  9. package/backend/engine/adapters/opencode/stream.ts +14 -14
  10. package/backend/engine/hot-reload.ts +25 -10
  11. package/backend/files/file-watcher.ts +35 -9
  12. package/backend/host/metrics.test.ts +110 -0
  13. package/backend/host/metrics.ts +235 -0
  14. package/backend/index.ts +5 -2
  15. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  16. package/backend/ports/attribute.test.ts +3 -2
  17. package/backend/ports/attribute.ts +5 -44
  18. package/backend/preview/browser/browser-pool.ts +81 -0
  19. package/backend/preview/browser/browser-preview-service.ts +142 -32
  20. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  21. package/backend/preview/browser/types.ts +9 -0
  22. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  23. package/backend/projects/project-cleanup.ts +7 -1
  24. package/backend/projects/shell-ownership.ts +65 -0
  25. package/backend/snapshot/snapshot-service.ts +6 -2
  26. package/backend/terminal/ptykit.ts +35 -6
  27. package/backend/utils/ws.ts +21 -1
  28. package/backend/worktrees/clone.ts +222 -0
  29. package/backend/worktrees/index.ts +29 -0
  30. package/backend/worktrees/merge.test.ts +93 -0
  31. package/backend/worktrees/merge.ts +232 -0
  32. package/backend/worktrees/paths.test.ts +60 -0
  33. package/backend/worktrees/paths.ts +60 -0
  34. package/backend/worktrees/resolve.ts +67 -0
  35. package/backend/worktrees/service.ts +315 -0
  36. package/backend/worktrees/tree.ts +59 -0
  37. package/backend/ws/access.ts +18 -0
  38. package/backend/ws/artifacts/generate.ts +2 -2
  39. package/backend/ws/chat/stream.ts +9 -2
  40. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  41. package/backend/ws/files/path-access.test.ts +93 -1
  42. package/backend/ws/files/path-access.ts +54 -5
  43. package/backend/ws/files/read.ts +15 -10
  44. package/backend/ws/files/search.ts +7 -7
  45. package/backend/ws/files/state.ts +70 -8
  46. package/backend/ws/files/watch.ts +16 -14
  47. package/backend/ws/git/branch-name.ts +3 -3
  48. package/backend/ws/git/branch.ts +15 -15
  49. package/backend/ws/git/commit-message.ts +3 -3
  50. package/backend/ws/git/commit.ts +17 -17
  51. package/backend/ws/git/conflict.ts +10 -10
  52. package/backend/ws/git/diff.ts +9 -9
  53. package/backend/ws/git/ignored.ts +9 -9
  54. package/backend/ws/git/log.ts +3 -3
  55. package/backend/ws/git/remote.ts +43 -43
  56. package/backend/ws/git/staging.ts +16 -16
  57. package/backend/ws/git/status.ts +13 -13
  58. package/backend/ws/index.ts +4 -0
  59. package/backend/ws/preview/access.ts +11 -3
  60. package/backend/ws/projects/index.ts +5 -1
  61. package/backend/ws/projects/info.test.ts +54 -0
  62. package/backend/ws/projects/info.ts +398 -0
  63. package/backend/ws/sessions/crud.ts +21 -6
  64. package/backend/ws/snapshot/restore.ts +11 -14
  65. package/backend/ws/system/device-info.ts +62 -144
  66. package/backend/ws/worktrees/crud.ts +187 -0
  67. package/backend/ws/worktrees/index.ts +33 -0
  68. package/backend/ws/worktrees/transfer.ts +88 -0
  69. package/dist/assets/{index-B0iIhSO9.js → index-Bg-SUCFg.js} +1 -1
  70. package/dist/assets/{index-BRJqss6F.js → index-Cz4YpHVi.js} +1 -1
  71. package/dist/assets/main-9G7IpQpK.css +1 -0
  72. package/dist/assets/main-BofFsH8E.js +1085 -0
  73. package/dist/index.html +2 -2
  74. package/package.json +1 -1
  75. package/shared/types/database/schema.ts +26 -0
  76. package/shared/utils/logger.ts +1 -0
  77. package/shared/utils/workspace-scope.test.ts +80 -0
  78. package/shared/utils/workspace-scope.ts +57 -0
  79. package/shared/utils/ws-client.ts +25 -5
  80. package/shared/utils/ws-server.ts +19 -3
  81. package/dist/assets/main-Buko4D0t.css +0 -1
  82. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -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,102 @@
1
+ /**
2
+ * Panel state is stored one row per (user, project) but must be separated per
3
+ * workspace inside it. Sharing one entry carried open tabs — including unsaved
4
+ * buffers — from the main tree into a worktree, which read as the edit having
5
+ * crossed between them.
6
+ *
7
+ * The envelope logic is what enforces that separation, so it is exercised here
8
+ * against the same shape the handlers read and write.
9
+ */
10
+ import { describe, expect, test } from 'bun:test';
11
+
12
+ interface ScopedPanelState {
13
+ v: 2;
14
+ scopes: Record<string, string>;
15
+ }
16
+
17
+ function parseStored(raw: string | null): ScopedPanelState {
18
+ if (!raw) return { v: 2, scopes: {} };
19
+ try {
20
+ const parsed = JSON.parse(raw) as ScopedPanelState;
21
+ if (parsed && parsed.v === 2 && typeof parsed.scopes === 'object') return parsed;
22
+ } catch {
23
+ // unparseable → treated as absent
24
+ }
25
+ return { v: 2, scopes: {} };
26
+ }
27
+
28
+ function isLegacyState(raw: string | null): boolean {
29
+ if (!raw) return false;
30
+ try {
31
+ return (JSON.parse(raw) as { v?: number })?.v !== 2;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ /** Mirrors files:set-panel-state. */
38
+ function writeScope(raw: string | null, projectId: string, scopeKey: string, state: string | null): string {
39
+ const stored = parseStored(raw);
40
+ if (isLegacyState(raw) && raw) stored.scopes[projectId] = raw;
41
+ if (state === null) delete stored.scopes[scopeKey];
42
+ else stored.scopes[scopeKey] = state;
43
+ return JSON.stringify(stored);
44
+ }
45
+
46
+ /** Mirrors files:get-panel-state. */
47
+ function readScope(raw: string | null, projectId: string, scopeKey: string): string | null {
48
+ if (isLegacyState(raw)) return scopeKey === projectId ? raw : null;
49
+ return parseStored(raw).scopes[scopeKey] ?? null;
50
+ }
51
+
52
+ const PROJECT = 'proj-1';
53
+ const MAIN = PROJECT;
54
+ const WORKTREE = 'proj-1~wt-1';
55
+
56
+ describe('files panel state scoping', () => {
57
+ test('a worktree does not see the main tree state', () => {
58
+ const stored = writeScope(null, PROJECT, MAIN, '{"openTabs":["a.ts"]}');
59
+ expect(readScope(stored, PROJECT, MAIN)).toBe('{"openTabs":["a.ts"]}');
60
+ expect(readScope(stored, PROJECT, WORKTREE)).toBeNull();
61
+ });
62
+
63
+ test('writing one workspace keeps the other', () => {
64
+ let stored = writeScope(null, PROJECT, MAIN, 'main-state');
65
+ stored = writeScope(stored, PROJECT, WORKTREE, 'worktree-state');
66
+
67
+ expect(readScope(stored, PROJECT, MAIN)).toBe('main-state');
68
+ expect(readScope(stored, PROJECT, WORKTREE)).toBe('worktree-state');
69
+ });
70
+
71
+ test('two worktrees of one project stay separate', () => {
72
+ const second = 'proj-1~wt-2';
73
+ let stored = writeScope(null, PROJECT, WORKTREE, 'first');
74
+ stored = writeScope(stored, PROJECT, second, 'second');
75
+
76
+ expect(readScope(stored, PROJECT, WORKTREE)).toBe('first');
77
+ expect(readScope(stored, PROJECT, second)).toBe('second');
78
+ });
79
+
80
+ test('legacy flat state belongs to the main tree only', () => {
81
+ const legacy = '{"v":1,"openTabs":[]}';
82
+ expect(readScope(legacy, PROJECT, MAIN)).toBe(legacy);
83
+ expect(readScope(legacy, PROJECT, WORKTREE)).toBeNull();
84
+ });
85
+
86
+ test('the first worktree write preserves legacy main state', () => {
87
+ const legacy = '{"v":1,"openTabs":[]}';
88
+ const stored = writeScope(legacy, PROJECT, WORKTREE, 'worktree-state');
89
+
90
+ expect(readScope(stored, PROJECT, MAIN)).toBe(legacy);
91
+ expect(readScope(stored, PROJECT, WORKTREE)).toBe('worktree-state');
92
+ });
93
+
94
+ test('clearing one workspace leaves the others intact', () => {
95
+ let stored = writeScope(null, PROJECT, MAIN, 'main-state');
96
+ stored = writeScope(stored, PROJECT, WORKTREE, 'worktree-state');
97
+ stored = writeScope(stored, PROJECT, WORKTREE, null);
98
+
99
+ expect(readScope(stored, PROJECT, MAIN)).toBe('main-state');
100
+ expect(readScope(stored, PROJECT, WORKTREE)).toBeNull();
101
+ });
102
+ });
@@ -27,6 +27,7 @@ const mockGetAllForUser = mock(() => [] as Array<{ id: string; path: string }>);
27
27
  const mockGetAll = mock(() => [] as Array<{ id: string; path: string }>);
28
28
  const mockUserHasProject = mock(() => false);
29
29
  const mockGetByPath = mock(() => null as { id: string; path: string } | null);
30
+ const mockGetById = mock(() => null as { id: string; path: string } | null);
30
31
 
31
32
  mock.module('../../database/queries/project-queries', () => ({
32
33
  projectQueries: {
@@ -34,6 +35,19 @@ mock.module('../../database/queries/project-queries', () => ({
34
35
  getAll: mockGetAll,
35
36
  userHasProject: mockUserHasProject,
36
37
  getByPath: mockGetByPath,
38
+ getById: mockGetById,
39
+ }
40
+ }));
41
+
42
+ // A project's accessible area now includes its worktrees, so the lookup is part
43
+ // of the data layer this test models.
44
+ const mockWorktreesByProject = mock(() => [] as Array<{ id: string; path: string }>);
45
+ const mockWorktreeByPath = mock(() => null as { id: string; project_id: string; path: string } | null);
46
+
47
+ mock.module('../../database/queries/worktree-queries', () => ({
48
+ worktreeQueries: {
49
+ getByProjectId: mockWorktreesByProject,
50
+ getByPath: mockWorktreeByPath,
37
51
  }
38
52
  }));
39
53
 
@@ -52,7 +66,7 @@ mock.module('../access', () => ({
52
66
  }));
53
67
 
54
68
  // Import after mocking
55
- const { requireFilePathAccess, requireSharedFilePathAccess, findContainingProjectId } = await import('./path-access');
69
+ const { requireFilePathAccess, requireSharedFilePathAccess, findContainingProjectId, resolveProjectForRoot, requireWorkspaceRootAccess } = await import('./path-access');
56
70
 
57
71
  let testDir: string;
58
72
 
@@ -69,6 +83,84 @@ describe('path-access symlink resolution', () => {
69
83
 
70
84
  afterEach(async () => {
71
85
  await rm(testDir, { recursive: true, force: true });
86
+ mockWorktreesByProject.mockReturnValue([]);
87
+ mockWorktreeByPath.mockReturnValue(null);
88
+ });
89
+
90
+ test('allows a path inside a worktree of an accessible project', async () => {
91
+ const projectPath = join(testDir, 'project');
92
+ const worktreePath = join(testDir, 'worktrees', 'feature');
93
+ await mkdir(projectPath, { recursive: true });
94
+ await mkdir(worktreePath, { recursive: true });
95
+ await writeFile(join(worktreePath, 'index.ts'), 'export {};');
96
+
97
+ mockGetAllForUser.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
98
+ mockWorktreesByProject.mockReturnValue([{ id: 'wt-1', path: worktreePath }]);
99
+
100
+ const target = join(worktreePath, 'index.ts');
101
+ await expect(requireFilePathAccess({} as any, target)).resolves.toBe(target);
102
+ });
103
+
104
+ test('still denies a worktree of a project the user cannot access', async () => {
105
+ const worktreePath = join(testDir, 'worktrees', 'other');
106
+ await mkdir(worktreePath, { recursive: true });
107
+ await writeFile(join(worktreePath, 'secret.txt'), 'nope');
108
+
109
+ mockGetAllForUser.mockReturnValue([]);
110
+ mockWorktreesByProject.mockReturnValue([{ id: 'wt-1', path: worktreePath }]);
111
+
112
+ await expect(
113
+ requireFilePathAccess({} as any, join(worktreePath, 'secret.txt'))
114
+ ).rejects.toThrow('Access denied');
115
+ });
116
+
117
+ test('resolves a worktree root back to its owning project', async () => {
118
+ const worktreePath = join(testDir, 'worktrees', 'feature');
119
+ mockGetByPath.mockReturnValue(null);
120
+ mockWorktreeByPath.mockReturnValue({ id: 'wt-1', project_id: 'proj-1', path: worktreePath });
121
+ mockGetById.mockReturnValue({ id: 'proj-1', path: join(testDir, 'project') });
122
+
123
+ expect(resolveProjectForRoot(worktreePath)?.id).toBe('proj-1');
124
+ });
125
+
126
+ test('returns the worktree root, not the project root, for a worktree path', async () => {
127
+ // The regression this guards: handlers validated the requested root and
128
+ // then operated on `project.path`, so opening a file in a worktree listed
129
+ // and read the main tree instead.
130
+ const projectPath = join(testDir, 'project');
131
+ const worktreePath = join(testDir, 'worktrees', 'feature');
132
+
133
+ mockGetByPath.mockReturnValue(null);
134
+ mockWorktreeByPath.mockReturnValue({ id: 'wt-1', project_id: 'proj-1', path: worktreePath });
135
+ mockGetById.mockReturnValue({ id: 'proj-1', path: projectPath });
136
+ mockGetRole.mockImplementation(() => 'admin');
137
+
138
+ const resolved = requireWorkspaceRootAccess({} as any, worktreePath);
139
+ expect(resolved.root).toBe(worktreePath);
140
+ expect(resolved.worktreeId).toBe('wt-1');
141
+ expect(resolved.project.id).toBe('proj-1');
142
+ });
143
+
144
+ test('returns the project root for the main tree', async () => {
145
+ const projectPath = join(testDir, 'project');
146
+
147
+ mockWorktreeByPath.mockReturnValue(null);
148
+ mockGetByPath.mockReturnValue({ id: 'proj-1', path: projectPath });
149
+ mockGetRole.mockImplementation(() => 'admin');
150
+
151
+ const resolved = requireWorkspaceRootAccess({} as any, projectPath);
152
+ expect(resolved.root).toBe(projectPath);
153
+ expect(resolved.worktreeId).toBeNull();
154
+ });
155
+
156
+ test('denies an unknown root', async () => {
157
+ mockWorktreeByPath.mockReturnValue(null);
158
+ mockGetByPath.mockReturnValue(null);
159
+ mockGetRole.mockImplementation(() => 'admin');
160
+
161
+ expect(() => requireWorkspaceRootAccess({} as any, join(testDir, 'nowhere'))).toThrow(
162
+ 'Access denied'
163
+ );
72
164
  });
73
165
 
74
166
  test('blocks read through symlink to external directory', async () => {