@myrialabs/clopen 0.4.35 → 0.4.37
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/git/conflict-state.test.ts +396 -0
- package/backend/git/git-executor.ts +6 -0
- package/backend/git/git-parser.ts +144 -48
- package/backend/git/git-service.ts +727 -57
- package/backend/git/push-target.test.ts +264 -0
- 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/project/status-manager.ts +20 -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 +9 -8
- package/backend/ws/git/branch.ts +58 -16
- package/backend/ws/git/commit-message.ts +16 -13
- package/backend/ws/git/commit.ts +17 -17
- package/backend/ws/git/conflict.ts +116 -13
- package/backend/ws/git/diff-budget.test.ts +125 -0
- package/backend/ws/git/diff-budget.ts +220 -0
- package/backend/ws/git/diff.ts +9 -9
- package/backend/ws/git/ignored.ts +9 -9
- package/backend/ws/git/log.ts +28 -3
- package/backend/ws/git/remote.ts +118 -44
- 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-BRJqss6F.js → index-Bik9TCBi.js} +1 -1
- package/dist/assets/{index-B0iIhSO9.js → index-sJmS_CCm.js} +1 -1
- package/dist/assets/main-DLqolBI2.css +1 -0
- package/dist/assets/main-Df1I3hnw.js +1096 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +26 -0
- package/shared/types/git.ts +123 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/workspace-scope.test.ts +80 -0
- package/shared/utils/workspace-scope.ts +57 -0
- package/shared/utils/ws-client.ts +25 -5
- package/shared/utils/ws-server.ts +19 -3
- package/dist/assets/main-Buko4D0t.css +0 -1
- package/dist/assets/main-C_iGUZyL.js +0 -1078
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Materialization must be IDEMPOTENT on disk, not just in outcome.
|
|
3
|
+
*
|
|
4
|
+
* `materializeArtifacts` runs at every stream start. It used to rewrite each
|
|
5
|
+
* enabled artifact unconditionally, which left the content identical but moved
|
|
6
|
+
* the file's mtime — and the Open Code pool fingerprints exactly these files to
|
|
7
|
+
* decide whether its baked config changed. The result was a brand-new
|
|
8
|
+
* `opencode serve` process for every single turn. These tests pin the property
|
|
9
|
+
* that prevents it: no content change, no write.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { describe, expect, test, afterAll } from 'bun:test';
|
|
13
|
+
import { rm, stat, readFile } from 'node:fs/promises';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
|
|
16
|
+
import { materializeArtifacts } from './sync';
|
|
17
|
+
import { resolveArtifact } from './matrix';
|
|
18
|
+
import type { ArtifactContext } from './types';
|
|
19
|
+
|
|
20
|
+
const CONTEXT: ArtifactContext = { engine: 'opencode', scope: 'global' };
|
|
21
|
+
const SLUG = 'sync-idempotence-fixture';
|
|
22
|
+
|
|
23
|
+
const targetDir = resolveArtifact('command', CONTEXT).locateEffective(CONTEXT);
|
|
24
|
+
const targetFile = targetDir ? join(targetDir, `${SLUG}.md`) : '';
|
|
25
|
+
|
|
26
|
+
/** Materialize a single command whose body is `document`. */
|
|
27
|
+
async function materialize(document: string): Promise<void> {
|
|
28
|
+
await materializeArtifacts('command', CONTEXT, {
|
|
29
|
+
enabled: [{ slug: SLUG, name: 'Fixture', description: 'sync test', document }],
|
|
30
|
+
managedSlugs: [SLUG]
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
afterAll(async () => {
|
|
35
|
+
if (targetFile) await rm(targetFile, { force: true });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
describe('materializeArtifacts', () => {
|
|
39
|
+
test('an unchanged artifact is not rewritten', async () => {
|
|
40
|
+
expect(targetDir).toBeTruthy();
|
|
41
|
+
|
|
42
|
+
await materialize('# Fixture\n\noriginal body\n');
|
|
43
|
+
const firstWrite = (await stat(targetFile)).mtimeMs;
|
|
44
|
+
|
|
45
|
+
// Space the calls out: two writes inside the same millisecond would pass
|
|
46
|
+
// this assertion even if the file had genuinely been rewritten.
|
|
47
|
+
await Bun.sleep(20);
|
|
48
|
+
await materialize('# Fixture\n\noriginal body\n');
|
|
49
|
+
|
|
50
|
+
expect((await stat(targetFile)).mtimeMs).toBe(firstWrite);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('a changed artifact is written', async () => {
|
|
54
|
+
await materialize('# Fixture\n\noriginal body\n');
|
|
55
|
+
const firstWrite = (await stat(targetFile)).mtimeMs;
|
|
56
|
+
|
|
57
|
+
await Bun.sleep(20);
|
|
58
|
+
await materialize('# Fixture\n\nedited body\n');
|
|
59
|
+
|
|
60
|
+
expect((await stat(targetFile)).mtimeMs).toBeGreaterThan(firstWrite);
|
|
61
|
+
expect(await readFile(targetFile, 'utf8')).toContain('edited body');
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { join } from 'path';
|
|
13
|
-
import { mkdir, readdir, rm, writeFile, cp, stat } from 'node:fs/promises';
|
|
13
|
+
import { mkdir, readdir, readFile, rm, writeFile, cp, stat } from 'node:fs/promises';
|
|
14
14
|
import { resolveArtifact } from './matrix';
|
|
15
15
|
import { markersFor, writeManagedBlock } from './markers';
|
|
16
16
|
import type { ArtifactContext, ArtifactType, ManagedArtifact } from './types';
|
|
@@ -37,10 +37,63 @@ async function pathExists(path: string): Promise<boolean> {
|
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* Write only when the bytes differ.
|
|
42
|
+
*
|
|
43
|
+
* This runs at every stream start, and a no-op rewrite still moves mtime. The
|
|
44
|
+
* Open Code pool fingerprints these files to decide whether its baked config
|
|
45
|
+
* changed, so an unconditional write made every single turn spawn a fresh
|
|
46
|
+
* `opencode serve` process for a config that was byte-identical.
|
|
47
|
+
*/
|
|
48
|
+
async function writeFileIfChanged(filePath: string, content: string): Promise<void> {
|
|
49
|
+
try {
|
|
50
|
+
if ((await readFile(filePath, 'utf8')) === content) return;
|
|
51
|
+
} catch { /* missing or unreadable — fall through and write */ }
|
|
52
|
+
await writeFile(filePath, content, 'utf8');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Every file under `dir`, keyed by path relative to it. Missing dir → empty map. */
|
|
56
|
+
async function fileStats(dir: string): Promise<Map<string, { size: number; mtimeMs: number }>> {
|
|
57
|
+
const out = new Map<string, { size: number; mtimeMs: number }>();
|
|
58
|
+
const walk = async (current: string, prefix: string): Promise<void> => {
|
|
59
|
+
let entries;
|
|
60
|
+
try {
|
|
61
|
+
entries = await readdir(current, { withFileTypes: true });
|
|
62
|
+
} catch {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
67
|
+
if (entry.isDirectory()) {
|
|
68
|
+
await walk(join(current, entry.name), relative);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const info = await stat(join(current, entry.name));
|
|
73
|
+
out.set(relative, { size: info.size, mtimeMs: info.mtimeMs });
|
|
74
|
+
} catch { /* raced away */ }
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
await walk(dir, '');
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** True when `destDir` already holds a current copy — same files, same sizes, none of them older than the source. */
|
|
82
|
+
async function folderInSync(sourceDir: string, destDir: string): Promise<boolean> {
|
|
83
|
+
const [source, dest] = await Promise.all([fileStats(sourceDir), fileStats(destDir)]);
|
|
84
|
+
if (source.size === 0 || source.size !== dest.size) return false;
|
|
85
|
+
for (const [relative, sourceInfo] of source) {
|
|
86
|
+
const destInfo = dest.get(relative);
|
|
87
|
+
if (!destInfo || destInfo.size !== sourceInfo.size || destInfo.mtimeMs < sourceInfo.mtimeMs) return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Mirror one canonical folder into a destination dir under `<slug>/`, skipping the copy when it is already current. */
|
|
41
93
|
async function mirrorFolder(sourceDir: string, destDir: string, slug: string): Promise<void> {
|
|
42
94
|
if (!(await pathExists(sourceDir))) return;
|
|
43
95
|
const dest = join(destDir, slug);
|
|
96
|
+
if (await folderInSync(sourceDir, dest)) return;
|
|
44
97
|
await rm(dest, { recursive: true, force: true });
|
|
45
98
|
await mkdir(destDir, { recursive: true });
|
|
46
99
|
await cp(sourceDir, dest, { recursive: true });
|
|
@@ -104,7 +157,7 @@ export async function materializeArtifacts(
|
|
|
104
157
|
if (resolution.format === 'folder-md') {
|
|
105
158
|
if (item.sourceDir) await mirrorFolder(item.sourceDir, target, item.slug);
|
|
106
159
|
} else if (item.document != null) {
|
|
107
|
-
await
|
|
160
|
+
await writeFileIfChanged(join(target, `${item.slug}.md`), item.document);
|
|
108
161
|
}
|
|
109
162
|
}
|
|
110
163
|
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration: Worktrees — isolated copies of a project that sessions can run in.
|
|
3
|
+
* Purpose: let several tasks run in parallel without touching the main tree.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
7
|
+
import { debug } from '$shared/utils/logger';
|
|
8
|
+
|
|
9
|
+
export const description = 'Create worktrees table and bind chat sessions to a worktree';
|
|
10
|
+
|
|
11
|
+
export const up = (db: DatabaseConnection): void => {
|
|
12
|
+
debug.log('migration', '📋 Creating worktrees table...');
|
|
13
|
+
|
|
14
|
+
// `base_tree` is the merge base: a TreeMap (relative path → blob hash) of the
|
|
15
|
+
// main tree captured when the worktree was cloned. Apply/sync compare against
|
|
16
|
+
// it, so it must survive restarts — hence a column rather than memory.
|
|
17
|
+
db.exec(`
|
|
18
|
+
CREATE TABLE IF NOT EXISTS worktrees (
|
|
19
|
+
id TEXT PRIMARY KEY,
|
|
20
|
+
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
21
|
+
name TEXT NOT NULL,
|
|
22
|
+
slug TEXT NOT NULL,
|
|
23
|
+
path TEXT NOT NULL,
|
|
24
|
+
status TEXT NOT NULL DEFAULT 'active'
|
|
25
|
+
CHECK (status IN ('active','applied','archived')),
|
|
26
|
+
clone_mode TEXT NOT NULL DEFAULT 'copy'
|
|
27
|
+
CHECK (clone_mode IN ('reflink','copy')),
|
|
28
|
+
base_tree TEXT NOT NULL,
|
|
29
|
+
created_by TEXT,
|
|
30
|
+
created_at TEXT NOT NULL,
|
|
31
|
+
last_opened_at TEXT,
|
|
32
|
+
last_applied_at TEXT
|
|
33
|
+
)
|
|
34
|
+
`);
|
|
35
|
+
|
|
36
|
+
db.exec(`
|
|
37
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_worktrees_project_slug
|
|
38
|
+
ON worktrees(project_id, slug)
|
|
39
|
+
`);
|
|
40
|
+
|
|
41
|
+
db.exec(`
|
|
42
|
+
CREATE INDEX IF NOT EXISTS idx_worktrees_project
|
|
43
|
+
ON worktrees(project_id)
|
|
44
|
+
`);
|
|
45
|
+
|
|
46
|
+
debug.log('migration', '📋 Binding chat sessions to worktrees...');
|
|
47
|
+
|
|
48
|
+
// NULL = the session runs in the main project tree.
|
|
49
|
+
db.exec(`ALTER TABLE chat_sessions ADD COLUMN worktree_id TEXT`);
|
|
50
|
+
|
|
51
|
+
db.exec(`
|
|
52
|
+
CREATE INDEX IF NOT EXISTS idx_chat_sessions_worktree
|
|
53
|
+
ON chat_sessions(worktree_id)
|
|
54
|
+
`);
|
|
55
|
+
|
|
56
|
+
debug.log('migration', '✅ Worktrees ready');
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export const down = (db: DatabaseConnection): void => {
|
|
60
|
+
debug.log('migration', '🗑️ Dropping worktrees...');
|
|
61
|
+
db.exec('DROP INDEX IF EXISTS idx_chat_sessions_worktree');
|
|
62
|
+
db.exec('DROP INDEX IF EXISTS idx_worktrees_project');
|
|
63
|
+
db.exec('DROP INDEX IF EXISTS idx_worktrees_project_slug');
|
|
64
|
+
db.exec('DROP TABLE IF EXISTS worktrees');
|
|
65
|
+
debug.warn('migration', '⚠️ chat_sessions.worktree_id remains (SQLite drop-column)');
|
|
66
|
+
debug.log('migration', '✅ Worktrees rollback completed');
|
|
67
|
+
};
|
|
@@ -68,6 +68,7 @@ import * as migration066 from './066_create_memory_graph';
|
|
|
68
68
|
import * as migration067 from './067_add_memory_graph_layout';
|
|
69
69
|
import * as migration068 from './068_create_engine_config_revision';
|
|
70
70
|
import * as migration069 from './069_create_ssh_client_tables';
|
|
71
|
+
import * as migration070 from './070_create_worktrees_table';
|
|
71
72
|
|
|
72
73
|
// Export all migrations in order
|
|
73
74
|
export const migrations = [
|
|
@@ -484,6 +485,12 @@ export const migrations = [
|
|
|
484
485
|
description: migration069.description,
|
|
485
486
|
up: migration069.up,
|
|
486
487
|
down: migration069.down
|
|
488
|
+
},
|
|
489
|
+
{
|
|
490
|
+
id: '070',
|
|
491
|
+
description: migration070.description,
|
|
492
|
+
up: migration070.up,
|
|
493
|
+
down: migration070.down
|
|
487
494
|
}
|
|
488
495
|
];
|
|
489
496
|
|
|
@@ -5,6 +5,7 @@ export { messageQueries } from './message-queries';
|
|
|
5
5
|
export { settingsQueries } from './settings-queries';
|
|
6
6
|
export { dbUtils } from './utils-queries';
|
|
7
7
|
export { snapshotQueries } from './snapshot-queries';
|
|
8
|
+
export { worktreeQueries } from './worktree-queries';
|
|
8
9
|
export { checkpointQueries } from './checkpoint-queries';
|
|
9
10
|
export { engineQueries } from './engine-queries';
|
|
10
11
|
export { authQueries } from './auth-queries';
|
|
@@ -41,8 +41,8 @@ export const sessionQueries = {
|
|
|
41
41
|
const newSession = { id, ...session };
|
|
42
42
|
|
|
43
43
|
db.prepare(`
|
|
44
|
-
INSERT INTO chat_sessions (id, project_id, title, engine, head_session_id, head_message_id, started_at, ended_at)
|
|
45
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
44
|
+
INSERT INTO chat_sessions (id, project_id, title, engine, head_session_id, head_message_id, started_at, ended_at, worktree_id)
|
|
45
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
46
46
|
`).run(
|
|
47
47
|
id,
|
|
48
48
|
session.project_id,
|
|
@@ -51,7 +51,8 @@ export const sessionQueries = {
|
|
|
51
51
|
session.head_session_id || null,
|
|
52
52
|
session.head_message_id || null,
|
|
53
53
|
session.started_at,
|
|
54
|
-
session.ended_at || null
|
|
54
|
+
session.ended_at || null,
|
|
55
|
+
session.worktree_id || null
|
|
55
56
|
);
|
|
56
57
|
|
|
57
58
|
return newSession;
|
|
@@ -104,6 +105,14 @@ export const sessionQueries = {
|
|
|
104
105
|
},
|
|
105
106
|
|
|
106
107
|
/** Persist the active profile for a session (NULL clears it). */
|
|
108
|
+
/** Bind a session to a worktree; null puts it back on the main project tree. */
|
|
109
|
+
setWorktree(id: string, worktreeId: string | null): void {
|
|
110
|
+
const db = getDatabase();
|
|
111
|
+
db.prepare(`
|
|
112
|
+
UPDATE chat_sessions SET worktree_id = ? WHERE id = ?
|
|
113
|
+
`).run(worktreeId, id);
|
|
114
|
+
},
|
|
115
|
+
|
|
107
116
|
updateProfile(id: string, profileId: number | null): void {
|
|
108
117
|
const db = getDatabase();
|
|
109
118
|
db.prepare(`
|
|
@@ -440,14 +449,37 @@ export const sessionQueries = {
|
|
|
440
449
|
* Get the active shared session for a project
|
|
441
450
|
* Returns the most recent session that hasn't ended
|
|
442
451
|
*/
|
|
443
|
-
|
|
452
|
+
/**
|
|
453
|
+
* Most recent active session, optionally restricted to one worktree.
|
|
454
|
+
* `worktreeId` undefined means "any"; null means "the main tree only".
|
|
455
|
+
*/
|
|
456
|
+
getActiveSessionForProject(projectId: string, worktreeId?: string | null): ChatSession | null {
|
|
444
457
|
const db = getDatabase();
|
|
458
|
+
|
|
459
|
+
if (worktreeId === undefined) {
|
|
460
|
+
return db.prepare(`
|
|
461
|
+
SELECT * FROM chat_sessions
|
|
462
|
+
WHERE project_id = ? AND ended_at IS NULL
|
|
463
|
+
ORDER BY started_at DESC
|
|
464
|
+
LIMIT 1
|
|
465
|
+
`).get(projectId) as ChatSession | null;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
if (worktreeId === null) {
|
|
469
|
+
return db.prepare(`
|
|
470
|
+
SELECT * FROM chat_sessions
|
|
471
|
+
WHERE project_id = ? AND ended_at IS NULL AND worktree_id IS NULL
|
|
472
|
+
ORDER BY started_at DESC
|
|
473
|
+
LIMIT 1
|
|
474
|
+
`).get(projectId) as ChatSession | null;
|
|
475
|
+
}
|
|
476
|
+
|
|
445
477
|
return db.prepare(`
|
|
446
|
-
SELECT * FROM chat_sessions
|
|
447
|
-
WHERE project_id = ? AND ended_at IS NULL
|
|
478
|
+
SELECT * FROM chat_sessions
|
|
479
|
+
WHERE project_id = ? AND ended_at IS NULL AND worktree_id = ?
|
|
448
480
|
ORDER BY started_at DESC
|
|
449
481
|
LIMIT 1
|
|
450
|
-
`).get(projectId) as ChatSession | null;
|
|
482
|
+
`).get(projectId, worktreeId) as ChatSession | null;
|
|
451
483
|
},
|
|
452
484
|
|
|
453
485
|
/**
|
|
@@ -468,10 +500,16 @@ export const sessionQueries = {
|
|
|
468
500
|
* When forceNew=true, creates a new session WITHOUT ending existing ones
|
|
469
501
|
* (multiple sessions can be active in parallel).
|
|
470
502
|
*/
|
|
471
|
-
getOrCreateSharedSession(
|
|
503
|
+
getOrCreateSharedSession(
|
|
504
|
+
projectId: string,
|
|
505
|
+
projectName: string,
|
|
506
|
+
forceNew: boolean = false,
|
|
507
|
+
worktreeId: string | null = null
|
|
508
|
+
): ChatSession {
|
|
472
509
|
if (!forceNew) {
|
|
473
|
-
//
|
|
474
|
-
|
|
510
|
+
// Reuse only within the same tree — a session bound to a worktree is
|
|
511
|
+
// not a substitute for one on main, and vice versa.
|
|
512
|
+
const activeSession = this.getActiveSessionForProject(projectId, worktreeId);
|
|
475
513
|
if (activeSession) {
|
|
476
514
|
return activeSession;
|
|
477
515
|
}
|
|
@@ -484,7 +522,8 @@ export const sessionQueries = {
|
|
|
484
522
|
title: `Shared Chat - ${projectName} (${new Date().toLocaleString()})`,
|
|
485
523
|
started_at: now,
|
|
486
524
|
ended_at: undefined,
|
|
487
|
-
head_session_id: undefined
|
|
525
|
+
head_session_id: undefined,
|
|
526
|
+
worktree_id: worktreeId
|
|
488
527
|
});
|
|
489
528
|
},
|
|
490
529
|
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Database queries for worktrees — isolated project copies that sessions run in.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { Worktree, WorktreeCloneMode, WorktreeStatus } from '$shared/types/database/schema';
|
|
6
|
+
import type { TreeMap } from '../../snapshot/blob-store';
|
|
7
|
+
import { getDatabase } from '../index';
|
|
8
|
+
|
|
9
|
+
export const worktreeQueries = {
|
|
10
|
+
getByProjectId(projectId: string): Worktree[] {
|
|
11
|
+
const db = getDatabase();
|
|
12
|
+
return db.prepare(`
|
|
13
|
+
SELECT * FROM worktrees
|
|
14
|
+
WHERE project_id = ?
|
|
15
|
+
ORDER BY created_at DESC
|
|
16
|
+
`).all(projectId) as Worktree[];
|
|
17
|
+
},
|
|
18
|
+
|
|
19
|
+
getById(id: string): Worktree | null {
|
|
20
|
+
const db = getDatabase();
|
|
21
|
+
return db.prepare(`SELECT * FROM worktrees WHERE id = ?`).get(id) as Worktree | null;
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
getByPath(worktreePath: string): Worktree | null {
|
|
25
|
+
const db = getDatabase();
|
|
26
|
+
return db.prepare(`SELECT * FROM worktrees WHERE path = ?`).get(worktreePath) as Worktree | null;
|
|
27
|
+
},
|
|
28
|
+
|
|
29
|
+
getBySlug(projectId: string, slug: string): Worktree | null {
|
|
30
|
+
const db = getDatabase();
|
|
31
|
+
return db.prepare(`
|
|
32
|
+
SELECT * FROM worktrees WHERE project_id = ? AND slug = ?
|
|
33
|
+
`).get(projectId, slug) as Worktree | null;
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
create(input: {
|
|
37
|
+
project_id: string;
|
|
38
|
+
name: string;
|
|
39
|
+
slug: string;
|
|
40
|
+
path: string;
|
|
41
|
+
clone_mode: WorktreeCloneMode;
|
|
42
|
+
base_tree: TreeMap;
|
|
43
|
+
created_by?: string | null;
|
|
44
|
+
}): Worktree {
|
|
45
|
+
const db = getDatabase();
|
|
46
|
+
const id = crypto.randomUUID();
|
|
47
|
+
const now = new Date().toISOString();
|
|
48
|
+
|
|
49
|
+
const worktree: Worktree = {
|
|
50
|
+
id,
|
|
51
|
+
project_id: input.project_id,
|
|
52
|
+
name: input.name,
|
|
53
|
+
slug: input.slug,
|
|
54
|
+
path: input.path,
|
|
55
|
+
status: 'active',
|
|
56
|
+
clone_mode: input.clone_mode,
|
|
57
|
+
base_tree: JSON.stringify(input.base_tree),
|
|
58
|
+
created_by: input.created_by ?? null,
|
|
59
|
+
created_at: now,
|
|
60
|
+
last_opened_at: now,
|
|
61
|
+
last_applied_at: null
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
db.prepare(`
|
|
65
|
+
INSERT INTO worktrees (
|
|
66
|
+
id, project_id, name, slug, path, status, clone_mode,
|
|
67
|
+
base_tree, created_by, created_at, last_opened_at, last_applied_at
|
|
68
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
|
|
69
|
+
`).run(
|
|
70
|
+
worktree.id,
|
|
71
|
+
worktree.project_id,
|
|
72
|
+
worktree.name,
|
|
73
|
+
worktree.slug,
|
|
74
|
+
worktree.path,
|
|
75
|
+
worktree.status,
|
|
76
|
+
worktree.clone_mode,
|
|
77
|
+
worktree.base_tree,
|
|
78
|
+
worktree.created_by,
|
|
79
|
+
worktree.created_at,
|
|
80
|
+
worktree.last_opened_at
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
return worktree;
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
rename(id: string, name: string): void {
|
|
87
|
+
const db = getDatabase();
|
|
88
|
+
db.prepare(`UPDATE worktrees SET name = ? WHERE id = ?`).run(name, id);
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
touch(id: string): void {
|
|
92
|
+
const db = getDatabase();
|
|
93
|
+
db.prepare(`UPDATE worktrees SET last_opened_at = ? WHERE id = ?`)
|
|
94
|
+
.run(new Date().toISOString(), id);
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
setStatus(id: string, status: WorktreeStatus): void {
|
|
98
|
+
const db = getDatabase();
|
|
99
|
+
db.prepare(`UPDATE worktrees SET status = ? WHERE id = ?`).run(status, id);
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
/** Record a successful apply and re-base the worktree onto the tree it just produced. */
|
|
103
|
+
markApplied(id: string, baseTree: TreeMap): void {
|
|
104
|
+
const db = getDatabase();
|
|
105
|
+
db.prepare(`
|
|
106
|
+
UPDATE worktrees SET status = 'applied', last_applied_at = ?, base_tree = ?
|
|
107
|
+
WHERE id = ?
|
|
108
|
+
`).run(new Date().toISOString(), JSON.stringify(baseTree), id);
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
/** Re-base without changing status — used by sync-from-main. */
|
|
112
|
+
updateBaseTree(id: string, baseTree: TreeMap): void {
|
|
113
|
+
const db = getDatabase();
|
|
114
|
+
db.prepare(`UPDATE worktrees SET base_tree = ? WHERE id = ?`)
|
|
115
|
+
.run(JSON.stringify(baseTree), id);
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
delete(id: string): void {
|
|
119
|
+
const db = getDatabase();
|
|
120
|
+
// Sessions outlive their worktree: they fall back to the main tree rather
|
|
121
|
+
// than disappearing with it, so only the pointer is cleared.
|
|
122
|
+
db.prepare(`UPDATE chat_sessions SET worktree_id = NULL WHERE worktree_id = ?`).run(id);
|
|
123
|
+
db.prepare(`DELETE FROM worktrees WHERE id = ?`).run(id);
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
deleteByProjectId(projectId: string): Worktree[] {
|
|
127
|
+
const db = getDatabase();
|
|
128
|
+
const worktrees = this.getByProjectId(projectId);
|
|
129
|
+
db.prepare(`DELETE FROM worktrees WHERE project_id = ?`).run(projectId);
|
|
130
|
+
return worktrees;
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
countSessions(worktreeId: string): number {
|
|
134
|
+
const db = getDatabase();
|
|
135
|
+
const row = db.prepare(`
|
|
136
|
+
SELECT COUNT(*) AS total FROM chat_sessions WHERE worktree_id = ?
|
|
137
|
+
`).get(worktreeId) as { total: number } | undefined;
|
|
138
|
+
return row?.total ?? 0;
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
parseBaseTree(worktree: Worktree): TreeMap {
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(worktree.base_tree) as TreeMap;
|
|
144
|
+
} catch {
|
|
145
|
+
return {};
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
};
|