playcanvas-agent-bridge-cli 0.6.1 → 0.6.2
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/README.md +79 -23
- package/README.zh-CN.md +71 -25
- package/dist/cli.js +132 -8
- package/dist/config.js +1 -1
- package/dist/daemon/server.js +79 -1
- package/dist/daemon/target-registry.js +3 -0
- package/dist/processing/manager.js +265 -0
- package/dist/processing/tools.js +97 -0
- package/dist/snippets.js +27 -0
- package/dist/workspace/json-sync.js +821 -0
- package/dist/workspace/manager.js +1973 -326
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-256.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/isolated.js +48 -0
- package/extension/main.js +708 -39
- package/extension/manifest.json +60 -10
- package/extension/popup.html +33 -2
- package/extension/popup.js +142 -11
- package/extension/service-worker.js +124 -1
- package/package.json +19 -18
- package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +76 -26
- package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +59 -44
- package/skills/cursor/playcanvas-agent-bridge-cli.mdc +57 -22
- package/skills/windsurf/playcanvas-agent-bridge-cli.md +56 -22
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { existsSync } from "node:fs";
|
|
3
|
-
import {
|
|
4
|
-
import { chmod, copyFile, lstat, mkdir, readFile, readdir, rename, rmdir, stat, unlink, writeFile, } from "node:fs/promises";
|
|
2
|
+
import { existsSync, watch } from "node:fs";
|
|
3
|
+
import { chmod, copyFile, lstat, mkdir, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile, } from "node:fs/promises";
|
|
5
4
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { DATA_JSON_TYPES, DEFAULT_EAGER_MAX_MB, TEXT_FILE_TYPES, buildAssetProjection, buildSceneProjection, clampEagerMaxMb, dataAssetFilename, diffAssetPatchOps, diffScenePatchOps, eagerMaxBytesFromMb, parseAssetProjection, parseDataAssetFilename, parseSceneFilename, parseSceneProjection, stripDataAssetSuffix, threeWayMergeAssetJson, threeWayMergeSceneJson, } from "./json-sync.js";
|
|
6
6
|
const PROJECT_FILE = "pcbridge.project.json";
|
|
7
7
|
const LEGACY_INDEX_FILE = join(".pcbridge", "asset-index.json");
|
|
8
8
|
const LEGACY_INDEX_BACKUP_FILE = join(".pcbridge", "asset-index.v1.json");
|
|
9
9
|
const SYNC_STATE_FILE = join(".pcbridge", "sync-state.json");
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
const
|
|
10
|
+
const BASELINES_DIR = join(".pcbridge", "baselines");
|
|
11
|
+
const DEFAULT_REFRESH_INTERVAL_MS = 0;
|
|
12
|
+
const DEFAULT_LOCAL_CHANGE_DEBOUNCE_MS = 300;
|
|
13
|
+
const SELF_WRITE_TTL_MS = 5000;
|
|
13
14
|
function hashContent(value) {
|
|
14
15
|
return createHash("md5").update(value).digest("hex");
|
|
15
16
|
}
|
|
@@ -56,11 +57,19 @@ export function safeAssetName(value, fallback) {
|
|
|
56
57
|
return safe || fallback;
|
|
57
58
|
}
|
|
58
59
|
function collisionName(filename, type, id) {
|
|
60
|
+
const parsedData = parseDataAssetFilename(filename);
|
|
61
|
+
if (parsedData) {
|
|
62
|
+
const safeType = safeAssetName(type, "asset").replaceAll(" ", "-").toLocaleLowerCase();
|
|
63
|
+
return `${parsedData.stem}.__pc_${safeType}_${id}.${parsedData.type}.json`;
|
|
64
|
+
}
|
|
59
65
|
const extension = extname(filename);
|
|
60
66
|
const stem = extension ? filename.slice(0, -extension.length) : filename;
|
|
61
67
|
const safeType = safeAssetName(type, "asset").replaceAll(" ", "-").toLocaleLowerCase();
|
|
62
68
|
return `${stem}.__pc_${safeType}_${id}${extension}`;
|
|
63
69
|
}
|
|
70
|
+
function stripCollisionTag(filename) {
|
|
71
|
+
return filename.replace(/\.__pc_[a-z0-9_-]+(?=\.[^.]+(?:\.json)?$|$)/i, "");
|
|
72
|
+
}
|
|
64
73
|
function pathNameKey(value) {
|
|
65
74
|
return value.normalize("NFKC").toLocaleLowerCase();
|
|
66
75
|
}
|
|
@@ -83,7 +92,41 @@ function assetRole(asset) {
|
|
|
83
92
|
return "derived";
|
|
84
93
|
return asset.source ? "source" : "standalone";
|
|
85
94
|
}
|
|
95
|
+
function desiredLocalFilename(asset, role) {
|
|
96
|
+
if (asset.type === "folder")
|
|
97
|
+
return null;
|
|
98
|
+
if (DATA_JSON_TYPES.has(asset.type) && !asset.file?.filename) {
|
|
99
|
+
return dataAssetFilename(asset.name || `${asset.type}-${asset.id}`, asset.type);
|
|
100
|
+
}
|
|
101
|
+
if (role === "derived" && asset.file?.filename) {
|
|
102
|
+
return asset.file.filename;
|
|
103
|
+
}
|
|
104
|
+
if (asset.file?.filename) {
|
|
105
|
+
const fileExt = extname(asset.file.filename);
|
|
106
|
+
const rawName = (asset.name || "").trim();
|
|
107
|
+
if (!rawName)
|
|
108
|
+
return asset.file.filename;
|
|
109
|
+
const nameExt = extname(rawName);
|
|
110
|
+
if (nameExt && /^\.[a-z][a-z0-9]*$/i.test(nameExt)) {
|
|
111
|
+
return rawName;
|
|
112
|
+
}
|
|
113
|
+
if (fileExt) {
|
|
114
|
+
return `${rawName}${fileExt}`;
|
|
115
|
+
}
|
|
116
|
+
return rawName;
|
|
117
|
+
}
|
|
118
|
+
if (TEXT_FILE_TYPES.has(asset.type)) {
|
|
119
|
+
return asset.name || null;
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
function sceneLocalFilename(name, id) {
|
|
124
|
+
const safe = safeAssetName(name || `Scene-${id}`, `Scene-${id}`);
|
|
125
|
+
return `${safe}.${id}.scene.json`;
|
|
126
|
+
}
|
|
86
127
|
async function mapWithConcurrency(values, limit, operation) {
|
|
128
|
+
if (!values.length)
|
|
129
|
+
return [];
|
|
87
130
|
const results = new Array(values.length);
|
|
88
131
|
let cursor = 0;
|
|
89
132
|
const worker = async () => {
|
|
@@ -101,6 +144,18 @@ async function atomicWrite(path, value) {
|
|
|
101
144
|
await writeFile(temporary, value);
|
|
102
145
|
await rename(temporary, path);
|
|
103
146
|
}
|
|
147
|
+
async function ensureFileMode(path, writable) {
|
|
148
|
+
try {
|
|
149
|
+
const info = await stat(path);
|
|
150
|
+
const isWritable = (info.mode & 0o200) !== 0;
|
|
151
|
+
if (isWritable !== writable) {
|
|
152
|
+
await chmod(path, writable ? 0o644 : 0o444);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
// Ignore unsupported chmod platforms or vanished files.
|
|
157
|
+
}
|
|
158
|
+
}
|
|
104
159
|
async function readJson(path) {
|
|
105
160
|
try {
|
|
106
161
|
return JSON.parse(await readFile(path, "utf8"));
|
|
@@ -125,36 +180,80 @@ export class WorkspaceManager {
|
|
|
125
180
|
#watchers = new Map();
|
|
126
181
|
#watchTimers = new Map();
|
|
127
182
|
#localChangeDebounceMs;
|
|
183
|
+
#eagerMaxMb;
|
|
184
|
+
#settingsPath;
|
|
185
|
+
#settingsLoaded = false;
|
|
128
186
|
constructor(options) {
|
|
129
187
|
this.rootDir = resolve(options.rootDir);
|
|
130
188
|
this.#requestTarget = options.requestTarget;
|
|
131
189
|
const interval = options.refreshIntervalMs ?? DEFAULT_REFRESH_INTERVAL_MS;
|
|
132
190
|
this.#localChangeDebounceMs = options.localChangeDebounceMs ?? DEFAULT_LOCAL_CHANGE_DEBOUNCE_MS;
|
|
191
|
+
this.#eagerMaxMb = clampEagerMaxMb(options.eagerMaxMb, DEFAULT_EAGER_MAX_MB);
|
|
192
|
+
this.#settingsPath = options.settingsPath ? resolve(options.settingsPath) : null;
|
|
133
193
|
if (interval > 0) {
|
|
134
194
|
this.#refreshTimer = setInterval(() => {
|
|
135
195
|
for (const record of this.#records.values()) {
|
|
136
|
-
if (record.connected)
|
|
137
|
-
void this.#
|
|
196
|
+
if (record.connected) {
|
|
197
|
+
void this.#enqueueSync(record, { fullSnapshot: true, force: false });
|
|
198
|
+
}
|
|
138
199
|
}
|
|
139
200
|
}, interval);
|
|
140
201
|
this.#refreshTimer.unref();
|
|
141
202
|
}
|
|
142
203
|
}
|
|
204
|
+
async #ensureSettingsLoaded() {
|
|
205
|
+
if (this.#settingsLoaded)
|
|
206
|
+
return;
|
|
207
|
+
this.#settingsLoaded = true;
|
|
208
|
+
if (!this.#settingsPath)
|
|
209
|
+
return;
|
|
210
|
+
const stored = await readJson(this.#settingsPath);
|
|
211
|
+
if (stored && stored.eagerMaxMb !== undefined) {
|
|
212
|
+
this.#eagerMaxMb = clampEagerMaxMb(stored.eagerMaxMb, this.#eagerMaxMb);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
getSettings() {
|
|
216
|
+
return {
|
|
217
|
+
eagerMaxMb: this.#eagerMaxMb,
|
|
218
|
+
eagerMaxBytes: eagerMaxBytesFromMb(this.#eagerMaxMb),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
async updateSettings(input) {
|
|
222
|
+
await this.#ensureSettingsLoaded();
|
|
223
|
+
this.#eagerMaxMb = clampEagerMaxMb(input.eagerMaxMb, this.#eagerMaxMb);
|
|
224
|
+
if (this.#settingsPath) {
|
|
225
|
+
await atomicWrite(this.#settingsPath, `${JSON.stringify({
|
|
226
|
+
schemaVersion: 1,
|
|
227
|
+
eagerMaxMb: this.#eagerMaxMb,
|
|
228
|
+
updatedAt: new Date().toISOString(),
|
|
229
|
+
}, null, 2)}\n`);
|
|
230
|
+
}
|
|
231
|
+
const syncs = [];
|
|
232
|
+
for (const record of this.#records.values()) {
|
|
233
|
+
if (record.connected) {
|
|
234
|
+
syncs.push(this.#enqueueSync(record, { fullSnapshot: true, force: false }));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
await Promise.allSettled(syncs);
|
|
238
|
+
return this.getSettings();
|
|
239
|
+
}
|
|
143
240
|
async close() {
|
|
144
241
|
if (this.#refreshTimer) {
|
|
145
242
|
clearInterval(this.#refreshTimer);
|
|
146
243
|
this.#refreshTimer = null;
|
|
147
244
|
}
|
|
148
|
-
await Promise.all(Array.from(this.#records.values(), (record) => record.syncPromise).filter(Boolean));
|
|
149
|
-
for (const watchers of this.#watchers.values())
|
|
150
|
-
for (const watcher of watchers)
|
|
151
|
-
watcher.close();
|
|
152
|
-
this.#watchers.clear();
|
|
153
245
|
for (const timer of this.#watchTimers.values())
|
|
154
246
|
clearTimeout(timer);
|
|
155
247
|
this.#watchTimers.clear();
|
|
248
|
+
for (const watchers of this.#watchers.values()) {
|
|
249
|
+
for (const watcher of watchers)
|
|
250
|
+
watcher.close();
|
|
251
|
+
}
|
|
252
|
+
this.#watchers.clear();
|
|
253
|
+
await Promise.all(Array.from(this.#records.values(), (record) => record.drainPromise).filter(Boolean));
|
|
156
254
|
}
|
|
157
255
|
async handleTarget(info) {
|
|
256
|
+
await this.#ensureSettingsLoaded();
|
|
158
257
|
if (info.kind !== "editor" ||
|
|
159
258
|
!info.ready ||
|
|
160
259
|
!info.projectId ||
|
|
@@ -175,7 +274,25 @@ export class WorkspaceManager {
|
|
|
175
274
|
record.branchName = info.branchName || record.branchName;
|
|
176
275
|
await this.#writeManifest(record);
|
|
177
276
|
this.#ensureWatcher(record);
|
|
178
|
-
await this.#
|
|
277
|
+
await this.#enqueueSync(record, { fullSnapshot: true, force: false });
|
|
278
|
+
}
|
|
279
|
+
async handleDelta(info, delta) {
|
|
280
|
+
await this.#ensureSettingsLoaded();
|
|
281
|
+
if (info.kind !== "editor" || !info.ready || !info.projectId)
|
|
282
|
+
return;
|
|
283
|
+
const record = this.#records.get(info.projectId);
|
|
284
|
+
if (!record) {
|
|
285
|
+
if (info.projectName)
|
|
286
|
+
await this.handleTarget(info);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (record.branchId && info.branchId && record.branchId !== info.branchId)
|
|
290
|
+
return;
|
|
291
|
+
record.targetId = info.id;
|
|
292
|
+
record.targetInfo = info;
|
|
293
|
+
record.connected = true;
|
|
294
|
+
record.dirtyRemoteDeltas.push(delta);
|
|
295
|
+
await this.#drainQueue(record);
|
|
179
296
|
}
|
|
180
297
|
markDisconnected(info) {
|
|
181
298
|
if (!info.projectId)
|
|
@@ -185,11 +302,14 @@ export class WorkspaceManager {
|
|
|
185
302
|
record.connected = false;
|
|
186
303
|
}
|
|
187
304
|
statusForTarget(info) {
|
|
305
|
+
const settings = this.getSettings();
|
|
188
306
|
if (!info?.projectId) {
|
|
189
307
|
return {
|
|
190
308
|
available: false,
|
|
191
309
|
state: "unavailable",
|
|
192
310
|
rootDirectory: this.rootDir,
|
|
311
|
+
eagerMaxMb: settings.eagerMaxMb,
|
|
312
|
+
eagerMaxBytes: settings.eagerMaxBytes,
|
|
193
313
|
};
|
|
194
314
|
}
|
|
195
315
|
const record = this.#records.get(info.projectId);
|
|
@@ -199,6 +319,8 @@ export class WorkspaceManager {
|
|
|
199
319
|
state: info.kind === "editor" ? "initializing" : "unavailable",
|
|
200
320
|
rootDirectory: this.rootDir,
|
|
201
321
|
projectId: info.projectId,
|
|
322
|
+
eagerMaxMb: settings.eagerMaxMb,
|
|
323
|
+
eagerMaxBytes: settings.eagerMaxBytes,
|
|
202
324
|
};
|
|
203
325
|
}
|
|
204
326
|
if (record.branchId && info.branchId && record.branchId !== info.branchId) {
|
|
@@ -214,6 +336,7 @@ export class WorkspaceManager {
|
|
|
214
336
|
return this.#status(record);
|
|
215
337
|
}
|
|
216
338
|
async syncTarget(info) {
|
|
339
|
+
await this.#ensureSettingsLoaded();
|
|
217
340
|
if (!info.projectId)
|
|
218
341
|
throw new Error("The selected target has no project metadata.");
|
|
219
342
|
const record = this.#records.get(info.projectId);
|
|
@@ -225,12 +348,11 @@ export class WorkspaceManager {
|
|
|
225
348
|
record.targetId = info.id;
|
|
226
349
|
record.targetInfo = info;
|
|
227
350
|
record.connected = true;
|
|
228
|
-
|
|
229
|
-
// turn lazy binary synchronization back into a full project download.
|
|
230
|
-
await this.#sync(record, false);
|
|
351
|
+
await this.#enqueueSync(record, { fullSnapshot: true, force: false });
|
|
231
352
|
return this.#status(record);
|
|
232
353
|
}
|
|
233
354
|
async prepareAssetFiles(info, assetIds) {
|
|
355
|
+
await this.#ensureSettingsLoaded();
|
|
234
356
|
if (!info.projectId)
|
|
235
357
|
throw new Error("The selected target has no project metadata.");
|
|
236
358
|
const record = this.#records.get(info.projectId);
|
|
@@ -239,7 +361,7 @@ export class WorkspaceManager {
|
|
|
239
361
|
record.targetId = info.id;
|
|
240
362
|
record.targetInfo = info;
|
|
241
363
|
record.connected = true;
|
|
242
|
-
await this.#
|
|
364
|
+
await this.#enqueueSync(record, { fullSnapshot: true, force: true });
|
|
243
365
|
const ids = [...new Set(assetIds.map(String))];
|
|
244
366
|
const assets = await mapWithConcurrency(ids, 4, async (id) => {
|
|
245
367
|
const entry = record.index.entries[id];
|
|
@@ -248,10 +370,17 @@ export class WorkspaceManager {
|
|
|
248
370
|
if (entry.status === "conflict" || entry.status === "error") {
|
|
249
371
|
throw new Error(`Asset ${id} cannot be built while its workspace state is ${entry.status}.`);
|
|
250
372
|
}
|
|
251
|
-
if (entry.localPath && !existsSync(this.#assetPath(record, entry.localPath))) {
|
|
252
|
-
|
|
373
|
+
if (entry.localPath && !DATA_JSON_TYPES.has(entry.type) && !existsSync(this.#assetPath(record, entry.localPath))) {
|
|
374
|
+
if (TEXT_FILE_TYPES.has(entry.type) && entry.writable) {
|
|
375
|
+
await this.#downloadTextAsset(record, entry);
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
await this.#downloadAsset(record, entry);
|
|
379
|
+
}
|
|
253
380
|
}
|
|
254
|
-
const preparedPath = entry.localPath
|
|
381
|
+
const preparedPath = entry.localPath && !DATA_JSON_TYPES.has(entry.type)
|
|
382
|
+
? this.#assetPath(record, entry.localPath)
|
|
383
|
+
: null;
|
|
255
384
|
const preparedHash = entry.localHash;
|
|
256
385
|
if (!preparedPath && entry.filename) {
|
|
257
386
|
throw new Error(`Asset ${id} has a remote file but no local assets projection.`);
|
|
@@ -276,6 +405,7 @@ export class WorkspaceManager {
|
|
|
276
405
|
};
|
|
277
406
|
}
|
|
278
407
|
async prepareAssetResources(info, requests) {
|
|
408
|
+
await this.#ensureSettingsLoaded();
|
|
279
409
|
if (!info.projectId)
|
|
280
410
|
throw new Error("The selected target has no project metadata.");
|
|
281
411
|
const record = this.#records.get(info.projectId);
|
|
@@ -339,6 +469,7 @@ export class WorkspaceManager {
|
|
|
339
469
|
await mkdir(dirname(nextPath), { recursive: true });
|
|
340
470
|
await chmod(oldPath, 0o644).catch(() => undefined);
|
|
341
471
|
await rename(oldPath, nextPath);
|
|
472
|
+
this.#markSelfDeleted(record, oldPath);
|
|
342
473
|
}
|
|
343
474
|
const advertisedRemoteHash = request.hash || null;
|
|
344
475
|
const metadataUnchanged = old?.url === request.url &&
|
|
@@ -373,6 +504,7 @@ export class WorkspaceManager {
|
|
|
373
504
|
});
|
|
374
505
|
}
|
|
375
506
|
async pullAsset(info, assetId) {
|
|
507
|
+
await this.#ensureSettingsLoaded();
|
|
376
508
|
if (!info.projectId)
|
|
377
509
|
throw new Error("The selected target has no project metadata.");
|
|
378
510
|
const record = this.#records.get(info.projectId);
|
|
@@ -383,10 +515,41 @@ export class WorkspaceManager {
|
|
|
383
515
|
throw new Error(`Asset ${assetId} is not present in the workspace index.`);
|
|
384
516
|
if (!entry.localPath)
|
|
385
517
|
throw new Error(`Asset ${assetId} has no downloadable file.`);
|
|
386
|
-
|
|
387
|
-
|
|
518
|
+
let result;
|
|
519
|
+
if (DATA_JSON_TYPES.has(entry.type)) {
|
|
520
|
+
const remoteAsset = record.remoteAssetsCache.get(entry.id);
|
|
521
|
+
if (!remoteAsset) {
|
|
522
|
+
await this.#enqueueSync(record, { fullSnapshot: true, force: false });
|
|
523
|
+
}
|
|
524
|
+
const cachedAsset = record.remoteAssetsCache.get(entry.id);
|
|
525
|
+
const projection = buildAssetProjection({
|
|
526
|
+
id: entry.id,
|
|
527
|
+
name: entry.name,
|
|
528
|
+
type: entry.type,
|
|
529
|
+
preload: cachedAsset?.preload ?? entry.preload,
|
|
530
|
+
tags: cachedAsset?.tags ?? entry.tags,
|
|
531
|
+
data: cachedAsset?.data ?? {},
|
|
532
|
+
role: entry.role,
|
|
533
|
+
sourceAssetId: entry.sourceAssetId,
|
|
534
|
+
writable: entry.writable,
|
|
535
|
+
});
|
|
536
|
+
const bytes = Buffer.from(projection.text, "utf8");
|
|
537
|
+
const hash = hashContent(bytes);
|
|
538
|
+
const path = await this.#writeManagedAssetFile(record, entry, bytes, hash);
|
|
539
|
+
await this.#saveAssetBaseline(record, entry.id, projection.doc);
|
|
540
|
+
entry.remoteFileHash = hash;
|
|
541
|
+
entry.remoteFileSize = bytes.byteLength;
|
|
542
|
+
entry.lastSyncedHash = hash;
|
|
543
|
+
entry.status = "synced";
|
|
544
|
+
delete entry.error;
|
|
545
|
+
result = { path, size: bytes.byteLength, hash };
|
|
546
|
+
}
|
|
547
|
+
else if (TEXT_FILE_TYPES.has(entry.type) && entry.writable) {
|
|
548
|
+
result = await this.#downloadTextAsset(record, entry);
|
|
549
|
+
}
|
|
550
|
+
else {
|
|
551
|
+
result = await this.#downloadAsset(record, entry);
|
|
388
552
|
}
|
|
389
|
-
const result = await this.#downloadAsset(record, entry);
|
|
390
553
|
await this.#persist(record);
|
|
391
554
|
return {
|
|
392
555
|
assetId,
|
|
@@ -405,15 +568,19 @@ export class WorkspaceManager {
|
|
|
405
568
|
throw new Error(`Workspace project directory cannot be a symbolic link: ${directory}`);
|
|
406
569
|
}
|
|
407
570
|
const assetsDirectory = join(directory, "assets");
|
|
571
|
+
const scenesDirectory = join(directory, "scenes");
|
|
408
572
|
const tmpDirectory = join(directory, "tmp");
|
|
409
573
|
const objectsDirectory = join(directory, ".pcbridge", "objects");
|
|
574
|
+
const baselinesDirectory = join(directory, BASELINES_DIR);
|
|
410
575
|
await mkdir(assetsDirectory, { recursive: true });
|
|
411
576
|
await mkdir(join(tmpDirectory, "scripts"), { recursive: true });
|
|
412
577
|
await mkdir(join(tmpDirectory, "captures"), { recursive: true });
|
|
413
578
|
await mkdir(join(tmpDirectory, "conflicts"), { recursive: true });
|
|
414
579
|
await mkdir(join(tmpDirectory, "trash", "remote"), { recursive: true });
|
|
580
|
+
await mkdir(join(tmpDirectory, "trash", "local"), { recursive: true });
|
|
415
581
|
await mkdir(join(directory, ".pcbridge"), { recursive: true });
|
|
416
582
|
await mkdir(objectsDirectory, { recursive: true });
|
|
583
|
+
await mkdir(baselinesDirectory, { recursive: true });
|
|
417
584
|
const manifest = await readJson(join(directory, PROJECT_FILE));
|
|
418
585
|
const syncState = await readJson(join(directory, SYNC_STATE_FILE));
|
|
419
586
|
const legacyPrimaryPath = join(directory, LEGACY_INDEX_FILE);
|
|
@@ -433,8 +600,10 @@ export class WorkspaceManager {
|
|
|
433
600
|
branchName: info.branchName || null,
|
|
434
601
|
directory,
|
|
435
602
|
assetsDirectory,
|
|
603
|
+
scenesDirectory,
|
|
436
604
|
tmpDirectory,
|
|
437
605
|
objectsDirectory,
|
|
606
|
+
baselinesDirectory,
|
|
438
607
|
targetId: info.id,
|
|
439
608
|
targetInfo: info,
|
|
440
609
|
connected: true,
|
|
@@ -453,64 +622,181 @@ export class WorkspaceManager {
|
|
|
453
622
|
pendingShrinkCount: 0,
|
|
454
623
|
legacyIndexPath: legacyPrimary?.schemaVersion === 1 ? legacyPrimaryPath : null,
|
|
455
624
|
index,
|
|
456
|
-
|
|
457
|
-
|
|
625
|
+
scenes: syncState?.scenes ? { ...syncState.scenes } : {},
|
|
626
|
+
remoteAssetsCache: new Map(),
|
|
627
|
+
activeSceneMemory: null,
|
|
628
|
+
lastSavedSyncStateComparable: null,
|
|
629
|
+
recentSelfWrites: new Map(),
|
|
630
|
+
drainPromise: null,
|
|
631
|
+
dirtyFullSnapshot: false,
|
|
632
|
+
dirtyForce: false,
|
|
633
|
+
dirtyLocalAssetPaths: new Set(),
|
|
634
|
+
dirtyLocalScenePaths: new Set(),
|
|
635
|
+
dirtyRemoteDeltas: [],
|
|
458
636
|
};
|
|
459
637
|
this.#records.set(record.projectId, record);
|
|
460
638
|
return record;
|
|
461
639
|
}
|
|
640
|
+
#pruneSelfWrites(record) {
|
|
641
|
+
const now = Date.now();
|
|
642
|
+
for (const [path, fp] of record.recentSelfWrites) {
|
|
643
|
+
if (fp.expiresAt <= now)
|
|
644
|
+
record.recentSelfWrites.delete(path);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
#markSelfDeleted(record, absPath) {
|
|
648
|
+
record.recentSelfWrites.set(absPath, {
|
|
649
|
+
size: 0,
|
|
650
|
+
mtimeMs: 0,
|
|
651
|
+
hash: "",
|
|
652
|
+
deleted: true,
|
|
653
|
+
expiresAt: Date.now() + SELF_WRITE_TTL_MS,
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
async #isSelfWriteEcho(record, absPath) {
|
|
657
|
+
this.#pruneSelfWrites(record);
|
|
658
|
+
const fp = record.recentSelfWrites.get(absPath);
|
|
659
|
+
if (!fp)
|
|
660
|
+
return false;
|
|
661
|
+
if (fp.deleted)
|
|
662
|
+
return !existsSync(absPath);
|
|
663
|
+
if (!existsSync(absPath))
|
|
664
|
+
return false;
|
|
665
|
+
try {
|
|
666
|
+
const info = await stat(absPath);
|
|
667
|
+
if (info.size === fp.size && hashContent(await readFile(absPath)) === fp.hash) {
|
|
668
|
+
record.recentSelfWrites.set(absPath, {
|
|
669
|
+
...fp,
|
|
670
|
+
mtimeMs: info.mtimeMs,
|
|
671
|
+
});
|
|
672
|
+
return true;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
catch {
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
return false;
|
|
679
|
+
}
|
|
462
680
|
#ensureWatcher(record) {
|
|
463
681
|
if (this.#watchers.has(record.projectId))
|
|
464
682
|
return;
|
|
465
683
|
const watchers = new Set();
|
|
466
684
|
this.#watchers.set(record.projectId, watchers);
|
|
467
|
-
const
|
|
468
|
-
if (!filename)
|
|
469
|
-
return;
|
|
470
|
-
const relativeName = toPosixPath(String(filename));
|
|
471
|
-
if (relativeName.startsWith(".pcbridge/") || relativeName.startsWith("tmp/") || relativeName.includes("/tmp/"))
|
|
472
|
-
return;
|
|
685
|
+
const scheduleFlush = () => {
|
|
473
686
|
const existing = this.#watchTimers.get(record.projectId);
|
|
474
687
|
if (existing)
|
|
475
688
|
clearTimeout(existing);
|
|
476
689
|
const timer = setTimeout(() => {
|
|
477
690
|
this.#watchTimers.delete(record.projectId);
|
|
478
691
|
if (record.connected)
|
|
479
|
-
void this.#
|
|
692
|
+
void this.#drainQueue(record);
|
|
480
693
|
}, this.#localChangeDebounceMs);
|
|
481
694
|
timer.unref();
|
|
482
695
|
this.#watchTimers.set(record.projectId, timer);
|
|
483
696
|
};
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
697
|
+
const onAssetEvent = (filename) => {
|
|
698
|
+
if (!filename)
|
|
699
|
+
return;
|
|
700
|
+
const relativeName = toPosixPath(String(filename));
|
|
701
|
+
if (!relativeName ||
|
|
702
|
+
basename(relativeName).startsWith(".") ||
|
|
703
|
+
relativeName.startsWith(".pcbridge/") ||
|
|
704
|
+
relativeName.startsWith("tmp/") ||
|
|
705
|
+
relativeName.includes("/tmp/")) {
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
record.dirtyLocalAssetPaths.add(relativeName);
|
|
709
|
+
scheduleFlush();
|
|
710
|
+
};
|
|
711
|
+
const onSceneEvent = (filename) => {
|
|
712
|
+
if (!filename)
|
|
713
|
+
return;
|
|
714
|
+
const relativeName = toPosixPath(String(filename));
|
|
715
|
+
if (!relativeName || basename(relativeName).startsWith(".") || !relativeName.endsWith(".scene.json")) {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
record.dirtyLocalScenePaths.add(relativeName);
|
|
719
|
+
scheduleFlush();
|
|
720
|
+
};
|
|
721
|
+
const watchTree = (targetDirectory, handler) => {
|
|
722
|
+
if (!existsSync(targetDirectory))
|
|
723
|
+
return;
|
|
724
|
+
try {
|
|
725
|
+
const watcher = watch(targetDirectory, { recursive: true }, (_event, filename) => {
|
|
726
|
+
handler(filename);
|
|
727
|
+
});
|
|
728
|
+
watcher.on("error", (error) => {
|
|
729
|
+
record.lastWarning = `Local workspace watcher stopped: ${String(error)}`;
|
|
730
|
+
});
|
|
731
|
+
watchers.add(watcher);
|
|
732
|
+
}
|
|
733
|
+
catch (error) {
|
|
734
|
+
const attach = async (directory, prefix = "") => {
|
|
735
|
+
let watcher;
|
|
736
|
+
try {
|
|
737
|
+
watcher = watch(directory, (_event, filename) => {
|
|
738
|
+
if (!filename)
|
|
739
|
+
return;
|
|
740
|
+
handler(prefix ? `${prefix}/${String(filename)}` : filename);
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
catch {
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
watchers.add(watcher);
|
|
747
|
+
let children;
|
|
748
|
+
try {
|
|
749
|
+
children = await readdir(directory, { withFileTypes: true });
|
|
750
|
+
}
|
|
751
|
+
catch {
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
await Promise.all(children
|
|
755
|
+
.filter((child) => child.isDirectory())
|
|
756
|
+
.map((child) => attach(join(directory, child.name), prefix ? `${prefix}/${child.name}` : child.name)));
|
|
757
|
+
};
|
|
758
|
+
void attach(targetDirectory);
|
|
759
|
+
record.lastWarning = `Recursive local watcher unavailable; using directory watchers (${String(error)})`;
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
watchTree(record.assetsDirectory, onAssetEvent);
|
|
763
|
+
if (existsSync(record.scenesDirectory)) {
|
|
764
|
+
record._scenesWatched = true;
|
|
765
|
+
watchTree(record.scenesDirectory, onSceneEvent);
|
|
490
766
|
}
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
767
|
+
}
|
|
768
|
+
#ensureScenesWatcher(record) {
|
|
769
|
+
const watchers = this.#watchers.get(record.projectId);
|
|
770
|
+
if (!watchers || !existsSync(record.scenesDirectory))
|
|
771
|
+
return;
|
|
772
|
+
if (record._scenesWatched)
|
|
773
|
+
return;
|
|
774
|
+
record._scenesWatched = true;
|
|
775
|
+
try {
|
|
776
|
+
const watcher = watch(record.scenesDirectory, { recursive: true }, (_event, filename) => {
|
|
777
|
+
if (!filename)
|
|
500
778
|
return;
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
let children;
|
|
504
|
-
try {
|
|
505
|
-
children = await readdir(directory, { withFileTypes: true });
|
|
506
|
-
}
|
|
507
|
-
catch {
|
|
779
|
+
const relativeName = toPosixPath(String(filename));
|
|
780
|
+
if (!relativeName || basename(relativeName).startsWith(".") || !relativeName.endsWith(".scene.json")) {
|
|
508
781
|
return;
|
|
509
782
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
783
|
+
record.dirtyLocalScenePaths.add(relativeName);
|
|
784
|
+
const existing = this.#watchTimers.get(record.projectId);
|
|
785
|
+
if (existing)
|
|
786
|
+
clearTimeout(existing);
|
|
787
|
+
const timer = setTimeout(() => {
|
|
788
|
+
this.#watchTimers.delete(record.projectId);
|
|
789
|
+
if (record.connected)
|
|
790
|
+
void this.#drainQueue(record);
|
|
791
|
+
}, this.#localChangeDebounceMs);
|
|
792
|
+
timer.unref();
|
|
793
|
+
this.#watchTimers.set(record.projectId, timer);
|
|
794
|
+
});
|
|
795
|
+
watcher.on("error", () => undefined);
|
|
796
|
+
watchers.add(watcher);
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
// Directory-level fallback is handled on manual sync if recursive watch is unavailable.
|
|
514
800
|
}
|
|
515
801
|
}
|
|
516
802
|
async #findProjectDirectory(projectId) {
|
|
@@ -545,6 +831,61 @@ export class WorkspaceManager {
|
|
|
545
831
|
}
|
|
546
832
|
return path;
|
|
547
833
|
}
|
|
834
|
+
#scenePath(record, localPath) {
|
|
835
|
+
const path = this.#withinRoot(join(record.scenesDirectory, localPath));
|
|
836
|
+
if (path !== record.scenesDirectory && !path.startsWith(`${record.scenesDirectory}${sep}`)) {
|
|
837
|
+
throw new Error(`Scene path escapes project scenes directory: ${localPath}`);
|
|
838
|
+
}
|
|
839
|
+
return path;
|
|
840
|
+
}
|
|
841
|
+
#assetBaselinePath(record, assetId) {
|
|
842
|
+
return this.#withinRoot(join(record.baselinesDirectory, `asset-${safeAssetName(assetId, "asset")}.json`));
|
|
843
|
+
}
|
|
844
|
+
#sceneBaselinePath(record, sceneId) {
|
|
845
|
+
return this.#withinRoot(join(record.baselinesDirectory, `scene-${safeAssetName(sceneId, "scene")}.json`));
|
|
846
|
+
}
|
|
847
|
+
async #loadAssetBaseline(record, assetId) {
|
|
848
|
+
return readJson(this.#assetBaselinePath(record, assetId));
|
|
849
|
+
}
|
|
850
|
+
async #saveAssetBaseline(record, assetId, doc) {
|
|
851
|
+
await atomicWrite(this.#assetBaselinePath(record, assetId), `${JSON.stringify(doc, null, 2)}\n`);
|
|
852
|
+
}
|
|
853
|
+
async #deleteAssetBaseline(record, assetId) {
|
|
854
|
+
await rm(this.#assetBaselinePath(record, assetId), { force: true }).catch(() => undefined);
|
|
855
|
+
}
|
|
856
|
+
async #loadSceneBaseline(record, sceneId) {
|
|
857
|
+
return readJson(this.#sceneBaselinePath(record, sceneId));
|
|
858
|
+
}
|
|
859
|
+
async #saveSceneBaseline(record, sceneId, doc) {
|
|
860
|
+
await atomicWrite(this.#sceneBaselinePath(record, sceneId), `${JSON.stringify(doc, null, 2)}\n`);
|
|
861
|
+
}
|
|
862
|
+
async #deleteSceneBaseline(record, sceneId) {
|
|
863
|
+
await rm(this.#sceneBaselinePath(record, sceneId), { force: true }).catch(() => undefined);
|
|
864
|
+
}
|
|
865
|
+
#syncTierForAsset(entry, estimatedBytes) {
|
|
866
|
+
if (entry.type === "folder")
|
|
867
|
+
return "folder";
|
|
868
|
+
const eagerMaxBytes = eagerMaxBytesFromMb(this.#eagerMaxMb);
|
|
869
|
+
if (DATA_JSON_TYPES.has(entry.type) && !entry.filename) {
|
|
870
|
+
if (!entry.writable)
|
|
871
|
+
return "derived-json";
|
|
872
|
+
const size = estimatedBytes ?? entry.remoteFileSize ?? 0;
|
|
873
|
+
return size <= eagerMaxBytes ? "eager-json" : "lazy-json";
|
|
874
|
+
}
|
|
875
|
+
if (entry.role === "derived")
|
|
876
|
+
return "derived-file";
|
|
877
|
+
if (TEXT_FILE_TYPES.has(entry.type)) {
|
|
878
|
+
const size = estimatedBytes ?? entry.remoteFileSize ?? 0;
|
|
879
|
+
return size <= eagerMaxBytes ? "eager-text" : "lazy-text";
|
|
880
|
+
}
|
|
881
|
+
return "lazy-binary";
|
|
882
|
+
}
|
|
883
|
+
#isTier1EagerWritable(entry) {
|
|
884
|
+
if (!entry.writable)
|
|
885
|
+
return false;
|
|
886
|
+
const tier = this.#syncTierForAsset(entry);
|
|
887
|
+
return tier === "eager-text" || tier === "eager-json";
|
|
888
|
+
}
|
|
548
889
|
#indexFromManifest(manifest, syncState, info) {
|
|
549
890
|
const entries = {};
|
|
550
891
|
for (const [id, rawAsset] of Object.entries(manifest.assets || {})) {
|
|
@@ -562,6 +903,7 @@ export class WorkspaceManager {
|
|
|
562
903
|
const advertisedHash = asset.remoteFile?.hash.advertised || null;
|
|
563
904
|
const observedSize = asset.remoteFile?.size.observed ?? null;
|
|
564
905
|
const observedHash = asset.remoteFile?.hash.observed || null;
|
|
906
|
+
const stateExtra = syncState?.entries?.[id];
|
|
565
907
|
const resources = Object.fromEntries((asset.local?.resources || []).flatMap((resource) => {
|
|
566
908
|
const resourcePath = manifestLocalPath(resource.path);
|
|
567
909
|
if (!resourcePath)
|
|
@@ -583,7 +925,12 @@ export class WorkspaceManager {
|
|
|
583
925
|
type: asset.type,
|
|
584
926
|
role: asset.origin.role,
|
|
585
927
|
sourceAssetId: asset.origin.sourceAssetId,
|
|
586
|
-
writable: asset.
|
|
928
|
+
writable: (DATA_JSON_TYPES.has(asset.type) && !asset.remoteFile?.filename)
|
|
929
|
+
? true
|
|
930
|
+
: (asset.local?.writable ?? asset.origin.role !== "derived"),
|
|
931
|
+
preload: stateExtra?.preload,
|
|
932
|
+
tags: stateExtra?.tags,
|
|
933
|
+
meta: asset.meta ?? stateExtra?.meta ?? null,
|
|
587
934
|
remotePath: asset.folder ? asset.folder.split("/").filter(Boolean) : [],
|
|
588
935
|
localFolderPath: asset.type === "folder"
|
|
589
936
|
? projectionPath?.split(sep).filter(Boolean) || []
|
|
@@ -598,10 +945,12 @@ export class WorkspaceManager {
|
|
|
598
945
|
remoteFileHash: asset.remoteFile?.hash.effective || observedHash || advertisedHash,
|
|
599
946
|
localHash: asset.local?.hash.current || null,
|
|
600
947
|
lastSyncedHash: asset.local?.hash.base || null,
|
|
601
|
-
legacyLastSyncedSha256:
|
|
602
|
-
pendingRemoteHash:
|
|
603
|
-
localFileSize:
|
|
604
|
-
localMtimeMs:
|
|
948
|
+
legacyLastSyncedSha256: stateExtra?.legacyLastSyncedSha256,
|
|
949
|
+
pendingRemoteHash: stateExtra?.pendingRemoteHash,
|
|
950
|
+
localFileSize: stateExtra?.localFileSize ?? asset.local?.size ?? undefined,
|
|
951
|
+
localMtimeMs: stateExtra?.localMtimeMs,
|
|
952
|
+
localIno: stateExtra?.localIno,
|
|
953
|
+
localDev: stateExtra?.localDev,
|
|
605
954
|
resources,
|
|
606
955
|
downloaded: present,
|
|
607
956
|
status: state,
|
|
@@ -615,6 +964,7 @@ export class WorkspaceManager {
|
|
|
615
964
|
const state = asset.state === "remote-only" ? "indexed" : asset.state;
|
|
616
965
|
const remoteFileSize = asset.file?.size ?? null;
|
|
617
966
|
const remoteFileHash = asset.file?.hash.remote || null;
|
|
967
|
+
const stateExtra = syncState?.entries?.[id];
|
|
618
968
|
entries[id] = {
|
|
619
969
|
id,
|
|
620
970
|
name: asset.name,
|
|
@@ -634,10 +984,12 @@ export class WorkspaceManager {
|
|
|
634
984
|
remoteFileHash,
|
|
635
985
|
localHash: asset.file?.hash.local || null,
|
|
636
986
|
lastSyncedHash: asset.file?.hash.base || null,
|
|
637
|
-
legacyLastSyncedSha256:
|
|
638
|
-
pendingRemoteHash:
|
|
639
|
-
localFileSize:
|
|
640
|
-
localMtimeMs:
|
|
987
|
+
legacyLastSyncedSha256: stateExtra?.legacyLastSyncedSha256,
|
|
988
|
+
pendingRemoteHash: stateExtra?.pendingRemoteHash,
|
|
989
|
+
localFileSize: stateExtra?.localFileSize,
|
|
990
|
+
localMtimeMs: stateExtra?.localMtimeMs,
|
|
991
|
+
localIno: stateExtra?.localIno,
|
|
992
|
+
localDev: stateExtra?.localDev,
|
|
641
993
|
resources: {},
|
|
642
994
|
downloaded: present,
|
|
643
995
|
status: state,
|
|
@@ -731,6 +1083,9 @@ export class WorkspaceManager {
|
|
|
731
1083
|
},
|
|
732
1084
|
};
|
|
733
1085
|
});
|
|
1086
|
+
const observedHashStr = typeof entry.observedRemoteFileHash === "string"
|
|
1087
|
+
? entry.observedRemoteFileHash
|
|
1088
|
+
: null;
|
|
734
1089
|
const asset = {
|
|
735
1090
|
id: entry.id,
|
|
736
1091
|
name: entry.name,
|
|
@@ -743,6 +1098,7 @@ export class WorkspaceManager {
|
|
|
743
1098
|
role: entry.role,
|
|
744
1099
|
sourceAssetId: entry.sourceAssetId,
|
|
745
1100
|
},
|
|
1101
|
+
...(entry.meta && Object.keys(entry.meta).length ? { meta: entry.meta } : {}),
|
|
746
1102
|
remoteFile: entry.filename
|
|
747
1103
|
? {
|
|
748
1104
|
filename: entry.filename,
|
|
@@ -754,7 +1110,7 @@ export class WorkspaceManager {
|
|
|
754
1110
|
hash: {
|
|
755
1111
|
algorithm: "md5",
|
|
756
1112
|
advertised: entry.advertisedRemoteFileHash,
|
|
757
|
-
observed:
|
|
1113
|
+
observed: observedHashStr,
|
|
758
1114
|
effective: entry.remoteFileHash,
|
|
759
1115
|
},
|
|
760
1116
|
}
|
|
@@ -784,18 +1140,41 @@ export class WorkspaceManager {
|
|
|
784
1140
|
}
|
|
785
1141
|
return assets;
|
|
786
1142
|
}
|
|
787
|
-
|
|
788
|
-
const
|
|
789
|
-
|
|
1143
|
+
#manifestScenes(record, existingScenes) {
|
|
1144
|
+
const sceneEntries = Object.values(record.scenes);
|
|
1145
|
+
if (sceneEntries.length) {
|
|
1146
|
+
return sceneEntries
|
|
1147
|
+
.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }))
|
|
1148
|
+
.map((scene) => {
|
|
1149
|
+
const item = {
|
|
1150
|
+
id: scene.id,
|
|
1151
|
+
name: scene.name,
|
|
1152
|
+
active: scene.active,
|
|
1153
|
+
writable: scene.writable,
|
|
1154
|
+
path: `scenes/${toPosixPath(scene.localPath)}`,
|
|
1155
|
+
entityCount: scene.entityCount,
|
|
1156
|
+
state: scene.status,
|
|
1157
|
+
};
|
|
1158
|
+
if (scene.error)
|
|
1159
|
+
item.error = scene.error;
|
|
1160
|
+
return item;
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
const scenes = Array.isArray(existingScenes) ? existingScenes.map((s) => ({ ...s })) : [];
|
|
790
1164
|
const info = record.targetInfo;
|
|
791
|
-
const scenes = Array.isArray(existing?.scenes) ? [...existing.scenes] : [];
|
|
792
1165
|
if (info.sceneId) {
|
|
793
|
-
const
|
|
794
|
-
if (
|
|
795
|
-
|
|
1166
|
+
const found = scenes.find((item) => item.id === info.sceneId);
|
|
1167
|
+
if (found)
|
|
1168
|
+
found.name = info.sceneName || found.name;
|
|
796
1169
|
else
|
|
797
1170
|
scenes.push({ id: info.sceneId, name: info.sceneName || null });
|
|
798
1171
|
}
|
|
1172
|
+
return scenes;
|
|
1173
|
+
}
|
|
1174
|
+
async #writeManifest(record) {
|
|
1175
|
+
const path = join(record.directory, PROJECT_FILE);
|
|
1176
|
+
const existing = await readJson(path);
|
|
1177
|
+
const scenes = this.#manifestScenes(record, existing?.scenes);
|
|
799
1178
|
const now = new Date().toISOString();
|
|
800
1179
|
const existingSettings = existing?.settings && typeof existing.settings === "object"
|
|
801
1180
|
? existing.settings
|
|
@@ -830,6 +1209,7 @@ export class WorkspaceManager {
|
|
|
830
1209
|
deletePolicy: "quarantine",
|
|
831
1210
|
...existingSync,
|
|
832
1211
|
contentMode: "all",
|
|
1212
|
+
eagerMaxMb: this.#eagerMaxMb,
|
|
833
1213
|
},
|
|
834
1214
|
},
|
|
835
1215
|
assets: this.#manifestAssets(record),
|
|
@@ -844,18 +1224,36 @@ export class WorkspaceManager {
|
|
|
844
1224
|
await atomicWrite(path, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
845
1225
|
}
|
|
846
1226
|
async #writeSyncState(record) {
|
|
847
|
-
record.index.updatedAt = new Date().toISOString();
|
|
848
1227
|
const entries = Object.fromEntries(Object.values(record.index.entries)
|
|
849
1228
|
.filter((entry) => entry.legacyLastSyncedSha256 ||
|
|
850
1229
|
entry.pendingRemoteHash ||
|
|
851
1230
|
entry.localFileSize !== undefined ||
|
|
852
|
-
entry.localMtimeMs !== undefined
|
|
1231
|
+
entry.localMtimeMs !== undefined ||
|
|
1232
|
+
entry.localIno !== undefined ||
|
|
1233
|
+
entry.preload !== undefined ||
|
|
1234
|
+
(entry.tags && entry.tags.length) ||
|
|
1235
|
+
entry.meta)
|
|
853
1236
|
.map((entry) => [entry.id, {
|
|
854
1237
|
legacyLastSyncedSha256: entry.legacyLastSyncedSha256,
|
|
855
1238
|
pendingRemoteHash: entry.pendingRemoteHash,
|
|
856
1239
|
localFileSize: entry.localFileSize,
|
|
857
1240
|
localMtimeMs: entry.localMtimeMs,
|
|
1241
|
+
localIno: entry.localIno,
|
|
1242
|
+
localDev: entry.localDev,
|
|
1243
|
+
preload: entry.preload,
|
|
1244
|
+
tags: entry.tags,
|
|
1245
|
+
meta: entry.meta,
|
|
858
1246
|
}]));
|
|
1247
|
+
const comparable = JSON.stringify({
|
|
1248
|
+
projectId: record.projectId,
|
|
1249
|
+
branchId: record.branchId,
|
|
1250
|
+
entries,
|
|
1251
|
+
scenes: record.scenes,
|
|
1252
|
+
});
|
|
1253
|
+
if (record.lastSavedSyncStateComparable === comparable)
|
|
1254
|
+
return;
|
|
1255
|
+
record.lastSavedSyncStateComparable = comparable;
|
|
1256
|
+
record.index.updatedAt = new Date().toISOString();
|
|
859
1257
|
await atomicWrite(join(record.directory, SYNC_STATE_FILE), `${JSON.stringify({
|
|
860
1258
|
schemaVersion: 1,
|
|
861
1259
|
projectId: record.projectId,
|
|
@@ -863,6 +1261,7 @@ export class WorkspaceManager {
|
|
|
863
1261
|
updatedAt: record.index.updatedAt,
|
|
864
1262
|
lastSuccessfulSyncAt: record.lastSyncedAt,
|
|
865
1263
|
entries,
|
|
1264
|
+
...(Object.keys(record.scenes).length ? { scenes: record.scenes } : {}),
|
|
866
1265
|
}, null, 2)}\n`);
|
|
867
1266
|
}
|
|
868
1267
|
async #persist(record) {
|
|
@@ -876,15 +1275,81 @@ export class WorkspaceManager {
|
|
|
876
1275
|
record.legacyIndexPath = null;
|
|
877
1276
|
}
|
|
878
1277
|
}
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
record.
|
|
883
|
-
|
|
1278
|
+
#recomputeOverallState(record) {
|
|
1279
|
+
const entries = Object.values(record.index.entries);
|
|
1280
|
+
const scenes = Object.values(record.scenes);
|
|
1281
|
+
record.state = entries.some((entry) => entry.status === "conflict") || scenes.some((s) => s.status === "conflict")
|
|
1282
|
+
? "conflict"
|
|
1283
|
+
: entries.some((entry) => entry.status === "local-change")
|
|
1284
|
+
? "local-change"
|
|
1285
|
+
: entries.some((entry) => entry.status === "remote-change")
|
|
1286
|
+
? "remote-change"
|
|
1287
|
+
: entries.some((entry) => entry.status === "error") || scenes.some((s) => s.status === "error")
|
|
1288
|
+
? "error"
|
|
1289
|
+
: "synced";
|
|
1290
|
+
}
|
|
1291
|
+
#hasQueuedWork(record) {
|
|
1292
|
+
return (record.dirtyFullSnapshot ||
|
|
1293
|
+
record.dirtyRemoteDeltas.length > 0 ||
|
|
1294
|
+
record.dirtyLocalAssetPaths.size > 0 ||
|
|
1295
|
+
record.dirtyLocalScenePaths.size > 0);
|
|
1296
|
+
}
|
|
1297
|
+
async #enqueueSync(record, options) {
|
|
1298
|
+
if (options.fullSnapshot)
|
|
1299
|
+
record.dirtyFullSnapshot = true;
|
|
1300
|
+
if (options.force)
|
|
1301
|
+
record.dirtyForce = true;
|
|
1302
|
+
await this.#drainQueue(record);
|
|
1303
|
+
}
|
|
1304
|
+
async #drainQueue(record) {
|
|
1305
|
+
if (record.drainPromise) {
|
|
1306
|
+
await record.drainPromise;
|
|
1307
|
+
if (this.#hasQueuedWork(record)) {
|
|
1308
|
+
await this.#drainQueue(record);
|
|
1309
|
+
}
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
record.drainPromise = (async () => {
|
|
1313
|
+
while (this.#hasQueuedWork(record)) {
|
|
1314
|
+
if (record.dirtyFullSnapshot) {
|
|
1315
|
+
const force = record.dirtyForce;
|
|
1316
|
+
record.dirtyFullSnapshot = false;
|
|
1317
|
+
record.dirtyForce = false;
|
|
1318
|
+
record.dirtyRemoteDeltas.length = 0;
|
|
1319
|
+
record.dirtyLocalAssetPaths.clear();
|
|
1320
|
+
record.dirtyLocalScenePaths.clear();
|
|
1321
|
+
const pendingTimer = this.#watchTimers.get(record.projectId);
|
|
1322
|
+
if (pendingTimer) {
|
|
1323
|
+
clearTimeout(pendingTimer);
|
|
1324
|
+
this.#watchTimers.delete(record.projectId);
|
|
1325
|
+
}
|
|
1326
|
+
await this.#performFullSync(record, force);
|
|
1327
|
+
continue;
|
|
1328
|
+
}
|
|
1329
|
+
if (record.dirtyRemoteDeltas.length > 0) {
|
|
1330
|
+
const batch = record.dirtyRemoteDeltas.splice(0, record.dirtyRemoteDeltas.length);
|
|
1331
|
+
await this.#performRemoteDeltas(record, batch);
|
|
1332
|
+
continue;
|
|
1333
|
+
}
|
|
1334
|
+
if (record.dirtyLocalScenePaths.size > 0) {
|
|
1335
|
+
const paths = [...record.dirtyLocalScenePaths];
|
|
1336
|
+
record.dirtyLocalScenePaths.clear();
|
|
1337
|
+
await this.#performLocalSceneChanges(record, paths);
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
if (record.dirtyLocalAssetPaths.size > 0) {
|
|
1341
|
+
const paths = [...record.dirtyLocalAssetPaths];
|
|
1342
|
+
record.dirtyLocalAssetPaths.clear();
|
|
1343
|
+
await this.#performLocalAssetChanges(record, paths);
|
|
1344
|
+
continue;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
})().finally(() => {
|
|
1348
|
+
record.drainPromise = null;
|
|
884
1349
|
});
|
|
885
|
-
return record.
|
|
1350
|
+
return record.drainPromise;
|
|
886
1351
|
}
|
|
887
|
-
async #
|
|
1352
|
+
async #performFullSync(record, force) {
|
|
888
1353
|
const previousState = record.state === "syncing" ? "initializing" : record.state;
|
|
889
1354
|
record.state = "syncing";
|
|
890
1355
|
record.lastError = null;
|
|
@@ -901,26 +1366,30 @@ export class WorkspaceManager {
|
|
|
901
1366
|
record.state = previousState;
|
|
902
1367
|
return;
|
|
903
1368
|
}
|
|
1369
|
+
for (const asset of assets) {
|
|
1370
|
+
record.remoteAssetsCache.set(String(asset.id), asset);
|
|
1371
|
+
}
|
|
904
1372
|
record.syncPhase = "reconciling";
|
|
905
1373
|
record.syncProgress = {
|
|
906
1374
|
completed: 0,
|
|
907
|
-
total: assets.filter((asset) => asset.type !== "folder" && asset.file).length,
|
|
1375
|
+
total: assets.filter((asset) => asset.type !== "folder" && (asset.file || DATA_JSON_TYPES.has(asset.type))).length,
|
|
908
1376
|
assetId: null,
|
|
909
1377
|
action: "comparing",
|
|
910
1378
|
};
|
|
911
|
-
await this.#
|
|
1379
|
+
const processedAssets = await this.#preProcessLocalRenamesAndDeletes(record, assets);
|
|
1380
|
+
await this.#applySnapshot(record, processedAssets, force);
|
|
912
1381
|
await this.#uploadUnindexedFiles(record);
|
|
1382
|
+
const activeScene = data.activeScene && typeof data.activeScene === "object" && !Array.isArray(data.activeScene)
|
|
1383
|
+
? data.activeScene
|
|
1384
|
+
: null;
|
|
1385
|
+
const sceneList = Array.isArray(data.scenes)
|
|
1386
|
+
? data.scenes
|
|
1387
|
+
: null;
|
|
1388
|
+
if (activeScene || sceneList) {
|
|
1389
|
+
await this.#reconcileAllScenes(record, activeScene, sceneList);
|
|
1390
|
+
}
|
|
913
1391
|
record.lastSyncedAt = new Date().toISOString();
|
|
914
|
-
|
|
915
|
-
record.state = entries.some((entry) => entry.status === "conflict")
|
|
916
|
-
? "conflict"
|
|
917
|
-
: entries.some((entry) => entry.status === "local-change")
|
|
918
|
-
? "local-change"
|
|
919
|
-
: entries.some((entry) => entry.status === "remote-change")
|
|
920
|
-
? "remote-change"
|
|
921
|
-
: entries.some((entry) => entry.status === "error")
|
|
922
|
-
? "error"
|
|
923
|
-
: "synced";
|
|
1392
|
+
this.#recomputeOverallState(record);
|
|
924
1393
|
record.syncPhase = "persisting";
|
|
925
1394
|
await this.#persist(record);
|
|
926
1395
|
}
|
|
@@ -934,124 +1403,571 @@ export class WorkspaceManager {
|
|
|
934
1403
|
record.syncProgress = null;
|
|
935
1404
|
}
|
|
936
1405
|
}
|
|
937
|
-
async #
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
continue;
|
|
963
|
-
const relativePath = relativeDirectory ? join(relativeDirectory, child.name) : child.name;
|
|
964
|
-
const path = join(directory, child.name);
|
|
965
|
-
if (child.isDirectory())
|
|
966
|
-
await visit(path, relativePath);
|
|
967
|
-
else if (child.isFile() && !known.has(toPosixPath(relativePath)))
|
|
968
|
-
files.push(relativePath);
|
|
1406
|
+
async #performRemoteDeltas(record, deltas) {
|
|
1407
|
+
try {
|
|
1408
|
+
const removedIds = new Set();
|
|
1409
|
+
const upsertedById = new Map();
|
|
1410
|
+
let fullActiveScene = null;
|
|
1411
|
+
const sceneDeltas = [];
|
|
1412
|
+
for (const delta of deltas) {
|
|
1413
|
+
for (const rawId of delta.removedAssetIds || []) {
|
|
1414
|
+
const id = String(rawId);
|
|
1415
|
+
removedIds.add(id);
|
|
1416
|
+
upsertedById.delete(id);
|
|
1417
|
+
}
|
|
1418
|
+
for (const asset of delta.upsertedAssets || []) {
|
|
1419
|
+
const id = String(asset.id);
|
|
1420
|
+
removedIds.delete(id);
|
|
1421
|
+
upsertedById.set(id, asset);
|
|
1422
|
+
record.remoteAssetsCache.set(id, asset);
|
|
1423
|
+
}
|
|
1424
|
+
if (delta.activeScene) {
|
|
1425
|
+
fullActiveScene = delta.activeScene;
|
|
1426
|
+
sceneDeltas.length = 0;
|
|
1427
|
+
}
|
|
1428
|
+
else if (delta.sceneDelta) {
|
|
1429
|
+
sceneDeltas.push(delta.sceneDelta);
|
|
1430
|
+
}
|
|
969
1431
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
record.lastWarning =
|
|
987
|
-
`Ignored a moved or copied projection of derived Asset ${derived.id}; ` +
|
|
988
|
-
`the local copy was saved to ${relative(record.directory, conflictPath)}.`;
|
|
989
|
-
continue;
|
|
1432
|
+
let changed = false;
|
|
1433
|
+
if (removedIds.size > 0) {
|
|
1434
|
+
const deletionBatch = new Date().toISOString().replaceAll(":", "-");
|
|
1435
|
+
for (const id of removedIds) {
|
|
1436
|
+
record.remoteAssetsCache.delete(id);
|
|
1437
|
+
const old = record.index.entries[id];
|
|
1438
|
+
if (!old)
|
|
1439
|
+
continue;
|
|
1440
|
+
changed = true;
|
|
1441
|
+
await this.#quarantineRemoteDeletedEntry(record, id, old, deletionBatch);
|
|
1442
|
+
await this.#deleteAssetBaseline(record, id);
|
|
1443
|
+
delete record.index.entries[id];
|
|
1444
|
+
if (old.type === "folder" && old.localFolderPath.length) {
|
|
1445
|
+
await rmdir(this.#assetPath(record, join(...old.localFolderPath))).catch(() => undefined);
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
990
1448
|
}
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
const
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
record.
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1449
|
+
if (upsertedById.size > 0) {
|
|
1450
|
+
changed = true;
|
|
1451
|
+
// Rebuild lightweight asset list from memory cache + current index so folder/collision paths stay exact without any RPC.
|
|
1452
|
+
const currentAssets = [];
|
|
1453
|
+
const allKnownIds = new Set([
|
|
1454
|
+
...Object.keys(record.index.entries),
|
|
1455
|
+
...upsertedById.keys(),
|
|
1456
|
+
]);
|
|
1457
|
+
for (const id of allKnownIds) {
|
|
1458
|
+
if (removedIds.has(id))
|
|
1459
|
+
continue;
|
|
1460
|
+
const cached = upsertedById.get(id) || record.remoteAssetsCache.get(id);
|
|
1461
|
+
if (cached) {
|
|
1462
|
+
currentAssets.push(cached);
|
|
1463
|
+
}
|
|
1464
|
+
else {
|
|
1465
|
+
const existing = record.index.entries[id];
|
|
1466
|
+
if (existing) {
|
|
1467
|
+
currentAssets.push({
|
|
1468
|
+
id: existing.id,
|
|
1469
|
+
name: existing.name,
|
|
1470
|
+
type: existing.type,
|
|
1471
|
+
source: existing.role === "source",
|
|
1472
|
+
source_asset_id: existing.sourceAssetId,
|
|
1473
|
+
file: existing.filename
|
|
1474
|
+
? {
|
|
1475
|
+
filename: existing.filename,
|
|
1476
|
+
hash: existing.advertisedRemoteFileHash || undefined,
|
|
1477
|
+
size: existing.advertisedRemoteFileSize ?? undefined,
|
|
1478
|
+
}
|
|
1479
|
+
: null,
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1013
1482
|
}
|
|
1014
|
-
continue;
|
|
1015
1483
|
}
|
|
1484
|
+
await this.#applySnapshot(record, currentAssets, false, new Set(upsertedById.keys()));
|
|
1016
1485
|
}
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
base64: content.toString("base64"),
|
|
1022
|
-
}, 120000);
|
|
1023
|
-
if (!response.ok) {
|
|
1024
|
-
record.lastWarning = `Failed to upload local file ${relativePath}: ${response.error.message}`;
|
|
1025
|
-
continue;
|
|
1486
|
+
if (fullActiveScene) {
|
|
1487
|
+
changed = true;
|
|
1488
|
+
record.activeSceneMemory = structuredClone(fullActiveScene);
|
|
1489
|
+
await this.#reconcileActiveScene(record, fullActiveScene);
|
|
1026
1490
|
}
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1491
|
+
else if (sceneDeltas.length > 0) {
|
|
1492
|
+
for (const sd of sceneDeltas) {
|
|
1493
|
+
const sceneId = String(sd.sceneId);
|
|
1494
|
+
if (!record.activeSceneMemory || String(record.activeSceneMemory.id) !== sceneId) {
|
|
1495
|
+
const readResp = await this.#requestTarget(record.targetId, "bridge:readScene", { sceneId }, 30000);
|
|
1496
|
+
if (readResp.ok) {
|
|
1497
|
+
record.activeSceneMemory = asObject(readResp.data);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
if (record.activeSceneMemory && String(record.activeSceneMemory.id) === sceneId) {
|
|
1501
|
+
changed = true;
|
|
1502
|
+
if (sd.sceneName)
|
|
1503
|
+
record.activeSceneMemory.name = sd.sceneName;
|
|
1504
|
+
if (sd.settings)
|
|
1505
|
+
record.activeSceneMemory.settings = structuredClone(sd.settings);
|
|
1506
|
+
const entities = (record.activeSceneMemory.entities || {});
|
|
1507
|
+
for (const remId of sd.removedEntityIds || []) {
|
|
1508
|
+
delete entities[String(remId)];
|
|
1509
|
+
}
|
|
1510
|
+
for (const [entId, entVal] of Object.entries(sd.upsertedEntities || {})) {
|
|
1511
|
+
entities[entId] = structuredClone(entVal);
|
|
1512
|
+
}
|
|
1513
|
+
record.activeSceneMemory.entities = entities;
|
|
1514
|
+
}
|
|
1037
1515
|
}
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
const snapshot = asObject(refresh.data);
|
|
1041
|
-
const refreshedAssets = Array.isArray(snapshot.assets)
|
|
1042
|
-
? snapshot.assets
|
|
1043
|
-
: [];
|
|
1044
|
-
if (refreshedAssets.length)
|
|
1045
|
-
await this.#applySnapshot(record, refreshedAssets, false);
|
|
1516
|
+
if (record.activeSceneMemory) {
|
|
1517
|
+
await this.#reconcileActiveScene(record, record.activeSceneMemory);
|
|
1046
1518
|
}
|
|
1047
1519
|
}
|
|
1520
|
+
if (changed) {
|
|
1521
|
+
record.lastSyncedAt = new Date().toISOString();
|
|
1522
|
+
this.#recomputeOverallState(record);
|
|
1523
|
+
await this.#persist(record);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
catch (error) {
|
|
1527
|
+
record.state = "error";
|
|
1528
|
+
record.lastError = error instanceof Error ? error.message : String(error);
|
|
1048
1529
|
}
|
|
1049
1530
|
}
|
|
1050
|
-
#
|
|
1051
|
-
const
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
record
|
|
1531
|
+
async #performLocalSceneChanges(record, dirtyPaths) {
|
|
1532
|
+
const actionable = [];
|
|
1533
|
+
for (const rel of dirtyPaths) {
|
|
1534
|
+
const abs = this.#scenePath(record, rel);
|
|
1535
|
+
if (await this.#isSelfWriteEcho(record, abs))
|
|
1536
|
+
continue;
|
|
1537
|
+
actionable.push(rel);
|
|
1538
|
+
}
|
|
1539
|
+
if (!actionable.length)
|
|
1540
|
+
return;
|
|
1541
|
+
try {
|
|
1542
|
+
let changed = false;
|
|
1543
|
+
for (const rel of actionable) {
|
|
1544
|
+
const parsedName = parseSceneFilename(basename(rel));
|
|
1545
|
+
const matchedEntry = Object.values(record.scenes).find((item) => toPosixPath(item.localPath) === rel || (parsedName && item.id === parsedName.sceneId));
|
|
1546
|
+
if (!matchedEntry)
|
|
1547
|
+
continue;
|
|
1548
|
+
const abs = this.#scenePath(record, matchedEntry.localPath);
|
|
1549
|
+
if (!existsSync(abs)) {
|
|
1550
|
+
// Restore accidentally deleted scene mirror from baseline.
|
|
1551
|
+
const baseline = await this.#loadSceneBaseline(record, matchedEntry.id);
|
|
1552
|
+
if (baseline) {
|
|
1553
|
+
const restored = buildSceneProjection({
|
|
1554
|
+
id: matchedEntry.id,
|
|
1555
|
+
name: baseline.name,
|
|
1556
|
+
active: matchedEntry.active,
|
|
1557
|
+
settings: baseline.settings,
|
|
1558
|
+
entities: baseline.entities,
|
|
1559
|
+
});
|
|
1560
|
+
await this.#writeManagedSceneFile(record, matchedEntry, Buffer.from(restored.text, "utf8"), hashContent(restored.text));
|
|
1561
|
+
changed = true;
|
|
1562
|
+
}
|
|
1563
|
+
continue;
|
|
1564
|
+
}
|
|
1565
|
+
if (!matchedEntry.active || !matchedEntry.writable) {
|
|
1566
|
+
await this.#quarantineInactiveSceneEdit(record, matchedEntry, abs);
|
|
1567
|
+
changed = true;
|
|
1568
|
+
continue;
|
|
1569
|
+
}
|
|
1570
|
+
const readResp = await this.#requestTarget(record.targetId, "bridge:readScene", { sceneId: matchedEntry.id }, 30000);
|
|
1571
|
+
if (!readResp.ok)
|
|
1572
|
+
throw new Error(readResp.error.message);
|
|
1573
|
+
const liveRemote = asObject(readResp.data);
|
|
1574
|
+
record.activeSceneMemory = structuredClone(liveRemote);
|
|
1575
|
+
await this.#reconcileActiveScene(record, liveRemote);
|
|
1576
|
+
changed = true;
|
|
1577
|
+
}
|
|
1578
|
+
if (changed) {
|
|
1579
|
+
record.lastSyncedAt = new Date().toISOString();
|
|
1580
|
+
this.#recomputeOverallState(record);
|
|
1581
|
+
await this.#persist(record);
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
catch (error) {
|
|
1585
|
+
record.state = "error";
|
|
1586
|
+
record.lastError = error instanceof Error ? error.message : String(error);
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
async #performLocalAssetChanges(record, dirtyPaths) {
|
|
1590
|
+
const genuinePaths = [];
|
|
1591
|
+
for (const rel of dirtyPaths) {
|
|
1592
|
+
let abs;
|
|
1593
|
+
try {
|
|
1594
|
+
abs = this.#assetPath(record, rel);
|
|
1595
|
+
}
|
|
1596
|
+
catch {
|
|
1597
|
+
continue;
|
|
1598
|
+
}
|
|
1599
|
+
if (await this.#isSelfWriteEcho(record, abs))
|
|
1600
|
+
continue;
|
|
1601
|
+
genuinePaths.push(rel);
|
|
1602
|
+
}
|
|
1603
|
+
if (!genuinePaths.length)
|
|
1604
|
+
return;
|
|
1605
|
+
// Check if every dirty path maps cleanly to an existing, still-present indexed writable asset.
|
|
1606
|
+
// If any path disappeared or is unindexed (possible rename, move, deletion, or new file), run full reconciliation.
|
|
1607
|
+
const byLocalPath = new Map();
|
|
1608
|
+
for (const entry of Object.values(record.index.entries)) {
|
|
1609
|
+
if (entry.localPath)
|
|
1610
|
+
byLocalPath.set(toPosixPath(entry.localPath), entry);
|
|
1611
|
+
}
|
|
1612
|
+
const targetedEntries = [];
|
|
1613
|
+
for (const rel of genuinePaths) {
|
|
1614
|
+
const entry = byLocalPath.get(rel);
|
|
1615
|
+
const abs = this.#assetPath(record, rel);
|
|
1616
|
+
if (!entry || !entry.writable || !existsSync(abs)) {
|
|
1617
|
+
await this.#performFullSync(record, false);
|
|
1618
|
+
return;
|
|
1619
|
+
}
|
|
1620
|
+
targetedEntries.push(entry);
|
|
1621
|
+
}
|
|
1622
|
+
try {
|
|
1623
|
+
for (const entry of targetedEntries) {
|
|
1624
|
+
const old = { ...entry };
|
|
1625
|
+
if (DATA_JSON_TYPES.has(entry.type) && !entry.filename) {
|
|
1626
|
+
const cachedRemote = record.remoteAssetsCache.get(entry.id);
|
|
1627
|
+
await this.#reconcileJsonAsset(record, entry, old, cachedRemote);
|
|
1628
|
+
}
|
|
1629
|
+
else if (TEXT_FILE_TYPES.has(entry.type)) {
|
|
1630
|
+
await this.#reconcileTextAsset(record, entry, old, true);
|
|
1631
|
+
}
|
|
1632
|
+
else {
|
|
1633
|
+
await this.#reconcileBinary(record, entry, old);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
record.lastSyncedAt = new Date().toISOString();
|
|
1637
|
+
this.#recomputeOverallState(record);
|
|
1638
|
+
await this.#persist(record);
|
|
1639
|
+
}
|
|
1640
|
+
catch (error) {
|
|
1641
|
+
record.state = "error";
|
|
1642
|
+
record.lastError = error instanceof Error ? error.message : String(error);
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
async #quarantineRemoteDeletedEntry(record, id, old, deletionBatch) {
|
|
1646
|
+
const deletedPaths = [
|
|
1647
|
+
old.localPath,
|
|
1648
|
+
...Object.values(old.resources).map((resource) => resource.localPath),
|
|
1649
|
+
].filter((path) => Boolean(path));
|
|
1650
|
+
for (const deletedPath of deletedPaths) {
|
|
1651
|
+
if (!existsSync(this.#assetPath(record, deletedPath)))
|
|
1652
|
+
continue;
|
|
1653
|
+
const source = this.#assetPath(record, deletedPath);
|
|
1654
|
+
await chmod(source, 0o644).catch(() => undefined);
|
|
1655
|
+
const destination = join(record.tmpDirectory, "trash", "remote", deletionBatch, `${id}-${safeWorkspaceName(basename(deletedPath), `asset-${id}`)}`);
|
|
1656
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
1657
|
+
await rename(source, destination);
|
|
1658
|
+
this.#markSelfDeleted(record, source);
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
async #backupLocalDeletedEntry(record, entry, deletionBatch) {
|
|
1662
|
+
const filename = basename(entry.localPath || entry.filename || entry.name || `asset-${entry.id}`);
|
|
1663
|
+
const destination = join(record.tmpDirectory, "trash", "local", deletionBatch, `${entry.id}-${safeWorkspaceName(filename, `asset-${entry.id}`)}`);
|
|
1664
|
+
if (DATA_JSON_TYPES.has(entry.type)) {
|
|
1665
|
+
const baseline = await this.#loadAssetBaseline(record, entry.id);
|
|
1666
|
+
if (baseline) {
|
|
1667
|
+
const proj = buildAssetProjection({
|
|
1668
|
+
id: entry.id,
|
|
1669
|
+
name: baseline.name,
|
|
1670
|
+
type: entry.type,
|
|
1671
|
+
preload: baseline.preload,
|
|
1672
|
+
tags: baseline.tags,
|
|
1673
|
+
data: baseline.data,
|
|
1674
|
+
role: entry.role,
|
|
1675
|
+
sourceAssetId: entry.sourceAssetId,
|
|
1676
|
+
writable: entry.writable,
|
|
1677
|
+
});
|
|
1678
|
+
await atomicWrite(destination, proj.text);
|
|
1679
|
+
}
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
const cached = await this.#cachedObject(record, entry, entry.lastSyncedHash || entry.localHash || entry.remoteFileHash);
|
|
1683
|
+
if (cached) {
|
|
1684
|
+
await atomicWrite(destination, cached.content);
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
async #scanUnindexedFiles(record, knownPaths) {
|
|
1688
|
+
const files = [];
|
|
1689
|
+
const visit = async (directory, relativeDirectory) => {
|
|
1690
|
+
let children;
|
|
1691
|
+
try {
|
|
1692
|
+
children = await readdir(directory, { withFileTypes: true });
|
|
1693
|
+
}
|
|
1694
|
+
catch {
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1697
|
+
for (const child of children) {
|
|
1698
|
+
if (child.name.startsWith(".") || child.name === "tmp")
|
|
1699
|
+
continue;
|
|
1700
|
+
const relativePath = relativeDirectory ? join(relativeDirectory, child.name) : child.name;
|
|
1701
|
+
const path = join(directory, child.name);
|
|
1702
|
+
if (child.isDirectory())
|
|
1703
|
+
await visit(path, relativePath);
|
|
1704
|
+
else if (child.isFile() && !knownPaths.has(toPosixPath(relativePath)))
|
|
1705
|
+
files.push(relativePath);
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
await visit(record.assetsDirectory, "");
|
|
1709
|
+
return files;
|
|
1710
|
+
}
|
|
1711
|
+
async #preProcessLocalRenamesAndDeletes(record, incomingAssets) {
|
|
1712
|
+
const previous = record.index.entries;
|
|
1713
|
+
const incomingById = new Map(incomingAssets.map((asset) => [String(asset.id), asset]));
|
|
1714
|
+
// Build expected folder map so we don't confuse a remote rename/move with a local deletion.
|
|
1715
|
+
const missingEntries = new Map();
|
|
1716
|
+
for (const [id, old] of Object.entries(previous)) {
|
|
1717
|
+
if (!old.writable || old.type === "folder" || !old.downloaded || !old.localPath)
|
|
1718
|
+
continue;
|
|
1719
|
+
if (!incomingById.has(id))
|
|
1720
|
+
continue;
|
|
1721
|
+
const oldAbs = this.#assetPath(record, old.localPath);
|
|
1722
|
+
if (!existsSync(oldAbs)) {
|
|
1723
|
+
missingEntries.set(id, old);
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
if (!missingEntries.size)
|
|
1727
|
+
return incomingAssets;
|
|
1728
|
+
const known = new Set(Object.values(previous)
|
|
1729
|
+
.flatMap((entry) => [
|
|
1730
|
+
entry.localPath ? toPosixPath(entry.localPath) : null,
|
|
1731
|
+
...Object.values(entry.resources).map((resource) => toPosixPath(resource.localPath)),
|
|
1732
|
+
])
|
|
1733
|
+
.filter((item) => Boolean(item)));
|
|
1734
|
+
const unindexedFiles = await this.#scanUnindexedFiles(record, known);
|
|
1735
|
+
let needsRefresh = false;
|
|
1736
|
+
for (const relativePath of unindexedFiles) {
|
|
1737
|
+
if (!missingEntries.size)
|
|
1738
|
+
break;
|
|
1739
|
+
const absPath = this.#assetPath(record, relativePath);
|
|
1740
|
+
let fileInfo;
|
|
1741
|
+
let content;
|
|
1742
|
+
try {
|
|
1743
|
+
fileInfo = await stat(absPath);
|
|
1744
|
+
content = await readFile(absPath);
|
|
1745
|
+
}
|
|
1746
|
+
catch {
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1749
|
+
const contentHash = hashContent(content);
|
|
1750
|
+
const parts = relativePath.split(/[\\/]/g);
|
|
1751
|
+
const rawFilename = parts.pop() || "asset.bin";
|
|
1752
|
+
const cleanFilename = stripCollisionTag(rawFilename);
|
|
1753
|
+
const folder = parts.map(stripCollisionTag).join("/");
|
|
1754
|
+
const parsedDataFile = parseDataAssetFilename(cleanFilename);
|
|
1755
|
+
let matched;
|
|
1756
|
+
// 1. Exact match by embedded $pcbridge.id for structured JSON assets.
|
|
1757
|
+
if (parsedDataFile) {
|
|
1758
|
+
try {
|
|
1759
|
+
const parsed = parseAssetProjection(content.toString("utf8"), {
|
|
1760
|
+
name: parsedDataFile.stem,
|
|
1761
|
+
type: parsedDataFile.type,
|
|
1762
|
+
});
|
|
1763
|
+
if (parsed.embeddedId && missingEntries.has(parsed.embeddedId)) {
|
|
1764
|
+
matched = missingEntries.get(parsed.embeddedId);
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
catch {
|
|
1768
|
+
// Fall through to inode/hash matching.
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
// 2. POSIX (dev, ino) inode match (handles mv + simultaneous content edit!).
|
|
1772
|
+
if (!matched && fileInfo.ino > 0) {
|
|
1773
|
+
for (const candidate of missingEntries.values()) {
|
|
1774
|
+
if (candidate.localIno !== undefined &&
|
|
1775
|
+
candidate.localIno > 0 &&
|
|
1776
|
+
candidate.localIno === fileInfo.ino &&
|
|
1777
|
+
(candidate.localDev === undefined || candidate.localDev === fileInfo.dev)) {
|
|
1778
|
+
matched = candidate;
|
|
1779
|
+
break;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
// 3. Content hash match (handles copy + unlink style renames).
|
|
1784
|
+
if (!matched) {
|
|
1785
|
+
for (const candidate of missingEntries.values()) {
|
|
1786
|
+
if (candidate.localHash && candidate.localHash === contentHash) {
|
|
1787
|
+
matched = candidate;
|
|
1788
|
+
break;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
if (!matched)
|
|
1793
|
+
continue;
|
|
1794
|
+
const remoteName = parsedDataFile ? parsedDataFile.stem : cleanFilename;
|
|
1795
|
+
const renameResponse = await this.#requestTarget(record.targetId, "bridge:renameAsset", {
|
|
1796
|
+
assetId: matched.id,
|
|
1797
|
+
name: remoteName,
|
|
1798
|
+
filename: cleanFilename,
|
|
1799
|
+
folder,
|
|
1800
|
+
}, 60000);
|
|
1801
|
+
if (renameResponse.ok) {
|
|
1802
|
+
missingEntries.delete(matched.id);
|
|
1803
|
+
matched.localPath = relativePath;
|
|
1804
|
+
matched.name = remoteName;
|
|
1805
|
+
matched.localFolderPath = parts;
|
|
1806
|
+
matched.remotePath = parts.map(stripCollisionTag);
|
|
1807
|
+
const remoteAsset = incomingById.get(matched.id);
|
|
1808
|
+
if (remoteAsset) {
|
|
1809
|
+
remoteAsset.name = remoteName;
|
|
1810
|
+
}
|
|
1811
|
+
needsRefresh = true;
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
// Any remaining missing Tier 1 eager writable assets were genuinely deleted locally -> delete remotely too.
|
|
1815
|
+
const tier1Deleted = [];
|
|
1816
|
+
for (const candidate of missingEntries.values()) {
|
|
1817
|
+
if (this.#isTier1EagerWritable(candidate)) {
|
|
1818
|
+
tier1Deleted.push(candidate);
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
if (tier1Deleted.length > 0) {
|
|
1822
|
+
const deletionBatch = new Date().toISOString().replaceAll(":", "-");
|
|
1823
|
+
for (const entry of tier1Deleted) {
|
|
1824
|
+
await this.#backupLocalDeletedEntry(record, entry, deletionBatch);
|
|
1825
|
+
}
|
|
1826
|
+
const deleteResp = await this.#requestTarget(record.targetId, "bridge:deleteAssets", { assetIds: tier1Deleted.map((entry) => entry.id) }, 60000);
|
|
1827
|
+
if (deleteResp.ok) {
|
|
1828
|
+
const deletedSet = new Set(tier1Deleted.map((entry) => entry.id));
|
|
1829
|
+
for (const id of deletedSet) {
|
|
1830
|
+
record.remoteAssetsCache.delete(id);
|
|
1831
|
+
await this.#deleteAssetBaseline(record, id);
|
|
1832
|
+
delete record.index.entries[id];
|
|
1833
|
+
incomingById.delete(id);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
else {
|
|
1837
|
+
record.lastWarning = `Failed to delete remote asset(s): ${deleteResp.error.message}`;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
if (needsRefresh) {
|
|
1841
|
+
const refresh = await this.#requestTarget(record.targetId, "bridge:workspaceSnapshot", {}, 60000);
|
|
1842
|
+
if (refresh.ok) {
|
|
1843
|
+
const snapshot = asObject(refresh.data);
|
|
1844
|
+
const refreshed = Array.isArray(snapshot.assets) ? snapshot.assets : [];
|
|
1845
|
+
if (refreshed.length) {
|
|
1846
|
+
for (const asset of refreshed)
|
|
1847
|
+
record.remoteAssetsCache.set(String(asset.id), asset);
|
|
1848
|
+
return refreshed;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
return [...incomingById.values()];
|
|
1853
|
+
}
|
|
1854
|
+
async #uploadUnindexedFiles(record) {
|
|
1855
|
+
const known = new Set(Object.values(record.index.entries)
|
|
1856
|
+
.flatMap((entry) => [
|
|
1857
|
+
entry.localPath ? toPosixPath(entry.localPath) : null,
|
|
1858
|
+
...Object.values(entry.resources).map((resource) => toPosixPath(resource.localPath)),
|
|
1859
|
+
])
|
|
1860
|
+
.filter((item) => Boolean(item)));
|
|
1861
|
+
const files = await this.#scanUnindexedFiles(record, known);
|
|
1862
|
+
if (!files.length)
|
|
1863
|
+
return;
|
|
1864
|
+
let uploadedAny = false;
|
|
1865
|
+
for (const relativePath of files) {
|
|
1866
|
+
const path = this.#assetPath(record, relativePath);
|
|
1867
|
+
const content = await readFile(path);
|
|
1868
|
+
const contentHash = hashContent(content);
|
|
1869
|
+
const parts = relativePath.split(/[\\/]/g);
|
|
1870
|
+
const filename = parts.pop() || "asset.bin";
|
|
1871
|
+
const folder = parts.map(stripCollisionTag).join("/");
|
|
1872
|
+
const derived = Object.values(record.index.entries).find((entry) => entry.role === "derived" &&
|
|
1873
|
+
!entry.writable &&
|
|
1874
|
+
(entry.localHash === contentHash || entry.lastSyncedHash === contentHash));
|
|
1875
|
+
if (derived) {
|
|
1876
|
+
const conflictPath = join(record.tmpDirectory, "conflicts", `${derived.id}-${safeWorkspaceName(filename, `asset-${derived.id}`)}.derived-local`);
|
|
1877
|
+
await mkdir(dirname(conflictPath), { recursive: true });
|
|
1878
|
+
await chmod(path, 0o644).catch(() => undefined);
|
|
1879
|
+
await rename(path, conflictPath);
|
|
1880
|
+
record.lastWarning =
|
|
1881
|
+
`Ignored a moved or copied projection of derived Asset ${derived.id}; ` +
|
|
1882
|
+
`the local copy was saved to ${relative(record.directory, conflictPath)}.`;
|
|
1883
|
+
continue;
|
|
1884
|
+
}
|
|
1885
|
+
const parsedDataFile = parseDataAssetFilename(filename);
|
|
1886
|
+
if (parsedDataFile) {
|
|
1887
|
+
let parsed;
|
|
1888
|
+
try {
|
|
1889
|
+
parsed = parseAssetProjection(content.toString("utf8"), {
|
|
1890
|
+
name: parsedDataFile.stem,
|
|
1891
|
+
type: parsedDataFile.type,
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
catch (error) {
|
|
1895
|
+
record.lastWarning = `Invalid JSON in ${relativePath}: ${error instanceof Error ? error.message : String(error)}`;
|
|
1896
|
+
continue;
|
|
1897
|
+
}
|
|
1898
|
+
const createResp = await this.#requestTarget(record.targetId, "bridge:createDataAsset", {
|
|
1899
|
+
name: parsed.doc.name || parsedDataFile.stem,
|
|
1900
|
+
type: parsed.embeddedType,
|
|
1901
|
+
folder,
|
|
1902
|
+
preload: parsed.doc.preload,
|
|
1903
|
+
tags: parsed.doc.tags,
|
|
1904
|
+
data: parsed.doc.data,
|
|
1905
|
+
}, 60000);
|
|
1906
|
+
if (!createResp.ok) {
|
|
1907
|
+
record.lastWarning = `Failed to create structured asset ${relativePath}: ${createResp.error.message}`;
|
|
1908
|
+
continue;
|
|
1909
|
+
}
|
|
1910
|
+
const createdObj = asObject(createResp.data).asset;
|
|
1911
|
+
if (createdObj && typeof createdObj === "object" && !Array.isArray(createdObj)) {
|
|
1912
|
+
const remoteCreated = createdObj;
|
|
1913
|
+
const newId = String(remoteCreated.id);
|
|
1914
|
+
record.remoteAssetsCache.set(newId, remoteCreated);
|
|
1915
|
+
const projection = buildAssetProjection({
|
|
1916
|
+
id: newId,
|
|
1917
|
+
name: remoteCreated.name || parsed.doc.name,
|
|
1918
|
+
type: remoteCreated.type || parsed.embeddedType,
|
|
1919
|
+
preload: remoteCreated.preload ?? parsed.doc.preload,
|
|
1920
|
+
tags: remoteCreated.tags ?? parsed.doc.tags,
|
|
1921
|
+
data: remoteCreated.data ?? parsed.doc.data,
|
|
1922
|
+
role: "standalone",
|
|
1923
|
+
sourceAssetId: null,
|
|
1924
|
+
writable: true,
|
|
1925
|
+
});
|
|
1926
|
+
const projBytes = Buffer.from(projection.text, "utf8");
|
|
1927
|
+
const projHash = hashContent(projBytes);
|
|
1928
|
+
await this.#writeRawSelfManaged(record, path, projBytes, projHash, true);
|
|
1929
|
+
await this.#saveAssetBaseline(record, newId, projection.doc);
|
|
1930
|
+
uploadedAny = true;
|
|
1931
|
+
}
|
|
1932
|
+
continue;
|
|
1933
|
+
}
|
|
1934
|
+
const response = await this.#requestTarget(record.targetId, "bridge:uploadAsset", {
|
|
1935
|
+
name: filename,
|
|
1936
|
+
filename,
|
|
1937
|
+
folder,
|
|
1938
|
+
base64: content.toString("base64"),
|
|
1939
|
+
}, 120000);
|
|
1940
|
+
if (!response.ok) {
|
|
1941
|
+
record.lastWarning = `Failed to upload local file ${relativePath}: ${response.error.message}`;
|
|
1942
|
+
continue;
|
|
1943
|
+
}
|
|
1944
|
+
const data = asObject(response.data);
|
|
1945
|
+
if (data.asset && typeof data.asset === "object" && !Array.isArray(data.asset)) {
|
|
1946
|
+
const uploadedAsset = data.asset;
|
|
1947
|
+
record.remoteAssetsCache.set(String(uploadedAsset.id), uploadedAsset);
|
|
1948
|
+
uploadedAny = true;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
if (uploadedAny) {
|
|
1952
|
+
const refresh = await this.#requestTarget(record.targetId, "bridge:workspaceSnapshot", {}, 60000);
|
|
1953
|
+
if (refresh.ok) {
|
|
1954
|
+
const snapshot = asObject(refresh.data);
|
|
1955
|
+
const refreshedAssets = Array.isArray(snapshot.assets)
|
|
1956
|
+
? snapshot.assets
|
|
1957
|
+
: [];
|
|
1958
|
+
if (refreshedAssets.length) {
|
|
1959
|
+
for (const asset of refreshedAssets)
|
|
1960
|
+
record.remoteAssetsCache.set(String(asset.id), asset);
|
|
1961
|
+
await this.#applySnapshot(record, refreshedAssets, false);
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
#acceptSnapshot(record, assets) {
|
|
1967
|
+
const previousIds = Object.keys(record.index.entries);
|
|
1968
|
+
if (!previousIds.length) {
|
|
1969
|
+
record.pendingShrinkDigest = null;
|
|
1970
|
+
record.pendingShrinkCount = 0;
|
|
1055
1971
|
return true;
|
|
1056
1972
|
}
|
|
1057
1973
|
const incomingIds = new Set(assets.map((asset) => String(asset.id)));
|
|
@@ -1086,7 +2002,7 @@ export class WorkspaceManager {
|
|
|
1086
2002
|
record.pendingShrinkCount = 0;
|
|
1087
2003
|
return true;
|
|
1088
2004
|
}
|
|
1089
|
-
async #applySnapshot(record, assets, force) {
|
|
2005
|
+
async #applySnapshot(record, assets, force, onlyReconcileIds) {
|
|
1090
2006
|
const previous = record.index.entries;
|
|
1091
2007
|
const incomingIds = new Set(assets.map((asset) => String(asset.id)));
|
|
1092
2008
|
const folderAssets = assets
|
|
@@ -1137,7 +2053,10 @@ export class WorkspaceManager {
|
|
|
1137
2053
|
const localPath = [...localParent, localName];
|
|
1138
2054
|
localFolderPaths.set(String(folder.id), localPath);
|
|
1139
2055
|
remoteFolderPaths.set(String(folder.id), [...remoteParent, folder.name]);
|
|
1140
|
-
|
|
2056
|
+
const folderAbs = this.#assetPath(record, join(...localPath));
|
|
2057
|
+
if (!existsSync(folderAbs)) {
|
|
2058
|
+
await mkdir(folderAbs, { recursive: true });
|
|
2059
|
+
}
|
|
1141
2060
|
}
|
|
1142
2061
|
const next = {};
|
|
1143
2062
|
const roleOrder = { source: 0, standalone: 1, derived: 2 };
|
|
@@ -1176,8 +2095,6 @@ export class WorkspaceManager {
|
|
|
1176
2095
|
remoteFileHash: null,
|
|
1177
2096
|
localHash: null,
|
|
1178
2097
|
lastSyncedHash: null,
|
|
1179
|
-
localFileSize: undefined,
|
|
1180
|
-
localMtimeMs: undefined,
|
|
1181
2098
|
resources: {},
|
|
1182
2099
|
downloaded: false,
|
|
1183
2100
|
status: "indexed",
|
|
@@ -1187,8 +2104,9 @@ export class WorkspaceManager {
|
|
|
1187
2104
|
const role = assetRole(asset);
|
|
1188
2105
|
const derived = role === "derived";
|
|
1189
2106
|
const sourceAssetId = derived ? String(asset.source_asset_id) : null;
|
|
1190
|
-
const remoteFilename = asset.file?.filename || (asset.type
|
|
1191
|
-
const
|
|
2107
|
+
const remoteFilename = asset.file?.filename || (TEXT_FILE_TYPES.has(asset.type) ? asset.name : null);
|
|
2108
|
+
const isEditableDataJson = DATA_JSON_TYPES.has(asset.type) && !remoteFilename;
|
|
2109
|
+
const localFilename = desiredLocalFilename(asset, role);
|
|
1192
2110
|
const localName = localFilename ? allocateName(localParent, localFilename, asset.type, id) : null;
|
|
1193
2111
|
const localPath = localName ? join(...localParent, localName) : null;
|
|
1194
2112
|
const old = previous[id];
|
|
@@ -1197,14 +2115,19 @@ export class WorkspaceManager {
|
|
|
1197
2115
|
const metadataUnchanged = old?.advertisedRemoteFileHash === advertisedRemoteFileHash &&
|
|
1198
2116
|
old?.advertisedRemoteFileSize === advertisedRemoteFileSize;
|
|
1199
2117
|
const observedRemoteFileSize = metadataUnchanged ? old?.observedRemoteFileSize ?? null : null;
|
|
1200
|
-
const observedRemoteFileHash = metadataUnchanged
|
|
2118
|
+
const observedRemoteFileHash = metadataUnchanged && typeof old?.observedRemoteFileHash === "string"
|
|
2119
|
+
? old.observedRemoteFileHash
|
|
2120
|
+
: null;
|
|
1201
2121
|
const entry = {
|
|
1202
2122
|
id,
|
|
1203
2123
|
name: asset.name,
|
|
1204
2124
|
type: asset.type,
|
|
1205
2125
|
role,
|
|
1206
2126
|
sourceAssetId,
|
|
1207
|
-
writable: !derived,
|
|
2127
|
+
writable: isEditableDataJson ? true : !derived,
|
|
2128
|
+
preload: asset.preload ?? old?.preload,
|
|
2129
|
+
tags: asset.tags ?? old?.tags,
|
|
2130
|
+
meta: asset.meta ?? old?.meta ?? null,
|
|
1208
2131
|
remotePath: remoteParent,
|
|
1209
2132
|
localFolderPath: localParent,
|
|
1210
2133
|
localPath,
|
|
@@ -1213,68 +2136,95 @@ export class WorkspaceManager {
|
|
|
1213
2136
|
advertisedRemoteFileHash,
|
|
1214
2137
|
observedRemoteFileSize,
|
|
1215
2138
|
observedRemoteFileHash,
|
|
1216
|
-
remoteFileSize: observedRemoteFileSize ?? advertisedRemoteFileSize
|
|
1217
|
-
|
|
2139
|
+
remoteFileSize: observedRemoteFileSize ?? advertisedRemoteFileSize ??
|
|
2140
|
+
(DATA_JSON_TYPES.has(asset.type) ? old?.remoteFileSize ?? null : null),
|
|
2141
|
+
remoteFileHash: observedRemoteFileHash || advertisedRemoteFileHash ||
|
|
2142
|
+
(DATA_JSON_TYPES.has(asset.type) ? old?.remoteFileHash ?? null : null),
|
|
1218
2143
|
localHash: old?.localHash || null,
|
|
1219
2144
|
lastSyncedHash: old?.lastSyncedHash || null,
|
|
1220
2145
|
legacyLastSyncedSha256: old?.legacyLastSyncedSha256,
|
|
1221
2146
|
pendingRemoteHash: old?.pendingRemoteHash,
|
|
1222
2147
|
localFileSize: old?.localFileSize,
|
|
1223
2148
|
localMtimeMs: old?.localMtimeMs,
|
|
2149
|
+
localIno: old?.localIno,
|
|
2150
|
+
localDev: old?.localDev,
|
|
1224
2151
|
resources: old?.resources || {},
|
|
1225
2152
|
downloaded: old?.downloaded || false,
|
|
1226
2153
|
status: old?.status || "indexed",
|
|
1227
2154
|
error: old?.error,
|
|
1228
2155
|
};
|
|
1229
2156
|
next[id] = entry;
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
record.syncProgress.action = "comparing";
|
|
1233
|
-
}
|
|
1234
|
-
if (old?.localPath && localPath && old.localPath !== localPath && existsSync(this.#assetPath(record, old.localPath))) {
|
|
2157
|
+
const pathChanged = Boolean(old?.localPath && localPath && old.localPath !== localPath);
|
|
2158
|
+
if (pathChanged && old?.localPath && localPath && existsSync(this.#assetPath(record, old.localPath))) {
|
|
1235
2159
|
const oldPath = this.#assetPath(record, old.localPath);
|
|
1236
2160
|
const newPath = this.#assetPath(record, localPath);
|
|
1237
2161
|
await mkdir(dirname(newPath), { recursive: true });
|
|
1238
|
-
if (!existsSync(newPath))
|
|
2162
|
+
if (!existsSync(newPath)) {
|
|
1239
2163
|
await rename(oldPath, newPath);
|
|
2164
|
+
const fp = record.recentSelfWrites.get(oldPath);
|
|
2165
|
+
this.#markSelfDeleted(record, oldPath);
|
|
2166
|
+
if (fp) {
|
|
2167
|
+
record.recentSelfWrites.set(newPath, fp);
|
|
2168
|
+
}
|
|
2169
|
+
else if (entry.localHash) {
|
|
2170
|
+
const movedStat = await stat(newPath).catch(() => null);
|
|
2171
|
+
if (movedStat) {
|
|
2172
|
+
record.recentSelfWrites.set(newPath, {
|
|
2173
|
+
size: movedStat.size,
|
|
2174
|
+
mtimeMs: movedStat.mtimeMs,
|
|
2175
|
+
hash: entry.localHash,
|
|
2176
|
+
expiresAt: Date.now() + SELF_WRITE_TTL_MS,
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
if (onlyReconcileIds && !onlyReconcileIds.has(id) && !pathChanged) {
|
|
2183
|
+
continue;
|
|
2184
|
+
}
|
|
2185
|
+
if ((asset.file || DATA_JSON_TYPES.has(asset.type)) && record.syncProgress) {
|
|
2186
|
+
record.syncProgress.assetId = id;
|
|
2187
|
+
record.syncProgress.action = "comparing";
|
|
1240
2188
|
}
|
|
1241
|
-
if (
|
|
2189
|
+
if (DATA_JSON_TYPES.has(asset.type) && !entry.filename && localPath) {
|
|
2190
|
+
await this.#reconcileJsonAsset(record, entry, old, asset);
|
|
2191
|
+
}
|
|
2192
|
+
else if (derived && localPath) {
|
|
1242
2193
|
await this.#reconcileDerived(record, entry, old);
|
|
1243
2194
|
if (existsSync(this.#assetPath(record, localPath))) {
|
|
1244
|
-
await
|
|
2195
|
+
await ensureFileMode(this.#assetPath(record, localPath), false);
|
|
1245
2196
|
}
|
|
1246
2197
|
}
|
|
1247
|
-
else if (asset.type
|
|
1248
|
-
|
|
1249
|
-
|
|
2198
|
+
else if (TEXT_FILE_TYPES.has(asset.type) && localPath) {
|
|
2199
|
+
const abs = this.#assetPath(record, localPath);
|
|
2200
|
+
const tier = this.#syncTierForAsset(entry);
|
|
2201
|
+
if (tier === "lazy-text" && !existsSync(abs)) {
|
|
2202
|
+
entry.downloaded = false;
|
|
2203
|
+
entry.status = "indexed";
|
|
2204
|
+
delete entry.error;
|
|
2205
|
+
}
|
|
2206
|
+
else {
|
|
2207
|
+
if (existsSync(abs))
|
|
2208
|
+
await ensureFileMode(abs, true);
|
|
2209
|
+
await this.#reconcileTextAsset(record, entry, old, force);
|
|
1250
2210
|
}
|
|
1251
|
-
await this.#reconcileScript(record, entry, old, force);
|
|
1252
2211
|
}
|
|
1253
2212
|
else if (localPath) {
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
2213
|
+
const abs = this.#assetPath(record, localPath);
|
|
2214
|
+
if (existsSync(abs))
|
|
2215
|
+
await ensureFileMode(abs, true);
|
|
1257
2216
|
await this.#reconcileBinary(record, entry, old);
|
|
1258
2217
|
}
|
|
1259
|
-
if (asset.file && record.syncProgress)
|
|
2218
|
+
if ((asset.file || DATA_JSON_TYPES.has(asset.type)) && record.syncProgress) {
|
|
1260
2219
|
record.syncProgress.completed += 1;
|
|
2220
|
+
}
|
|
1261
2221
|
}
|
|
1262
2222
|
const deletionBatch = new Date().toISOString().replaceAll(":", "-");
|
|
1263
2223
|
for (const [id, old] of Object.entries(previous)) {
|
|
1264
2224
|
if (next[id])
|
|
1265
2225
|
continue;
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
...Object.values(old.resources).map((resource) => resource.localPath),
|
|
1269
|
-
].filter((path) => Boolean(path));
|
|
1270
|
-
for (const deletedPath of deletedPaths) {
|
|
1271
|
-
if (!existsSync(this.#assetPath(record, deletedPath)))
|
|
1272
|
-
continue;
|
|
1273
|
-
const source = this.#assetPath(record, deletedPath);
|
|
1274
|
-
const destination = join(record.tmpDirectory, "trash", "remote", deletionBatch, `${id}-${safeWorkspaceName(basename(deletedPath), `asset-${id}`)}`);
|
|
1275
|
-
await mkdir(dirname(destination), { recursive: true });
|
|
1276
|
-
await rename(source, destination);
|
|
1277
|
-
}
|
|
2226
|
+
await this.#quarantineRemoteDeletedEntry(record, id, old, deletionBatch);
|
|
2227
|
+
await this.#deleteAssetBaseline(record, id);
|
|
1278
2228
|
}
|
|
1279
2229
|
const obsoleteFolders = Object.entries(previous)
|
|
1280
2230
|
.filter(([id, old]) => old.type === "folder" &&
|
|
@@ -1293,12 +2243,6 @@ export class WorkspaceManager {
|
|
|
1293
2243
|
updatedAt: new Date().toISOString(),
|
|
1294
2244
|
entries: next,
|
|
1295
2245
|
};
|
|
1296
|
-
for (const [path, pending] of record.pendingLocalFiles) {
|
|
1297
|
-
const entry = next[pending.assetId];
|
|
1298
|
-
if (entry?.localPath && toPosixPath(entry.localPath) === path) {
|
|
1299
|
-
record.pendingLocalFiles.delete(path);
|
|
1300
|
-
}
|
|
1301
|
-
}
|
|
1302
2246
|
}
|
|
1303
2247
|
async #localFileSnapshot(record, entry, old) {
|
|
1304
2248
|
if (!entry.localPath)
|
|
@@ -1316,19 +2260,62 @@ export class WorkspaceManager {
|
|
|
1316
2260
|
hash: cachedHash || hashContent(await readFile(path)),
|
|
1317
2261
|
size: info.size,
|
|
1318
2262
|
mtimeMs: info.mtimeMs,
|
|
2263
|
+
ino: info.ino,
|
|
2264
|
+
dev: info.dev,
|
|
1319
2265
|
};
|
|
1320
2266
|
}
|
|
1321
2267
|
async #recordLocalFile(record, entry, hash) {
|
|
1322
2268
|
if (!entry.localPath)
|
|
1323
2269
|
return;
|
|
1324
|
-
const
|
|
2270
|
+
const absPath = this.#assetPath(record, entry.localPath);
|
|
2271
|
+
const info = await stat(absPath);
|
|
1325
2272
|
entry.localHash = hash;
|
|
1326
2273
|
entry.localFileSize = info.size;
|
|
1327
2274
|
entry.localMtimeMs = info.mtimeMs;
|
|
2275
|
+
entry.localIno = info.ino;
|
|
2276
|
+
entry.localDev = info.dev;
|
|
1328
2277
|
entry.downloaded = true;
|
|
2278
|
+
record.recentSelfWrites.set(absPath, {
|
|
2279
|
+
size: info.size,
|
|
2280
|
+
mtimeMs: info.mtimeMs,
|
|
2281
|
+
hash,
|
|
2282
|
+
expiresAt: Date.now() + SELF_WRITE_TTL_MS,
|
|
2283
|
+
});
|
|
2284
|
+
}
|
|
2285
|
+
async #writeRawSelfManaged(record, absPath, content, hash, writable) {
|
|
2286
|
+
if (existsSync(absPath))
|
|
2287
|
+
await ensureFileMode(absPath, true);
|
|
2288
|
+
await atomicWrite(absPath, content);
|
|
2289
|
+
await ensureFileMode(absPath, writable);
|
|
2290
|
+
const info = await stat(absPath);
|
|
2291
|
+
record.recentSelfWrites.set(absPath, {
|
|
2292
|
+
size: info.size,
|
|
2293
|
+
mtimeMs: info.mtimeMs,
|
|
2294
|
+
hash,
|
|
2295
|
+
expiresAt: Date.now() + SELF_WRITE_TTL_MS,
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
async #writeManagedAssetFile(record, entry, content, hash) {
|
|
2299
|
+
if (!entry.localPath)
|
|
2300
|
+
throw new Error(`Asset ${entry.id} has no local projection path.`);
|
|
2301
|
+
const path = this.#assetPath(record, entry.localPath);
|
|
2302
|
+
await this.#writeRawSelfManaged(record, path, content, hash, entry.writable);
|
|
2303
|
+
await this.#recordLocalFile(record, entry, hash);
|
|
2304
|
+
return path;
|
|
2305
|
+
}
|
|
2306
|
+
async #writeManagedSceneFile(record, scene, content, hash) {
|
|
2307
|
+
await mkdir(record.scenesDirectory, { recursive: true });
|
|
2308
|
+
this.#ensureScenesWatcher(record);
|
|
2309
|
+
const path = this.#scenePath(record, scene.localPath);
|
|
2310
|
+
await this.#writeRawSelfManaged(record, path, content, hash, scene.writable);
|
|
2311
|
+
const info = await stat(path);
|
|
2312
|
+
scene.localHash = hash;
|
|
2313
|
+
scene.localFileSize = info.size;
|
|
2314
|
+
scene.localMtimeMs = info.mtimeMs;
|
|
2315
|
+
return path;
|
|
1329
2316
|
}
|
|
1330
2317
|
#objectPath(record, entry, hash) {
|
|
1331
|
-
const path = this.#withinRoot(join(record.objectsDirectory, safeAssetName(entry.id, "asset"), safeAssetName(hash, "unknown"), safeAssetName(entry.filename || entry.name, "file.bin")));
|
|
2318
|
+
const path = this.#withinRoot(join(record.objectsDirectory, safeAssetName(entry.id, "asset"), safeAssetName(hash, "unknown"), safeAssetName(entry.filename || basename(entry.localPath || "") || entry.name, "file.bin")));
|
|
1332
2319
|
if (path !== record.objectsDirectory && !path.startsWith(`${record.objectsDirectory}${sep}`)) {
|
|
1333
2320
|
throw new Error(`Object path escapes workspace cache: ${path}`);
|
|
1334
2321
|
}
|
|
@@ -1379,10 +2366,7 @@ export class WorkspaceManager {
|
|
|
1379
2366
|
}
|
|
1380
2367
|
async #materializeResource(record, resource, content, hash) {
|
|
1381
2368
|
const path = this.#assetPath(record, resource.localPath);
|
|
1382
|
-
|
|
1383
|
-
await chmod(path, 0o644).catch(() => undefined);
|
|
1384
|
-
await atomicWrite(path, content);
|
|
1385
|
-
await chmod(path, 0o444).catch(() => undefined);
|
|
2369
|
+
await this.#writeRawSelfManaged(record, path, content, hash, false);
|
|
1386
2370
|
resource.localHash = hash;
|
|
1387
2371
|
resource.remoteFileSize = content.byteLength;
|
|
1388
2372
|
return path;
|
|
@@ -1440,7 +2424,7 @@ export class WorkspaceManager {
|
|
|
1440
2424
|
if (localContent && (!resource.remoteHash || localHash === resource.remoteHash)) {
|
|
1441
2425
|
resource.localHash = localHash;
|
|
1442
2426
|
resource.remoteFileSize = localContent.byteLength;
|
|
1443
|
-
await
|
|
2427
|
+
await ensureFileMode(path, false);
|
|
1444
2428
|
if (resource.remoteHash) {
|
|
1445
2429
|
await this.#storeResourceObject(record, entry, resource, localContent, resource.remoteHash);
|
|
1446
2430
|
}
|
|
@@ -1505,17 +2489,6 @@ export class WorkspaceManager {
|
|
|
1505
2489
|
hash: remote.hash,
|
|
1506
2490
|
};
|
|
1507
2491
|
}
|
|
1508
|
-
async #materializeObject(record, entry, content, hash) {
|
|
1509
|
-
if (!entry.localPath)
|
|
1510
|
-
throw new Error(`Asset ${entry.id} has no local projection path.`);
|
|
1511
|
-
const path = this.#assetPath(record, entry.localPath);
|
|
1512
|
-
if (existsSync(path))
|
|
1513
|
-
await chmod(path, 0o644).catch(() => undefined);
|
|
1514
|
-
await atomicWrite(path, content);
|
|
1515
|
-
await chmod(path, entry.writable ? 0o644 : 0o444).catch(() => undefined);
|
|
1516
|
-
await this.#recordLocalFile(record, entry, hash);
|
|
1517
|
-
return path;
|
|
1518
|
-
}
|
|
1519
2492
|
async #readRemoteAsset(record, entry) {
|
|
1520
2493
|
const readOnce = async () => {
|
|
1521
2494
|
const response = await this.#requestTarget(record.targetId, "bridge:readAssetFile", { assetId: entry.id }, 120000);
|
|
@@ -1531,8 +2504,6 @@ export class WorkspaceManager {
|
|
|
1531
2504
|
const expectedHash = entry.remoteFileHash;
|
|
1532
2505
|
let remote = await readOnce();
|
|
1533
2506
|
if (expectedHash && expectedHash !== remote.hash) {
|
|
1534
|
-
// Processed assets can expose stale metadata after their generated file has been replaced.
|
|
1535
|
-
// A second identical download distinguishes that case from an actively changing resource.
|
|
1536
2507
|
const confirmed = await readOnce();
|
|
1537
2508
|
if (confirmed.hash !== remote.hash) {
|
|
1538
2509
|
throw new Error(`Asset ${entry.id} changed while it was being downloaded: ` +
|
|
@@ -1571,7 +2542,7 @@ export class WorkspaceManager {
|
|
|
1571
2542
|
const cached = legacy || await this.#cachedObject(record, entry, entry.remoteFileHash);
|
|
1572
2543
|
const remote = cached || await this.#readRemoteAsset(record, entry);
|
|
1573
2544
|
await this.#storeObject(record, entry, remote.content, remote.hash);
|
|
1574
|
-
const path = await this.#
|
|
2545
|
+
const path = await this.#writeManagedAssetFile(record, entry, remote.content, remote.hash);
|
|
1575
2546
|
await this.#removeLegacyResource(legacyPath);
|
|
1576
2547
|
entry.lastSyncedHash = remote.hash;
|
|
1577
2548
|
entry.status = "synced";
|
|
@@ -1580,6 +2551,42 @@ export class WorkspaceManager {
|
|
|
1580
2551
|
delete entry.error;
|
|
1581
2552
|
return { path, size: remote.content.byteLength, hash: remote.hash };
|
|
1582
2553
|
}
|
|
2554
|
+
async #downloadTextAsset(record, entry) {
|
|
2555
|
+
if (!entry.localPath)
|
|
2556
|
+
throw new Error(`Asset ${entry.id} has no downloadable file.`);
|
|
2557
|
+
if (record.syncProgress) {
|
|
2558
|
+
record.syncProgress.assetId = entry.id;
|
|
2559
|
+
record.syncProgress.action = "downloading";
|
|
2560
|
+
}
|
|
2561
|
+
const cached = await this.#cachedObject(record, entry, entry.remoteFileHash);
|
|
2562
|
+
let content;
|
|
2563
|
+
let hash;
|
|
2564
|
+
if (cached) {
|
|
2565
|
+
content = cached.content;
|
|
2566
|
+
hash = cached.hash;
|
|
2567
|
+
}
|
|
2568
|
+
else {
|
|
2569
|
+
const response = await this.#requestTarget(record.targetId, "bridge:readAssetText", { assetId: entry.id }, 30000);
|
|
2570
|
+
if (!response.ok)
|
|
2571
|
+
throw new Error(response.error.message);
|
|
2572
|
+
const data = asObject(response.data);
|
|
2573
|
+
const text = typeof data.text === "string" ? data.text : "";
|
|
2574
|
+
content = Buffer.from(text, "utf8");
|
|
2575
|
+
hash = hashContent(content);
|
|
2576
|
+
entry.observedRemoteFileHash = entry.advertisedRemoteFileHash !== hash ? hash : null;
|
|
2577
|
+
entry.observedRemoteFileSize = entry.advertisedRemoteFileSize !== content.byteLength ? content.byteLength : null;
|
|
2578
|
+
entry.remoteFileHash = hash;
|
|
2579
|
+
entry.remoteFileSize = content.byteLength;
|
|
2580
|
+
await this.#storeObject(record, entry, content, hash);
|
|
2581
|
+
}
|
|
2582
|
+
const path = await this.#writeManagedAssetFile(record, entry, content, hash);
|
|
2583
|
+
entry.lastSyncedHash = hash;
|
|
2584
|
+
entry.status = "synced";
|
|
2585
|
+
delete entry.legacyLastSyncedSha256;
|
|
2586
|
+
delete entry.pendingRemoteHash;
|
|
2587
|
+
delete entry.error;
|
|
2588
|
+
return { path, size: content.byteLength, hash };
|
|
2589
|
+
}
|
|
1583
2590
|
async #uploadBinary(record, entry, content, localHash) {
|
|
1584
2591
|
if (!entry.writable)
|
|
1585
2592
|
throw new Error(`Derived Asset ${entry.id} is read-only.`);
|
|
@@ -1597,6 +2604,7 @@ export class WorkspaceManager {
|
|
|
1597
2604
|
entry.error = response.error.message;
|
|
1598
2605
|
return;
|
|
1599
2606
|
}
|
|
2607
|
+
await this.#storeObject(record, entry, content, localHash);
|
|
1600
2608
|
await this.#recordLocalFile(record, entry, localHash);
|
|
1601
2609
|
entry.pendingRemoteHash = localHash;
|
|
1602
2610
|
entry.status = "local-change";
|
|
@@ -1627,7 +2635,7 @@ export class WorkspaceManager {
|
|
|
1627
2635
|
if (old?.downloaded && entry.remoteFileHash) {
|
|
1628
2636
|
const cached = await this.#cachedObject(record, entry, entry.remoteFileHash);
|
|
1629
2637
|
if (cached) {
|
|
1630
|
-
await this.#
|
|
2638
|
+
await this.#writeManagedAssetFile(record, entry, cached.content, cached.hash);
|
|
1631
2639
|
entry.lastSyncedHash = cached.hash;
|
|
1632
2640
|
entry.status = "synced";
|
|
1633
2641
|
delete entry.error;
|
|
@@ -1647,6 +2655,8 @@ export class WorkspaceManager {
|
|
|
1647
2655
|
entry.localHash = local.hash;
|
|
1648
2656
|
entry.localFileSize = local.size;
|
|
1649
2657
|
entry.localMtimeMs = local.mtimeMs;
|
|
2658
|
+
entry.localIno = local.ino;
|
|
2659
|
+
entry.localDev = local.dev;
|
|
1650
2660
|
entry.downloaded = true;
|
|
1651
2661
|
if (entry.remoteFileHash && local.hash === entry.remoteFileHash) {
|
|
1652
2662
|
entry.lastSyncedHash = local.hash;
|
|
@@ -1670,8 +2680,6 @@ export class WorkspaceManager {
|
|
|
1670
2680
|
const baseline = old?.lastSyncedHash || null;
|
|
1671
2681
|
const advertisedRemoteHash = entry.remoteFileHash;
|
|
1672
2682
|
if (!local) {
|
|
1673
|
-
// Binary assets are lazy. Keep the catalog and remote hash locally, and
|
|
1674
|
-
// only fetch bytes through workspace pull or a Template build.
|
|
1675
2683
|
entry.downloaded = false;
|
|
1676
2684
|
entry.status = "indexed";
|
|
1677
2685
|
delete entry.error;
|
|
@@ -1680,8 +2688,11 @@ export class WorkspaceManager {
|
|
|
1680
2688
|
entry.localHash = local.hash;
|
|
1681
2689
|
entry.localFileSize = local.size;
|
|
1682
2690
|
entry.localMtimeMs = local.mtimeMs;
|
|
2691
|
+
entry.localIno = local.ino;
|
|
2692
|
+
entry.localDev = local.dev;
|
|
1683
2693
|
entry.downloaded = true;
|
|
1684
2694
|
if (advertisedRemoteHash && local.hash === advertisedRemoteHash) {
|
|
2695
|
+
await this.#storeObject(record, entry, await readFile(this.#assetPath(record, entry.localPath)), local.hash);
|
|
1685
2696
|
entry.lastSyncedHash = local.hash;
|
|
1686
2697
|
entry.status = "synced";
|
|
1687
2698
|
delete entry.legacyLastSyncedSha256;
|
|
@@ -1707,6 +2718,7 @@ export class WorkspaceManager {
|
|
|
1707
2718
|
}
|
|
1708
2719
|
const remote = await this.#readRemoteAsset(record, entry);
|
|
1709
2720
|
if (remote.hash === local.hash) {
|
|
2721
|
+
await this.#storeObject(record, entry, remote.content, local.hash);
|
|
1710
2722
|
entry.lastSyncedHash = local.hash;
|
|
1711
2723
|
entry.status = "synced";
|
|
1712
2724
|
delete entry.legacyLastSyncedSha256;
|
|
@@ -1719,8 +2731,8 @@ export class WorkspaceManager {
|
|
|
1719
2731
|
return;
|
|
1720
2732
|
}
|
|
1721
2733
|
if (baseline && local.hash === baseline) {
|
|
1722
|
-
await
|
|
1723
|
-
await this.#
|
|
2734
|
+
await this.#storeObject(record, entry, remote.content, remote.hash);
|
|
2735
|
+
await this.#writeManagedAssetFile(record, entry, remote.content, remote.hash);
|
|
1724
2736
|
entry.lastSyncedHash = remote.hash;
|
|
1725
2737
|
entry.status = "synced";
|
|
1726
2738
|
delete entry.pendingRemoteHash;
|
|
@@ -1734,16 +2746,24 @@ export class WorkspaceManager {
|
|
|
1734
2746
|
}
|
|
1735
2747
|
await this.#writeBinaryConflict(record, entry, remote.content, local.hash);
|
|
1736
2748
|
}
|
|
1737
|
-
async #
|
|
2749
|
+
async #reconcileTextAsset(record, entry, old, force) {
|
|
1738
2750
|
if (!entry.localPath)
|
|
1739
2751
|
return;
|
|
1740
2752
|
const path = this.#assetPath(record, entry.localPath);
|
|
1741
|
-
const
|
|
1742
|
-
const
|
|
1743
|
-
const localHash = localBytes === null ? null : hashContent(localBytes);
|
|
2753
|
+
const localSnap = await this.#localFileSnapshot(record, entry, old);
|
|
2754
|
+
const localHash = localSnap?.hash ?? null;
|
|
1744
2755
|
const baseline = old?.lastSyncedHash || null;
|
|
1745
2756
|
const advertisedRemoteHash = entry.remoteFileHash;
|
|
1746
|
-
if (
|
|
2757
|
+
if (localSnap) {
|
|
2758
|
+
entry.localFileSize = localSnap.size;
|
|
2759
|
+
entry.localMtimeMs = localSnap.mtimeMs;
|
|
2760
|
+
entry.localIno = localSnap.ino;
|
|
2761
|
+
entry.localDev = localSnap.dev;
|
|
2762
|
+
}
|
|
2763
|
+
if (localHash !== null && advertisedRemoteHash && localHash === advertisedRemoteHash) {
|
|
2764
|
+
if (!(await this.#cachedObject(record, entry, localHash))) {
|
|
2765
|
+
await this.#storeObject(record, entry, await readFile(path), localHash);
|
|
2766
|
+
}
|
|
1747
2767
|
entry.localHash = localHash;
|
|
1748
2768
|
entry.lastSyncedHash = localHash;
|
|
1749
2769
|
entry.downloaded = true;
|
|
@@ -1753,7 +2773,7 @@ export class WorkspaceManager {
|
|
|
1753
2773
|
delete entry.error;
|
|
1754
2774
|
return;
|
|
1755
2775
|
}
|
|
1756
|
-
if (
|
|
2776
|
+
if (localHash !== null &&
|
|
1757
2777
|
old?.pendingRemoteHash &&
|
|
1758
2778
|
localHash === old.pendingRemoteHash &&
|
|
1759
2779
|
advertisedRemoteHash !== old.pendingRemoteHash) {
|
|
@@ -1772,9 +2792,14 @@ export class WorkspaceManager {
|
|
|
1772
2792
|
}
|
|
1773
2793
|
const data = asObject(response.data);
|
|
1774
2794
|
const pendingRemoteContent = typeof data.text === "string" ? data.text : "";
|
|
1775
|
-
const
|
|
2795
|
+
const pendingRemoteBytes = Buffer.from(pendingRemoteContent, "utf8");
|
|
2796
|
+
const pendingRemoteHash = hashContent(pendingRemoteBytes);
|
|
2797
|
+
entry.observedRemoteFileHash = entry.advertisedRemoteFileHash !== pendingRemoteHash ? pendingRemoteHash : null;
|
|
2798
|
+
entry.observedRemoteFileSize = entry.advertisedRemoteFileSize !== pendingRemoteBytes.byteLength ? pendingRemoteBytes.byteLength : null;
|
|
1776
2799
|
entry.remoteFileHash = pendingRemoteHash;
|
|
2800
|
+
entry.remoteFileSize = pendingRemoteBytes.byteLength;
|
|
1777
2801
|
if (pendingRemoteHash === old.pendingRemoteHash) {
|
|
2802
|
+
await this.#storeObject(record, entry, pendingRemoteBytes, localHash);
|
|
1778
2803
|
entry.localHash = localHash;
|
|
1779
2804
|
entry.lastSyncedHash = localHash;
|
|
1780
2805
|
entry.downloaded = true;
|
|
@@ -1785,10 +2810,9 @@ export class WorkspaceManager {
|
|
|
1785
2810
|
return;
|
|
1786
2811
|
}
|
|
1787
2812
|
if (pendingRemoteHash !== baseline) {
|
|
1788
|
-
await
|
|
1789
|
-
entry
|
|
2813
|
+
await this.#storeObject(record, entry, pendingRemoteBytes, pendingRemoteHash);
|
|
2814
|
+
await this.#writeManagedAssetFile(record, entry, pendingRemoteBytes, pendingRemoteHash);
|
|
1790
2815
|
entry.lastSyncedHash = pendingRemoteHash;
|
|
1791
|
-
entry.downloaded = true;
|
|
1792
2816
|
entry.status = "synced";
|
|
1793
2817
|
delete entry.legacyLastSyncedSha256;
|
|
1794
2818
|
delete entry.pendingRemoteHash;
|
|
@@ -1804,7 +2828,7 @@ export class WorkspaceManager {
|
|
|
1804
2828
|
}
|
|
1805
2829
|
const localChanged = localHash !== null && localHash !== baseline;
|
|
1806
2830
|
const remoteMetadataChanged = !old || old.remoteFileHash !== advertisedRemoteHash;
|
|
1807
|
-
if (!force &&
|
|
2831
|
+
if (!force && localHash !== null && baseline && !localChanged && !remoteMetadataChanged) {
|
|
1808
2832
|
entry.localHash = localHash;
|
|
1809
2833
|
entry.lastSyncedHash = baseline;
|
|
1810
2834
|
entry.downloaded = true;
|
|
@@ -1812,40 +2836,52 @@ export class WorkspaceManager {
|
|
|
1812
2836
|
delete entry.error;
|
|
1813
2837
|
return;
|
|
1814
2838
|
}
|
|
1815
|
-
if (
|
|
1816
|
-
await
|
|
2839
|
+
if (localHash !== null && baseline && advertisedRemoteHash === baseline && localChanged) {
|
|
2840
|
+
const localContent = await readFile(path, "utf8");
|
|
2841
|
+
await this.#uploadTextAsset(record, entry, localContent, localHash);
|
|
1817
2842
|
return;
|
|
1818
2843
|
}
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
2844
|
+
let remoteContent;
|
|
2845
|
+
let remoteBytes;
|
|
2846
|
+
let remoteHash;
|
|
2847
|
+
const cachedRemote = localHash === null && advertisedRemoteHash
|
|
2848
|
+
? await this.#cachedObject(record, entry, advertisedRemoteHash)
|
|
2849
|
+
: null;
|
|
2850
|
+
if (cachedRemote) {
|
|
2851
|
+
remoteBytes = cachedRemote.content;
|
|
2852
|
+
remoteContent = remoteBytes.toString("utf8");
|
|
2853
|
+
remoteHash = cachedRemote.hash;
|
|
1828
2854
|
}
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
2855
|
+
else {
|
|
2856
|
+
if (record.syncProgress) {
|
|
2857
|
+
record.syncProgress.assetId = entry.id;
|
|
2858
|
+
record.syncProgress.action = "downloading";
|
|
2859
|
+
}
|
|
2860
|
+
const response = await this.#requestTarget(record.targetId, "bridge:readAssetText", { assetId: entry.id }, 30000);
|
|
2861
|
+
if (!response.ok) {
|
|
2862
|
+
entry.status = "error";
|
|
2863
|
+
entry.error = response.error.message;
|
|
2864
|
+
return;
|
|
2865
|
+
}
|
|
2866
|
+
const data = asObject(response.data);
|
|
2867
|
+
remoteContent = typeof data.text === "string" ? data.text : "";
|
|
2868
|
+
remoteBytes = Buffer.from(remoteContent, "utf8");
|
|
2869
|
+
remoteHash = hashContent(remoteBytes);
|
|
2870
|
+
entry.observedRemoteFileHash = entry.advertisedRemoteFileHash !== remoteHash ? remoteHash : null;
|
|
2871
|
+
entry.observedRemoteFileSize = entry.advertisedRemoteFileSize !== remoteBytes.byteLength ? remoteBytes.byteLength : null;
|
|
2872
|
+
entry.remoteFileHash = remoteHash;
|
|
2873
|
+
entry.remoteFileSize = remoteBytes.byteLength;
|
|
2874
|
+
await this.#storeObject(record, entry, remoteBytes, remoteHash);
|
|
2875
|
+
}
|
|
2876
|
+
if (localHash === null) {
|
|
2877
|
+
await this.#writeManagedAssetFile(record, entry, remoteBytes, remoteHash);
|
|
1839
2878
|
entry.lastSyncedHash = remoteHash;
|
|
1840
|
-
entry.downloaded = true;
|
|
1841
2879
|
entry.status = "synced";
|
|
1842
2880
|
delete entry.legacyLastSyncedSha256;
|
|
1843
2881
|
delete entry.pendingRemoteHash;
|
|
1844
2882
|
delete entry.error;
|
|
1845
2883
|
return;
|
|
1846
2884
|
}
|
|
1847
|
-
if (!localHash)
|
|
1848
|
-
throw new Error(`Could not hash local script ${entry.id}.`);
|
|
1849
2885
|
if (localHash === remoteHash) {
|
|
1850
2886
|
entry.localHash = localHash;
|
|
1851
2887
|
entry.lastSyncedHash = localHash;
|
|
@@ -1856,12 +2892,12 @@ export class WorkspaceManager {
|
|
|
1856
2892
|
delete entry.error;
|
|
1857
2893
|
return;
|
|
1858
2894
|
}
|
|
2895
|
+
const localBytes = await readFile(path);
|
|
2896
|
+
const localContent = localBytes.toString("utf8");
|
|
1859
2897
|
if (baseline) {
|
|
1860
2898
|
if (localHash === baseline) {
|
|
1861
|
-
await
|
|
1862
|
-
entry.localHash = remoteHash;
|
|
2899
|
+
await this.#writeManagedAssetFile(record, entry, remoteBytes, remoteHash);
|
|
1863
2900
|
entry.lastSyncedHash = remoteHash;
|
|
1864
|
-
entry.downloaded = true;
|
|
1865
2901
|
entry.status = "synced";
|
|
1866
2902
|
delete entry.legacyLastSyncedSha256;
|
|
1867
2903
|
delete entry.pendingRemoteHash;
|
|
@@ -1869,21 +2905,19 @@ export class WorkspaceManager {
|
|
|
1869
2905
|
return;
|
|
1870
2906
|
}
|
|
1871
2907
|
if (remoteHash === baseline) {
|
|
1872
|
-
await this.#
|
|
2908
|
+
await this.#uploadTextAsset(record, entry, localContent, localHash);
|
|
1873
2909
|
return;
|
|
1874
2910
|
}
|
|
1875
2911
|
await this.#writeConflict(record, entry, localContent, remoteContent);
|
|
1876
2912
|
return;
|
|
1877
2913
|
}
|
|
1878
2914
|
const legacyBaseline = old?.legacyLastSyncedSha256;
|
|
1879
|
-
if (legacyBaseline
|
|
2915
|
+
if (legacyBaseline) {
|
|
1880
2916
|
const localChangedFromLegacy = hashLegacyContent(localBytes) !== legacyBaseline;
|
|
1881
2917
|
const remoteChangedFromLegacy = hashLegacyContent(remoteContent) !== legacyBaseline;
|
|
1882
2918
|
if (!localChangedFromLegacy) {
|
|
1883
|
-
await
|
|
1884
|
-
entry.localHash = remoteHash;
|
|
2919
|
+
await this.#writeManagedAssetFile(record, entry, remoteBytes, remoteHash);
|
|
1885
2920
|
entry.lastSyncedHash = remoteHash;
|
|
1886
|
-
entry.downloaded = true;
|
|
1887
2921
|
entry.status = "synced";
|
|
1888
2922
|
delete entry.legacyLastSyncedSha256;
|
|
1889
2923
|
delete entry.pendingRemoteHash;
|
|
@@ -1891,31 +2925,629 @@ export class WorkspaceManager {
|
|
|
1891
2925
|
return;
|
|
1892
2926
|
}
|
|
1893
2927
|
if (!remoteChangedFromLegacy) {
|
|
1894
|
-
await this.#
|
|
2928
|
+
await this.#uploadTextAsset(record, entry, localContent, localHash);
|
|
1895
2929
|
return;
|
|
1896
2930
|
}
|
|
1897
2931
|
}
|
|
1898
2932
|
await this.#writeConflict(record, entry, localContent, remoteContent);
|
|
1899
2933
|
}
|
|
1900
|
-
async #
|
|
2934
|
+
async #uploadTextAsset(record, entry, localContent, localHash) {
|
|
1901
2935
|
if (record.syncProgress) {
|
|
1902
2936
|
record.syncProgress.assetId = entry.id;
|
|
1903
2937
|
record.syncProgress.action = "uploading";
|
|
1904
2938
|
}
|
|
1905
|
-
const
|
|
2939
|
+
const method = entry.type === "script" ? "bridge:writeScriptText" : "bridge:writeAssetText";
|
|
2940
|
+
const writeResponse = await this.#requestTarget(record.targetId, method, { assetId: entry.id, text: localContent, filename: entry.filename || entry.name }, 60000);
|
|
1906
2941
|
if (!writeResponse.ok) {
|
|
1907
2942
|
entry.localHash = localHash;
|
|
1908
2943
|
entry.status = "local-change";
|
|
1909
2944
|
entry.error = writeResponse.error.message;
|
|
1910
2945
|
return;
|
|
1911
2946
|
}
|
|
1912
|
-
entry.
|
|
2947
|
+
await this.#storeObject(record, entry, Buffer.from(localContent, "utf8"), localHash);
|
|
2948
|
+
await this.#recordLocalFile(record, entry, localHash);
|
|
1913
2949
|
entry.pendingRemoteHash = localHash;
|
|
1914
|
-
entry.downloaded = true;
|
|
1915
2950
|
entry.status = "local-change";
|
|
1916
2951
|
delete entry.legacyLastSyncedSha256;
|
|
1917
2952
|
entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
|
|
1918
2953
|
}
|
|
2954
|
+
async #reconcileJsonAsset(record, entry, old, remoteAsset) {
|
|
2955
|
+
if (!entry.localPath)
|
|
2956
|
+
return;
|
|
2957
|
+
const remoteProj = buildAssetProjection({
|
|
2958
|
+
id: entry.id,
|
|
2959
|
+
name: remoteAsset?.name ?? entry.name,
|
|
2960
|
+
type: entry.type,
|
|
2961
|
+
preload: remoteAsset?.preload ?? entry.preload,
|
|
2962
|
+
tags: remoteAsset?.tags ?? entry.tags,
|
|
2963
|
+
data: remoteAsset?.data ?? {},
|
|
2964
|
+
role: entry.role,
|
|
2965
|
+
sourceAssetId: entry.sourceAssetId,
|
|
2966
|
+
writable: entry.writable,
|
|
2967
|
+
});
|
|
2968
|
+
const remoteBytes = Buffer.from(remoteProj.text, "utf8");
|
|
2969
|
+
const remoteHash = hashContent(remoteBytes);
|
|
2970
|
+
entry.remoteFileHash = remoteHash;
|
|
2971
|
+
entry.remoteFileSize = remoteBytes.byteLength;
|
|
2972
|
+
const absPath = this.#assetPath(record, entry.localPath);
|
|
2973
|
+
const localSnap = await this.#localFileSnapshot(record, entry, old);
|
|
2974
|
+
// Derived JSON assets (e.g. GLB-imported materials/templates) are eagerly projected read-only for Agent inspection.
|
|
2975
|
+
if (!entry.writable) {
|
|
2976
|
+
if (localSnap && localSnap.hash === remoteHash) {
|
|
2977
|
+
await ensureFileMode(absPath, false);
|
|
2978
|
+
entry.localHash = localSnap.hash;
|
|
2979
|
+
entry.localFileSize = localSnap.size;
|
|
2980
|
+
entry.localMtimeMs = localSnap.mtimeMs;
|
|
2981
|
+
entry.localIno = localSnap.ino;
|
|
2982
|
+
entry.localDev = localSnap.dev;
|
|
2983
|
+
entry.lastSyncedHash = remoteHash;
|
|
2984
|
+
entry.downloaded = true;
|
|
2985
|
+
entry.status = "synced";
|
|
2986
|
+
delete entry.error;
|
|
2987
|
+
return;
|
|
2988
|
+
}
|
|
2989
|
+
if (localSnap && old?.lastSyncedHash && localSnap.hash !== old.lastSyncedHash) {
|
|
2990
|
+
const conflictPath = join(record.tmpDirectory, "conflicts", `${entry.id}-${safeWorkspaceName(basename(entry.localPath), `asset-${entry.id}`)}.derived-local`);
|
|
2991
|
+
await mkdir(dirname(conflictPath), { recursive: true });
|
|
2992
|
+
await copyFile(absPath, conflictPath);
|
|
2993
|
+
record.lastWarning =
|
|
2994
|
+
`Ignored a local edit to derived Asset ${entry.id}; restored the PlayCanvas projection. ` +
|
|
2995
|
+
`The local copy was saved to ${relative(record.directory, conflictPath)}.`;
|
|
2996
|
+
}
|
|
2997
|
+
await this.#writeManagedAssetFile(record, entry, remoteBytes, remoteHash);
|
|
2998
|
+
await this.#saveAssetBaseline(record, entry.id, remoteProj.doc);
|
|
2999
|
+
entry.lastSyncedHash = remoteHash;
|
|
3000
|
+
entry.status = "synced";
|
|
3001
|
+
delete entry.error;
|
|
3002
|
+
return;
|
|
3003
|
+
}
|
|
3004
|
+
const tier = this.#syncTierForAsset(entry, remoteBytes.byteLength);
|
|
3005
|
+
if (!localSnap) {
|
|
3006
|
+
if (tier === "lazy-json") {
|
|
3007
|
+
entry.downloaded = false;
|
|
3008
|
+
entry.status = "indexed";
|
|
3009
|
+
delete entry.error;
|
|
3010
|
+
return;
|
|
3011
|
+
}
|
|
3012
|
+
await this.#writeManagedAssetFile(record, entry, remoteBytes, remoteHash);
|
|
3013
|
+
await this.#saveAssetBaseline(record, entry.id, remoteProj.doc);
|
|
3014
|
+
entry.lastSyncedHash = remoteHash;
|
|
3015
|
+
entry.status = "synced";
|
|
3016
|
+
delete entry.error;
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
entry.localHash = localSnap.hash;
|
|
3020
|
+
entry.localFileSize = localSnap.size;
|
|
3021
|
+
entry.localMtimeMs = localSnap.mtimeMs;
|
|
3022
|
+
entry.localIno = localSnap.ino;
|
|
3023
|
+
entry.localDev = localSnap.dev;
|
|
3024
|
+
entry.downloaded = true;
|
|
3025
|
+
if (localSnap.hash === remoteHash) {
|
|
3026
|
+
await ensureFileMode(absPath, true);
|
|
3027
|
+
if (!existsSync(this.#assetBaselinePath(record, entry.id))) {
|
|
3028
|
+
await this.#saveAssetBaseline(record, entry.id, remoteProj.doc);
|
|
3029
|
+
}
|
|
3030
|
+
entry.lastSyncedHash = remoteHash;
|
|
3031
|
+
entry.status = "synced";
|
|
3032
|
+
delete entry.error;
|
|
3033
|
+
return;
|
|
3034
|
+
}
|
|
3035
|
+
await ensureFileMode(absPath, true);
|
|
3036
|
+
const localRawText = await readFile(absPath, "utf8");
|
|
3037
|
+
let localParsed;
|
|
3038
|
+
try {
|
|
3039
|
+
localParsed = parseAssetProjection(localRawText, {
|
|
3040
|
+
name: stripDataAssetSuffix(entry.name, entry.type),
|
|
3041
|
+
type: entry.type,
|
|
3042
|
+
});
|
|
3043
|
+
}
|
|
3044
|
+
catch (error) {
|
|
3045
|
+
entry.status = "error";
|
|
3046
|
+
entry.error = `Invalid JSON in ${entry.localPath}: ${error instanceof Error ? error.message : String(error)}`;
|
|
3047
|
+
return;
|
|
3048
|
+
}
|
|
3049
|
+
const localCanonical = buildAssetProjection({
|
|
3050
|
+
id: entry.id,
|
|
3051
|
+
name: localParsed.doc.name,
|
|
3052
|
+
type: entry.type,
|
|
3053
|
+
preload: localParsed.doc.preload,
|
|
3054
|
+
tags: localParsed.doc.tags,
|
|
3055
|
+
data: localParsed.doc.data,
|
|
3056
|
+
role: entry.role,
|
|
3057
|
+
sourceAssetId: entry.sourceAssetId,
|
|
3058
|
+
writable: entry.writable,
|
|
3059
|
+
});
|
|
3060
|
+
// Formatting-only edit in local JSON -> semantically identical to remote, zero RPC needed.
|
|
3061
|
+
if (localCanonical.text === remoteProj.text) {
|
|
3062
|
+
const rawHeader = (() => {
|
|
3063
|
+
try {
|
|
3064
|
+
return JSON.parse(localRawText)?.$pcbridge;
|
|
3065
|
+
}
|
|
3066
|
+
catch {
|
|
3067
|
+
return null;
|
|
3068
|
+
}
|
|
3069
|
+
})();
|
|
3070
|
+
if (rawHeader?.readonly === true) {
|
|
3071
|
+
await this.#writeManagedAssetFile(record, entry, remoteBytes, remoteHash);
|
|
3072
|
+
await this.#saveAssetBaseline(record, entry.id, remoteProj.doc);
|
|
3073
|
+
entry.lastSyncedHash = remoteHash;
|
|
3074
|
+
entry.remoteFileHash = remoteHash;
|
|
3075
|
+
entry.status = "synced";
|
|
3076
|
+
delete entry.error;
|
|
3077
|
+
return;
|
|
3078
|
+
}
|
|
3079
|
+
await this.#saveAssetBaseline(record, entry.id, remoteProj.doc);
|
|
3080
|
+
entry.lastSyncedHash = localSnap.hash;
|
|
3081
|
+
entry.remoteFileHash = localSnap.hash;
|
|
3082
|
+
entry.status = "synced";
|
|
3083
|
+
delete entry.error;
|
|
3084
|
+
return;
|
|
3085
|
+
}
|
|
3086
|
+
const baseDoc = await this.#loadAssetBaseline(record, entry.id);
|
|
3087
|
+
if (!baseDoc) {
|
|
3088
|
+
await this.#writeJsonConflict(record, `${entry.id}-${safeWorkspaceName(basename(entry.localPath), `asset-${entry.id}`)}`, localRawText, remoteProj.text, ["$no_baseline"]);
|
|
3089
|
+
entry.status = "conflict";
|
|
3090
|
+
entry.error = `Local and remote JSON asset ${entry.id} differ without a shared baseline.`;
|
|
3091
|
+
return;
|
|
3092
|
+
}
|
|
3093
|
+
const mergeResult = threeWayMergeAssetJson(entry.type, baseDoc, localParsed.doc, remoteProj.doc);
|
|
3094
|
+
if (mergeResult.conflicts.length > 0) {
|
|
3095
|
+
const conflictName = `${entry.id}-${safeWorkspaceName(basename(entry.localPath), `asset-${entry.id}`)}`;
|
|
3096
|
+
await this.#writeJsonConflict(record, conflictName, localRawText, remoteProj.text, mergeResult.conflicts);
|
|
3097
|
+
entry.status = "conflict";
|
|
3098
|
+
entry.error =
|
|
3099
|
+
`Conflicting changes on ${mergeResult.conflicts.join(", ")}. ` +
|
|
3100
|
+
`See tmp/conflicts/${conflictName}.*`;
|
|
3101
|
+
return;
|
|
3102
|
+
}
|
|
3103
|
+
const patch = diffAssetPatchOps(remoteProj.doc, mergeResult.merged);
|
|
3104
|
+
let finalDoc = mergeResult.merged;
|
|
3105
|
+
if (patch) {
|
|
3106
|
+
if (record.syncProgress) {
|
|
3107
|
+
record.syncProgress.assetId = entry.id;
|
|
3108
|
+
record.syncProgress.action = "uploading";
|
|
3109
|
+
}
|
|
3110
|
+
const patchResp = await this.#requestTarget(record.targetId, "bridge:patchAssetData", {
|
|
3111
|
+
assetId: entry.id,
|
|
3112
|
+
...(patch.name !== undefined ? { name: patch.name } : {}),
|
|
3113
|
+
...(patch.preload !== undefined ? { preload: patch.preload } : {}),
|
|
3114
|
+
...(patch.tags !== undefined ? { tags: patch.tags } : {}),
|
|
3115
|
+
sets: patch.sets,
|
|
3116
|
+
unsets: patch.unsets,
|
|
3117
|
+
}, 60000);
|
|
3118
|
+
if (!patchResp.ok) {
|
|
3119
|
+
entry.status = "local-change";
|
|
3120
|
+
entry.error = patchResp.error.message;
|
|
3121
|
+
return;
|
|
3122
|
+
}
|
|
3123
|
+
const updatedAssetObj = asObject(patchResp.data).asset;
|
|
3124
|
+
if (updatedAssetObj && typeof updatedAssetObj === "object" && !Array.isArray(updatedAssetObj)) {
|
|
3125
|
+
const updatedRemote = updatedAssetObj;
|
|
3126
|
+
record.remoteAssetsCache.set(entry.id, updatedRemote);
|
|
3127
|
+
entry.name = updatedRemote.name || finalDoc.name;
|
|
3128
|
+
entry.preload = updatedRemote.preload ?? finalDoc.preload;
|
|
3129
|
+
entry.tags = updatedRemote.tags ?? finalDoc.tags;
|
|
3130
|
+
const rebuilt = buildAssetProjection({
|
|
3131
|
+
id: entry.id,
|
|
3132
|
+
name: entry.name,
|
|
3133
|
+
type: entry.type,
|
|
3134
|
+
preload: entry.preload,
|
|
3135
|
+
tags: entry.tags,
|
|
3136
|
+
data: updatedRemote.data ?? finalDoc.data,
|
|
3137
|
+
role: entry.role,
|
|
3138
|
+
sourceAssetId: entry.sourceAssetId,
|
|
3139
|
+
writable: entry.writable,
|
|
3140
|
+
});
|
|
3141
|
+
finalDoc = rebuilt.doc;
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
const finalProj = buildAssetProjection({
|
|
3145
|
+
id: entry.id,
|
|
3146
|
+
name: finalDoc.name,
|
|
3147
|
+
type: entry.type,
|
|
3148
|
+
preload: finalDoc.preload,
|
|
3149
|
+
tags: finalDoc.tags,
|
|
3150
|
+
data: finalDoc.data,
|
|
3151
|
+
role: entry.role,
|
|
3152
|
+
sourceAssetId: entry.sourceAssetId,
|
|
3153
|
+
writable: entry.writable,
|
|
3154
|
+
});
|
|
3155
|
+
const finalBytes = Buffer.from(finalProj.text, "utf8");
|
|
3156
|
+
const finalHash = hashContent(finalBytes);
|
|
3157
|
+
entry.name = finalDoc.name;
|
|
3158
|
+
const nextDesiredFilename = safeAssetName(dataAssetFilename(finalDoc.name, entry.type), `asset-${entry.id}.${entry.type}.json`);
|
|
3159
|
+
const nextDesiredLocalPath = join(...entry.localFolderPath, nextDesiredFilename);
|
|
3160
|
+
if (nextDesiredLocalPath !== entry.localPath) {
|
|
3161
|
+
const nextAbs = this.#assetPath(record, nextDesiredLocalPath);
|
|
3162
|
+
if (!existsSync(nextAbs)) {
|
|
3163
|
+
await rename(absPath, nextAbs);
|
|
3164
|
+
entry.localPath = nextDesiredLocalPath;
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
if (localRawText !== finalProj.text || nextDesiredLocalPath !== old?.localPath) {
|
|
3168
|
+
await this.#writeManagedAssetFile(record, entry, finalBytes, finalHash);
|
|
3169
|
+
}
|
|
3170
|
+
else {
|
|
3171
|
+
await this.#recordLocalFile(record, entry, finalHash);
|
|
3172
|
+
}
|
|
3173
|
+
await this.#saveAssetBaseline(record, entry.id, finalProj.doc);
|
|
3174
|
+
entry.remoteFileHash = finalHash;
|
|
3175
|
+
entry.remoteFileSize = finalBytes.byteLength;
|
|
3176
|
+
entry.lastSyncedHash = finalHash;
|
|
3177
|
+
entry.status = "synced";
|
|
3178
|
+
delete entry.error;
|
|
3179
|
+
}
|
|
3180
|
+
async #reconcileAllScenes(record, activeScene, sceneList) {
|
|
3181
|
+
const activeId = activeScene ? String(activeScene.id) : null;
|
|
3182
|
+
if (activeScene) {
|
|
3183
|
+
record.activeSceneMemory = structuredClone(activeScene);
|
|
3184
|
+
await this.#reconcileActiveScene(record, activeScene);
|
|
3185
|
+
}
|
|
3186
|
+
if (!sceneList)
|
|
3187
|
+
return;
|
|
3188
|
+
const incomingSceneIds = new Set(sceneList.map((s) => String(s.id)));
|
|
3189
|
+
if (activeId)
|
|
3190
|
+
incomingSceneIds.add(activeId);
|
|
3191
|
+
// Quarantine deleted remote scenes.
|
|
3192
|
+
const deletionBatch = new Date().toISOString().replaceAll(":", "-");
|
|
3193
|
+
for (const [id, oldScene] of Object.entries(record.scenes)) {
|
|
3194
|
+
if (incomingSceneIds.has(id))
|
|
3195
|
+
continue;
|
|
3196
|
+
const oldAbs = this.#scenePath(record, oldScene.localPath);
|
|
3197
|
+
if (existsSync(oldAbs)) {
|
|
3198
|
+
await chmod(oldAbs, 0o644).catch(() => undefined);
|
|
3199
|
+
const dest = join(record.tmpDirectory, "trash", "remote", deletionBatch, `scene-${id}-${safeWorkspaceName(oldScene.localPath, `scene-${id}`)}`);
|
|
3200
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
3201
|
+
await rename(oldAbs, dest);
|
|
3202
|
+
this.#markSelfDeleted(record, oldAbs);
|
|
3203
|
+
}
|
|
3204
|
+
await this.#deleteSceneBaseline(record, id);
|
|
3205
|
+
delete record.scenes[id];
|
|
3206
|
+
}
|
|
3207
|
+
for (const summary of sceneList) {
|
|
3208
|
+
const id = String(summary.id);
|
|
3209
|
+
if (id === activeId)
|
|
3210
|
+
continue;
|
|
3211
|
+
await this.#reconcileInactiveScene(record, summary);
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
async #reconcileActiveScene(record, remoteScene) {
|
|
3215
|
+
const id = String(remoteScene.id);
|
|
3216
|
+
const old = record.scenes[id];
|
|
3217
|
+
const desiredFile = sceneLocalFilename(remoteScene.name || old?.name || `Scene-${id}`, id);
|
|
3218
|
+
// Lock any previously active scene to read-only if the Editor switched scenes.
|
|
3219
|
+
for (const other of Object.values(record.scenes)) {
|
|
3220
|
+
if (other.id !== id && other.active) {
|
|
3221
|
+
other.active = false;
|
|
3222
|
+
other.writable = false;
|
|
3223
|
+
const otherAbs = this.#scenePath(record, other.localPath);
|
|
3224
|
+
const otherBase = await this.#loadSceneBaseline(record, other.id);
|
|
3225
|
+
if (otherBase) {
|
|
3226
|
+
const inactiveProj = buildSceneProjection({
|
|
3227
|
+
id: other.id,
|
|
3228
|
+
name: otherBase.name,
|
|
3229
|
+
active: false,
|
|
3230
|
+
settings: otherBase.settings,
|
|
3231
|
+
entities: otherBase.entities,
|
|
3232
|
+
});
|
|
3233
|
+
const inactiveBytes = Buffer.from(inactiveProj.text, "utf8");
|
|
3234
|
+
const inactiveHash = hashContent(inactiveBytes);
|
|
3235
|
+
await this.#writeManagedSceneFile(record, other, inactiveBytes, inactiveHash);
|
|
3236
|
+
other.remoteHash = inactiveHash;
|
|
3237
|
+
other.lastSyncedHash = inactiveHash;
|
|
3238
|
+
}
|
|
3239
|
+
else if (existsSync(otherAbs)) {
|
|
3240
|
+
await ensureFileMode(otherAbs, false);
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
if (old && old.localPath !== desiredFile && existsSync(this.#scenePath(record, old.localPath))) {
|
|
3245
|
+
const oldAbs = this.#scenePath(record, old.localPath);
|
|
3246
|
+
const nextAbs = this.#scenePath(record, desiredFile);
|
|
3247
|
+
await ensureFileMode(oldAbs, true);
|
|
3248
|
+
if (!existsSync(nextAbs)) {
|
|
3249
|
+
await rename(oldAbs, nextAbs);
|
|
3250
|
+
this.#markSelfDeleted(record, oldAbs);
|
|
3251
|
+
}
|
|
3252
|
+
}
|
|
3253
|
+
const remoteProj = buildSceneProjection({
|
|
3254
|
+
id,
|
|
3255
|
+
name: remoteScene.name || "Scene",
|
|
3256
|
+
active: true,
|
|
3257
|
+
settings: remoteScene.settings,
|
|
3258
|
+
entities: remoteScene.entities,
|
|
3259
|
+
});
|
|
3260
|
+
const remoteBytes = Buffer.from(remoteProj.text, "utf8");
|
|
3261
|
+
const remoteHash = hashContent(remoteBytes);
|
|
3262
|
+
const entityCount = Object.keys(remoteProj.doc.entities).length;
|
|
3263
|
+
const sceneEntry = {
|
|
3264
|
+
id,
|
|
3265
|
+
name: remoteProj.doc.name,
|
|
3266
|
+
active: true,
|
|
3267
|
+
writable: true,
|
|
3268
|
+
localPath: desiredFile,
|
|
3269
|
+
modified: remoteScene.modified ?? old?.modified ?? null,
|
|
3270
|
+
entityCount,
|
|
3271
|
+
remoteHash,
|
|
3272
|
+
localHash: old?.localHash ?? null,
|
|
3273
|
+
lastSyncedHash: old?.lastSyncedHash ?? null,
|
|
3274
|
+
localFileSize: old?.localFileSize,
|
|
3275
|
+
localMtimeMs: old?.localMtimeMs,
|
|
3276
|
+
status: "synced",
|
|
3277
|
+
};
|
|
3278
|
+
record.scenes[id] = sceneEntry;
|
|
3279
|
+
await mkdir(record.scenesDirectory, { recursive: true });
|
|
3280
|
+
this.#ensureScenesWatcher(record);
|
|
3281
|
+
const absPath = this.#scenePath(record, desiredFile);
|
|
3282
|
+
if (!existsSync(absPath)) {
|
|
3283
|
+
await this.#writeManagedSceneFile(record, sceneEntry, remoteBytes, remoteHash);
|
|
3284
|
+
await this.#saveSceneBaseline(record, id, remoteProj.doc);
|
|
3285
|
+
sceneEntry.lastSyncedHash = remoteHash;
|
|
3286
|
+
return;
|
|
3287
|
+
}
|
|
3288
|
+
await ensureFileMode(absPath, true);
|
|
3289
|
+
const info = await stat(absPath);
|
|
3290
|
+
const cachedLocalHash = old?.localHash &&
|
|
3291
|
+
old.localFileSize === info.size &&
|
|
3292
|
+
old.localMtimeMs === info.mtimeMs
|
|
3293
|
+
? old.localHash
|
|
3294
|
+
: null;
|
|
3295
|
+
const localHash = cachedLocalHash || hashContent(await readFile(absPath));
|
|
3296
|
+
sceneEntry.localHash = localHash;
|
|
3297
|
+
sceneEntry.localFileSize = info.size;
|
|
3298
|
+
sceneEntry.localMtimeMs = info.mtimeMs;
|
|
3299
|
+
if (localHash === remoteHash) {
|
|
3300
|
+
if (!existsSync(this.#sceneBaselinePath(record, id))) {
|
|
3301
|
+
await this.#saveSceneBaseline(record, id, remoteProj.doc);
|
|
3302
|
+
}
|
|
3303
|
+
sceneEntry.lastSyncedHash = remoteHash;
|
|
3304
|
+
return;
|
|
3305
|
+
}
|
|
3306
|
+
const localRawText = await readFile(absPath, "utf8");
|
|
3307
|
+
const baseDoc = await this.#loadSceneBaseline(record, id);
|
|
3308
|
+
let localParsed;
|
|
3309
|
+
try {
|
|
3310
|
+
localParsed = parseSceneProjection(localRawText, { id, name: sceneEntry.name }, baseDoc?.entities);
|
|
3311
|
+
}
|
|
3312
|
+
catch (error) {
|
|
3313
|
+
sceneEntry.status = "error";
|
|
3314
|
+
sceneEntry.error = `Invalid scene JSON in scenes/${desiredFile}: ${error instanceof Error ? error.message : String(error)}`;
|
|
3315
|
+
record.lastError = sceneEntry.error;
|
|
3316
|
+
return;
|
|
3317
|
+
}
|
|
3318
|
+
const localCanonical = buildSceneProjection({
|
|
3319
|
+
id,
|
|
3320
|
+
name: localParsed.doc.name,
|
|
3321
|
+
active: true,
|
|
3322
|
+
settings: localParsed.doc.settings,
|
|
3323
|
+
entities: localParsed.doc.entities,
|
|
3324
|
+
});
|
|
3325
|
+
if (localCanonical.text === remoteProj.text) {
|
|
3326
|
+
const rawHeader = (() => {
|
|
3327
|
+
try {
|
|
3328
|
+
return JSON.parse(localRawText)?.$pcbridge;
|
|
3329
|
+
}
|
|
3330
|
+
catch {
|
|
3331
|
+
return null;
|
|
3332
|
+
}
|
|
3333
|
+
})();
|
|
3334
|
+
if (rawHeader?.active !== true || rawHeader?.readonly === true) {
|
|
3335
|
+
await this.#writeManagedSceneFile(record, sceneEntry, remoteBytes, remoteHash);
|
|
3336
|
+
await this.#saveSceneBaseline(record, id, remoteProj.doc);
|
|
3337
|
+
sceneEntry.lastSyncedHash = remoteHash;
|
|
3338
|
+
sceneEntry.remoteHash = remoteHash;
|
|
3339
|
+
return;
|
|
3340
|
+
}
|
|
3341
|
+
await this.#saveSceneBaseline(record, id, remoteProj.doc);
|
|
3342
|
+
sceneEntry.lastSyncedHash = localHash;
|
|
3343
|
+
sceneEntry.remoteHash = localHash;
|
|
3344
|
+
return;
|
|
3345
|
+
}
|
|
3346
|
+
if (!baseDoc) {
|
|
3347
|
+
const conflictName = `scene-${id}-${safeWorkspaceName(desiredFile, `scene-${id}`)}`;
|
|
3348
|
+
await this.#writeJsonConflict(record, conflictName, localRawText, remoteProj.text, ["$no_baseline"]);
|
|
3349
|
+
sceneEntry.status = "conflict";
|
|
3350
|
+
sceneEntry.error = `Local and remote scene ${id} differ without a shared baseline.`;
|
|
3351
|
+
return;
|
|
3352
|
+
}
|
|
3353
|
+
const mergeResult = threeWayMergeSceneJson(baseDoc, localParsed.doc, remoteProj.doc);
|
|
3354
|
+
if (mergeResult.conflicts.length > 0) {
|
|
3355
|
+
const conflictName = `scene-${id}-${safeWorkspaceName(desiredFile, `scene-${id}`)}`;
|
|
3356
|
+
await this.#writeJsonConflict(record, conflictName, localRawText, remoteProj.text, mergeResult.conflicts);
|
|
3357
|
+
sceneEntry.status = "conflict";
|
|
3358
|
+
sceneEntry.error =
|
|
3359
|
+
`Conflicting scene changes on ${mergeResult.conflicts.join(", ")}. ` +
|
|
3360
|
+
`See tmp/conflicts/${conflictName}.*`;
|
|
3361
|
+
return;
|
|
3362
|
+
}
|
|
3363
|
+
let finalDoc = mergeResult.merged;
|
|
3364
|
+
const patch = diffScenePatchOps(remoteProj.doc, mergeResult.merged);
|
|
3365
|
+
if (patch) {
|
|
3366
|
+
const patchResp = await this.#requestTarget(record.targetId, "bridge:patchScene", {
|
|
3367
|
+
sceneId: id,
|
|
3368
|
+
...(patch.name !== undefined ? { name: patch.name } : {}),
|
|
3369
|
+
creates: patch.creates,
|
|
3370
|
+
reparents: patch.reparents,
|
|
3371
|
+
updates: patch.updates,
|
|
3372
|
+
deletes: patch.deletes,
|
|
3373
|
+
settingsSets: patch.settingsSets,
|
|
3374
|
+
settingsUnsets: patch.settingsUnsets,
|
|
3375
|
+
}, 60000);
|
|
3376
|
+
if (!patchResp.ok) {
|
|
3377
|
+
sceneEntry.status = "error";
|
|
3378
|
+
sceneEntry.error = patchResp.error.message;
|
|
3379
|
+
record.lastError = sceneEntry.error;
|
|
3380
|
+
return;
|
|
3381
|
+
}
|
|
3382
|
+
const patchedSceneObj = asObject(patchResp.data).scene;
|
|
3383
|
+
if (patchedSceneObj && typeof patchedSceneObj === "object" && !Array.isArray(patchedSceneObj)) {
|
|
3384
|
+
const patchedRemote = patchedSceneObj;
|
|
3385
|
+
record.activeSceneMemory = structuredClone(patchedRemote);
|
|
3386
|
+
const rebuilt = buildSceneProjection({
|
|
3387
|
+
id,
|
|
3388
|
+
name: patchedRemote.name || finalDoc.name,
|
|
3389
|
+
active: true,
|
|
3390
|
+
settings: patchedRemote.settings,
|
|
3391
|
+
entities: patchedRemote.entities,
|
|
3392
|
+
});
|
|
3393
|
+
finalDoc = rebuilt.doc;
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
const finalProj = buildSceneProjection({
|
|
3397
|
+
id,
|
|
3398
|
+
name: finalDoc.name,
|
|
3399
|
+
active: true,
|
|
3400
|
+
settings: finalDoc.settings,
|
|
3401
|
+
entities: finalDoc.entities,
|
|
3402
|
+
});
|
|
3403
|
+
const finalBytes = Buffer.from(finalProj.text, "utf8");
|
|
3404
|
+
const finalHash = hashContent(finalBytes);
|
|
3405
|
+
const finalSceneFile = sceneLocalFilename(finalDoc.name, id);
|
|
3406
|
+
if (finalSceneFile !== sceneEntry.localPath) {
|
|
3407
|
+
const nextSceneAbs = this.#scenePath(record, finalSceneFile);
|
|
3408
|
+
if (!existsSync(nextSceneAbs)) {
|
|
3409
|
+
await rename(absPath, nextSceneAbs);
|
|
3410
|
+
sceneEntry.localPath = finalSceneFile;
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
sceneEntry.name = finalDoc.name;
|
|
3414
|
+
sceneEntry.entityCount = Object.keys(finalProj.doc.entities).length;
|
|
3415
|
+
sceneEntry.remoteHash = finalHash;
|
|
3416
|
+
sceneEntry.lastSyncedHash = finalHash;
|
|
3417
|
+
if (localRawText !== finalProj.text || finalSceneFile !== desiredFile) {
|
|
3418
|
+
await this.#writeManagedSceneFile(record, sceneEntry, finalBytes, finalHash);
|
|
3419
|
+
}
|
|
3420
|
+
await this.#saveSceneBaseline(record, id, finalProj.doc);
|
|
3421
|
+
}
|
|
3422
|
+
async #quarantineInactiveSceneEdit(record, sceneEntry, absPath) {
|
|
3423
|
+
const conflictPath = join(record.tmpDirectory, "conflicts", `scene-${sceneEntry.id}-${safeWorkspaceName(sceneEntry.localPath, `scene-${sceneEntry.id}`)}.inactive-scene-local`);
|
|
3424
|
+
await mkdir(dirname(conflictPath), { recursive: true });
|
|
3425
|
+
await copyFile(absPath, conflictPath);
|
|
3426
|
+
const baseline = await this.#loadSceneBaseline(record, sceneEntry.id);
|
|
3427
|
+
if (baseline) {
|
|
3428
|
+
const restored = buildSceneProjection({
|
|
3429
|
+
id: sceneEntry.id,
|
|
3430
|
+
name: baseline.name,
|
|
3431
|
+
active: false,
|
|
3432
|
+
settings: baseline.settings,
|
|
3433
|
+
entities: baseline.entities,
|
|
3434
|
+
});
|
|
3435
|
+
const bytes = Buffer.from(restored.text, "utf8");
|
|
3436
|
+
const hash = hashContent(bytes);
|
|
3437
|
+
await this.#writeManagedSceneFile(record, sceneEntry, bytes, hash);
|
|
3438
|
+
sceneEntry.lastSyncedHash = hash;
|
|
3439
|
+
}
|
|
3440
|
+
record.lastWarning =
|
|
3441
|
+
`Ignored a local edit to inactive Scene ${sceneEntry.id} (${sceneEntry.name}); ` +
|
|
3442
|
+
`run pcbridge scene open --id ${sceneEntry.id} before editing it. ` +
|
|
3443
|
+
`The local copy was saved to ${relative(record.directory, conflictPath)}.`;
|
|
3444
|
+
}
|
|
3445
|
+
async #reconcileInactiveScene(record, summary) {
|
|
3446
|
+
const id = String(summary.id);
|
|
3447
|
+
const old = record.scenes[id];
|
|
3448
|
+
const desiredFile = sceneLocalFilename(summary.name || old?.name || `Scene-${id}`, id);
|
|
3449
|
+
if (old && old.localPath !== desiredFile && existsSync(this.#scenePath(record, old.localPath))) {
|
|
3450
|
+
const oldAbs = this.#scenePath(record, old.localPath);
|
|
3451
|
+
const nextAbs = this.#scenePath(record, desiredFile);
|
|
3452
|
+
await ensureFileMode(oldAbs, true);
|
|
3453
|
+
if (!existsSync(nextAbs)) {
|
|
3454
|
+
await rename(oldAbs, nextAbs);
|
|
3455
|
+
this.#markSelfDeleted(record, oldAbs);
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
await mkdir(record.scenesDirectory, { recursive: true });
|
|
3459
|
+
this.#ensureScenesWatcher(record);
|
|
3460
|
+
const absPath = this.#scenePath(record, desiredFile);
|
|
3461
|
+
const modified = summary.modified ?? null;
|
|
3462
|
+
if (old && existsSync(absPath) && old.modified && modified && old.modified === modified) {
|
|
3463
|
+
const info = await stat(absPath);
|
|
3464
|
+
const localHash = (old.localFileSize === info.size && old.localMtimeMs === info.mtimeMs && old.localHash)
|
|
3465
|
+
? old.localHash
|
|
3466
|
+
: hashContent(await readFile(absPath));
|
|
3467
|
+
old.active = false;
|
|
3468
|
+
old.writable = false;
|
|
3469
|
+
old.localPath = desiredFile;
|
|
3470
|
+
old.name = summary.name || old.name;
|
|
3471
|
+
if (old.lastSyncedHash && localHash !== old.lastSyncedHash) {
|
|
3472
|
+
await this.#quarantineInactiveSceneEdit(record, old, absPath);
|
|
3473
|
+
}
|
|
3474
|
+
else {
|
|
3475
|
+
// Refresh header if upgrading from an older projection without active/readonly flags.
|
|
3476
|
+
const rawText = await readFile(absPath, "utf8");
|
|
3477
|
+
const rawHeader = (() => {
|
|
3478
|
+
try {
|
|
3479
|
+
return JSON.parse(rawText)?.$pcbridge;
|
|
3480
|
+
}
|
|
3481
|
+
catch {
|
|
3482
|
+
return null;
|
|
3483
|
+
}
|
|
3484
|
+
})();
|
|
3485
|
+
if (rawHeader?.active !== false || rawHeader?.readonly !== true) {
|
|
3486
|
+
const baseDoc = await this.#loadSceneBaseline(record, id);
|
|
3487
|
+
if (baseDoc) {
|
|
3488
|
+
const refreshed = buildSceneProjection({
|
|
3489
|
+
id,
|
|
3490
|
+
name: baseDoc.name,
|
|
3491
|
+
active: false,
|
|
3492
|
+
settings: baseDoc.settings,
|
|
3493
|
+
entities: baseDoc.entities,
|
|
3494
|
+
});
|
|
3495
|
+
const refreshedBytes = Buffer.from(refreshed.text, "utf8");
|
|
3496
|
+
const refreshedHash = hashContent(refreshedBytes);
|
|
3497
|
+
await this.#writeManagedSceneFile(record, old, refreshedBytes, refreshedHash);
|
|
3498
|
+
old.remoteHash = refreshedHash;
|
|
3499
|
+
old.lastSyncedHash = refreshedHash;
|
|
3500
|
+
return;
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
await ensureFileMode(absPath, false);
|
|
3504
|
+
}
|
|
3505
|
+
return;
|
|
3506
|
+
}
|
|
3507
|
+
if (old && existsSync(absPath) && old.lastSyncedHash) {
|
|
3508
|
+
const currentHash = hashContent(await readFile(absPath));
|
|
3509
|
+
if (currentHash !== old.lastSyncedHash) {
|
|
3510
|
+
await this.#quarantineInactiveSceneEdit(record, old, absPath);
|
|
3511
|
+
}
|
|
3512
|
+
}
|
|
3513
|
+
const resp = await this.#requestTarget(record.targetId, "bridge:readScene", { sceneId: id }, 30000);
|
|
3514
|
+
if (!resp.ok) {
|
|
3515
|
+
record.lastWarning = `Could not read inactive scene ${id}: ${resp.error.message}`;
|
|
3516
|
+
return;
|
|
3517
|
+
}
|
|
3518
|
+
const payload = asObject(resp.data);
|
|
3519
|
+
const proj = buildSceneProjection({
|
|
3520
|
+
id,
|
|
3521
|
+
name: payload.name || summary.name || `Scene ${id}`,
|
|
3522
|
+
active: false,
|
|
3523
|
+
settings: payload.settings,
|
|
3524
|
+
entities: payload.entities,
|
|
3525
|
+
});
|
|
3526
|
+
const bytes = Buffer.from(proj.text, "utf8");
|
|
3527
|
+
const hash = hashContent(bytes);
|
|
3528
|
+
const entry = {
|
|
3529
|
+
id,
|
|
3530
|
+
name: proj.doc.name,
|
|
3531
|
+
active: false,
|
|
3532
|
+
writable: false,
|
|
3533
|
+
localPath: desiredFile,
|
|
3534
|
+
modified: payload.modified ?? modified,
|
|
3535
|
+
entityCount: Object.keys(proj.doc.entities).length,
|
|
3536
|
+
remoteHash: hash,
|
|
3537
|
+
localHash: hash,
|
|
3538
|
+
lastSyncedHash: hash,
|
|
3539
|
+
status: "synced",
|
|
3540
|
+
};
|
|
3541
|
+
record.scenes[id] = entry;
|
|
3542
|
+
await this.#writeManagedSceneFile(record, entry, bytes, hash);
|
|
3543
|
+
await this.#saveSceneBaseline(record, id, proj.doc);
|
|
3544
|
+
}
|
|
3545
|
+
async #writeJsonConflict(record, baseName, localText, remoteText, conflictingPaths) {
|
|
3546
|
+
const conflictBase = join(record.tmpDirectory, "conflicts", baseName);
|
|
3547
|
+
await atomicWrite(`${conflictBase}.local`, localText);
|
|
3548
|
+
await atomicWrite(`${conflictBase}.remote`, remoteText);
|
|
3549
|
+
await atomicWrite(`${conflictBase}.conflict.json`, `${JSON.stringify({ conflictingPaths, detectedAt: new Date().toISOString() }, null, 2)}\n`);
|
|
3550
|
+
}
|
|
1919
3551
|
async #writeConflict(record, entry, localContent, remoteContent) {
|
|
1920
3552
|
if (record.syncProgress) {
|
|
1921
3553
|
record.syncProgress.assetId = entry.id;
|
|
@@ -1932,19 +3564,29 @@ export class WorkspaceManager {
|
|
|
1932
3564
|
#status(record) {
|
|
1933
3565
|
const entries = Object.values(record.index.entries);
|
|
1934
3566
|
const scripts = entries.filter((entry) => entry.type === "script");
|
|
1935
|
-
const
|
|
3567
|
+
const jsonAssets = entries.filter((entry) => DATA_JSON_TYPES.has(entry.type));
|
|
3568
|
+
const scenes = Object.values(record.scenes);
|
|
3569
|
+
const downloadable = entries.filter((entry) => entry.localPath && !this.#isTier1EagerWritable(entry) && entry.role !== "derived"
|
|
3570
|
+
? true
|
|
3571
|
+
: Boolean(entry.localPath && entry.type !== "script" && !DATA_JSON_TYPES.has(entry.type) && !TEXT_FILE_TYPES.has(entry.type)));
|
|
3572
|
+
const lazyCandidates = entries.filter((entry) => entry.localPath && !entry.downloaded);
|
|
3573
|
+
const downloadedNonScripts = entries.filter((entry) => entry.localPath && entry.type !== "script" && entry.downloaded);
|
|
3574
|
+
const settings = this.getSettings();
|
|
1936
3575
|
return {
|
|
1937
3576
|
available: true,
|
|
1938
3577
|
state: record.state,
|
|
1939
3578
|
rootDirectory: this.rootDir,
|
|
1940
3579
|
projectDirectory: record.directory,
|
|
1941
3580
|
assetsDirectory: record.assetsDirectory,
|
|
3581
|
+
scenesDirectory: record.scenesDirectory,
|
|
1942
3582
|
tmpDirectory: record.tmpDirectory,
|
|
1943
3583
|
projectId: record.projectId,
|
|
1944
3584
|
projectName: record.projectName,
|
|
1945
3585
|
branchId: record.branchId,
|
|
1946
3586
|
branchName: record.branchName,
|
|
1947
3587
|
connected: record.connected,
|
|
3588
|
+
eagerMaxMb: settings.eagerMaxMb,
|
|
3589
|
+
eagerMaxBytes: settings.eagerMaxBytes,
|
|
1948
3590
|
lastSyncedAt: record.lastSyncedAt,
|
|
1949
3591
|
lastError: record.lastError,
|
|
1950
3592
|
lastWarning: record.lastWarning,
|
|
@@ -1960,11 +3602,16 @@ export class WorkspaceManager {
|
|
|
1960
3602
|
folders: entries.filter((entry) => entry.type === "folder").length,
|
|
1961
3603
|
scripts: scripts.length,
|
|
1962
3604
|
scriptsSynced: scripts.filter((entry) => entry.status === "synced").length,
|
|
3605
|
+
jsonAssets: jsonAssets.length,
|
|
3606
|
+
jsonAssetsSynced: jsonAssets.filter((entry) => entry.status === "synced").length,
|
|
3607
|
+
scenes: scenes.length,
|
|
3608
|
+
scenesSynced: scenes.filter((scene) => scene.status === "synced").length,
|
|
1963
3609
|
localChanges: entries.filter((entry) => entry.status === "local-change").length,
|
|
1964
3610
|
remoteChanges: entries.filter((entry) => entry.status === "remote-change").length,
|
|
1965
|
-
conflicts: entries.filter((entry) => entry.status === "conflict").length
|
|
1966
|
-
|
|
1967
|
-
|
|
3611
|
+
conflicts: entries.filter((entry) => entry.status === "conflict").length +
|
|
3612
|
+
scenes.filter((scene) => scene.status === "conflict").length,
|
|
3613
|
+
lazyAssets: lazyCandidates.length || downloadable.filter((entry) => !entry.downloaded).length,
|
|
3614
|
+
downloadedAssets: downloadedNonScripts.length,
|
|
1968
3615
|
},
|
|
1969
3616
|
};
|
|
1970
3617
|
}
|