@witbitz/sdk 4.3.0 → 4.5.0
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 +2 -2
- package/a2aCore.js +41 -5
- package/accountErase.js +15 -4
- package/accountIndexDoc.js +24 -7
- package/accountRecord.js +6 -2
- package/accountStores.js +21 -5
- package/acctV2App.js +111 -12
- package/acctV2Client.js +11 -1
- package/acctV2UiCore.js +27 -7
- package/agentDoorTools.js +28 -0
- package/awsKey.js +3 -1
- package/backupRecord.js +3 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +101 -0
- package/codeCache.js +173 -0
- package/codeCloud.js +2 -2
- package/codeComputers.js +9 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeModes.js +2 -0
- package/codeProgress.js +54 -0
- package/codeSent.js +109 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +46 -5
- package/connections.js +37 -20
- package/decrypt.html +69 -9
- package/deviceAttest.js +9 -3
- package/eraseFile.js +15 -0
- package/idb.js +19 -3
- package/idbSeal.js +5 -2
- package/inviteReceive.js +44 -0
- package/inviteSend.js +8 -2
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +122 -43
- package/laneAssociation.js +78 -0
- package/laneConfig.js +4 -3
- package/laneLinkCore.js +9 -0
- package/ledgerView.js +30 -4
- package/manifest.json +112 -87
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/offlineBundle.js +21 -0
- package/opRouting.js +10 -0
- package/package.json +27 -2
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/protectedLocal.js +52 -13
- package/reactionHolders.js +86 -0
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomIntake.js +324 -0
- package/roomName.js +1 -1
- package/roomRoster.js +30 -7
- package/rosterCount.js +6 -3
- package/scheduleNext.js +60 -0
- package/sdkA2A.js +200 -42
- package/sdkAccount.js +88 -18
- package/sdkAccountDoc.js +13 -5
- package/sdkAccountSections.js +172 -23
- package/sdkAgui.js +33 -6
- package/sdkBackup.js +53 -11
- package/sdkBackupV2.js +15 -3
- package/sdkCloudDevice.js +20 -5
- package/sdkComputers.js +695 -65
- package/sdkDictation.js +115 -25
- package/sdkErase.js +12 -5
- package/sdkExports.js +19 -8
- package/sdkInvitations.js +4 -2
- package/sdkKeptAgent.js +19 -3
- package/sdkKeptIntake.js +100 -0
- package/sdkLaneLink.js +8 -9
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +122 -22
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSchedules.js +8 -1
- package/sdkSpeech.js +32 -2
- package/sdkTemporaryRooms.js +124 -0
- package/sdkTurn.js +12 -4
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +34 -4
- package/siri.js +140 -9
- package/spaceClient.js +112 -17
- package/spaceEmailGate.js +2 -2
- package/spaceExport.js +50 -5
- package/spaceFork.js +15 -7
- package/spaceTemplates.js +99 -0
- package/speechOut.js +21 -5
- package/store.js +134 -27
- package/sw-notif-core.js +11 -8
- package/tapTrail.js +58 -0
- package/turnVerdict.js +1 -0
- package/usageReceipts.js +12 -5
- package/vault-core.js +568 -126
- package/vault-kit.mjs +3 -3
- package/vault-screens.js +30 -18
- package/vaultAtRest.js +38 -6
- package/vaultCoreLock.js +3 -1
- package/vaultCorePush.js +58 -7
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +32 -7
- package/witbitz-admin.d.ts +3 -0
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +170 -43
- package/witbitz-sdk.js +833 -203
package/l1-worker.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
// room, `auth(room)` round-trips to the main thread via {authReq}. The enclave tier (mkPub/enclave) is
|
|
13
13
|
// read SYNCHRONOUSLY by keyFields, so we keep a pushed snapshot {enclaveKey, enclaveRooms} and read it
|
|
14
14
|
// locally rather than round-trip.
|
|
15
|
+
import { routingIndex } from './opRouting.js'
|
|
15
16
|
import { prefetchUsable, positionOf, prefetchAnswer, prefetchHashKey } from './prefetchPoll.js'
|
|
16
17
|
import { makeSpaceClient, setAttestProvider, setPushSelf, setPushAcct, pushAcctSecretOf, viewingTag } from './spaceClient.js'
|
|
17
18
|
import { idb } from './idb.js'
|
|
@@ -57,12 +58,24 @@ const TEMP_SK = /^[A-Za-z0-9_-]{43}$/
|
|
|
57
58
|
// ROOM STREAMS: room → { s, holders }. The stream client needs mk, so it runs in this realm; only EVENTS go out — the
|
|
58
59
|
// reply text as it grows (the same plaintext a poll's partialText already carries out), "poll now", "the turn ended".
|
|
59
60
|
// Several frames can share this worker (the hoisted vault: the app + a lane panel), hence a holder count.
|
|
61
|
+
const grantsByRoom = new Map()
|
|
60
62
|
const streams = new Map()
|
|
63
|
+
function rekeyStream(room, mk) {
|
|
64
|
+
const held = streams.get(room)
|
|
65
|
+
if (!held?.s || held.mk === mk) return
|
|
66
|
+
held.s.stop()
|
|
67
|
+
grantsByRoom.delete(room)
|
|
68
|
+
held.mk = mk
|
|
69
|
+
held.grants = null
|
|
70
|
+
held.s = openStreamHere(room, mk, null, held.tag)
|
|
71
|
+
}
|
|
61
72
|
const streamFeed = (room, result) => {
|
|
62
73
|
const h = streams.get(room)
|
|
63
|
-
if (!
|
|
64
|
-
if (Array.isArray(result.streamGrants))
|
|
65
|
-
h
|
|
74
|
+
if (!result || result.status !== 200) return
|
|
75
|
+
if (Array.isArray(result.streamGrants)) grantsByRoom.set(room, result.streamGrants)
|
|
76
|
+
if (!h) return
|
|
77
|
+
if (Array.isArray(result.streamGrants)) { h.s?.setGrants(result.streamGrants); h.grants = result.streamGrants }
|
|
78
|
+
h.s?.sync(typeof result.partialText === 'string' ? result.partialText : '')
|
|
66
79
|
}
|
|
67
80
|
const mks = new Map() // room → mk — the worker's authoritative key store (A2b); mk never posts back out
|
|
68
81
|
// §9 SPLIT-KEY (confinement mode): a split room's key store is the user's userShare + the commit. resolveMk fetches the
|
|
@@ -78,6 +91,11 @@ const splits = new Map() // room → { userShare, commit }
|
|
|
78
91
|
// persisted key is sealed; at boot, sealed entries are PARKED until the page unlocks and sends the key again; `relock` drops
|
|
79
92
|
// the maps and the key from memory. With the switch off (no key, no sealed entries) every store is byte-identical to before.
|
|
80
93
|
let sealKey = null
|
|
94
|
+
// THE ACCOUNT TAG ASKED BEFORE ITS KEY WAS HERE (side sweep 2026-11-28): a restarted worker is told setPushAcct before the store is
|
|
95
|
+
// unsealed and the account rooms are remembered — the tag came out empty and the sender's other devices were notified of its turns.
|
|
96
|
+
// The room is kept and the tag derived when its key arrives (remember, unseal).
|
|
97
|
+
let pushAcctRoom = ''
|
|
98
|
+
const derivePendingAcct = async () => { const mk = pushAcctRoom && mks.get(pushAcctRoom); if (!mk) return; pushAcctRoom = ''; try { setPushAcct(await pushAcctSecretOf(mk)) } catch { /* */ } }
|
|
81
99
|
let storageEpoch = 0, storageWiped = false
|
|
82
100
|
let nkClear = false // §PREVIEWS (opt-in under protection): the push-preview keys (nk:) are written CLEAR so a locked device's tickle still shows sender + first line; everything else stays sealed
|
|
83
101
|
let protectedAtRest = false // sealed entries were seen at boot (or `seal` ran): the store is protected — NEVER write a clear key over it
|
|
@@ -89,19 +107,23 @@ const parked = new Map() // idb key ('mk:'/'us:'/'nk:' + room) → se
|
|
|
89
107
|
const volatile = new Set()
|
|
90
108
|
const postAttNk = (room, nk) => { if (!room || !nk || String(room).startsWith('tmp-')) return; try { self.postMessage({ t: 'attNk', room, nk }) } catch { /* */ } }
|
|
91
109
|
const roomOfKey = (k) => String(k).slice(String(k).indexOf(':') + 1)
|
|
110
|
+
// A TEMPORARY room's key is never written either (side sweep: temporary-worker-persists-room-keys): the page keeps no saved key
|
|
111
|
+
// for a tmp- room (space.js rememberMk) — its keys live in the shreddable temp index — and this worker's copy on disk let a
|
|
112
|
+
// temporary Space's key survive an app restart. Held in memory only; the boot scan drops what an older build wrote.
|
|
113
|
+
const memOnlyRoom = (room) => volatile.has(room) || String(room).startsWith('tmp-')
|
|
92
114
|
const persist = (k, v) => {
|
|
93
115
|
const epoch = storageEpoch
|
|
94
|
-
return storageWiped ||
|
|
116
|
+
return storageWiped || memOnlyRoom(roomOfKey(k)) ? Promise.resolve() : keysReady.then(() => ((!sealKey && protectedAtRest) ? undefined : sealIf(sealKey, v).then((stored) => epoch === storageEpoch && !storageWiped ? idb.set(k, stored) : undefined))).catch(() => {})
|
|
95
117
|
} // a wipe also cancels keys whose asynchronous sealing was still running
|
|
96
118
|
// AN ATTESTED ROOM'S PREVIEW KEY (the owner, 2026-11-24: "the notification preview for attested rooms doesn't work"): its room key stays
|
|
97
119
|
// in this worker's memory, so the vault — whose service worker and native shell show the notification — never learned its preview key.
|
|
98
120
|
// The vault gets the PREVIEW KEY alone (it opens a notification's preview, never the room): `attNk`. Nothing is written here.
|
|
99
|
-
const persistNk = (room, nk) => storageWiped ? Promise.resolve() : volatile.has(room) ? (postAttNk(room, nk), Promise.resolve()) : (nkClear ? keysReady.then(() => storageWiped ? undefined : idb.set('nk:' + room, nk)).catch(() => {}) : protectedAtRest ? keysReady.then(() => idb.delRaw('nk:' + room)).catch(() => {}) : persist('nk:' + room, nk))
|
|
121
|
+
const persistNk = (room, nk) => storageWiped ? Promise.resolve() : volatile.has(room) ? (postAttNk(room, nk), Promise.resolve()) : memOnlyRoom(room) ? Promise.resolve() : (nkClear ? keysReady.then(() => storageWiped ? undefined : idb.set('nk:' + room, nk)).catch(() => {}) : protectedAtRest ? keysReady.then(() => idb.delRaw('nk:' + room)).catch(() => {}) : persist('nk:' + room, nk))
|
|
100
122
|
// A ROOM'S KEY EPOCH (docs/key-rotation-design.md § (b)): a verified room re-keyed in place counts its keys. Kept per room
|
|
101
123
|
// (not secret: a count) so a key arriving from the account index can be refused when it is OLDER than the one held — a
|
|
102
124
|
// device that had not yet learned the new key, writing the index, must not put the old key back (never backwards).
|
|
103
125
|
const eps = new Map()
|
|
104
|
-
const noteEp = (room, ep) => { const n = Number(ep) || 0; if (room && n > (eps.get(room) || 0)) { eps.set(room, n); if (!
|
|
126
|
+
const noteEp = (room, ep) => { const n = Number(ep) || 0; if (room && n > (eps.get(room) || 0)) { eps.set(room, n); if (!memOnlyRoom(room)) idb.set('ep:' + room, n).catch(() => {}) } }
|
|
105
127
|
// NEVER BACKWARDS: a key for a room this worker holds a NEWER key of (a higher epoch) is refused — the hosted vault re-seeds
|
|
106
128
|
// every key it holds at each launch with no epoch, an old link carries its old key, the index of a device that had not yet
|
|
107
129
|
// learned the change carries the old one. A room never re-keyed has epoch 0 everywhere: nothing is refused (as before).
|
|
@@ -111,7 +133,7 @@ const backwards = (room, held, incoming, ep) => held !== incoming && (Number(ep)
|
|
|
111
133
|
// never hands the frame or the next worker the old one. Only a key with an epoch, only when it changed. The vault page is
|
|
112
134
|
// this worker's owner and already holds every key; the regular app's page ignores the message.
|
|
113
135
|
const tellEpoch = (room, ep, key) => { if (volatile.has(room) || String(room).startsWith('tmp-')) return; try { self.postMessage({ t: 'keyEpoch', room, ep, ...key }) } catch { /* */ } } // never a memory-only (attested) or temporary room's key: the vault would keep it in its account cache
|
|
114
|
-
const keep = (room, mk, ep) => { if (backwards(room, mks.get(room), mk, ep)) return false; if ((Number(ep) || 0) > 0 && (mks.get(room) !== mk || Number(ep) > (eps.get(room) || 0))) tellEpoch(room, Number(ep), { mk }); if (ep) noteEp(room, ep); mks.set(room, mk); persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // + NK mirror: every mk the kernel holds (normal OR reconstructed-split) yields a push-preview key, so a background notification for THIS room shows sender+text (vault-sw.js notifPreview), not the generic nudge
|
|
136
|
+
const keep = (room, mk, ep) => { if (backwards(room, mks.get(room), mk, ep)) return false; if ((Number(ep) || 0) > 0 && (mks.get(room) !== mk || Number(ep) > (eps.get(room) || 0))) tellEpoch(room, Number(ep), { mk }); if (ep) noteEp(room, ep); mks.set(room, mk); rekeyStream(room, mk); persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // + NK mirror: every mk the kernel holds (normal OR reconstructed-split) yields a push-preview key, so a background notification for THIS room shows sender+text (vault-sw.js notifPreview), not the generic nudge
|
|
115
137
|
// WHY a room has no key, per room — the worker's own verdict rides the no_key answer (the owner's trail said only "no key on
|
|
116
138
|
// this device" while the index held a share for every room, 2026-10-03).
|
|
117
139
|
const APPSHARE_URL = (() => { try { const o = self.location && self.location.origin; return (o && o !== 'null') ? o + '/api/appshare' : '/api/appshare' } catch (e) { return '/api/appshare' } })()
|
|
@@ -138,17 +160,18 @@ async function heldMatchesShare (room, have) {
|
|
|
138
160
|
if (ok) { heldOk.set(room, have); return true }
|
|
139
161
|
dropOldKey(room); return false
|
|
140
162
|
}
|
|
141
|
-
const dropOldKey = (room) => { if (!mks.has(room)) return; mks.delete(room); keysReady.then(() => idb.del('mk:' + room)).catch(() => {}) }
|
|
163
|
+
const dropOldKey = (room) => { if (!mks.has(room)) return; const h = streams.get(room); if (h) { h.s?.stop(); h.mk = null; h.grants = null }; grantsByRoom.delete(room); mks.delete(room); keysReady.then(() => idb.del('mk:' + room)).catch(() => {}) }
|
|
142
164
|
const keepSplit = (room, sp, ep) => { if (backwards(room, splits.get(room) && splits.get(room).userShare, sp.userShare, ep)) return false; if ((Number(ep) || 0) > 0 && ((splits.get(room) || {}).userShare !== sp.userShare || Number(ep) > (eps.get(room) || 0))) { tellEpoch(room, Number(ep), { split: { userShare: sp.userShare, commit: sp.commit || '' } }); if (Number(ep) > (eps.get(room) || 0) || (splits.get(room) || {}).userShare !== sp.userShare) dropOldKey(room) } if (ep) noteEp(room, ep); const held = splits.get(room); if (held && held.userShare !== sp.userShare) { const alts = splitAlts.get(room) || []; if (!alts.some((a) => a.userShare === held.userShare)) splitAlts.set(room, [held, ...alts].slice(0, 4)) } splits.set(room, sp); persist('us:' + room, sp) }
|
|
143
165
|
// The mirror of keep/keepSplit, and the thing that makes "delete this Space" mean anything: without it the app cleared
|
|
144
166
|
// localStorage while the WORKER kept the key — in memory AND in idb, from which a freshly-created worker reloads it at
|
|
145
167
|
// boot (the idb.entries('mk:') restore below). So a deleted room's key came BACK on the next page load. Clears every
|
|
146
168
|
// trace: the live maps, the persisted mk, the derived notification key, and the split half.
|
|
147
169
|
const forget = (room) => {
|
|
170
|
+
grantsByRoom.delete(room); streams.get(room)?.s?.stop(); streams.delete(room)
|
|
148
171
|
mks.delete(room); splits.delete(room); eps.delete(room)
|
|
149
172
|
for (const prefix of ['mk:', 'us:', 'nk:']) parked.delete(prefix + room)
|
|
150
173
|
lastPos.delete(room); heldOk.delete(room); splitAlts.delete(room)
|
|
151
|
-
return Promise.all([
|
|
174
|
+
return Promise.all(['mk:', 'nk:', 'us:', 'ep:', 'cnt:'].map(prefix => idb.delStrict(prefix + room)))
|
|
152
175
|
}
|
|
153
176
|
async function resolveMk(room) {
|
|
154
177
|
// ⚑ WAIT for the idb key map. EVERY page load starts a FRESH worker (plus browsers evict them), and the map loads
|
|
@@ -213,11 +236,12 @@ const publishPresence = () => self.postMessage({ t: 'presence', rooms: [...new S
|
|
|
213
236
|
// would strip EVERY room's key from the shared index doc in a single write, account-wide and unrecoverable.
|
|
214
237
|
// §NAMES: a store already kept under opaque names (the flag, or any `p:` key) is protected: the names go on, LOCKED, before the
|
|
215
238
|
// scan — the scan then finds nothing until the unlock gives the key, and no clear key is ever written meanwhile.
|
|
239
|
+
const dropTempCopy = (k) => { const room = k.slice(3); for (const pfx of ['mk:', 'us:', 'nk:', 'ep:']) idb.del(pfx + room).catch(() => {}) } // an older build's copy of a temporary room's key (memOnlyRoom)
|
|
216
240
|
const namesReady = Promise.all([idb.getRaw('protectedNames'), idb.keysRaw('p:')]).then(([f, ks]) => { if (f || (ks && ks.length)) { setIdbNaming({ on: true }); protectedAtRest = true } }).catch(() => {})
|
|
217
241
|
const keysReady = namesReady.then(() => Promise.all([
|
|
218
|
-
idb.entries('mk:').then((es) => { let n = 0; for (const [k, v] of es) if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v) { mks.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // a sealed entry waits for the device key (§PROTECT)
|
|
242
|
+
idb.entries('mk:').then((es) => { let n = 0; for (const [k, v] of es) if (k.startsWith('mk:tmp-')) dropTempCopy(k); else if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v) { mks.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // a sealed entry waits for the device key (§PROTECT)
|
|
219
243
|
idb.entries('ep:').then((es) => { for (const [k, v] of es) { const n = Number(v); if (n > 0) eps.set(k.slice(3), n) } }).catch(() => {}), // key epochs (noteEp)
|
|
220
|
-
idb.entries('us:').then((es) => { let n = 0; for (const [k, v] of es) if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v && v.userShare) { splits.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // reload the split shares too — the reclaim-window fix
|
|
244
|
+
idb.entries('us:').then((es) => { let n = 0; for (const [k, v] of es) if (k.startsWith('us:tmp-')) dropTempCopy(k); else if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v && v.userShare) { splits.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // reload the split shares too — the reclaim-window fix
|
|
221
245
|
]))
|
|
222
246
|
|
|
223
247
|
// auth shim → main thread (which holds the localStorage-backed cachedEmailAuth)
|
|
@@ -252,7 +276,7 @@ setAttestProvider(attestShim)
|
|
|
252
276
|
// push handler leaves a PREFETCHED poll answer here and reads the room's position from here. Every call is bounded —
|
|
253
277
|
// a hung database must never hold a poll.
|
|
254
278
|
const IDB_WAIT = 2500
|
|
255
|
-
const idbOpen = () => new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); try { const r = indexedDB.open('spaces', 1); r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* */ } }; r.onsuccess = () => { clearTimeout(t);
|
|
279
|
+
const idbOpen = () => new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); try { const r = indexedDB.open('spaces', 1); r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* */ } }; r.onsuccess = () => { clearTimeout(t); const db = r.result; db.onversionchange = () => db.close(); res(db) }; r.onerror = () => { clearTimeout(t); res(null) } } catch { clearTimeout(t); res(null) } })
|
|
256
280
|
const idbGet = async (k) => { try { const db = await idbOpen(); if (!db) return null; return await new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); const q = db.transaction('kv', 'readonly').objectStore('kv').get(k); q.onsuccess = () => { clearTimeout(t); res(q.result || null) }; q.onerror = () => { clearTimeout(t); res(null) } }) } catch { return null } }
|
|
257
281
|
const idbSet = async (k, v) => { try { const db = await idbOpen(); if (!db) return false; return await new Promise((res) => { const t = setTimeout(() => res(false), IDB_WAIT); const q = db.transaction('kv', 'readwrite').objectStore('kv').put(v, k); q.onsuccess = () => { clearTimeout(t); res(true) }; q.onerror = () => { clearTimeout(t); res(false) } }) } catch { return false } }
|
|
258
282
|
const idbDel = async (k) => { try { const db = await idbOpen(); if (!db) return false; return await new Promise((res) => { const t = setTimeout(() => res(false), IDB_WAIT); const q = db.transaction('kv', 'readwrite').objectStore('kv').delete(k); q.onsuccess = () => { clearTimeout(t); res(true) }; q.onerror = () => { clearTimeout(t); res(false) } }) } catch { return false } }
|
|
@@ -319,6 +343,8 @@ self.onmessage = async (e) => {
|
|
|
319
343
|
if ((await idb.keysRaw('p:')).length && !(await idb.nameIndex()).length) { setIdbNaming({ on: true }); throw new Error('this key opens nothing here') } // §NAMES: a wrong key reads no name — refuse, and stay locked (never write under its names)
|
|
320
344
|
ms.check = performance.now() - t0
|
|
321
345
|
if (!parked.size) for (const pfx of ['mk:', 'us:', 'nk:']) for (const [k, v] of await idb.entries(pfx)) if (isSealed(v)) parked.set(k, v) // after a relock the maps are empty: re-read the sealed store
|
|
346
|
+
// a TEMPORARY room's older copy (memOnlyRoom; 67bea680d recheck): under opaque names the boot scan never saw it — dropped here, never opened
|
|
347
|
+
for (const k of [...parked.keys()]) if (/^(?:mk|us|nk):tmp-/.test(k)) { parked.delete(k); dropTempCopy(k) }
|
|
322
348
|
ms.read = performance.now() - t0; ms.n = parked.size
|
|
323
349
|
let n = 0
|
|
324
350
|
// ALL AT ONCE, then into the maps (2026-11-17: one by one, WebKit's WebCrypto costs a thread hop per key — ~450 rooms on the
|
|
@@ -329,6 +355,7 @@ self.onmessage = async (e) => {
|
|
|
329
355
|
if (k.startsWith('mk:')) { mks.set(k.slice(3), v); n++ } else if (k.startsWith('us:')) { if (v && v.userShare) { splits.set(k.slice(3), v); n++ } } // nk: is derived from mk at keep(); nothing to hold in memory
|
|
330
356
|
})
|
|
331
357
|
parked.clear(); sealKey = key; protectedAtRest = true
|
|
358
|
+
derivePendingAcct() // the account's index key may have been among them
|
|
332
359
|
for (const [room, mk] of mks) { persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // keys that reached the locked worker (the page re-sent them at open) are persisted sealed now
|
|
333
360
|
for (const [room, sp] of splits) persist('us:' + room, sp)
|
|
334
361
|
ms.open = performance.now() - t0
|
|
@@ -377,10 +404,13 @@ self.onmessage = async (e) => {
|
|
|
377
404
|
case 'wipeKeys': { // root-vault only: parked/opaque keys count even when no room list can name them
|
|
378
405
|
storageWiped = true; storageEpoch++
|
|
379
406
|
await keysReady
|
|
407
|
+
for (const h of streams.values()) h.s?.stop()
|
|
408
|
+
streams.clear(); grantsByRoom.clear()
|
|
380
409
|
mks.clear(); splits.clear(); parked.clear(); splitAlts.clear(); eps.clear(); heldOk.clear(); lastPos.clear()
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
self.postMessage({ id: m.id,
|
|
410
|
+
ids.clear()
|
|
411
|
+
try { await idb.clearStrict(); self.postMessage({ id: m.id, result: true }) }
|
|
412
|
+
catch (error) { self.postMessage({ id: m.id, error: String(error?.message || error) }) }
|
|
413
|
+
finally { publishPresence() }
|
|
384
414
|
return
|
|
385
415
|
}
|
|
386
416
|
case 'volatile': { // {rooms} → these rooms' keys are memory-only from now on: drop what is stored, write nothing
|
|
@@ -391,7 +421,7 @@ self.onmessage = async (e) => {
|
|
|
391
421
|
case 'remember': { // {room, mk} → store a key in the map (the worker becomes the mk store)
|
|
392
422
|
// AFTER the boot scan: the stored key and its epoch are loaded first, so a launch's re-seed (no epoch) is judged against
|
|
393
423
|
// them — before, the scan put the new key back in memory and the re-seed's queued write put the old one on disk
|
|
394
|
-
keysReady.then(() => { if (m.room && m.mk) { keep(m.room, m.mk, m.ep); publishPresence() } if (m.id != null) self.postMessage({ id: m.id, result: true }) }) // m.ep: a re-keyed room's epoch (space.js adoptRoomKey)
|
|
424
|
+
keysReady.then(() => { if (m.room && m.mk) { keep(m.room, m.mk, m.ep); publishPresence(); if (m.room === pushAcctRoom) derivePendingAcct() } if (m.id != null) self.postMessage({ id: m.id, result: true }) }) // m.ep: a re-keyed room's epoch (space.js adoptRoomKey)
|
|
395
425
|
return
|
|
396
426
|
}
|
|
397
427
|
case 'create': { // {id, cfg, base} → mint a Space HERE (vault-core.js, docs/sdk-vault-mode.md): its key is born in
|
|
@@ -417,9 +447,13 @@ self.onmessage = async (e) => {
|
|
|
417
447
|
case 'forget': { // {room} → DROP the key. AWAITS the idb deletes before replying: the caller holds
|
|
418
448
|
// navigation until it resolves, and a dedicated worker dies with its page — a fire-and-forget delete could be
|
|
419
449
|
// cut off mid-write, leaving the key in idb for the next worker to reload.
|
|
450
|
+
try {
|
|
420
451
|
await keysReady
|
|
421
|
-
if (m.room)
|
|
422
|
-
|
|
452
|
+
if (m.room) await forget(m.room)
|
|
453
|
+
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
454
|
+
} catch (error) {
|
|
455
|
+
if (m.id != null) self.postMessage({ id: m.id, error: String(error?.message || error) })
|
|
456
|
+
} finally { publishPresence() }
|
|
423
457
|
return
|
|
424
458
|
}
|
|
425
459
|
case 'setPushAcct': { // {room} = the account's INDEX room → derive the account push secret from ITS key, here,
|
|
@@ -428,8 +462,8 @@ self.onmessage = async (e) => {
|
|
|
428
462
|
// {secret}: the secret itself (a one-way derivation, never a key), from a page that holds the index key on its own thread —
|
|
429
463
|
// the builders' vault (vault-core.js; sync sweep 11-16 #14). '' clears it (signed out).
|
|
430
464
|
try {
|
|
431
|
-
if (typeof m.secret === 'string') { if (m.secret === '' || /^[A-Za-z0-9_-]{43}$/.test(m.secret)) setPushAcct(m.secret) }
|
|
432
|
-
else { const mk = m.room ? (mks.get(m.room) || await resolveMk(m.room)) : ''; setPushAcct(await pushAcctSecretOf(mk || '')) }
|
|
465
|
+
if (typeof m.secret === 'string') { pushAcctRoom = ''; if (m.secret === '' || /^[A-Za-z0-9_-]{43}$/.test(m.secret)) setPushAcct(m.secret) }
|
|
466
|
+
else { const mk = m.room ? (mks.get(m.room) || await resolveMk(m.room)) : ''; pushAcctRoom = m.room && !mk ? String(m.room) : ''; setPushAcct(await pushAcctSecretOf(mk || '')) } // no key yet: kept for when it comes
|
|
433
467
|
} catch { /* */ }
|
|
434
468
|
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
435
469
|
return
|
|
@@ -447,7 +481,10 @@ self.onmessage = async (e) => {
|
|
|
447
481
|
// A stream opened before the endpoint arrived carries no viewing tag: reopen it with one (the server then skips this
|
|
448
482
|
// device's tickle for the room on screen). Same room, same key; only the socket's name changes.
|
|
449
483
|
for (const [room, h] of streams) {
|
|
450
|
-
|
|
484
|
+
// …and only a stream still HELD after the wait: a final streamClose meanwhile stopped it and dropped it from `streams`, and a
|
|
485
|
+
// socket reopened for it would stay tagged "viewing" with no holder, silencing this device's notices for a room it left (side
|
|
486
|
+
// sweep: room-worker-pending-stream-open-outlives-close)
|
|
487
|
+
try { const tag = await viewingTag(room); if (streams.get(room) !== h) continue; if (tag && tag !== h.tag && h.mk) { h.s?.stop(); h.s = openStreamHere(room, h.mk, h.grants || null, tag); h.tag = tag } } catch { /* the old socket stays */ }
|
|
451
488
|
}
|
|
452
489
|
if (m.id != null) self.postMessage({ id: m.id, result: true })
|
|
453
490
|
return
|
|
@@ -490,10 +527,10 @@ self.onmessage = async (e) => {
|
|
|
490
527
|
case 'inviteLink': { // {id, room, base, suffix} → the invite link, with the split key fragment (#us=…&spc=…) INJECTED here from the confined store. Main thread supplies only the non-secret base/suffix; it never sees the userShare. null if we hold no split for the room.
|
|
491
528
|
const { id, room, base, suffix } = m
|
|
492
529
|
try {
|
|
493
|
-
const sp = splits.get(room)
|
|
530
|
+
const sp = splits.get(room), held = !(sp && sp.userShare) && m.plain === true && typeof mks.get(room) === 'string' ? mks.get(room) : '' // plain: a non-split room whose key only this worker holds (a protected device)
|
|
494
531
|
const link = (sp && sp.userShare)
|
|
495
532
|
? (base + '#us=' + encodeURIComponent(sp.userShare) + (sp.commit ? '&spc=' + encodeURIComponent(sp.commit) : '') + (suffix || ''))
|
|
496
|
-
: null
|
|
533
|
+
: held ? base + '#mk=' + held + (suffix || '') : null
|
|
497
534
|
self.postMessage({ id, result: { link } })
|
|
498
535
|
} catch (err) { self.postMessage({ id, error: 'inviteLink: ' + String((err && err.message) || err) }) }
|
|
499
536
|
return
|
|
@@ -578,7 +615,7 @@ self.onmessage = async (e) => {
|
|
|
578
615
|
await keysReady // so hasMk/presence reflect the FULL map right after an absorb (a half-loaded map reads as "no key")
|
|
579
616
|
if (indexMk && !mks.get(indexRoom)) { keep(indexRoom, indexMk); publishPresence() } // the app passes the index ROOM's key so we can open the doc even when it was adopted from a backup
|
|
580
617
|
const r = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc }) // SEALED on the device (accountStores.js); the plain doc read through until it moves
|
|
581
|
-
if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null } }); return }
|
|
618
|
+
if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null, ...(r && Number.isInteger(r.v) ? { v: r.v } : {}) } }); return } // v even for an EMPTY doc: the first sealing write is pinned to it (side sweep: index2-version-lost-during-key-transition)
|
|
582
619
|
let st = r.state
|
|
583
620
|
const mirror = {} // → the main thread's localStorage cache (see below); `rooms` itself stays KEYLESS as before
|
|
584
621
|
const splitRooms = {} // room → commit: which listed rooms are split, with no share (what a keyless caller is told)
|
|
@@ -599,6 +636,15 @@ self.onmessage = async (e) => {
|
|
|
599
636
|
// not leaving one arrival path out.
|
|
600
637
|
// ⛔ …but NEVER to a keyless caller (above): in the hosted app this answer crossed into the app frame and carried every
|
|
601
638
|
// room key and split share of the account on every index sync. It gets `splits` alone.
|
|
639
|
+
if (name === 'index' && st && typeof st === 'object') {
|
|
640
|
+
for (const field of ['pipesRoom', 'msgsRoom']) {
|
|
641
|
+
const ptr = st[field]
|
|
642
|
+
if (!ptr?.room) continue
|
|
643
|
+
if (ptr.mk) keep(ptr.room, ptr.mk)
|
|
644
|
+
if (keylessAsk) st = { ...st, [field]: { room: ptr.room } }
|
|
645
|
+
}
|
|
646
|
+
publishPresence()
|
|
647
|
+
}
|
|
602
648
|
self.postMessage({ id, result: { status: 200, state: st, splits: splitRooms, ...(keylessAsk ? {} : { mkeys: mirror }), ...(Number.isInteger(r.v) ? { v: r.v } : {}) } }) // v: the version a write names (accountStores put ifV)
|
|
603
649
|
} catch (err) { self.postMessage({ id, error: 'indexRead: ' + String((err && err.message) || err) }) }
|
|
604
650
|
return
|
|
@@ -610,6 +656,7 @@ self.onmessage = async (e) => {
|
|
|
610
656
|
await keysReady // NEVER write the index from a half-loaded key map — an empty `mks` would strip every room's key (below)
|
|
611
657
|
if (indexMk && !mks.get(indexRoom)) { keep(indexRoom, indexMk); publishPresence() } // index ROOM key passed by the app (adopted-from-backup case)
|
|
612
658
|
let p = { ...(patch || {}) }
|
|
659
|
+
let previousIndex
|
|
613
660
|
if (p.rooms && typeof p.rooms === 'object') {
|
|
614
661
|
// PRESERVE keys we don't hold. The patch arrives KEYLESS (indexRead strips keys before handing it up), so a room
|
|
615
662
|
// whose key is missing from THIS worker used to be dropped outright — silently deleting that key from the shared
|
|
@@ -617,8 +664,9 @@ self.onmessage = async (e) => {
|
|
|
617
664
|
// (and absorb it, self-healing this worker). Only a room whose key exists NOWHERE is dropped, as before.
|
|
618
665
|
let cur = {}
|
|
619
666
|
try {
|
|
620
|
-
let s = null; const rr = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc })
|
|
667
|
+
let s = null; const rr = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc, notePlain: false }) // for the keys only: the cleanup still empties over the app's read (accountStores.js)
|
|
621
668
|
if (rr && rr.status === 200 && rr.state) s = rr.state
|
|
669
|
+
previousIndex = s
|
|
622
670
|
if (s && s.rooms && typeof s.rooms === 'object') cur = s.rooms
|
|
623
671
|
} catch { /* read failed → fall back to inject-what-we-hold (the pre-existing behaviour) */ }
|
|
624
672
|
const rooms = {}
|
|
@@ -637,6 +685,14 @@ self.onmessage = async (e) => {
|
|
|
637
685
|
publishPresence()
|
|
638
686
|
}
|
|
639
687
|
// ⛔ SEALED on the device — the doc carries every room key (accountStores.js); without the account key nothing is written
|
|
688
|
+
if (name === 'index') for (const field of ['pipesRoom', 'msgsRoom']) {
|
|
689
|
+
const ptr = p[field]
|
|
690
|
+
if (!ptr?.room || ptr.mk) continue
|
|
691
|
+
const saved = previousIndex?.[field]
|
|
692
|
+
const mk = (saved?.room === ptr.room && saved.mk) || mks.get(ptr.room)
|
|
693
|
+
if (!mk) throw new Error('The account room key is unavailable. Retry sync.')
|
|
694
|
+
p[field] = { room: ptr.room, mk }
|
|
695
|
+
}
|
|
640
696
|
const r = await acct.put(indexRoom, mks.get(indexRoom) || indexMk, name, p, summary, by, { ifV }) // ifV: only over the version the app merged
|
|
641
697
|
self.postMessage({ id, result: { status: (r && r.status) || 0, bytes: _jsonBytes(p), z: true, ...(r && r.error ? { error: r.error } : {}) } })
|
|
642
698
|
} catch (err) { self.postMessage({ id, error: 'indexWrite: ' + String((err && err.message) || err) }) }
|
|
@@ -648,7 +704,7 @@ self.onmessage = async (e) => {
|
|
|
648
704
|
if (!client) throw new Error('l1-worker: pipesRead before open')
|
|
649
705
|
if (pipesMk && !mks.get(pipesRoom)) { keep(pipesRoom, pipesMk); publishPresence() }
|
|
650
706
|
const r = await acct.get(pipesRoom, mks.get(pipesRoom) || pipesMk, name) // SEALED on the device (accountStores.js)
|
|
651
|
-
if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null } }); return }
|
|
707
|
+
if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null, ...(r && Number.isInteger(r.v) ? { v: r.v } : {}) } }); return } // v even for an EMPTY doc: the first sealing write is pinned to it (side sweep: index2-version-lost-during-key-transition)
|
|
652
708
|
let st = r.state
|
|
653
709
|
if (st && typeof st === 'object' && st.pipes && typeof st.pipes === 'object') {
|
|
654
710
|
const keyless = {}
|
|
@@ -731,23 +787,32 @@ self.onmessage = async (e) => {
|
|
|
731
787
|
})()
|
|
732
788
|
return
|
|
733
789
|
}
|
|
734
|
-
case 'streamOpen': {
|
|
735
|
-
const { room
|
|
736
|
-
const
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
790
|
+
case 'streamOpen': {
|
|
791
|
+
const { room } = m
|
|
792
|
+
const grants = m.grants || grantsByRoom.get(room)
|
|
793
|
+
let held = streams.get(room)
|
|
794
|
+
if (held) {
|
|
795
|
+
held.holders++
|
|
796
|
+
if (Array.isArray(grants)) { held.grants = grants; held.s?.setGrants(grants) }
|
|
797
|
+
return
|
|
798
|
+
}
|
|
799
|
+
held = { holders: 1, mk: null, s: null, tag: '', grants: Array.isArray(grants) ? grants : null }
|
|
800
|
+
streams.set(room, held)
|
|
801
|
+
try {
|
|
802
|
+
await keysReady
|
|
803
|
+
const mk = (typeof m.mk === 'string' && m.mk) || mks.get(room) || await resolveMk(room)
|
|
804
|
+
if (streams.get(room) !== held) return
|
|
805
|
+
if (!mk) { streams.delete(room); return }
|
|
806
|
+
const tag = await viewingTag(room).catch(() => '')
|
|
807
|
+
if (streams.get(room) !== held) return
|
|
808
|
+
held.tag = tag; held.mk = mks.get(room) || mk
|
|
809
|
+
held.s = openStreamHere(room, held.mk, held.grants, tag)
|
|
810
|
+
} catch (error) { if (streams.get(room) === held) streams.delete(room) }
|
|
746
811
|
return
|
|
747
812
|
}
|
|
748
|
-
case 'streamClose': {
|
|
749
|
-
const
|
|
750
|
-
if (
|
|
813
|
+
case 'streamClose': {
|
|
814
|
+
const held = streams.get(m.room)
|
|
815
|
+
if (held && --held.holders <= 0) { held.s?.stop(); streams.delete(m.room) }
|
|
751
816
|
return
|
|
752
817
|
}
|
|
753
818
|
case 'op': { // {id, op, room, args} → client[op](room, mks[room], …args) → {id, result}
|
|
@@ -762,8 +827,22 @@ self.onmessage = async (e) => {
|
|
|
762
827
|
// hold no identity for stays unsigned (open/legacy), unchanged. Only substitutes when the arg is absent — an app
|
|
763
828
|
// that still passes identity (flag off / email turn) is untouched.
|
|
764
829
|
if (op === 'turn' && (aa[1] == null) && ids.has(room)) aa[1] = ids.get(room)
|
|
765
|
-
|
|
766
|
-
|
|
830
|
+
const index = routingIndex(op)
|
|
831
|
+
if (index >= 0 && aa[index] && typeof aa[index] === 'object') {
|
|
832
|
+
const route = { ...aa[index] }
|
|
833
|
+
aa[index] = route
|
|
834
|
+
if (route.bridgeRoom && !route.bridgeMk) {
|
|
835
|
+
const key = mks.get(route.bridgeRoom) || await resolveMk(route.bridgeRoom)
|
|
836
|
+
if (key) route.bridgeMk = key
|
|
837
|
+
}
|
|
838
|
+
if (op === 'turn' && Array.isArray(route.links)) {
|
|
839
|
+
route.links = await Promise.all(route.links.map(async link => {
|
|
840
|
+
if (!link?.room || link.mk) return link
|
|
841
|
+
const key = mks.get(link.room) || await resolveMk(link.room).catch(() => null)
|
|
842
|
+
return key ? { ...link, mk: key } : link
|
|
843
|
+
}))
|
|
844
|
+
}
|
|
845
|
+
}
|
|
767
846
|
const mkHere = await resolveMk(room) // §9: reconstruct a split room's mk (fetch appShare + combine) on demand
|
|
768
847
|
let result = null
|
|
769
848
|
let pfNote = '' // what the prefetch lookup found, for the page's tap timeline ('' = not looked up)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Room activity and changes to who a private room is linked to have distinct clocks.
|
|
2
|
+
export function associationTime(record, now = Date.now()) {
|
|
3
|
+
return Math.max(now, (Number(record?.associationAt || record?.at) || 0) + 1)
|
|
4
|
+
}
|
|
5
|
+
// Normalize legacy records before cursor or key maintenance can move their activity time.
|
|
6
|
+
export function reconcilePrivateRooms(pipes) {
|
|
7
|
+
const byRoom = new Map()
|
|
8
|
+
for (const pipe of Object.values(pipes)) {
|
|
9
|
+
if (pipe?.kind === 'lane-lane') { pipe.associationAt ||= Number(pipe.at) || 1; continue }
|
|
10
|
+
if (pipe?.kind !== 'private-lane') continue
|
|
11
|
+
// a time COPIED from activity is marked so (side sweep: legacy-mirror-cursor-revives-unlinked-lane): against an unlink it is
|
|
12
|
+
// still activity (legacyUndoesUnlink); a link this build makes writes its own associationAt on a new row, unmarked
|
|
13
|
+
if (!pipe.associationAt) { pipe.associationAt = Number(pipe.at) || 1; pipe.associationInferred = true }
|
|
14
|
+
const room = pipe.lane?.room
|
|
15
|
+
if (!room || pipe.removed) continue
|
|
16
|
+
if (!byRoom.has(room)) byRoom.set(room, [])
|
|
17
|
+
byRoom.get(room).push(pipe)
|
|
18
|
+
}
|
|
19
|
+
const conflicting = new Set()
|
|
20
|
+
for (const parents of byRoom.values()) {
|
|
21
|
+
for (const pipe of parents) {
|
|
22
|
+
const upstream = byRoom.get(pipe.shared?.room)
|
|
23
|
+
if (!upstream) continue
|
|
24
|
+
conflicting.add(pipe)
|
|
25
|
+
for (const other of upstream) conflicting.add(other)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
for (const parents of byRoom.values()) {
|
|
29
|
+
if (parents.length < 2 && !conflicting.has(parents[0])) continue
|
|
30
|
+
const decision = Math.max(...parents.map(p => p.associationAt))
|
|
31
|
+
for (const pipe of parents) {
|
|
32
|
+
pipe.removed = true
|
|
33
|
+
pipe.associationAt = decision
|
|
34
|
+
pipe.cursor = 0
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return pipes
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A LIVE ROW FROM AN OLDER DEVICE CANNOT UNDO A NEWER UNLINK OF THE SAME ASSISTANT (side sweep 2026-11-28): an older device stamps `at`
|
|
41
|
+
// on every mirror step and writes no `associationAt`, so its live row, stamped after an explicit unlink, read as the newer link and
|
|
42
|
+
// copying to the former assistant began again. Against a removal that names its decision, such a row's `at` is activity.
|
|
43
|
+
const legacyUndoesUnlink = (live, gone) => live.kind === 'private-lane' && gone.kind === 'private-lane' && !live.removed && !live.detachedLane && (!Number(live.associationAt) || live.associationInferred === true) &&
|
|
44
|
+
gone.removed === true && Number(gone.associationAt) > 0 && !!live.lane?.room && (live.lane.room === gone.lane?.room || (Array.isArray(gone.unlinkedRooms) && gone.unlinkedRooms.includes(live.lane.room)))
|
|
45
|
+
|
|
46
|
+
export function preferredAssociation(left, right) {
|
|
47
|
+
if (!left || !right) return left || right
|
|
48
|
+
if (legacyUndoesUnlink(left, right)) return right
|
|
49
|
+
if (legacyUndoesUnlink(right, left)) return left
|
|
50
|
+
const explicit = record => Number(record.associationAt) || (record.kind === 'private-lane' || record.kind === 'lane-lane' || record.detachedLane || record.removed ? Number(record.at) || 0 : 0)
|
|
51
|
+
const a = explicit(left), b = explicit(right)
|
|
52
|
+
if (a !== b) return a > b ? left : right
|
|
53
|
+
if (left.detachedLane || left.removed) return left
|
|
54
|
+
if (right.detachedLane || right.removed) return right
|
|
55
|
+
const activity = Number(right.at || 0) - Number(left.at || 0)
|
|
56
|
+
if (activity) return activity > 0 ? right : left
|
|
57
|
+
const destination = record => record.lane?.room || (typeof record.shared === 'string' ? record.shared : '') || ''
|
|
58
|
+
return destination(right) > destination(left) ? right : left
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A private room cannot itself parent another private room. Suspend both edges of any merged chain. */
|
|
62
|
+
export function reconcileAccountLanes(rooms) {
|
|
63
|
+
const parents = new Map(rooms.filter(r => r.shared && !r.detachedLane).map(r => [r.room, r]))
|
|
64
|
+
const suspend = new Map()
|
|
65
|
+
for (const child of parents.values()) {
|
|
66
|
+
const parent = parents.get(child.shared)
|
|
67
|
+
if (!parent) continue
|
|
68
|
+
const at = Math.max(Number(child.associationAt || child.at) || 1, Number(parent.associationAt || parent.at) || 1)
|
|
69
|
+
for (const r of [parent, child]) suspend.set(r.room, Math.max(at, suspend.get(r.room) || 0))
|
|
70
|
+
}
|
|
71
|
+
return rooms.map(r => {
|
|
72
|
+
if (!suspend.has(r.room)) return r
|
|
73
|
+
const detached = { ...r, kind: 'space', detachedLane: true, associationAt: suspend.get(r.room) }
|
|
74
|
+
delete detached.shared
|
|
75
|
+
delete detached.laneOrigin
|
|
76
|
+
return detached
|
|
77
|
+
})
|
|
78
|
+
}
|
package/laneConfig.js
CHANGED
|
@@ -15,11 +15,12 @@ const toolName = (t) => (t && typeof t === 'object' ? t.name : t)
|
|
|
15
15
|
/** The shared room's tools a lane takes on (the app's lanes do: the member's assistant can search what the room's can). */
|
|
16
16
|
export function inheritToolsFrom (sharedConfig) {
|
|
17
17
|
const c = sharedConfig && typeof sharedConfig === 'object' ? sharedConfig : null
|
|
18
|
-
|
|
18
|
+
const inherited = c && (c.platformTools === false || Array.isArray(c.platformTools)) ? { platformTools: Array.isArray(c.platformTools) ? [...c.platformTools] : false } : {}
|
|
19
|
+
if (!c || !Array.isArray(c.tools)) return inherited
|
|
19
20
|
const tools = c.tools.filter((t) => !LANE_WITHHELD.has(toolName(t)))
|
|
20
|
-
if (!tools.length) return
|
|
21
|
+
if (!tools.length) return inherited
|
|
21
22
|
const immediate = Array.isArray(c.immediateTools) ? c.immediateTools.filter((n) => !LANE_WITHHELD.has(n)) : []
|
|
22
|
-
return { tools, ...(immediate.length ? { immediateTools: immediate } : {}) }
|
|
23
|
+
return { ...inherited, tools, ...(immediate.length ? { immediateTools: immediate } : {}) }
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
/** WHAT A PRIVATE LANE TAKES FROM ITS SPACE: everything but the members (the owner, 2026-10-15: "the private lane inherits
|
package/laneLinkCore.js
CHANGED
|
@@ -81,6 +81,15 @@ export function askHopFrom(entries) {
|
|
|
81
81
|
/** The built-in hop ceiling when neither the pipe nor the account names one (docs/spaces-linked-lanes.md, Decision 4).
|
|
82
82
|
* Resolution lives in roomSync.effectiveLaneLaneCap: pipe `cap` → account default → this. */
|
|
83
83
|
export const DEFAULT_LANE_LINK_CAP = 3
|
|
84
|
+
/** A linked assistant's label no earlier one in `used` has: `base`, else "base (2)", "base (3)"… (side sweep:
|
|
85
|
+
* linked-assistant-label-selects-wrong-room — counted by the original names, a generated "Assistant (2)" could equal another
|
|
86
|
+
* assistant's own name, and tell_lane asked the first match). Adds the label to `used`. */
|
|
87
|
+
export function uniqueLabel(used, base) {
|
|
88
|
+
let label = base, n = 1
|
|
89
|
+
while (used.has(label)) label = `${base} (${++n})`
|
|
90
|
+
used.add(label)
|
|
91
|
+
return label
|
|
92
|
+
}
|
|
84
93
|
export function canForward(hop, cap, defaultCap = DEFAULT_LANE_LINK_CAP) {
|
|
85
94
|
const c = Number.isFinite(Number(cap)) && Number(cap) >= 0 ? Number(cap) : defaultCap
|
|
86
95
|
return (Number(hop) || 0) <= c
|
package/ledgerView.js
CHANGED
|
@@ -12,6 +12,11 @@ export const entryKeyOf = (e) => `${canonId(e && e.id)}|${e && e.ts != null ? e.
|
|
|
12
12
|
// with no new entries" means: re-read a short tail — never adopting its etag, or a reply landing in between is swallowed.
|
|
13
13
|
export const REACTION_RESYNC_TAIL = 50
|
|
14
14
|
export const needsTailResync = (r, held) => !!(r && r.status === 200 && r.changed && Array.isArray(r.entries) && !r.entries.length && held > 0)
|
|
15
|
+
// …and a changed poll that ALSO brought new entries may carry an in-place edit as well: a reaction and a message landing between two polls
|
|
16
|
+
// come back as the message only — the server lists no edited ids (side sweep: reaction-refresh-misses-edited-history). The tail is re-read
|
|
17
|
+
// for it too, but at most every TAIL_RESYNC_WITH_NEW_MS: a busy room must not pay a second read for every message.
|
|
18
|
+
export const TAIL_RESYNC_WITH_NEW_MS = 10_000
|
|
19
|
+
export const mayHideEdit = (r, held) => !!(r && r.status === 200 && r.changed && Array.isArray(r.entries) && r.entries.length && held > 0)
|
|
15
20
|
|
|
16
21
|
const same = (a, b) => { try { return JSON.stringify(a) === JSON.stringify(b) } catch { return false } }
|
|
17
22
|
|
|
@@ -35,6 +40,17 @@ export function makeLedgerView () {
|
|
|
35
40
|
}
|
|
36
41
|
return { added, updated }
|
|
37
42
|
},
|
|
43
|
+
/** Drop the held entry with this id (and ts, when both carry one) from the list, in place → whether one was dropped. A
|
|
44
|
+
* deleted mail's place (agent/mailPurge.mjs) leaves nothing of the mail (side sweep: sdk-purged-mail-retains-original-entry). */
|
|
45
|
+
remove (id, ts) {
|
|
46
|
+
const cid = id != null ? canonId(id) : null
|
|
47
|
+
if (cid == null || !at.has(cid)) return false
|
|
48
|
+
const i = at.get(cid)
|
|
49
|
+
if (ts != null && list[i] && list[i].ts != null && list[i].ts !== ts) return false
|
|
50
|
+
list.splice(i, 1); at.delete(cid)
|
|
51
|
+
for (const [k, j] of at) if (j > i) at.set(k, j - 1)
|
|
52
|
+
return true
|
|
53
|
+
},
|
|
38
54
|
}
|
|
39
55
|
}
|
|
40
56
|
|
|
@@ -51,14 +67,24 @@ export async function readAllPages (read, { maxPages = 400 } = {}) {
|
|
|
51
67
|
// a FIRST read that failed is not an empty room: say so, as a later page's failure does (sync sweep, 2026-10-10)
|
|
52
68
|
if (!first || !Array.isArray(first.entries) || (first.status && first.status !== 200)) return { ...(first || {}), entries: (first && Array.isArray(first.entries)) ? first.entries : [], incomplete: true }
|
|
53
69
|
const entries = [...first.entries]
|
|
70
|
+
// `refused`: entries a page could not open (an earlier room key out of reach just now) — summed over EVERY page, so a reader
|
|
71
|
+
// that needs the whole history (export) can tell a partly readable one from it (side sweep 2026-11-28)
|
|
72
|
+
let refused = Number(first.refused) || 0
|
|
73
|
+
// `mixed`: a later page came from ANOTHER revision of the room (its etag, less the page's `#<end>`, differs from the first
|
|
74
|
+
// page's) — a reaction or a new message landed between the reads, so the pages do not make one snapshot. Said, additively; a
|
|
75
|
+
// reader that needs one snapshot (export) reads again (side sweep: portable-export-mixes-history-revisions)
|
|
76
|
+
let mixed = false
|
|
77
|
+
const revision = (etag) => (typeof etag === 'string' && etag ? etag.replace(/#\d+$/, '') : '')
|
|
78
|
+
const out = (o) => ({ ...o, ...(refused ? { refused } : {}), ...(mixed ? { mixed: true } : {}) })
|
|
54
79
|
let p = first
|
|
55
80
|
for (let i = 1; i < maxPages && p && p.more; i++) {
|
|
56
81
|
const since = Number(p.version)
|
|
57
82
|
if (!Number.isFinite(since) || since <= 0) break
|
|
58
83
|
const next = await read(since).catch(() => null)
|
|
59
|
-
if (!next || !Array.isArray(next.entries) || (next.status && next.status !== 200)) return { ...first, entries, incomplete: true }
|
|
60
|
-
|
|
84
|
+
if (!next || !Array.isArray(next.entries) || (next.status && next.status !== 200)) return out({ ...first, entries, incomplete: true })
|
|
85
|
+
if (revision(first.etag) && revision(next.etag) && revision(next.etag) !== revision(first.etag)) mixed = true
|
|
86
|
+
entries.push(...next.entries); p = next; refused += Number(next.refused) || 0
|
|
61
87
|
}
|
|
62
|
-
if (p && p.more) return { ...first, entries, incomplete: true } // stopped at maxPages with pages still to come: not the whole history (sync sweep, 2026-10-10)
|
|
63
|
-
return { ...first, entries, more: false }
|
|
88
|
+
if (p && p.more) return out({ ...first, entries, incomplete: true }) // stopped at maxPages with pages still to come: not the whole history (sync sweep, 2026-10-10)
|
|
89
|
+
return out({ ...first, entries, more: false })
|
|
64
90
|
}
|