@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
|
@@ -6,6 +6,7 @@ import { projectContextService } from '../mcp';
|
|
|
6
6
|
import { fileWatcher } from '../files/file-watcher';
|
|
7
7
|
import { clearProjectPresence } from '../project/status-manager';
|
|
8
8
|
import { registerProjectCleanup } from './project-cleanup-registry';
|
|
9
|
+
import { removeProjectWorktrees } from '../worktrees';
|
|
9
10
|
|
|
10
11
|
registerProjectCleanup({
|
|
11
12
|
name: 'engine',
|
|
@@ -20,7 +21,7 @@ registerProjectCleanup({
|
|
|
20
21
|
registerProjectCleanup({
|
|
21
22
|
name: 'file-watcher',
|
|
22
23
|
run: (projectId) => {
|
|
23
|
-
fileWatcher.
|
|
24
|
+
fileWatcher.releaseProjectScopes(projectId);
|
|
24
25
|
}
|
|
25
26
|
});
|
|
26
27
|
|
|
@@ -30,3 +31,8 @@ registerProjectCleanup({
|
|
|
30
31
|
clearProjectPresence(projectId);
|
|
31
32
|
}
|
|
32
33
|
});
|
|
34
|
+
|
|
35
|
+
registerProjectCleanup({
|
|
36
|
+
name: 'worktrees',
|
|
37
|
+
run: (projectId) => removeProjectWorktrees(projectId)
|
|
38
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which processes belong to a project.
|
|
3
|
+
*
|
|
4
|
+
* A PtyKit namespace is a project id, so an active PTY session's shell pid is
|
|
5
|
+
* the root of everything that project spawned. Two features ask this and walk
|
|
6
|
+
* it in opposite directions — Ports climbs from a listening socket's pid to
|
|
7
|
+
* find the owning session, Project Info descends from the project to total its
|
|
8
|
+
* usage — so the roots themselves are defined once, here.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { projectQueries } from '$backend/database/queries';
|
|
12
|
+
import { ptyKitManager } from '../terminal/ptykit';
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
|
|
15
|
+
/** An active terminal shell, and the project it belongs to. */
|
|
16
|
+
export interface ProjectShell {
|
|
17
|
+
pid: number;
|
|
18
|
+
sessionId: string;
|
|
19
|
+
projectId: string;
|
|
20
|
+
projectName: string | null;
|
|
21
|
+
cwd: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function shellsOf(projectId: string, projectName: string | null): ProjectShell[] {
|
|
25
|
+
const shells: ProjectShell[] = [];
|
|
26
|
+
for (const session of ptyKitManager.list(projectId)) {
|
|
27
|
+
const info = session.info();
|
|
28
|
+
if (info.status !== 'active' || !Number.isFinite(info.pid) || info.pid <= 0) continue;
|
|
29
|
+
shells.push({
|
|
30
|
+
pid: info.pid,
|
|
31
|
+
sessionId: info.sessionId,
|
|
32
|
+
projectId,
|
|
33
|
+
projectName,
|
|
34
|
+
cwd: info.cwd
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return shells;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Every active shell on this host, keyed by pid. */
|
|
41
|
+
export function collectSessionPids(): Map<number, ProjectShell> {
|
|
42
|
+
const sessions = new Map<number, ProjectShell>();
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
for (const project of projectQueries.getAll()) {
|
|
46
|
+
for (const shell of shellsOf(project.id, project.name ?? null)) {
|
|
47
|
+
sessions.set(shell.pid, shell);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
} catch (error) {
|
|
51
|
+
debug.log('project', 'could not read terminal sessions:', error);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return sessions;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Root pids to descend from when totalling one project's usage. */
|
|
58
|
+
export function projectShellPids(projectId: string): number[] {
|
|
59
|
+
try {
|
|
60
|
+
return shellsOf(projectId, null).map((shell) => shell.pid);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
debug.log('project', 'could not read terminal sessions:', error);
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -21,6 +21,7 @@ import { getSnapshotFiles } from './gitignore';
|
|
|
21
21
|
import { fileWatcher } from '../files/file-watcher';
|
|
22
22
|
import type { MessageSnapshot, SessionScopedChanges } from '$shared/types/database/schema';
|
|
23
23
|
import { calculateFileChangeStats } from '$shared/utils/diff-calculator';
|
|
24
|
+
import { makeScopeKey } from '$shared/utils/workspace-scope';
|
|
24
25
|
import { debug } from '$shared/utils/logger';
|
|
25
26
|
|
|
26
27
|
interface SnapshotMetadata {
|
|
@@ -218,8 +219,11 @@ export class SnapshotService {
|
|
|
218
219
|
}
|
|
219
220
|
|
|
220
221
|
// The dirty set is no longer the snapshot source, but clear it so it does
|
|
221
|
-
// not grow unbounded for the Files panel UI.
|
|
222
|
-
|
|
222
|
+
// not grow unbounded for the Files panel UI. Keyed per workspace, so a
|
|
223
|
+
// worktree session must not clear the main tree's set.
|
|
224
|
+
fileWatcher.clearDirtyFiles(
|
|
225
|
+
makeScopeKey(projectId, sessionQueries.getById(sessionId)?.worktree_id ?? null)
|
|
226
|
+
);
|
|
223
227
|
|
|
224
228
|
// No changes vs the baseline → reuse the existing head snapshot.
|
|
225
229
|
if (Object.keys(sessionChanges).length === 0 && previousSnapshot) {
|
|
@@ -7,13 +7,14 @@
|
|
|
7
7
|
* There is no second WebSocket — the server is driven over Clopen's existing
|
|
8
8
|
* app-wide socket via `handleFrame` (see `backend/ws/terminal/tunnel.ts`).
|
|
9
9
|
*
|
|
10
|
-
* - `namespace` =
|
|
10
|
+
* - `namespace` = workspace scope key (project, or one of its worktrees).
|
|
11
11
|
* - `authorize` bridges to Clopen's project-access check.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import { PtyKitManager } from '@myrialabs/ptykit/core';
|
|
15
15
|
import { createPtyKitServer } from '@myrialabs/ptykit/server';
|
|
16
16
|
import { projectQueries } from '$backend/database/queries';
|
|
17
|
+
import { isScopeOfProject, makeScopeKey, scopeProjectId } from '$shared/utils/workspace-scope';
|
|
17
18
|
|
|
18
19
|
/** Terminal-friendly env, matching the previous `createCleanPtyEnv` overrides. */
|
|
19
20
|
const TERMINAL_ENV = {
|
|
@@ -46,19 +47,47 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
|
46
47
|
authorize: (ctx) => {
|
|
47
48
|
const userId = ctx.conn.data.userId;
|
|
48
49
|
if (typeof userId !== 'string' || !userId) return false;
|
|
49
|
-
|
|
50
|
+
// The namespace separates worktrees; access is still the project's call.
|
|
51
|
+
const allowed = projectQueries.userHasProject(userId, scopeProjectId(ctx.namespace));
|
|
52
|
+
if (allowed) knownNamespaces.add(ctx.namespace);
|
|
53
|
+
return allowed;
|
|
50
54
|
}
|
|
51
55
|
});
|
|
52
56
|
|
|
53
57
|
/**
|
|
54
|
-
*
|
|
55
|
-
*
|
|
58
|
+
* Namespaces this process has served. PtyKit lists sessions per namespace only,
|
|
59
|
+
* so reaping a whole project needs the set of its workspace scopes.
|
|
56
60
|
*/
|
|
57
|
-
|
|
61
|
+
const knownNamespaces = new Set<string>();
|
|
62
|
+
|
|
63
|
+
/** Kill every session in one namespace. */
|
|
64
|
+
function killNamespace(namespace: string): number {
|
|
58
65
|
let killed = 0;
|
|
59
|
-
for (const session of ptyKitManager.list(
|
|
66
|
+
for (const session of ptyKitManager.list(namespace)) {
|
|
60
67
|
ptyKitManager.killSession(session.sessionId, 'SIGKILL');
|
|
61
68
|
killed++;
|
|
62
69
|
}
|
|
63
70
|
return killed;
|
|
64
71
|
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Kill every PTY session belonging to a project, across the main tree and all
|
|
75
|
+
* of its worktrees. Used on project delete/remove to reap orphaned shells.
|
|
76
|
+
*/
|
|
77
|
+
export function cleanupProjectSessions(projectId: string): number {
|
|
78
|
+
let killed = 0;
|
|
79
|
+
for (const namespace of knownNamespaces) {
|
|
80
|
+
if (!isScopeOfProject(namespace, projectId)) continue;
|
|
81
|
+
killed += killNamespace(namespace);
|
|
82
|
+
knownNamespaces.delete(namespace);
|
|
83
|
+
}
|
|
84
|
+
return killed;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Kill every PTY session inside one worktree — used when it is deleted. */
|
|
88
|
+
export function cleanupWorktreeSessions(projectId: string, worktreeId: string): number {
|
|
89
|
+
const namespace = makeScopeKey(projectId, worktreeId);
|
|
90
|
+
const killed = killNamespace(namespace);
|
|
91
|
+
knownNamespaces.delete(namespace);
|
|
92
|
+
return killed;
|
|
93
|
+
}
|
package/backend/utils/ws.ts
CHANGED
|
@@ -64,6 +64,8 @@ interface WSMetrics {
|
|
|
64
64
|
interface ConnectionState {
|
|
65
65
|
userId: string | null;
|
|
66
66
|
projectId: string | null;
|
|
67
|
+
/** Worktree this connection is viewing; null = the main project tree */
|
|
68
|
+
worktreeId: string | null;
|
|
67
69
|
/** Chat session IDs this connection is subscribed to */
|
|
68
70
|
chatSessionIds: Set<string>;
|
|
69
71
|
/** Cleanup functions called automatically on unregister (connection close) */
|
|
@@ -149,7 +151,7 @@ class WSServer {
|
|
|
149
151
|
const id = crypto.randomUUID();
|
|
150
152
|
this.rawToId.set(raw, id);
|
|
151
153
|
this.connections.set(id, conn);
|
|
152
|
-
this.connectionState.set(id, { userId: null, projectId: null, chatSessionIds: new Set(), cleanups: new Set(), authenticated: false, role: null, sessionTokenHash: null, lastSessionCheck: 0 });
|
|
154
|
+
this.connectionState.set(id, { userId: null, projectId: null, worktreeId: null, chatSessionIds: new Set(), cleanups: new Set(), authenticated: false, role: null, sessionTokenHash: null, lastSessionCheck: 0 });
|
|
153
155
|
|
|
154
156
|
this.metrics.totalConnections = this.connections.size;
|
|
155
157
|
debug.log('websocket', `Connection registered: ${id} (total: ${this.connections.size})`);
|
|
@@ -366,6 +368,9 @@ class WSServer {
|
|
|
366
368
|
// Update connection state
|
|
367
369
|
if (state) {
|
|
368
370
|
state.projectId = projectId;
|
|
371
|
+
// A worktree belongs to one project; carrying it across would point
|
|
372
|
+
// the connection at a tree the new project does not own.
|
|
373
|
+
if (oldProjectId !== projectId) state.worktreeId = null;
|
|
369
374
|
}
|
|
370
375
|
|
|
371
376
|
// Add to new project room by ID (Map.set replaces if same key → no duplicates)
|
|
@@ -390,6 +395,21 @@ class WSServer {
|
|
|
390
395
|
debug.log('websocket', `Connection ${wsId} set to project: ${projectId}`);
|
|
391
396
|
}
|
|
392
397
|
|
|
398
|
+
/** Set the worktree this connection is viewing (null = main tree). */
|
|
399
|
+
setWorktree(conn: WSConnection, worktreeId: string | null): void {
|
|
400
|
+
const wsId = this.ensureRegistered(conn);
|
|
401
|
+
const state = this.connectionState.get(wsId);
|
|
402
|
+
if (state) state.worktreeId = worktreeId;
|
|
403
|
+
debug.log('websocket', `Connection ${wsId} set to worktree: ${worktreeId ?? 'main'}`);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Worktree this connection is viewing, or null for the main project tree. */
|
|
407
|
+
getWorktreeId(conn: WSConnection): string | null {
|
|
408
|
+
const id = this.resolveId(conn);
|
|
409
|
+
if (!id) return null;
|
|
410
|
+
return this.connectionState.get(id)?.worktreeId ?? null;
|
|
411
|
+
}
|
|
412
|
+
|
|
393
413
|
/**
|
|
394
414
|
* Get project ID for a connection.
|
|
395
415
|
* Throws if not set - ensures single source of truth.
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Materialising a worktree from the main tree.
|
|
3
|
+
*
|
|
4
|
+
* Preferred path is a copy-on-write clone (`COPYFILE_FICLONE`): on APFS, btrfs
|
|
5
|
+
* and reflink-capable XFS this is near-instant and costs no extra disk until a
|
|
6
|
+
* file is written, so the worktree can carry everything the project needs to
|
|
7
|
+
* actually run — `.git`, `node_modules`, `.env` — not just tracked files.
|
|
8
|
+
*
|
|
9
|
+
* Where reflink is unavailable (different volume, ext4 without reflink, NTFS)
|
|
10
|
+
* a real byte copy of that much data would be unacceptable, so the clone falls
|
|
11
|
+
* back to gitignore-eligible files plus `.git` and the caller is told to run a
|
|
12
|
+
* setup command for dependencies.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'fs/promises';
|
|
16
|
+
import { constants as fsConstants, type Dirent } from 'fs';
|
|
17
|
+
import path from 'path';
|
|
18
|
+
import type { WorktreeCloneMode } from '$shared/types/database/schema';
|
|
19
|
+
import { debug } from '$shared/utils/logger';
|
|
20
|
+
import { getSnapshotFiles } from '../snapshot/gitignore';
|
|
21
|
+
|
|
22
|
+
/** Above this many entries a full-tree walk is refused and the lean clone is used. */
|
|
23
|
+
const MAX_FULL_CLONE_ENTRIES = 200_000;
|
|
24
|
+
|
|
25
|
+
/** Never copied — process-local state that must not be shared between trees. */
|
|
26
|
+
const NEVER_CLONE = new Set(['.DS_Store', '.clopen-reflink-probe']);
|
|
27
|
+
|
|
28
|
+
export interface CloneResult {
|
|
29
|
+
mode: WorktreeCloneMode;
|
|
30
|
+
fileCount: number;
|
|
31
|
+
/** True when ignored files (dependencies, .env) were carried over. */
|
|
32
|
+
carriedIgnoredFiles: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Probe whether `targetDir` can hold reflinks of files from `sourceDir`.
|
|
37
|
+
* Uses a real file from the project so the answer accounts for both filesystems.
|
|
38
|
+
*/
|
|
39
|
+
export async function probeReflinkSupport(sourceDir: string, targetDir: string): Promise<boolean> {
|
|
40
|
+
const probeSource = await findProbeFile(sourceDir);
|
|
41
|
+
if (!probeSource) return false;
|
|
42
|
+
|
|
43
|
+
const probeTarget = path.join(targetDir, '.clopen-reflink-probe');
|
|
44
|
+
try {
|
|
45
|
+
await fs.copyFile(probeSource, probeTarget, fsConstants.COPYFILE_FICLONE_FORCE);
|
|
46
|
+
return true;
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
} finally {
|
|
50
|
+
await fs.rm(probeTarget, { force: true }).catch(() => {});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Find a small regular file to probe with; returns null for an empty project. */
|
|
55
|
+
async function findProbeFile(dirPath: string): Promise<string | null> {
|
|
56
|
+
let entries: Dirent[];
|
|
57
|
+
try {
|
|
58
|
+
entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
if (!entry.isFile()) continue;
|
|
65
|
+
const full = path.join(dirPath, entry.name);
|
|
66
|
+
try {
|
|
67
|
+
const stat = await fs.stat(full);
|
|
68
|
+
if (stat.size > 0 && stat.size < 1024 * 1024) return full;
|
|
69
|
+
} catch {
|
|
70
|
+
// Unreadable — try the next one
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// No usable file at the top level; one level down is enough to decide.
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
if (!entry.isDirectory() || entry.name === '.git') continue;
|
|
77
|
+
const nested = await findProbeFile(path.join(dirPath, entry.name));
|
|
78
|
+
if (nested) return nested;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Clone `sourceRoot` into `targetRoot`.
|
|
86
|
+
* `targetRoot` must already exist and be empty.
|
|
87
|
+
*/
|
|
88
|
+
export async function cloneTree(sourceRoot: string, targetRoot: string): Promise<CloneResult> {
|
|
89
|
+
const canReflink = await probeReflinkSupport(sourceRoot, targetRoot);
|
|
90
|
+
|
|
91
|
+
if (canReflink) {
|
|
92
|
+
const entries = await enumerateFullTree(sourceRoot);
|
|
93
|
+
if (entries !== null) {
|
|
94
|
+
const fileCount = await copyEntries(sourceRoot, targetRoot, entries);
|
|
95
|
+
debug.log('worktree', `Cloned ${fileCount} entries via reflink: ${targetRoot}`);
|
|
96
|
+
return { mode: 'reflink', fileCount, carriedIgnoredFiles: true };
|
|
97
|
+
}
|
|
98
|
+
debug.warn('worktree', `Tree too large for a full clone, falling back to tracked files: ${sourceRoot}`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const lean = await enumerateLeanTree(sourceRoot);
|
|
102
|
+
const fileCount = await copyEntries(sourceRoot, targetRoot, lean);
|
|
103
|
+
debug.log('worktree', `Cloned ${fileCount} tracked files: ${targetRoot}`);
|
|
104
|
+
return { mode: canReflink ? 'reflink' : 'copy', fileCount, carriedIgnoredFiles: false };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Relative paths of everything under a root, split by kind. */
|
|
108
|
+
interface TreeEntries {
|
|
109
|
+
dirs: string[];
|
|
110
|
+
files: string[];
|
|
111
|
+
symlinks: string[];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Walk everything under `root`, including ignored files and `.git`.
|
|
116
|
+
* Returns null when the tree exceeds `MAX_FULL_CLONE_ENTRIES`.
|
|
117
|
+
*/
|
|
118
|
+
async function enumerateFullTree(root: string): Promise<TreeEntries | null> {
|
|
119
|
+
const entries: TreeEntries = { dirs: [], files: [], symlinks: [] };
|
|
120
|
+
const queue: string[] = [''];
|
|
121
|
+
let total = 0;
|
|
122
|
+
|
|
123
|
+
while (queue.length > 0) {
|
|
124
|
+
const relativeDir = queue.pop() as string;
|
|
125
|
+
let dirEntries: Dirent[];
|
|
126
|
+
try {
|
|
127
|
+
dirEntries = await fs.readdir(path.join(root, relativeDir), { withFileTypes: true });
|
|
128
|
+
} catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
for (const entry of dirEntries) {
|
|
133
|
+
if (NEVER_CLONE.has(entry.name)) continue;
|
|
134
|
+
const relativePath = relativeDir ? path.join(relativeDir, entry.name) : entry.name;
|
|
135
|
+
|
|
136
|
+
if (++total > MAX_FULL_CLONE_ENTRIES) return null;
|
|
137
|
+
|
|
138
|
+
if (entry.isSymbolicLink()) {
|
|
139
|
+
entries.symlinks.push(relativePath);
|
|
140
|
+
} else if (entry.isDirectory()) {
|
|
141
|
+
entries.dirs.push(relativePath);
|
|
142
|
+
queue.push(relativePath);
|
|
143
|
+
} else if (entry.isFile()) {
|
|
144
|
+
entries.files.push(relativePath);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return entries;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Tracked/untracked-not-ignored files, plus `.git` so the Git panel still works. */
|
|
153
|
+
async function enumerateLeanTree(root: string): Promise<TreeEntries> {
|
|
154
|
+
const entries: TreeEntries = { dirs: [], files: [], symlinks: [] };
|
|
155
|
+
const dirs = new Set<string>();
|
|
156
|
+
|
|
157
|
+
const snapshotFiles = await getSnapshotFiles(root);
|
|
158
|
+
for (const absolute of snapshotFiles) {
|
|
159
|
+
const relativePath = path.relative(root, absolute);
|
|
160
|
+
if (!relativePath || relativePath.startsWith('..')) continue;
|
|
161
|
+
entries.files.push(relativePath);
|
|
162
|
+
collectParentDirs(relativePath, dirs);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const gitDir = await enumerateFullTree(path.join(root, '.git'));
|
|
166
|
+
if (gitDir) {
|
|
167
|
+
dirs.add('.git');
|
|
168
|
+
for (const dir of gitDir.dirs) dirs.add(path.join('.git', dir));
|
|
169
|
+
for (const file of gitDir.files) entries.files.push(path.join('.git', file));
|
|
170
|
+
for (const link of gitDir.symlinks) entries.symlinks.push(path.join('.git', link));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
entries.dirs = [...dirs].sort((a, b) => a.length - b.length);
|
|
174
|
+
return entries;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function collectParentDirs(relativePath: string, into: Set<string>): void {
|
|
178
|
+
let parent = path.dirname(relativePath);
|
|
179
|
+
while (parent && parent !== '.' && parent !== path.sep) {
|
|
180
|
+
into.add(parent);
|
|
181
|
+
parent = path.dirname(parent);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Create the directories, then clone files and re-create symlinks. */
|
|
186
|
+
async function copyEntries(sourceRoot: string, targetRoot: string, entries: TreeEntries): Promise<number> {
|
|
187
|
+
for (const relativeDir of entries.dirs) {
|
|
188
|
+
await fs.mkdir(path.join(targetRoot, relativeDir), { recursive: true });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let copied = 0;
|
|
192
|
+
|
|
193
|
+
for (const relativeFile of entries.files) {
|
|
194
|
+
const source = path.join(sourceRoot, relativeFile);
|
|
195
|
+
const target = path.join(targetRoot, relativeFile);
|
|
196
|
+
try {
|
|
197
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
198
|
+
// FICLONE (not FORCE): reflink where the filesystem supports it,
|
|
199
|
+
// plain copy where it does not, without a second code path.
|
|
200
|
+
await fs.copyFile(source, target, fsConstants.COPYFILE_FICLONE);
|
|
201
|
+
copied++;
|
|
202
|
+
} catch (error) {
|
|
203
|
+
debug.warn('worktree', `Skipped ${relativeFile}: ${error}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Symlinks are re-created, never followed — following them would duplicate
|
|
208
|
+
// whatever they point at and break links that are relative by design.
|
|
209
|
+
for (const relativeLink of entries.symlinks) {
|
|
210
|
+
try {
|
|
211
|
+
const linkTarget = await fs.readlink(path.join(sourceRoot, relativeLink));
|
|
212
|
+
const target = path.join(targetRoot, relativeLink);
|
|
213
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
214
|
+
await fs.symlink(linkTarget, target);
|
|
215
|
+
copied++;
|
|
216
|
+
} catch (error) {
|
|
217
|
+
debug.warn('worktree', `Skipped symlink ${relativeLink}: ${error}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return copied;
|
|
222
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worktrees — isolated copies of a project that chat sessions can run in.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export {
|
|
6
|
+
createWorktree,
|
|
7
|
+
countPendingChanges,
|
|
8
|
+
executeTransfer,
|
|
9
|
+
getWorktreeDiskUsage,
|
|
10
|
+
previewTransfer,
|
|
11
|
+
removeProjectWorktrees,
|
|
12
|
+
removeWorktree,
|
|
13
|
+
type TransferDirection,
|
|
14
|
+
type TransferPreview,
|
|
15
|
+
type TransferResult,
|
|
16
|
+
type WorktreeChange,
|
|
17
|
+
type WorktreeConflictPreview,
|
|
18
|
+
type WorktreeCreateResult
|
|
19
|
+
} from './service';
|
|
20
|
+
|
|
21
|
+
export {
|
|
22
|
+
resolveSessionPath,
|
|
23
|
+
resolveSessionRoot,
|
|
24
|
+
resolveWorktreeRoot,
|
|
25
|
+
type SessionRoot
|
|
26
|
+
} from './resolve';
|
|
27
|
+
|
|
28
|
+
export { planMerge, type MergeEntry, type MergePlan, type MergeResolution } from './merge';
|
|
29
|
+
export { getProjectWorktreesDir, getWorktreePath, getWorktreesRootDir, isPathInside, slugifyWorktreeName, uniqueWorktreeSlug } from './paths';
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { planMerge } from './merge';
|
|
3
|
+
|
|
4
|
+
const HASH_A = 'aaaa';
|
|
5
|
+
const HASH_B = 'bbbb';
|
|
6
|
+
const HASH_C = 'cccc';
|
|
7
|
+
|
|
8
|
+
describe('planMerge', () => {
|
|
9
|
+
test('carries a file the source added', () => {
|
|
10
|
+
const plan = planMerge({}, { 'new.ts': HASH_A }, {});
|
|
11
|
+
|
|
12
|
+
expect(plan.entries).toHaveLength(1);
|
|
13
|
+
expect(plan.entries[0]).toMatchObject({
|
|
14
|
+
path: 'new.ts',
|
|
15
|
+
status: 'added',
|
|
16
|
+
conflict: false
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('carries a file the source modified', () => {
|
|
21
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, { 'a.ts': HASH_A });
|
|
22
|
+
|
|
23
|
+
expect(plan.entries[0]).toMatchObject({ path: 'a.ts', status: 'modified', conflict: false });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('carries a file the source deleted', () => {
|
|
27
|
+
const plan = planMerge({ 'a.ts': HASH_A }, {}, { 'a.ts': HASH_A });
|
|
28
|
+
|
|
29
|
+
expect(plan.entries[0]).toMatchObject({ path: 'a.ts', status: 'deleted', conflict: false });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('ignores files the source never touched', () => {
|
|
33
|
+
// The target moved on alone — a transfer must not drag it back to the base.
|
|
34
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_A }, { 'a.ts': HASH_B });
|
|
35
|
+
|
|
36
|
+
expect(plan.entries).toHaveLength(0);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('ignores files where both sides made the same change', () => {
|
|
40
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, { 'a.ts': HASH_B });
|
|
41
|
+
|
|
42
|
+
expect(plan.entries).toHaveLength(0);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('flags a file both sides changed differently', () => {
|
|
46
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, { 'a.ts': HASH_C });
|
|
47
|
+
|
|
48
|
+
expect(plan.conflicts).toHaveLength(1);
|
|
49
|
+
expect(plan.conflicts[0]).toMatchObject({
|
|
50
|
+
path: 'a.ts',
|
|
51
|
+
status: 'modified',
|
|
52
|
+
conflict: true,
|
|
53
|
+
baseHash: HASH_A,
|
|
54
|
+
sourceHash: HASH_B,
|
|
55
|
+
targetHash: HASH_C
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('flags a source edit against a target deletion', () => {
|
|
60
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, {});
|
|
61
|
+
|
|
62
|
+
expect(plan.conflicts[0]).toMatchObject({
|
|
63
|
+
path: 'a.ts',
|
|
64
|
+
status: 'modified',
|
|
65
|
+
conflict: true,
|
|
66
|
+
targetHash: null
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('treats an add on both sides with different content as a conflict', () => {
|
|
71
|
+
const plan = planMerge({}, { 'a.ts': HASH_A }, { 'a.ts': HASH_B });
|
|
72
|
+
|
|
73
|
+
expect(plan.conflicts[0]).toMatchObject({ path: 'a.ts', status: 'added', conflict: true });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('leaves an empty plan when nothing diverged', () => {
|
|
77
|
+
const tree = { 'a.ts': HASH_A, 'b.ts': HASH_B };
|
|
78
|
+
const plan = planMerge(tree, { ...tree }, { ...tree });
|
|
79
|
+
|
|
80
|
+
expect(plan.entries).toHaveLength(0);
|
|
81
|
+
expect(plan.conflicts).toHaveLength(0);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('returns entries in a stable path order', () => {
|
|
85
|
+
const plan = planMerge(
|
|
86
|
+
{},
|
|
87
|
+
{ 'z.ts': HASH_A, 'a.ts': HASH_A, 'm.ts': HASH_A },
|
|
88
|
+
{}
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
expect(plan.entries.map((entry) => entry.path)).toEqual(['a.ts', 'm.ts', 'z.ts']);
|
|
92
|
+
});
|
|
93
|
+
});
|