@myrialabs/clopen 0.4.44 → 0.4.46
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/project/bridge.ts +218 -0
- package/backend/artifacts/project/edit.ts +243 -0
- package/backend/artifacts/project/index.ts +38 -0
- package/backend/artifacts/project/project.test.ts +181 -0
- package/backend/artifacts/project/scan.ts +368 -0
- package/backend/artifacts/project/sources.ts +100 -0
- package/backend/artifacts/sync.ts +1 -1
- package/backend/auth/permissions.ts +15 -0
- package/backend/chat/stream-manager.ts +20 -3
- package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
- package/backend/engine/adapters/claude/models.test.ts +49 -0
- package/backend/engine/adapters/claude/models.ts +81 -562
- package/backend/engine/adapters/claude/stream.ts +32 -5
- package/backend/engine/adapters/cline/credential.ts +42 -18
- package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
- package/backend/engine/adapters/cline/message-converter.ts +31 -1
- package/backend/engine/adapters/cline/models.test.ts +77 -0
- package/backend/engine/adapters/cline/models.ts +89 -3
- package/backend/engine/adapters/cline/presets.ts +5 -0
- package/backend/engine/adapters/cline/stream.ts +29 -8
- package/backend/engine/adapters/codex/message-converter.ts +1 -1
- package/backend/engine/adapters/codex/models.ts +54 -31
- package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
- package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
- package/backend/engine/adapters/codex/session-fork.ts +5 -0
- package/backend/engine/adapters/codex/stream.ts +29 -11
- package/backend/engine/adapters/copilot/models.test.ts +40 -0
- package/backend/engine/adapters/copilot/models.ts +51 -24
- package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
- package/backend/engine/adapters/copilot/permissions.ts +72 -0
- package/backend/engine/adapters/copilot/stream.ts +83 -70
- package/backend/engine/adapters/cursor/stream.ts +27 -12
- package/backend/engine/adapters/opencode/server.ts +14 -4
- package/backend/engine/adapters/opencode/stream.ts +18 -3
- package/backend/engine/adapters/pi/credential.test.ts +83 -0
- package/backend/engine/adapters/pi/credential.ts +68 -12
- package/backend/engine/adapters/pi/environment.ts +9 -5
- package/backend/engine/adapters/pi/mcp.test.ts +194 -0
- package/backend/engine/adapters/pi/mcp.ts +88 -0
- package/backend/engine/adapters/pi/message-converter.ts +6 -4
- package/backend/engine/adapters/pi/presets.ts +10 -5
- package/backend/engine/adapters/pi/stream.ts +77 -41
- package/backend/engine/adapters/qwen/environment.ts +39 -2
- package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
- package/backend/engine/adapters/qwen/message-converter.ts +40 -23
- package/backend/engine/adapters/qwen/models.test.ts +25 -0
- package/backend/engine/adapters/qwen/models.ts +42 -5
- package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
- package/backend/engine/adapters/qwen/session-store.ts +66 -0
- package/backend/engine/adapters/qwen/stream.ts +118 -87
- package/backend/engine/artifact-sync.ts +12 -5
- package/backend/engine/docs/adapter-contract.md +7 -4
- package/backend/engine/docs/lessons-learned.md +405 -62
- package/backend/engine/docs/quick-reference.md +2 -2
- package/backend/engine/docs/stack.md +17 -4
- package/backend/engine/docs/websocket-routes.md +5 -5
- package/backend/engine/install-recipes.test.ts +105 -5
- package/backend/engine/install-recipes.ts +102 -42
- package/backend/engine/install-runner.ts +56 -2
- package/backend/engine/stack-project.ts +71 -1
- package/backend/files/file-watcher.test.ts +77 -0
- package/backend/files/file-watcher.ts +92 -60
- package/backend/files/watch-ignore.test.ts +182 -0
- package/backend/files/watch-ignore.ts +244 -0
- package/backend/git/git-executor.ts +14 -4
- package/backend/index.ts +16 -1
- package/backend/instructions/service.ts +5 -3
- package/backend/instructions/sync.ts +10 -27
- package/backend/mcp/README.md +2 -2
- package/backend/mcp/external/config.ts +83 -23
- package/backend/mcp/external/project.ts +124 -0
- package/backend/mcp/external/proxy.ts +65 -11
- package/backend/mcp/index.ts +22 -9
- package/backend/mcp/internal/config.ts +42 -3
- package/backend/mcp/internal/remote-server.ts +11 -1
- package/backend/memory/embedding/install.ts +29 -1
- package/backend/skills/marketplace.ts +1 -1
- package/backend/snapshot/blob-store.ts +9 -5
- package/backend/snapshot/git-attribution.test.ts +42 -0
- package/backend/snapshot/git-attribution.ts +306 -0
- package/backend/snapshot/gitignore.test.ts +62 -0
- package/backend/snapshot/gitignore.ts +158 -78
- package/backend/snapshot/snapshot-service.test.ts +270 -0
- package/backend/snapshot/snapshot-service.ts +412 -136
- package/backend/snapshot/turn-activity.test.ts +52 -0
- package/backend/snapshot/turn-activity.ts +83 -0
- package/backend/snapshot/turn-changes.test.ts +58 -1
- package/backend/snapshot/turn-changes.ts +66 -0
- package/backend/utils/keyed-lock.test.ts +33 -0
- package/backend/utils/keyed-lock.ts +17 -0
- package/backend/utils/port-utils.test.ts +29 -0
- package/backend/utils/port-utils.ts +19 -0
- package/backend/worktrees/tree.ts +1 -1
- package/backend/ws/chat/composer.ts +504 -0
- package/backend/ws/chat/index.ts +3 -1
- package/backend/ws/chat/stream.ts +252 -440
- package/backend/ws/engine/cline/accounts.ts +26 -6
- package/backend/ws/engine/codex/accounts.test.ts +49 -0
- package/backend/ws/engine/codex/accounts.ts +17 -13
- package/backend/ws/engine/pi/accounts.ts +61 -6
- package/backend/ws/index.ts +4 -0
- package/backend/ws/project-artifacts/index.ts +236 -0
- package/backend/ws/snapshot/changes.ts +66 -31
- package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
- package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
- package/dist/assets/main-BiDNMWb3.css +1 -0
- package/dist/assets/main-BlhKWz2B.js +1241 -0
- package/dist/index.html +2 -2
- package/package.json +19 -15
- package/shared/types/stores/settings.ts +5 -0
- package/shared/types/unified/message.ts +2 -0
- package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
- package/backend/engine/adapters/qwen/session-fork.ts +0 -109
- package/dist/assets/main-DOkwqXRU.js +0 -1215
- package/dist/assets/main-DzCY0n-j.css +0 -1
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* Snapshot Service for Time Travel Feature (v2 - Session-Scoped)
|
|
3
3
|
*
|
|
4
4
|
* Architecture:
|
|
5
|
-
* -
|
|
6
|
-
* - Per-checkpoint delta:
|
|
5
|
+
* - Turn baseline: full scan at the start of EVERY turn (blob-stored)
|
|
6
|
+
* - Per-checkpoint delta: files that changed during the turn, minus what git
|
|
7
|
+
* (see git-attribution.ts) and other chats in the same workspace account for
|
|
7
8
|
* - Session-scoped restore: bidirectional (forward + backward) using session_changes
|
|
8
9
|
* - Cross-session conflict detection: warns when restoring would affect other sessions' changes
|
|
9
10
|
*
|
|
@@ -17,7 +18,9 @@ import path from 'path';
|
|
|
17
18
|
import { snapshotQueries, sessionQueries, messageQueries } from '../database/queries';
|
|
18
19
|
import { getDatabase } from '../database/index';
|
|
19
20
|
import { blobStore, type TreeMap } from './blob-store';
|
|
20
|
-
import {
|
|
21
|
+
import { scanSnapshotFiles } from './gitignore';
|
|
22
|
+
import { attributeGitChanges, readRepoHeads, type RepoHeads } from './git-attribution';
|
|
23
|
+
import { TurnActivity, type ObservedOutput } from './turn-activity';
|
|
21
24
|
import { fileWatcher } from '../files/file-watcher';
|
|
22
25
|
import type { MessageSnapshot, SessionScopedChanges } from '$shared/types/database/schema';
|
|
23
26
|
import { calculateFileChangeStats } from '$shared/utils/diff-calculator';
|
|
@@ -71,15 +74,75 @@ export interface ConflictResolution {
|
|
|
71
74
|
[filepath: string]: 'restore' | 'keep';
|
|
72
75
|
}
|
|
73
76
|
|
|
77
|
+
/** Files hashed at once during a scan: hides stat/read latency without exhausting handles. */
|
|
78
|
+
const SCAN_CONCURRENCY = 32;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* What a running turn recorded when it began. Everything the capture needs to
|
|
82
|
+
* tell the turn's own changes from everybody else's.
|
|
83
|
+
*/
|
|
84
|
+
interface TurnState {
|
|
85
|
+
root: string;
|
|
86
|
+
projectId: string;
|
|
87
|
+
worktreeId: string | null;
|
|
88
|
+
scopeKey: string;
|
|
89
|
+
/** Epoch ms, taken before the baseline scan so nothing slips between them. */
|
|
90
|
+
startedAt: number;
|
|
91
|
+
/** HEAD of every repository in the project, for {@link attributeGitChanges}. */
|
|
92
|
+
heads: RepoHeads;
|
|
93
|
+
/** When this turn's tools were running. See turn-activity.ts. */
|
|
94
|
+
activity: TurnActivity;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isMissingFile(error: unknown): boolean {
|
|
98
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
99
|
+
return code === 'ENOENT' || code === 'ENOTDIR';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function forEachConcurrently<T>(items: T[], limit: number, work: (item: T) => Promise<void>): Promise<void> {
|
|
103
|
+
let next = 0;
|
|
104
|
+
const worker = async () => {
|
|
105
|
+
while (next < items.length) {
|
|
106
|
+
const item = items[next++];
|
|
107
|
+
await work(item);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Everything that differs between two trees, as oldHash/newHash pairs. */
|
|
114
|
+
function diffTrees(before: TreeMap, after: TreeMap): SessionScopedChanges {
|
|
115
|
+
const changes: SessionScopedChanges = {};
|
|
116
|
+
for (const [filepath, newHash] of Object.entries(after)) {
|
|
117
|
+
const oldHash = before[filepath] || '';
|
|
118
|
+
if (oldHash !== newHash) changes[filepath] = { oldHash, newHash };
|
|
119
|
+
}
|
|
120
|
+
for (const [filepath, oldHash] of Object.entries(before)) {
|
|
121
|
+
if (!(filepath in after)) changes[filepath] = { oldHash, newHash: '' };
|
|
122
|
+
}
|
|
123
|
+
return changes;
|
|
124
|
+
}
|
|
125
|
+
|
|
74
126
|
export class SnapshotService {
|
|
75
127
|
private static instance: SnapshotService;
|
|
76
128
|
|
|
77
129
|
/**
|
|
78
|
-
* Per-session
|
|
79
|
-
*
|
|
130
|
+
* Per-session tree: sessionId → TreeMap. Re-taken at the start of every
|
|
131
|
+
* turn, and after each capture and restore.
|
|
80
132
|
*/
|
|
81
133
|
private sessionBaselines = new Map<string, TreeMap>();
|
|
82
134
|
|
|
135
|
+
/** Turns currently running, by session. */
|
|
136
|
+
private activeTurns = new Map<string, TurnState>();
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Per-session work queue. A turn's baseline, its capture and a restore
|
|
140
|
+
* all read and replace the same tree, and they must not interleave: a
|
|
141
|
+
* capture still scanning when the next turn begins would fold that turn's
|
|
142
|
+
* first writes into the one before it.
|
|
143
|
+
*/
|
|
144
|
+
private sessionQueues = new Map<string, Promise<void>>();
|
|
145
|
+
|
|
83
146
|
private constructor() {}
|
|
84
147
|
|
|
85
148
|
static getInstance(): SnapshotService {
|
|
@@ -89,43 +152,87 @@ export class SnapshotService {
|
|
|
89
152
|
return SnapshotService.instance;
|
|
90
153
|
}
|
|
91
154
|
|
|
155
|
+
private enqueue<T>(sessionId: string, work: () => Promise<T>): Promise<T> {
|
|
156
|
+
const previous = this.sessionQueues.get(sessionId) ?? Promise.resolve();
|
|
157
|
+
const result = previous.then(work);
|
|
158
|
+
const tail = result.then(() => undefined, () => undefined);
|
|
159
|
+
this.sessionQueues.set(sessionId, tail);
|
|
160
|
+
void tail.then(() => {
|
|
161
|
+
if (this.sessionQueues.get(sessionId) === tail) this.sessionQueues.delete(sessionId);
|
|
162
|
+
});
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
|
|
92
166
|
// ========================================================================
|
|
93
|
-
//
|
|
167
|
+
// Scanning
|
|
94
168
|
// ========================================================================
|
|
95
169
|
|
|
96
170
|
/**
|
|
97
|
-
*
|
|
98
|
-
*
|
|
171
|
+
* Hash every snapshot-eligible file under `root`.
|
|
172
|
+
*
|
|
173
|
+
* `previous` is the tree this scan replaces, and it decides what a file
|
|
174
|
+
* that cannot be read right now becomes: whatever it was. Only a file that
|
|
175
|
+
* is really gone is left out — anything else (a directory git or the OS
|
|
176
|
+
* could not list, a permission error, a file that grew past the size cap)
|
|
177
|
+
* used to fall out of the tree and be recorded as a deletion, which a later
|
|
178
|
+
* restore would then carry out.
|
|
99
179
|
*/
|
|
100
|
-
async
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
): Promise<
|
|
104
|
-
|
|
180
|
+
private async scanTree(
|
|
181
|
+
root: string,
|
|
182
|
+
previous: TreeMap
|
|
183
|
+
): Promise<{ tree: TreeMap; contents: Map<string, Buffer> }> {
|
|
184
|
+
const scan = await scanSnapshotFiles(root, { pruneGenerated: true });
|
|
185
|
+
if (scan.incomplete.includes('')) {
|
|
186
|
+
throw new Error(`Could not list the files of ${root}`);
|
|
187
|
+
}
|
|
105
188
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const baseline: TreeMap = {};
|
|
189
|
+
const tree: TreeMap = {};
|
|
190
|
+
const contents = new Map<string, Buffer>();
|
|
109
191
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
192
|
+
if (scan.incomplete.length > 0) {
|
|
193
|
+
for (const [filepath, hash] of Object.entries(previous)) {
|
|
194
|
+
if (scan.incomplete.some((dir) => filepath.startsWith(dir))) tree[filepath] = hash;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
114
197
|
|
|
115
|
-
|
|
116
|
-
|
|
198
|
+
await forEachConcurrently(scan.files, SCAN_CONCURRENCY, async (filepath) => {
|
|
199
|
+
const relativePath = path.relative(root, filepath).replace(/\\/g, '/');
|
|
200
|
+
try {
|
|
201
|
+
const stat = await fs.stat(filepath);
|
|
202
|
+
if (!stat.isFile()) return;
|
|
203
|
+
if (stat.size > MAX_FILE_SIZE) {
|
|
204
|
+
if (previous[relativePath]) tree[relativePath] = previous[relativePath];
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
117
207
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
208
|
+
const result = await blobStore.hashFile(filepath);
|
|
209
|
+
tree[relativePath] = result.hash;
|
|
210
|
+
if (result.content !== null && result.hash !== previous[relativePath]) {
|
|
211
|
+
contents.set(relativePath, result.content);
|
|
122
212
|
}
|
|
213
|
+
} catch (error) {
|
|
214
|
+
if (isMissingFile(error)) return;
|
|
215
|
+
if (previous[relativePath]) tree[relativePath] = previous[relativePath];
|
|
123
216
|
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
return { tree, contents };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ========================================================================
|
|
223
|
+
// Session Baseline
|
|
224
|
+
// ========================================================================
|
|
124
225
|
|
|
125
|
-
|
|
126
|
-
|
|
226
|
+
/** Re-take a session's tree from disk. Not queued: callers already are. */
|
|
227
|
+
private async rescanBaseline(projectPath: string, sessionId: string): Promise<TreeMap | null> {
|
|
228
|
+
try {
|
|
229
|
+
const { tree } = await this.scanTree(projectPath, this.sessionBaselines.get(sessionId) ?? {});
|
|
230
|
+
this.sessionBaselines.set(sessionId, tree);
|
|
231
|
+
debug.log('snapshot', `Session baseline taken: ${Object.keys(tree).length} files for session ${sessionId}`);
|
|
232
|
+
return tree;
|
|
127
233
|
} catch (error) {
|
|
128
|
-
debug.error('snapshot', 'Error
|
|
234
|
+
debug.error('snapshot', 'Error taking session baseline:', error);
|
|
235
|
+
return this.sessionBaselines.get(sessionId) ?? null;
|
|
129
236
|
}
|
|
130
237
|
}
|
|
131
238
|
|
|
@@ -133,32 +240,185 @@ export class SnapshotService {
|
|
|
133
240
|
projectPath: string,
|
|
134
241
|
sessionId: string
|
|
135
242
|
): Promise<TreeMap> {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
return this.sessionBaselines.get(sessionId) || {};
|
|
243
|
+
const baseline = this.sessionBaselines.get(sessionId);
|
|
244
|
+
if (baseline) return baseline;
|
|
245
|
+
return (await this.rescanBaseline(projectPath, sessionId)) ?? {};
|
|
140
246
|
}
|
|
141
247
|
|
|
142
248
|
// ========================================================================
|
|
143
|
-
//
|
|
249
|
+
// Turn lifecycle
|
|
144
250
|
// ========================================================================
|
|
145
251
|
|
|
146
252
|
/**
|
|
147
|
-
*
|
|
253
|
+
* Start a turn: take the "before" picture this turn will be measured
|
|
254
|
+
* against.
|
|
148
255
|
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
* real capture a moment later.
|
|
256
|
+
* Re-taken at EVERY turn, not only the first. The tree used to be carried
|
|
257
|
+
* over from the previous capture, so everything that happened while the
|
|
258
|
+
* chat sat idle — a pull, a branch switch, the user's own edits, another
|
|
259
|
+
* chat's work — was charged to whichever turn came next, and undoing that
|
|
260
|
+
* turn reverted it.
|
|
155
261
|
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
|
|
160
|
-
|
|
262
|
+
* Must complete before the engine can write (the caller awaits it). Never
|
|
263
|
+
* throws: a turn without a fresh baseline still runs, it just measures
|
|
264
|
+
* against the last good one.
|
|
265
|
+
*/
|
|
266
|
+
async beginTurn(projectPath: string, projectId: string, sessionId: string): Promise<void> {
|
|
267
|
+
await this.enqueue(sessionId, async () => {
|
|
268
|
+
const worktreeId = sessionQueries.getById(sessionId)?.worktree_id ?? null;
|
|
269
|
+
const startedAt = Date.now();
|
|
270
|
+
const [heads] = await Promise.all([
|
|
271
|
+
readRepoHeads(projectPath).catch((error) => {
|
|
272
|
+
debug.warn('snapshot', 'Could not read repository HEADs:', error);
|
|
273
|
+
return new Map() as RepoHeads;
|
|
274
|
+
}),
|
|
275
|
+
this.rescanBaseline(projectPath, sessionId)
|
|
276
|
+
]);
|
|
277
|
+
this.activeTurns.set(sessionId, {
|
|
278
|
+
root: projectPath,
|
|
279
|
+
projectId,
|
|
280
|
+
worktreeId,
|
|
281
|
+
scopeKey: makeScopeKey(projectId, worktreeId),
|
|
282
|
+
startedAt,
|
|
283
|
+
heads,
|
|
284
|
+
activity: new TurnActivity(startedAt)
|
|
285
|
+
});
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Feed a running turn's engine output, to learn when its tools ran. */
|
|
290
|
+
observeEngineOutput(sessionId: string, output: ObservedOutput): void {
|
|
291
|
+
this.activeTurns.get(sessionId)?.activity.observe(output);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Close a turn that will not be captured (it failed before it began). */
|
|
295
|
+
async endTurn(sessionId: string): Promise<void> {
|
|
296
|
+
await this.enqueue(sessionId, async () => {
|
|
297
|
+
this.finishTurn(sessionId);
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private finishTurn(sessionId: string): void {
|
|
302
|
+
const turn = this.activeTurns.get(sessionId);
|
|
303
|
+
if (!turn) return;
|
|
304
|
+
this.activeTurns.delete(sessionId);
|
|
305
|
+
|
|
306
|
+
// The dirty set feeds every running turn's live indicators in this
|
|
307
|
+
// workspace, so it is only cleared once none is left running.
|
|
308
|
+
const othersRunning = Array.from(this.activeTurns.values()).some((t) => t.scopeKey === turn.scopeKey);
|
|
309
|
+
if (!othersRunning) fileWatcher.clearDirtyFiles(turn.scopeKey);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Changes another chat in the same workspace can account for.
|
|
314
|
+
*
|
|
315
|
+
* Two chats running in one folder both see every write. A change is handed
|
|
316
|
+
* to the other chat when the other one already recorded the exact same
|
|
317
|
+
* result since this turn began, or when it was written while one of the
|
|
318
|
+
* other chat's tools was running and none of this turn's was. When both or
|
|
319
|
+
* neither were running, the first capture keeps it — there is nothing
|
|
320
|
+
* better to go on, and it is still counted only once.
|
|
321
|
+
*
|
|
322
|
+
* Only consulted when another chat shares the workspace; alone, a turn
|
|
323
|
+
* owns everything it sees and this costs nothing.
|
|
324
|
+
*/
|
|
325
|
+
private async foreignChanges(
|
|
326
|
+
sessionId: string,
|
|
327
|
+
turn: TurnState,
|
|
328
|
+
changes: SessionScopedChanges
|
|
329
|
+
): Promise<Set<string>> {
|
|
330
|
+
const foreign = new Set<string>();
|
|
331
|
+
const paths = Object.keys(changes);
|
|
332
|
+
if (paths.length === 0) return foreign;
|
|
333
|
+
|
|
334
|
+
const others = Array.from(this.activeTurns.entries())
|
|
335
|
+
.filter(([id, other]) => id !== sessionId && other.scopeKey === turn.scopeKey)
|
|
336
|
+
.map(([, other]) => other);
|
|
337
|
+
|
|
338
|
+
const claimed = new Map<string, Set<string>>();
|
|
339
|
+
for (const row of this.getScopeSnapshotsSince(turn, sessionId)) {
|
|
340
|
+
if (!row.session_changes) continue;
|
|
341
|
+
try {
|
|
342
|
+
const settled = JSON.parse(row.session_changes) as SessionScopedChanges;
|
|
343
|
+
for (const [filepath, change] of Object.entries(settled)) {
|
|
344
|
+
const hashes = claimed.get(filepath) ?? new Set<string>();
|
|
345
|
+
hashes.add(change.newHash);
|
|
346
|
+
claimed.set(filepath, hashes);
|
|
347
|
+
}
|
|
348
|
+
} catch { /* skip malformed */ }
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
for (const filepath of paths) {
|
|
352
|
+
if (claimed.get(filepath)?.has(changes[filepath].newHash)) {
|
|
353
|
+
foreign.add(filepath);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (others.length === 0) continue;
|
|
357
|
+
|
|
358
|
+
const writtenAt = await this.changeTime(turn, filepath, changes[filepath]);
|
|
359
|
+
if (writtenAt === undefined) continue;
|
|
360
|
+
const mine = turn.activity.wasRunningAt(writtenAt);
|
|
361
|
+
const theirs = others.some((other) => other.activity.wasRunningAt(writtenAt));
|
|
362
|
+
if (theirs && !mine) foreign.add(filepath);
|
|
363
|
+
}
|
|
364
|
+
return foreign;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* When a change happened (epoch ms), or undefined when nothing says.
|
|
369
|
+
*
|
|
370
|
+
* A file still on disk carries its modification time. A deleted one does
|
|
371
|
+
* not, so the watcher's record of the event is used, and failing that the
|
|
372
|
+
* nearest surviving directory's mtime — removing an entry updates it.
|
|
161
373
|
*/
|
|
374
|
+
private async changeTime(
|
|
375
|
+
turn: TurnState,
|
|
376
|
+
filepath: string,
|
|
377
|
+
change: SessionScopedChanges[string]
|
|
378
|
+
): Promise<number | undefined> {
|
|
379
|
+
if (change.newHash) {
|
|
380
|
+
try {
|
|
381
|
+
return (await fs.stat(path.join(turn.root, filepath))).mtimeMs;
|
|
382
|
+
} catch {
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const seen = fileWatcher.getLastChangeAt(turn.scopeKey, filepath);
|
|
388
|
+
if (seen !== undefined) return seen;
|
|
389
|
+
|
|
390
|
+
let dir = path.dirname(filepath);
|
|
391
|
+
while (true) {
|
|
392
|
+
try {
|
|
393
|
+
return (await fs.stat(path.join(turn.root, dir === '.' ? '' : dir))).mtimeMs;
|
|
394
|
+
} catch {
|
|
395
|
+
if (dir === '.' || dir === '') return undefined;
|
|
396
|
+
dir = path.dirname(dir);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Other chats' snapshots in the same workspace, captured since `turn` began. */
|
|
402
|
+
private getScopeSnapshotsSince(turn: TurnState, sessionId: string): Array<{ session_changes: string | null }> {
|
|
403
|
+
const db = getDatabase();
|
|
404
|
+
return db.prepare(`
|
|
405
|
+
SELECT s.session_changes FROM message_snapshots s
|
|
406
|
+
JOIN chat_sessions c ON c.id = s.session_id
|
|
407
|
+
WHERE s.project_id = ? AND s.session_id != ? AND s.created_at >= ?
|
|
408
|
+
AND (s.is_deleted IS NULL OR s.is_deleted = 0)
|
|
409
|
+
AND COALESCE(c.worktree_id, '') = ?
|
|
410
|
+
`).all(
|
|
411
|
+
turn.projectId,
|
|
412
|
+
sessionId,
|
|
413
|
+
new Date(turn.startedAt).toISOString(),
|
|
414
|
+
turn.worktreeId ?? ''
|
|
415
|
+
) as Array<{ session_changes: string | null }>;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// ========================================================================
|
|
419
|
+
// In-flight turn
|
|
420
|
+
// ========================================================================
|
|
421
|
+
|
|
162
422
|
/**
|
|
163
423
|
* The hash a file had when the running turn started.
|
|
164
424
|
*
|
|
@@ -172,16 +432,34 @@ export class SnapshotService {
|
|
|
172
432
|
return { known: true, hash: baseline[relativePath] || '' };
|
|
173
433
|
}
|
|
174
434
|
|
|
435
|
+
/**
|
|
436
|
+
* Changes made since the turn began, for a turn that is still running.
|
|
437
|
+
*
|
|
438
|
+
* The settled source of truth is `captureSnapshot`, but it only lands when
|
|
439
|
+
* the stream ends — and the AI-change indicators have to light up while the
|
|
440
|
+
* model is still working. This answers the same question early, from the
|
|
441
|
+
* same baseline, without writing anything: no snapshot row, no baseline
|
|
442
|
+
* move, no dirty-set clear. Whatever it reports is replaced wholesale by the
|
|
443
|
+
* real capture a moment later, which also applies the git attribution this
|
|
444
|
+
* cheaper read skips.
|
|
445
|
+
*
|
|
446
|
+
* Candidates come from the file watcher's dirty set, so the cost is
|
|
447
|
+
* proportional to what actually changed rather than to repository size. The
|
|
448
|
+
* watcher only runs while a client is watching the project — which is
|
|
449
|
+
* exactly when a panel that renders these indicators is mounted — and any
|
|
450
|
+
* event it missed is recovered by the full scan at turn end.
|
|
451
|
+
*/
|
|
175
452
|
async getPendingChanges(
|
|
176
453
|
projectPath: string,
|
|
177
454
|
scopeKey: string,
|
|
178
455
|
sessionId: string
|
|
179
456
|
): Promise<SessionScopedChanges> {
|
|
180
|
-
// No baseline
|
|
181
|
-
// Building
|
|
182
|
-
// unchanged, blinding the indicators for the whole turn — so decline.
|
|
457
|
+
// No running turn, or no baseline for it: nothing this chat is doing now.
|
|
458
|
+
// Building a baseline here would hash the mid-turn disk state and declare
|
|
459
|
+
// it unchanged, blinding the indicators for the whole turn — so decline.
|
|
460
|
+
const turn = this.activeTurns.get(sessionId);
|
|
183
461
|
const baseline = this.sessionBaselines.get(sessionId);
|
|
184
|
-
if (!baseline) return {};
|
|
462
|
+
if (!turn || !baseline) return {};
|
|
185
463
|
|
|
186
464
|
const dirty = fileWatcher.getDirtyFiles(scopeKey);
|
|
187
465
|
if (dirty.size === 0) return {};
|
|
@@ -193,7 +471,7 @@ export class SnapshotService {
|
|
|
193
471
|
const hasNewPaths = Array.from(dirty).some((relativePath) => !(relativePath in baseline));
|
|
194
472
|
if (hasNewPaths) {
|
|
195
473
|
try {
|
|
196
|
-
const files = await
|
|
474
|
+
const { files } = await scanSnapshotFiles(projectPath, { pruneGenerated: true });
|
|
197
475
|
eligible = new Set(
|
|
198
476
|
files.map((filepath) => path.relative(projectPath, filepath).replace(/\\/g, '/'))
|
|
199
477
|
);
|
|
@@ -215,17 +493,22 @@ export class SnapshotService {
|
|
|
215
493
|
const stat = await fs.stat(fullPath);
|
|
216
494
|
if (stat.size > MAX_FILE_SIZE) continue;
|
|
217
495
|
|
|
218
|
-
const result = await blobStore.hashFile(
|
|
496
|
+
const result = await blobStore.hashFile(fullPath);
|
|
219
497
|
if (result.hash !== oldHash) {
|
|
220
498
|
changes[relativePath] = { oldHash, newHash: result.hash };
|
|
221
499
|
}
|
|
222
|
-
} catch {
|
|
500
|
+
} catch (error) {
|
|
223
501
|
// Gone from disk: a deletion when we knew the file, nothing otherwise
|
|
224
|
-
// (a temp file the turn created and removed again).
|
|
225
|
-
|
|
502
|
+
// (a temp file the turn created and removed again). Unreadable is
|
|
503
|
+
// not gone.
|
|
504
|
+
if (oldHash && isMissingFile(error)) changes[relativePath] = { oldHash, newHash: '' };
|
|
226
505
|
}
|
|
227
506
|
}
|
|
228
507
|
|
|
508
|
+
for (const filepath of await this.foreignChanges(sessionId, turn, changes)) {
|
|
509
|
+
delete changes[filepath];
|
|
510
|
+
}
|
|
511
|
+
|
|
229
512
|
return changes;
|
|
230
513
|
}
|
|
231
514
|
|
|
@@ -234,11 +517,25 @@ export class SnapshotService {
|
|
|
234
517
|
// ========================================================================
|
|
235
518
|
|
|
236
519
|
/**
|
|
237
|
-
* Capture
|
|
238
|
-
*
|
|
239
|
-
* Stores session-scoped changes (oldHash/newHash per file).
|
|
520
|
+
* Capture the end of a turn: what changed on disk since it began, minus
|
|
521
|
+
* what git and other chats account for. Closes the turn.
|
|
240
522
|
*/
|
|
241
|
-
|
|
523
|
+
captureSnapshot(
|
|
524
|
+
projectPath: string,
|
|
525
|
+
projectId: string,
|
|
526
|
+
sessionId: string,
|
|
527
|
+
messageId: string
|
|
528
|
+
): Promise<MessageSnapshot> {
|
|
529
|
+
return this.enqueue(sessionId, async () => {
|
|
530
|
+
try {
|
|
531
|
+
return await this.captureTurn(projectPath, projectId, sessionId, messageId);
|
|
532
|
+
} finally {
|
|
533
|
+
this.finishTurn(sessionId);
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
private async captureTurn(
|
|
242
539
|
projectPath: string,
|
|
243
540
|
projectId: string,
|
|
244
541
|
sessionId: string,
|
|
@@ -250,70 +547,40 @@ export class SnapshotService {
|
|
|
250
547
|
? previousSnapshots[previousSnapshots.length - 1]
|
|
251
548
|
: null;
|
|
252
549
|
|
|
253
|
-
//
|
|
254
|
-
// last capture/restore).
|
|
550
|
+
// The disk at the start of this turn.
|
|
255
551
|
const previousTree = await this.getSessionBaseline(projectPath, sessionId);
|
|
256
552
|
|
|
257
553
|
// The source of truth is the DISK, not the file watcher's dirty set. The
|
|
258
554
|
// watcher only runs while the Files/Git panel is mounted, so relying on it
|
|
259
555
|
// silently dropped snapshots whenever the user chatted with those panels
|
|
260
|
-
// closed
|
|
261
|
-
//
|
|
262
|
-
//
|
|
263
|
-
|
|
264
|
-
const
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
// Files over the size cap are never tracked (mirrors the baseline
|
|
276
|
-
// scan). If one was tracked before, the deletion pass below records
|
|
277
|
-
// its removal from the tree.
|
|
278
|
-
if (stat.size > MAX_FILE_SIZE) continue;
|
|
279
|
-
|
|
280
|
-
seen.add(relativePath);
|
|
281
|
-
|
|
282
|
-
const result = await blobStore.hashFile(relativePath, filepath);
|
|
283
|
-
const newHash = result.hash;
|
|
284
|
-
const oldHash = previousTree[relativePath] || '';
|
|
285
|
-
|
|
286
|
-
currentTree[relativePath] = newHash;
|
|
287
|
-
|
|
288
|
-
if (oldHash !== newHash) {
|
|
289
|
-
sessionChanges[relativePath] = { oldHash, newHash };
|
|
290
|
-
|
|
291
|
-
if (result.content !== null) {
|
|
292
|
-
readContents.set(relativePath, result.content);
|
|
293
|
-
}
|
|
556
|
+
// closed. A gitignore-aware scan + hash diff against the baseline is
|
|
557
|
+
// always correct, and blobStore.hashFile's mtime+size cache keeps it
|
|
558
|
+
// cheap — only files that actually changed are re-read.
|
|
559
|
+
const { tree: currentTree, contents: readContents } = await this.scanTree(projectPath, previousTree);
|
|
560
|
+
const sessionChanges = diffTrees(previousTree, currentTree);
|
|
561
|
+
|
|
562
|
+
// A disk diff sees every writer. Take out what is not this turn's.
|
|
563
|
+
const turn = this.activeTurns.get(sessionId);
|
|
564
|
+
if (turn && Object.keys(sessionChanges).length > 0) {
|
|
565
|
+
const git = await attributeGitChanges(projectPath, turn.heads, turn.startedAt, sessionChanges);
|
|
566
|
+
for (const filepath of git.explained) delete sessionChanges[filepath];
|
|
567
|
+
for (const [filepath, oldHash] of git.rebased) {
|
|
568
|
+
if (oldHash === sessionChanges[filepath].newHash) delete sessionChanges[filepath];
|
|
569
|
+
else sessionChanges[filepath].oldHash = oldHash;
|
|
570
|
+
}
|
|
294
571
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
} catch {
|
|
300
|
-
// Unreadable file — skip it
|
|
572
|
+
for (const filepath of await this.foreignChanges(sessionId, turn, sessionChanges)) {
|
|
573
|
+
delete sessionChanges[filepath];
|
|
301
574
|
}
|
|
302
|
-
}
|
|
303
575
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
if (!seen.has(relativePath)) {
|
|
307
|
-
sessionChanges[relativePath] = { oldHash: previousTree[relativePath], newHash: '' };
|
|
576
|
+
if (git.explained.size > 0 || git.rebased.size > 0) {
|
|
577
|
+
debug.log('snapshot', `Git accounts for ${git.explained.size} file(s), ${git.rebased.size} re-based`);
|
|
308
578
|
}
|
|
309
579
|
}
|
|
310
580
|
|
|
311
|
-
// The
|
|
312
|
-
//
|
|
313
|
-
|
|
314
|
-
fileWatcher.clearDirtyFiles(
|
|
315
|
-
makeScopeKey(projectId, sessionQueries.getById(sessionId)?.worktree_id ?? null)
|
|
316
|
-
);
|
|
581
|
+
// The next turn re-takes its own baseline; this keeps getBaselineHash
|
|
582
|
+
// honest in between, and is the tree a restore compares against.
|
|
583
|
+
this.sessionBaselines.set(sessionId, currentTree);
|
|
317
584
|
|
|
318
585
|
// No changes vs the baseline → reuse the existing head snapshot.
|
|
319
586
|
if (Object.keys(sessionChanges).length === 0 && previousSnapshot) {
|
|
@@ -322,9 +589,7 @@ export class SnapshotService {
|
|
|
322
589
|
}
|
|
323
590
|
|
|
324
591
|
// Calculate line-level file change stats
|
|
325
|
-
const fileStats = await this.calculateChangeStats(
|
|
326
|
-
previousTree, currentTree, sessionChanges, readContents
|
|
327
|
-
);
|
|
592
|
+
const fileStats = await this.calculateChangeStats(sessionChanges, readContents);
|
|
328
593
|
|
|
329
594
|
const metadata: SnapshotMetadata = {
|
|
330
595
|
totalFiles: Object.keys(currentTree).length,
|
|
@@ -337,9 +602,6 @@ export class SnapshotService {
|
|
|
337
602
|
|
|
338
603
|
const snapshotId = `snapshot_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
339
604
|
|
|
340
|
-
// Update in-memory baseline
|
|
341
|
-
this.sessionBaselines.set(sessionId, { ...currentTree });
|
|
342
|
-
|
|
343
605
|
const dbSnapshot = snapshotQueries.createSnapshot({
|
|
344
606
|
id: snapshotId,
|
|
345
607
|
message_id: messageId,
|
|
@@ -463,7 +725,10 @@ export class SnapshotService {
|
|
|
463
725
|
const projectId = targetSnapshot
|
|
464
726
|
? targetSnapshot.project_id
|
|
465
727
|
: (sessionSnapshots[0]?.project_id || '');
|
|
466
|
-
|
|
728
|
+
// Only chats working on the same copy of the project can conflict: a
|
|
729
|
+
// worktree session edits its own files, however alike the paths look.
|
|
730
|
+
const worktreeId = sessionQueries.getById(sessionId)?.worktree_id ?? null;
|
|
731
|
+
const allProjectSnapshots = this.getAllProjectSnapshots(projectId, worktreeId);
|
|
467
732
|
|
|
468
733
|
for (const otherSnap of allProjectSnapshots) {
|
|
469
734
|
if (otherSnap.session_id === sessionId) continue;
|
|
@@ -557,13 +822,15 @@ export class SnapshotService {
|
|
|
557
822
|
};
|
|
558
823
|
}
|
|
559
824
|
|
|
560
|
-
private getAllProjectSnapshots(projectId: string): MessageSnapshot[] {
|
|
825
|
+
private getAllProjectSnapshots(projectId: string, worktreeId: string | null): MessageSnapshot[] {
|
|
561
826
|
const db = getDatabase();
|
|
562
827
|
return db.prepare(`
|
|
563
|
-
SELECT
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
828
|
+
SELECT s.* FROM message_snapshots s
|
|
829
|
+
JOIN chat_sessions c ON c.id = s.session_id
|
|
830
|
+
WHERE s.project_id = ? AND (s.is_deleted IS NULL OR s.is_deleted = 0)
|
|
831
|
+
AND COALESCE(c.worktree_id, '') = ?
|
|
832
|
+
ORDER BY s.created_at ASC
|
|
833
|
+
`).all(projectId, worktreeId ?? '') as MessageSnapshot[];
|
|
567
834
|
}
|
|
568
835
|
|
|
569
836
|
// ========================================================================
|
|
@@ -582,7 +849,21 @@ export class SnapshotService {
|
|
|
582
849
|
*
|
|
583
850
|
* Falls back to linear algorithm when targetPath is not provided.
|
|
584
851
|
*/
|
|
585
|
-
|
|
852
|
+
restoreSessionScoped(
|
|
853
|
+
projectPath: string,
|
|
854
|
+
sessionId: string,
|
|
855
|
+
targetCheckpointMessageId: string | null,
|
|
856
|
+
conflictResolutions?: ConflictResolution,
|
|
857
|
+
targetPath?: string[]
|
|
858
|
+
): Promise<{ restoredFiles: number; skippedFiles: number }> {
|
|
859
|
+
// Queued with the session's captures: a restore rewrites the tree a
|
|
860
|
+
// capture still scanning would otherwise record as the turn's work.
|
|
861
|
+
return this.enqueue(sessionId, () => this.restoreNow(
|
|
862
|
+
projectPath, sessionId, targetCheckpointMessageId, conflictResolutions, targetPath
|
|
863
|
+
));
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
private async restoreNow(
|
|
586
867
|
projectPath: string,
|
|
587
868
|
sessionId: string,
|
|
588
869
|
targetCheckpointMessageId: string | null,
|
|
@@ -651,15 +932,11 @@ export class SnapshotService {
|
|
|
651
932
|
}
|
|
652
933
|
}
|
|
653
934
|
|
|
654
|
-
//
|
|
655
|
-
//
|
|
656
|
-
//
|
|
657
|
-
//
|
|
658
|
-
|
|
659
|
-
// Without this, subsequent captures would compute oldHash='' for files missing
|
|
660
|
-
// from the baseline, causing future restores to incorrectly delete those files.
|
|
661
|
-
this.sessionBaselines.delete(sessionId);
|
|
662
|
-
await this.initializeSessionBaseline(projectPath, sessionId);
|
|
935
|
+
// Re-take the baseline from actual disk state: files already at their
|
|
936
|
+
// expected state were skipped, and after a server restart there is no
|
|
937
|
+
// baseline at all. A partial one would compute oldHash='' for every
|
|
938
|
+
// file it misses, and a later restore would delete those files.
|
|
939
|
+
await this.rescanBaseline(projectPath, sessionId);
|
|
663
940
|
|
|
664
941
|
debug.log('snapshot', `Restore complete: ${restoredFiles} restored, ${skippedFiles} skipped`);
|
|
665
942
|
return { restoredFiles, skippedFiles };
|
|
@@ -795,8 +1072,6 @@ export class SnapshotService {
|
|
|
795
1072
|
* Calculate line-level change stats for changed files.
|
|
796
1073
|
*/
|
|
797
1074
|
private async calculateChangeStats(
|
|
798
|
-
previousTree: TreeMap,
|
|
799
|
-
currentTree: TreeMap,
|
|
800
1075
|
sessionChanges: SessionScopedChanges,
|
|
801
1076
|
readContents: Map<string, Buffer>
|
|
802
1077
|
): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
|
|
@@ -846,6 +1121,7 @@ export class SnapshotService {
|
|
|
846
1121
|
*/
|
|
847
1122
|
clearSessionBaseline(sessionId: string): void {
|
|
848
1123
|
this.sessionBaselines.delete(sessionId);
|
|
1124
|
+
this.activeTurns.delete(sessionId);
|
|
849
1125
|
}
|
|
850
1126
|
}
|
|
851
1127
|
|