@xsok/dsh-enhanced 0.2.2-7 → 0.2.2-9
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/CHANGELOG.md +28 -0
- package/README.md +1 -15
- package/client.js +532 -21
- package/host/engine/archive.js +23 -7
- package/host/engine/index.js +18 -3
- package/host/engine/projcache.js +38 -1
- package/host/engine/sessions.js +35 -3
- package/host/schedule.js +30 -11
- package/host/sync.js +15 -0
- package/index.js +62 -0
- package/package.json +1 -1
package/host/engine/archive.js
CHANGED
|
@@ -104,16 +104,30 @@ export function pruneArchiveEvents(events, keepIds) {
|
|
|
104
104
|
return { events: kept, removed };
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* Apply the merged event table to this machine's archived set.
|
|
109
|
+
*
|
|
110
|
+
* An `active` event releases a local entry; an `archived` event from another
|
|
111
|
+
* machine adds one, so archiving propagates in both directions.
|
|
112
|
+
*/
|
|
108
113
|
export function applyArchiveEvents(archived, events) {
|
|
109
|
-
const
|
|
114
|
+
const own = archived instanceof Set ? archived : new Set(archived ?? []);
|
|
115
|
+
const kept = new Set();
|
|
110
116
|
const released = [];
|
|
111
|
-
|
|
117
|
+
const added = [];
|
|
118
|
+
for (const id of own) {
|
|
112
119
|
const event = events[id];
|
|
113
120
|
if (event !== undefined && event.state === 'active') released.push(id);
|
|
114
|
-
else kept.
|
|
121
|
+
else kept.add(id);
|
|
122
|
+
}
|
|
123
|
+
for (const [id, event] of Object.entries(events)) {
|
|
124
|
+
if (event?.state !== 'archived') continue;
|
|
125
|
+
if (own.has(id)) continue;
|
|
126
|
+
if (kept.has(id)) continue;
|
|
127
|
+
kept.add(id);
|
|
128
|
+
added.push(id);
|
|
115
129
|
}
|
|
116
|
-
return { kept, released };
|
|
130
|
+
return { kept: [...kept], released, added };
|
|
117
131
|
}
|
|
118
132
|
|
|
119
133
|
/**
|
|
@@ -128,7 +142,9 @@ export async function syncArchiveState(deps) {
|
|
|
128
142
|
const incoming = diffArchiveEvents(localArchived, previous, machineId);
|
|
129
143
|
const merged = mergeArchiveEvents(existing, incoming);
|
|
130
144
|
if (apply && Object.keys(incoming).length > 0) await writeArchiveEvents(stateDir, merged);
|
|
131
|
-
const { kept, released } = applyArchiveEvents(localArchived, merged);
|
|
145
|
+
const { kept, released, added } = applyArchiveEvents(localArchived, merged);
|
|
132
146
|
if (apply) await writeArchiveSnapshot(stateDir, machineId, kept);
|
|
133
|
-
|
|
147
|
+
// Any difference against the local set came from the share, so it needs a
|
|
148
|
+
// restart to show; a purely local change does not.
|
|
149
|
+
return { archived: kept, released, added, changed: released.length + added.length, emitted: incoming, events: merged };
|
|
134
150
|
}
|
package/host/engine/index.js
CHANGED
|
@@ -142,7 +142,7 @@ async function runSyncJsInner(deps) {
|
|
|
142
142
|
|
|
143
143
|
let sessions = { pushed: 0, pulled: 0, skipped: 0, created: 0, missing: 0, aborted: null };
|
|
144
144
|
let prune = { quarantined: 0, hardDeleted: 0, sharedDeleted: 0, kept: 0, throttled: 0, quarantinePurged: 0 };
|
|
145
|
-
let archive = { archived: [], released: [], events: {} };
|
|
145
|
+
let archive = { archived: [], released: [], added: [], changed: 0, events: {} };
|
|
146
146
|
let workspace = { local: null, shared: null, missing: [] };
|
|
147
147
|
let projcache = { parsed: 0, updated: 0, mirrored: 0, untouched: 0 };
|
|
148
148
|
let pluginList = { count: 0, file: '' };
|
|
@@ -164,6 +164,9 @@ async function runSyncJsInner(deps) {
|
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
+
// A session that was created but never used carries a blank projection shard;
|
|
168
|
+
// uploading it hides the conversation on every machine that later pulls it.
|
|
169
|
+
// The session phase applies that guard while it already holds the scan.
|
|
167
170
|
sessions = await step('sessions', () => syncSessions({
|
|
168
171
|
localRoot: localSessions,
|
|
169
172
|
sharedRoot: sharedSessions,
|
|
@@ -171,6 +174,8 @@ async function runSyncJsInner(deps) {
|
|
|
171
174
|
machineId,
|
|
172
175
|
resolveCwd,
|
|
173
176
|
apply,
|
|
177
|
+
cacheDir: path.join(dshHome, 'storages', 'session_projcache', 'sessions'),
|
|
178
|
+
guardStateFile: path.join(dshHome, 'dsh-enhanced', 'blank-guard-state.json'),
|
|
174
179
|
journalFile: path.join(dshHome, 'dsh-enhanced', 'delete-journal.json'),
|
|
175
180
|
}));
|
|
176
181
|
|
|
@@ -229,6 +234,13 @@ async function runSyncJsInner(deps) {
|
|
|
229
234
|
const merged = new Set([...own, ...effective].filter((id) => id && !released.has(id)));
|
|
230
235
|
doc.global.archivedSessionIds = [...merged].sort();
|
|
231
236
|
}
|
|
237
|
+
// What the merge actually produced for this machine decides whether the list
|
|
238
|
+
// changes: it covers both archive events and ids arriving via workspace.json.
|
|
239
|
+
const finalLocalArchived = new Set(workspace.local.global?.archivedSessionIds ?? []);
|
|
240
|
+
let mergedArchiveChanged = 0;
|
|
241
|
+
for (const id of finalLocalArchived) if (!archivedBefore.has(id)) mergedArchiveChanged += 1;
|
|
242
|
+
for (const id of archivedBefore) if (!finalLocalArchived.has(id)) mergedArchiveChanged += 1;
|
|
243
|
+
archive.changed = mergedArchiveChanged;
|
|
232
244
|
if (apply) {
|
|
233
245
|
if (validWorkspaceDoc(workspace.local)) {
|
|
234
246
|
await writeJson(path.join(dshHome, 'storages', 'workspace.json'), workspace.local);
|
|
@@ -250,6 +262,7 @@ async function runSyncJsInner(deps) {
|
|
|
250
262
|
machineId,
|
|
251
263
|
force: !apply,
|
|
252
264
|
apply,
|
|
265
|
+
skipIds: sessions.blankGuard?.skipIds ?? new Set(),
|
|
253
266
|
}));
|
|
254
267
|
|
|
255
268
|
pluginList = await step('plugins', () => (apply
|
|
@@ -292,8 +305,9 @@ async function runSyncJsInner(deps) {
|
|
|
292
305
|
prune: { quarantined: prune.quarantined, hardDeleted: prune.hardDeleted, sharedDeleted: prune.sharedDeleted, kept: prune.kept, throttled: prune.throttled, quarantinePurged: prune.quarantinePurged ?? 0 },
|
|
293
306
|
workspace: { local: Object.keys(workspace.local?.tables?.workspaces ?? {}).length, shared: Object.keys(workspace.shared?.tables?.workspaces ?? {}).length, skipped: workspace.skipped ?? null, error: workspace.error ?? null },
|
|
294
307
|
titleMerge: projcache,
|
|
308
|
+
blankGuard: { skipped: sessions.blankGuard?.skipped ?? 0, repaired: (sessions.blankGuard?.repaired ?? 0) + (sessions.blankRepaired ?? 0) },
|
|
295
309
|
plugins: pluginList.count,
|
|
296
|
-
archive: { released: archive.released.length, archived: archive.archived.length, eventsPruned: prunedEvents.removed },
|
|
310
|
+
archive: { released: archive.released.length, archived: archive.archived.length, changed: archive.changed ?? 0, eventsPruned: prunedEvents.removed },
|
|
297
311
|
missing: { sessions: sessions.missing ?? 0, groups: missingGroups.length },
|
|
298
312
|
paths: { created: sessions.created ?? 0, failed: sessions.missing ?? 0 },
|
|
299
313
|
};
|
|
@@ -326,8 +340,9 @@ async function runSyncJsInner(deps) {
|
|
|
326
340
|
},
|
|
327
341
|
workspace: { local: Object.keys(workspace.local?.tables?.workspaces ?? {}).length, shared: Object.keys(workspace.shared?.tables?.workspaces ?? {}).length, skipped: workspace.skipped ?? null, error: workspace.error ?? null },
|
|
328
342
|
titleMerge: projcache,
|
|
343
|
+
blankGuard: { skipped: sessions.blankGuard?.skipped ?? 0, repaired: (sessions.blankGuard?.repaired ?? 0) + (sessions.blankRepaired ?? 0) },
|
|
329
344
|
plugins: pluginList.count,
|
|
330
|
-
archive: { released: archive.released.length, archived: archive.archived.length, eventsPruned: prunedEvents.removed },
|
|
345
|
+
archive: { released: archive.released.length, archived: archive.archived.length, changed: archive.changed ?? 0, eventsPruned: prunedEvents.removed },
|
|
331
346
|
missing: { sessions: sessions.missing ?? 0, groups: missingGroups.length },
|
|
332
347
|
paths: { created: sessions.created ?? 0, failed: sessions.missing ?? 0 },
|
|
333
348
|
};
|
package/host/engine/projcache.js
CHANGED
|
@@ -56,6 +56,13 @@ function setTitle(doc, winner) {
|
|
|
56
56
|
record.rows.title = winner;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/** Whether one shard still claims its session was never used. */
|
|
60
|
+
function isBlank(doc) {
|
|
61
|
+
if (doc === null || typeof doc !== 'object') return false;
|
|
62
|
+
const record = doc.record !== undefined && doc.record !== null ? doc.record : doc;
|
|
63
|
+
return record?.rows?.sessionListMetadata?.val?.blank === true;
|
|
64
|
+
}
|
|
65
|
+
|
|
59
66
|
/** Map of session id -> { file, mtime } for one shard directory. */
|
|
60
67
|
async function indexShards(dir) {
|
|
61
68
|
const map = new Map();
|
|
@@ -83,7 +90,17 @@ async function indexShards(dir) {
|
|
|
83
90
|
* @returns counters for the run summary.
|
|
84
91
|
*/
|
|
85
92
|
export async function mergeProjcacheTitles(deps) {
|
|
86
|
-
const {
|
|
93
|
+
const {
|
|
94
|
+
localDir,
|
|
95
|
+
sharedDir,
|
|
96
|
+
stateDir,
|
|
97
|
+
machineId,
|
|
98
|
+
force = false,
|
|
99
|
+
apply = true,
|
|
100
|
+
// Sessions the blank-session guard keeps out of the share this run: their
|
|
101
|
+
// shard must not be mirrored either, or the empty state would still travel.
|
|
102
|
+
skipIds = new Set(),
|
|
103
|
+
} = deps;
|
|
87
104
|
const localIndex = await indexShards(localDir);
|
|
88
105
|
const sharedIndex = await indexShards(sharedDir);
|
|
89
106
|
if (localIndex.size === 0 && sharedIndex.size === 0) {
|
|
@@ -101,6 +118,10 @@ export async function mergeProjcacheTitles(deps) {
|
|
|
101
118
|
let untouched = 0;
|
|
102
119
|
|
|
103
120
|
for (const id of new Set([...localIndex.keys(), ...sharedIndex.keys()])) {
|
|
121
|
+
if (skipIds.has(id)) {
|
|
122
|
+
untouched += 1;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
104
125
|
const localEntry = localIndex.get(id);
|
|
105
126
|
const sharedEntry = sharedIndex.get(id);
|
|
106
127
|
const currentLocal = localEntry === undefined ? -1 : localEntry.mtime;
|
|
@@ -144,6 +165,22 @@ export async function mergeProjcacheTitles(deps) {
|
|
|
144
165
|
} else {
|
|
145
166
|
mirrored += 1;
|
|
146
167
|
}
|
|
168
|
+
} else if (localEntry !== undefined && sharedEntry !== undefined
|
|
169
|
+
&& isBlank(sharedDoc) && !isBlank(localDoc)) {
|
|
170
|
+
// The local shard says the session has a conversation while the share still
|
|
171
|
+
// says it is empty: overwrite the share, or every other machine that pulls
|
|
172
|
+
// it keeps hiding the conversation.
|
|
173
|
+
if (apply) {
|
|
174
|
+
try {
|
|
175
|
+
await fsp.copyFile(localEntry.file, sharedEntry.file);
|
|
176
|
+
await fsp.utimes(sharedEntry.file, new Date(localEntry.mtime), new Date(localEntry.mtime)).catch(() => {});
|
|
177
|
+
mirrored += 1;
|
|
178
|
+
} catch {
|
|
179
|
+
// Retried next round.
|
|
180
|
+
}
|
|
181
|
+
} else {
|
|
182
|
+
mirrored += 1;
|
|
183
|
+
}
|
|
147
184
|
}
|
|
148
185
|
}
|
|
149
186
|
|
package/host/engine/sessions.js
CHANGED
|
@@ -9,6 +9,7 @@ import { promises as fsp } from 'node:fs';
|
|
|
9
9
|
import { randomUUID } from 'node:crypto';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { scanSessions, projectKey } from './scan.js';
|
|
12
|
+
import { buildBlankGuard, repairPulledSessions } from './blank-guard.js';
|
|
12
13
|
import { lastContentSeq, readSessionFile, rewriteCwd, writeSessionFile } from './session.js';
|
|
13
14
|
import {
|
|
14
15
|
SESSION_LEDGER,
|
|
@@ -143,6 +144,8 @@ export async function syncSessions(deps) {
|
|
|
143
144
|
skipIds = new Set(),
|
|
144
145
|
apply = true,
|
|
145
146
|
journalFile = null,
|
|
147
|
+
cacheDir = null,
|
|
148
|
+
guardStateFile = null,
|
|
146
149
|
sharedTrashRoot = path.join(path.dirname(sharedRoot), 'trash'),
|
|
147
150
|
} = deps;
|
|
148
151
|
|
|
@@ -255,9 +258,23 @@ export async function syncSessions(deps) {
|
|
|
255
258
|
}
|
|
256
259
|
|
|
257
260
|
// 3. Push local sessions the share does not have (or has in an older state).
|
|
261
|
+
// A session that was created but never used carries a blank projection
|
|
262
|
+
// shard; letting it reach the share hides the conversation on every machine
|
|
263
|
+
// that later pulls it, so the guard keeps it (and its shard) out. The scan
|
|
264
|
+
// above is reused: no second walk of the sessions root.
|
|
265
|
+
let blankGuard = { skipIds: new Set(), skipped: 0, repaired: 0 };
|
|
266
|
+
if (cacheDir !== null) {
|
|
267
|
+
try {
|
|
268
|
+
blankGuard = await buildBlankGuard({ sessions: local, cacheDir, apply, stateFile: guardStateFile });
|
|
269
|
+
} catch {
|
|
270
|
+
blankGuard = { skipIds: new Set(), skipped: 0, repaired: 0 };
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const guardedIds = new Set([...skipIds, ...blankGuard.skipIds]);
|
|
274
|
+
|
|
258
275
|
for (const [id, entry] of local) {
|
|
259
276
|
if (ledger.deleted[id] !== undefined) continue;
|
|
260
|
-
if (
|
|
277
|
+
if (guardedIds.has(id)) {
|
|
261
278
|
skipped += 1;
|
|
262
279
|
continue;
|
|
263
280
|
}
|
|
@@ -308,9 +325,10 @@ export async function syncSessions(deps) {
|
|
|
308
325
|
// 4. Pull shared sessions this machine lacks or holds in an older state.
|
|
309
326
|
let created = 0;
|
|
310
327
|
let missing = 0;
|
|
328
|
+
const pulledLocal = [];
|
|
311
329
|
for (const [id, entry] of refreshedShare) {
|
|
312
330
|
if (ledger.deleted[id] !== undefined) continue;
|
|
313
|
-
if (
|
|
331
|
+
if (guardedIds.has(id)) continue;
|
|
314
332
|
const localEntry = local.get(id);
|
|
315
333
|
if (localEntry !== undefined) {
|
|
316
334
|
const sharedSeq = await lastContentSeq(entry.file);
|
|
@@ -340,6 +358,7 @@ export async function syncSessions(deps) {
|
|
|
340
358
|
await writeSessionFile(target, texts);
|
|
341
359
|
const seconds = entry.mtime / 1000;
|
|
342
360
|
await fsp.utimes(target, seconds, seconds).catch(() => {});
|
|
361
|
+
pulledLocal.push({ id, file: target });
|
|
343
362
|
}
|
|
344
363
|
pulled += 1;
|
|
345
364
|
if (pulledIds.length < 300) pulledIds.push(id);
|
|
@@ -348,6 +367,19 @@ export async function syncSessions(deps) {
|
|
|
348
367
|
}
|
|
349
368
|
}
|
|
350
369
|
|
|
370
|
+
// The regular guard ran before these sessions existed locally, so a shard that
|
|
371
|
+
// still says "blank" is repaired now, in the same run, before the config phase
|
|
372
|
+
// pushes it back to the share.
|
|
373
|
+
let blankRepaired = 0;
|
|
374
|
+
if (apply && pulledLocal.length > 0) {
|
|
375
|
+
try {
|
|
376
|
+
const fixed = await repairPulledSessions({ items: pulledLocal, cacheDir, apply });
|
|
377
|
+
blankRepaired = fixed.repaired;
|
|
378
|
+
} catch {
|
|
379
|
+
blankRepaired = 0;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
351
383
|
// 5. Remember what this machine holds so the next run can spot deletions.
|
|
352
384
|
const keys = {};
|
|
353
385
|
for (const [id, entry] of (await scanSessions(localRoot))) keys[id] = new Date(entry.mtime).toISOString();
|
|
@@ -359,5 +391,5 @@ export async function syncSessions(deps) {
|
|
|
359
391
|
await writeJsonAtomic(legacyFile, { version: 1, deleted: {} });
|
|
360
392
|
}
|
|
361
393
|
|
|
362
|
-
return { pushed, pulled, skipped, revived, tombstoned, created, missing, failed, trashed: Object.keys(ledger.deleted).length, pushedIds, pulledIds };
|
|
394
|
+
return { pushed, pulled, skipped, revived, tombstoned, created, missing, failed, trashed: Object.keys(ledger.deleted).length, pushedIds, pulledIds, blankGuard, blankRepaired };
|
|
363
395
|
}
|
package/host/schedule.js
CHANGED
|
@@ -80,11 +80,22 @@ export function installSyncScheduler(ctx, deps) {
|
|
|
80
80
|
let retryTimer = null;
|
|
81
81
|
let disposed = false;
|
|
82
82
|
let running = false;
|
|
83
|
+
// Subscribers are told about start and finish so a reader can follow the run
|
|
84
|
+
// without polling.
|
|
85
|
+
const watchers = new Set();
|
|
86
|
+
const notifyWatchers = () => {
|
|
87
|
+
for (const watcher of [...watchers]) {
|
|
88
|
+
try {
|
|
89
|
+
watcher();
|
|
90
|
+
} catch {
|
|
91
|
+
// A broken watcher must not affect the run.
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
83
95
|
let cooldownUntil = 0;
|
|
84
96
|
let failures = 0;
|
|
85
97
|
let paused = false;
|
|
86
98
|
let pausedAt = null;
|
|
87
|
-
let startupTimer = null;
|
|
88
99
|
let lastIntervalAt = 0;
|
|
89
100
|
let lastDailyKey = '';
|
|
90
101
|
|
|
@@ -110,7 +121,11 @@ export function installSyncScheduler(ctx, deps) {
|
|
|
110
121
|
*/
|
|
111
122
|
async function restartForNewSessions(record, context) {
|
|
112
123
|
const pulled = Number(record?.summary?.sessions?.pulled) || Number(record?.summary?.sessions?.created) || 0;
|
|
113
|
-
|
|
124
|
+
const repaired = Number(record?.summary?.blankGuard?.repaired) || 0;
|
|
125
|
+
const archiveChanged = Number(record?.summary?.archive?.changed) || 0;
|
|
126
|
+
// A repaired shard or a share-side archive change alters the list just like a
|
|
127
|
+
// new session does.
|
|
128
|
+
if (pulled <= 0 && repaired <= 0 && archiveChanged <= 0) return false;
|
|
114
129
|
const { paths, settings, agents } = context;
|
|
115
130
|
const busy = (agents?.list?.() ?? []).some((agent) => agent?.status === 'running');
|
|
116
131
|
if (busy) {
|
|
@@ -136,7 +151,7 @@ async function restartForNewSessions(record, context) {
|
|
|
136
151
|
} catch {
|
|
137
152
|
// A missing marker only means the next run may restart sooner.
|
|
138
153
|
}
|
|
139
|
-
trace(`restarting for ${String(pulled)}
|
|
154
|
+
trace(`restarting for ${String(pulled)} pulled / ${String(repaired)} repaired / ${String(archiveChanged)} archive`);
|
|
140
155
|
await restartApplication(paths);
|
|
141
156
|
return true;
|
|
142
157
|
}
|
|
@@ -177,6 +192,7 @@ async function autoRun(reason) {
|
|
|
177
192
|
return false;
|
|
178
193
|
}
|
|
179
194
|
running = true;
|
|
195
|
+
notifyWatchers();
|
|
180
196
|
trace(`autoRun ${reason}: start`);
|
|
181
197
|
try {
|
|
182
198
|
const record = await runSync({ paths, settings, agents }, { probe: false });
|
|
@@ -213,6 +229,7 @@ async function autoRun(reason) {
|
|
|
213
229
|
note(`${reason}: ${String(error?.message ?? error)}${paused ? ', auto sync paused' : ''}`, 'error');
|
|
214
230
|
} finally {
|
|
215
231
|
running = false;
|
|
232
|
+
notifyWatchers();
|
|
216
233
|
cooldownUntil = Date.now() + Math.max(1, Number(settings.syncCooldownMinutes) || 5) * 60_000;
|
|
217
234
|
}
|
|
218
235
|
}
|
|
@@ -254,6 +271,12 @@ async function autoRun(reason) {
|
|
|
254
271
|
|
|
255
272
|
const status = () => ({ paused, failures, pausedAt, cooldownUntil, running });
|
|
256
273
|
|
|
274
|
+
/** Wake every waiting reader; the returned function unsubscribes. */
|
|
275
|
+
const subscribe = (watcher) => {
|
|
276
|
+
watchers.add(watcher);
|
|
277
|
+
return () => watchers.delete(watcher);
|
|
278
|
+
};
|
|
279
|
+
|
|
257
280
|
const resume = () => {
|
|
258
281
|
failures = 0;
|
|
259
282
|
paused = false;
|
|
@@ -263,12 +286,8 @@ async function autoRun(reason) {
|
|
|
263
286
|
return status();
|
|
264
287
|
};
|
|
265
288
|
|
|
266
|
-
//
|
|
267
|
-
//
|
|
268
|
-
// costs nothing.
|
|
269
|
-
startupTimer = setTimeout(() => {
|
|
270
|
-
void autoRun('startup');
|
|
271
|
-
}, 5000);
|
|
289
|
+
// Launch-time catch-up is driven by the client, so the reader sees the restart
|
|
290
|
+
// countdown before the window closes. Host-side runs stay on idle/interval/daily.
|
|
272
291
|
|
|
273
292
|
const statusListener = ctx.on('agent/status', (payload) => {
|
|
274
293
|
trace(`agent/status=${String(payload?.status)}`);
|
|
@@ -288,9 +307,9 @@ async function autoRun(reason) {
|
|
|
288
307
|
if (tick !== null) clearInterval(tick);
|
|
289
308
|
if (idleTimer !== null) clearTimeout(idleTimer);
|
|
290
309
|
if (retryTimer !== null) clearTimeout(retryTimer);
|
|
291
|
-
if (startupTimer !== null) clearTimeout(startupTimer);
|
|
292
310
|
if (typeof statusListener === 'function') statusListener();
|
|
311
|
+
watchers.clear();
|
|
293
312
|
};
|
|
294
313
|
|
|
295
|
-
return { dispose, status, resume };
|
|
314
|
+
return { dispose, status, resume, subscribe };
|
|
296
315
|
}
|
package/host/sync.js
CHANGED
|
@@ -195,6 +195,12 @@ function logLines(summary, transport, titleMap = new Map()) {
|
|
|
195
195
|
...(summary.sessions?.pushedIds ?? []).map((id) => `推送上云:${titleMap.get(id) ?? id}`),
|
|
196
196
|
...(summary.sessions?.pulledIds ?? []).map((id) => `从云取回:${titleMap.get(id) ?? id}`),
|
|
197
197
|
]);
|
|
198
|
+
const guardSkipped = Number(summary.blankGuard?.skipped) || 0;
|
|
199
|
+
const guardRepaired = Number(summary.blankGuard?.repaired) || 0;
|
|
200
|
+
if (guardSkipped > 0 || guardRepaired > 0) {
|
|
201
|
+
const repaired = guardRepaired > 0 ? `,修复过期缓存 ${counts(guardRepaired)} 个` : '';
|
|
202
|
+
push(`空白会话:跳过 ${counts(guardSkipped)} 个${repaired}`);
|
|
203
|
+
}
|
|
198
204
|
push(configCopied === 0 && attachCopied === 0
|
|
199
205
|
? '配置附件:双端一致,无更新'
|
|
200
206
|
: `配置附件:更新配置 ${counts(configCopied)} 个、附件 ${counts(attachCopied)} 个`,
|
|
@@ -500,7 +506,16 @@ async function appendHistory(file, record) {
|
|
|
500
506
|
paths: record.summary?.paths ?? null,
|
|
501
507
|
missing: record.summary?.missing ?? null,
|
|
502
508
|
log: Array.isArray(record.log) ? record.log.slice(-60) : [],
|
|
509
|
+
// File lists per log line, bounded so the history file stays small.
|
|
510
|
+
details: Array.isArray(record.details)
|
|
511
|
+
? record.details.map((files) => (Array.isArray(files) ? files.slice(0, 40) : []))
|
|
512
|
+
: [],
|
|
503
513
|
});
|
|
514
|
+
// Only the newest runs keep their file lists; older rows stay text-only.
|
|
515
|
+
const DETAIL_KEEP = 20;
|
|
516
|
+
for (let i = DETAIL_KEEP; i < list.length; i += 1) {
|
|
517
|
+
if (Object.prototype.hasOwnProperty.call(list[i], 'details')) delete list[i].details;
|
|
518
|
+
}
|
|
504
519
|
await writeJson(file, pruneHistory(list));
|
|
505
520
|
}
|
|
506
521
|
|
package/index.js
CHANGED
|
@@ -79,6 +79,27 @@ export function apply(ctx, config = {}) {
|
|
|
79
79
|
}
|
|
80
80
|
})();
|
|
81
81
|
|
|
82
|
+
// Bumped for every committed user message; the composer badge watches it to
|
|
83
|
+
// know the reader sent something and the finished-sync line may go away.
|
|
84
|
+
let userMessageSeq = 0;
|
|
85
|
+
const watchWaiters = new Set();
|
|
86
|
+
try {
|
|
87
|
+
ctx.effect(() => ctx.on('session/event', (session, event) => {
|
|
88
|
+
if (event?.type !== 'user/message') return;
|
|
89
|
+
userMessageSeq += 1;
|
|
90
|
+
// Wake the waiting call so the client sees the new count immediately.
|
|
91
|
+
for (const wake of [...watchWaiters]) {
|
|
92
|
+
try {
|
|
93
|
+
wake();
|
|
94
|
+
} catch {
|
|
95
|
+
// A broken waiter must not affect the others.
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}), 'dsh-enhanced: user message counter');
|
|
99
|
+
} catch {
|
|
100
|
+
// Without the event the line simply clears on the next sync instead.
|
|
101
|
+
}
|
|
102
|
+
|
|
82
103
|
const dependencies = (settings) => ({
|
|
83
104
|
paths,
|
|
84
105
|
settings,
|
|
@@ -148,8 +169,49 @@ export function apply(ctx, config = {}) {
|
|
|
148
169
|
const history = await readSyncHistory({ paths, settings });
|
|
149
170
|
return { settings: { syncEnabled: settings.syncEnabled, syncDir: settings.syncDir, syncScript: settings.syncScript, syncMachineId: settings.syncMachineId, syncSkipAttachments: settings.syncSkipAttachments }, target, state, history, auto: scheduler.status(), running: live };
|
|
150
171
|
}
|
|
172
|
+
case 'sync.watch': {
|
|
173
|
+
// Resolve as soon as the automatic run starts or stops (or after 25 s),
|
|
174
|
+
// so the client follows the state without a polling timer.
|
|
175
|
+
const current = () => {
|
|
176
|
+
const live = typeof ctx.get('agents')?.list === 'function'
|
|
177
|
+
? ctx.get('agents').list().filter((agent) => agent?.status === 'running').length
|
|
178
|
+
: 0;
|
|
179
|
+
return { auto: scheduler.status(), running: live, userSeq: userMessageSeq };
|
|
180
|
+
};
|
|
181
|
+
return await new Promise((resolve) => {
|
|
182
|
+
let settled = false;
|
|
183
|
+
let unsubscribe = () => {};
|
|
184
|
+
const finish = () => {
|
|
185
|
+
if (settled) return;
|
|
186
|
+
settled = true;
|
|
187
|
+
unsubscribe();
|
|
188
|
+
watchWaiters.delete(finish);
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
resolve(current());
|
|
191
|
+
};
|
|
192
|
+
const timer = setTimeout(finish, 25_000);
|
|
193
|
+
unsubscribe = scheduler.subscribe(finish);
|
|
194
|
+
watchWaiters.add(finish);
|
|
195
|
+
signal?.addEventListener?.('abort', finish, { once: true });
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
case 'sync.auto': {
|
|
199
|
+
const live = typeof ctx.get('agents')?.list === 'function'
|
|
200
|
+
? ctx.get('agents').list().filter((agent) => agent?.status === 'running').length
|
|
201
|
+
: 0;
|
|
202
|
+
return { auto: scheduler.status(), running: live };
|
|
203
|
+
}
|
|
151
204
|
case 'sync.probe':
|
|
152
205
|
case 'sync.run': {
|
|
206
|
+
// A running turn is writing session files; syncing then risks reading a
|
|
207
|
+
// half-written log. The launch-time call asks for quiet so it can skip.
|
|
208
|
+
if (action === 'sync.run') {
|
|
209
|
+
const busy = (ctx.get('agents')?.list?.() ?? []).some((agent) => agent?.status === 'running');
|
|
210
|
+
if (busy) {
|
|
211
|
+
if (request?.quiet === true) return { skipped: 'busy' };
|
|
212
|
+
throw failure('sync-task-running', '有会话正在运行,稍后再同步。');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
153
215
|
const settings = await readSettings(paths);
|
|
154
216
|
return runSync({ paths, settings, agents: ctx.get('agents'), registry: ctx.workspaceRegistry }, { probe: action === 'sync.probe' });
|
|
155
217
|
}
|