@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.
Files changed (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
package/store.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { PENDING_MS } from './connPending.js'
1
2
  // store.js — local data-persistence layer (Verified-Client Phase 1). Recents, contacts, the hidden
2
3
  // room pointers (pipes/index/invite), the name, and lanes flags — all localStorage. saveRecents's
3
4
  // durability+sync side effects (queueBackup/scheduleIndexPush) are INJECTED via setRecentsSaveHook.
@@ -95,22 +96,39 @@ export const isCloudKept = (r) => !!r && !!((recentOf(r) || {}).alwaysOn)
95
96
  /** Set or clear a Space's always-on mark in the account's room list (→ synced to every device). Only a change is written. */
96
97
  export function setAlwaysOn (r, on, now = Date.now()) {
97
98
  if (!r || isCloudKept(r) === !!on) return false
98
- mutateRecent(r, (it) => { it.alwaysOn = !!on; it.alwaysOnAt = now })
99
+ mutateRecent(r, (it) => { it.alwaysOn = !!on; it.alwaysOnAt = Math.max(now, (Number(it.alwaysOnAt) || 0) + 1) }) // after the mark it replaces (side sweep 2026-11-28: a Keep dated ahead of this clock won the sync over a later release here), as the SDK does
99
100
  return isCloudKept(r) === !!on
100
101
  }
101
102
  /** The cloud device was signed out (here, or from the hosted vault's account screen): no Space is kept any more. */
102
103
  export function clearAlwaysOn (now = Date.now()) { for (const r of loadRecents()) if (r && r.alwaysOn) setAlwaysOn(r.room, false, now) }
103
104
  /** The cloud device answered which Spaces it holds (its card): a Space it runs is kept, so its mark is set (a Space kept before the
104
105
  * mark existed arrives here). A Space it does NOT hold keeps its mark: that is the card's warning to show (the device let it go, or
105
- * was signed out) — never a silent change. The old one-device list is dropped. */
106
- export function adoptCloudKept (rooms, now = Date.now()) {
107
- for (const r of new Set((rooms || []).filter((x) => typeof x === 'string'))) setAlwaysOn(r, true, now)
106
+ * was signed out) — never a silent change. The old one-device list is dropped. `readAt` = when the device was asked: a Space taken
107
+ * off AFTER that (here or on another device, synced meanwhile) keeps its Off — the answer is older than the release (side sweep:
108
+ * always-on-delayed-status-restores-released-mark). */
109
+ export function adoptCloudKept (rooms, now = Date.now(), readAt = 0) {
110
+ const releasedSince = (r) => { const it = recentOf(r); return !!readAt && !!it && it.alwaysOn === false && (Number(it.alwaysOnAt) || 0) > readAt }
111
+ for (const r of new Set((rooms || []).filter((x) => typeof x === 'string'))) if (!releasedSince(r)) setAlwaysOn(r, true, now)
108
112
  try { localStorage.removeItem(CD_KEPT_OLD) } catch { /* */ }
109
113
  }
110
114
  export const KEPT_NO_LINKS = 'Your cloud device keeps this Space always on, and it takes only a Space with no private lane of its own. Stop keeping it always on first (⋯ → Assistant → Always on).'
111
115
  export const KEPT_NO_PEOPLE = 'Your cloud device keeps this Space always on, and it takes only a Space that is yours alone. Stop keeping it always on first (⋯ → Assistant → Always on).'
112
116
  export const wantsLanes = (r) => { try { return localStorage.getItem(lanesKey(r)) === '1' } catch { return false } }
113
117
  export const CONTACTS_KEY = 'space:contacts'
118
+ // ⛔ A FIELD CLEARED IN THE EDITOR STAYS CLEARED (side sweep: contact-sync-restores-cleared-fields). The editor's row simply lacked a
119
+ // removed phone or @username, so a merge (Object.assign) onto another device's row kept the old value, and an older row refilled a
120
+ // name deliberately emptied. The editor names what it emptied — `cleared`, an ADDITIVE field (an older app ignores it and merges as
121
+ // before) — and mergeContactLists / dedupePeople honour it: a newer row's cleared field is removed, and no older row refills it.
122
+ const CLEARABLE = ['fn', 'tel', 'username']
123
+ /** The fields `prior` (the row being edited) had and the edited `rec` no longer has — what the person cleared — and the ones an
124
+ * EARLIER edit cleared that are still empty: a later rename replaced the row with one that named only its own clears, and a device
125
+ * that missed the first edit kept the removed phone (side sweep cycle 165, contact-sync-restores-cleared-fields revised). */
126
+ export function clearedFields(prior, rec) {
127
+ if (!prior || typeof prior !== 'object') return []
128
+ const empty = (f) => !String((rec && rec[f]) || '').trim()
129
+ return CLEARABLE.filter((f) => empty(f) && (String(prior[f] || '').trim() || isCleared(prior, f)))
130
+ }
131
+ const isCleared = (c, f) => !!(c && Array.isArray(c.cleared) && c.cleared.includes(f))
114
132
  export function normContact(c) {
115
133
  if (!c || typeof c !== 'object') return null
116
134
  if (c.kind === 'agent') {
@@ -123,7 +141,8 @@ export function normContact(c) {
123
141
  const email = (typeof c.email === 'string' && c.email.indexOf('@') > 0) ? c.email.trim().toLowerCase() : ''
124
142
  const username = (typeof c.username === 'string' && /^[a-z0-9][a-z0-9_]{2,29}$/.test(String(c.username).trim().toLowerCase().replace(/^@/, ''))) ? String(c.username).trim().toLowerCase().replace(/^@/, '') : ''
125
143
  if (!email && !username) return null
126
- return { kind: 'person', fn: typeof c.fn === 'string' ? c.fn.trim().slice(0, 80) : '', ...(email ? { email } : {}), ...(username ? { username } : {}), ...(typeof c.handle === 'string' && /^[A-Za-z0-9_-]{43}$/.test(c.handle) ? { handle: c.handle } : {}), ...(c.tel ? { tel: String(c.tel).slice(0, 40) } : {}), ...(c.at ? { at: +c.at || 0 } : {}), deleted: !!c.deleted } // `deleted` = a TOMBSTONE for a removed person; `at` gives persons LWW so a delete/edit survives the union merge
144
+ const cleared = Array.isArray(c.cleared) ? CLEARABLE.filter((f) => c.cleared.includes(f)) : [] // what the editor emptied (contact-sync-restores-cleared-fields)
145
+ return { kind: 'person', fn: typeof c.fn === 'string' ? c.fn.trim().slice(0, 80) : '', ...(email ? { email } : {}), ...(username ? { username } : {}), ...(typeof c.handle === 'string' && /^[A-Za-z0-9_-]{43}$/.test(c.handle) ? { handle: c.handle } : {}), ...(c.tel ? { tel: String(c.tel).slice(0, 40) } : {}), ...(c.at ? { at: +c.at || 0 } : {}), ...(cleared.length ? { cleared } : {}), deleted: !!c.deleted } // `deleted` = a TOMBSTONE for a removed person; `at` gives persons LWW so a delete/edit survives the union merge
127
146
  }
128
147
  // The one key a contact is deduped and merged by: an agent by id, a person by email, else by "@username".
129
148
  export const contactKey = (c) => c && (c.kind === 'agent' ? 'a:' + c.id : (c.email || (c.username ? '@' + c.username : undefined)))
@@ -154,9 +173,10 @@ export function dedupePeople(list) {
154
173
  for (const [r, g] of groups) {
155
174
  if (g.length === 1) { merged.set(r, g[0]); continue }
156
175
  const by = g.slice().sort((a, b) => (b.at || 0) - (a.at || 0)) // newest first
157
- const pick = (f) => (by.find((c) => c[f]) || {})[f]
176
+ const pick = (f) => { for (const c of by) { if (c[f]) return c[f]; if (isCleared(c, f)) return undefined } return undefined } // a newer row that CLEARED it: no older row fills it
158
177
  const out = { kind: 'person', fn: pick('fn') || '' }
159
178
  for (const f of ['email', 'username', 'handle', 'tel']) { const v = pick(f); if (v) out[f] = v }
179
+ if (Array.isArray(by[0].cleared) && by[0].cleared.length) out.cleared = by[0].cleared.slice()
160
180
  const at = by[0].at || 0; if (at) out.at = at
161
181
  out.deleted = !!by[0].deleted
162
182
  merged.set(r, out)
@@ -245,17 +265,24 @@ const CONN_ID = /^[A-Za-z0-9_-]{1,64}$/
245
265
  const isHeldStub = (k) => (k.held === 1 || k.held === true) && (k.callKey == null || k.callKey === '')
246
266
  function vaultConnStore () { try { const s = globalThis.__wbAppStoreState; return s && s.active && s.connKeys && typeof s.ask === 'function' ? s : null } catch { return null } }
247
267
  export function connKeysInVault () { return !!vaultConnStore() }
268
+ const MAX_CONNECTION_KEYS = 64
269
+ export function checkConnectionCapacity(held, pending, id) {
270
+ const reserved = new Set([...Object.keys(held || {}), ...Object.keys(pending || {})])
271
+ if (!reserved.has(id) && reserved.size >= MAX_CONNECTION_KEYS) {
272
+ throw Object.assign(new Error('Remove a connection before adding another on this device.'), { code: 'connection_limit' })
273
+ }
274
+ }
248
275
  export function normConnectionKeys(o) {
249
276
  if (!o || typeof o !== 'object' || Array.isArray(o)) return {}
250
277
  const out = {}
251
278
  const s = (v) => (typeof v === 'string' ? v.slice(0, 256) : '')
252
279
  for (const [id, k] of Object.entries(o)) {
253
- if (Object.keys(out).length >= 64) break
280
+ if (Object.keys(out).length >= MAX_CONNECTION_KEYS) break
254
281
  if (!CONN_ID.test(id) || !k || typeof k !== 'object') continue
255
282
  const held = isHeldStub(k)
256
283
  if (!held && (typeof k.callKey !== 'string' || !k.callKey || k.callKey.length > 256)) continue
257
284
  const at = Number(k.at)
258
- out[id] = { callKey: held ? '' : k.callKey, label: s(k.label), host: s(k.host), account: s(k.account), ...(Number.isFinite(at) && at > 0 ? { at } : {}), ...(held ? { held: 1 } : {}) }
285
+ out[id] = { callKey: held ? '' : k.callKey, label: s(k.label), host: s(k.host), account: s(k.account), ...(s(k.peerId) ? { peerId: s(k.peerId), ...(s(k.peerRoom) ? { peerRoom: s(k.peerRoom) } : {}) } : {}), ...(k.mcp === true ? { mcp: true } : {}), ...(Number.isFinite(at) && at > 0 ? { at } : {}), ...(held ? { held: 1 } : {}) }
259
286
  }
260
287
  return out
261
288
  }
@@ -333,7 +360,7 @@ const b64bytes = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
333
360
  export const vaultCallKeyMinter = {
334
361
  async seal ({ spki, nonce, payload, id, rec }) {
335
362
  const s = vaultConnStore(); if (!s || !s.connMint) return null
336
- let r = null; try { r = await s.ask('connSeal', { conn: id, spki: b64bytes(spki), nonce: b64bytes(nonce), payload, rec: rec || {} }, null, 8000) } catch { return null }
363
+ let r = null; try { r = await s.ask('connSeal', { conn: id, spki: b64bytes(spki), nonce: b64bytes(nonce), payload, rec: rec || {} }, null, 8000) } catch (e) { if (e?.code === 'connection_limit') throw e; return null }
337
364
  if (!r || !r.sealed || typeof r.sealed.ct !== 'string') return null
338
365
  return { sealed: r.sealed, settle: (ok, as = {}) => s.ask('connSettle', { conn: id, ok: !!ok, as }, null, 8000).then((x) => !!(x && x.held)) }
339
366
  },
@@ -345,9 +372,9 @@ export const vaultCallKeyMinter = {
345
372
  return r && r.ok && typeof r.mac === 'string' && r.keySealed && typeof r.keySealed.ct === 'string' ? { mac: r.mac, keySealed: r.keySealed } : null
346
373
  },
347
374
  /** The account's list was read: the vault adopts the pending keys it shows → [[id, { label, host, account }]] (the page keeps stubs). */
348
- async adopt (ids) {
375
+ async adopt (ids, account) {
349
376
  const s = vaultConnStore(); if (!s || !s.connMint) return []
350
- try { const r = await s.ask('connAdopt', { ids: (ids || []).slice(0, 256) }, null, 8000); return Array.isArray(r && r.adopted) ? r.adopted.filter((x) => Array.isArray(x) && typeof x[0] === 'string') : [] } catch { return [] }
377
+ try { const r = await s.ask('connAdopt', { ids: (ids || []).slice(0, 256), account }, null, 8000); return Array.isArray(r && r.adopted) ? r.adopted.filter((x) => Array.isArray(x) && typeof x[0] === 'string') : [] } catch { return [] }
351
378
  },
352
379
  }
353
380
  // a launch whose copy still holds whole keys (written before this, or while the vault was away): asked in once, after the launch
@@ -366,6 +393,13 @@ export const connGoneField = (g = loadConnGone()) => (Object.keys(g).length ? {
366
393
  export function mergeConnectionRecords(cur, inc) {
367
394
  const gone = unionMarks(normConnGone(cur && cur.gone), normConnGone(inc && inc.gone))
368
395
  const keys = normConnectionKeys(mergeByMarks(normConnectionKeys(cur && cur.keys), normConnectionKeys(inc && inc.keys), gone))
396
+ const incoming = normConnectionKeys(inc?.keys)
397
+ for (const [id, saved] of Object.entries(keys)) {
398
+ const fresh = incoming[id]
399
+ if (!fresh?.peerId || !saved.account || fresh.account !== saved.account || (fresh.at || 0) <= (saved.at || 0)) continue
400
+ if (saved.callKey && fresh.callKey && fresh.callKey !== saved.callKey) continue
401
+ keys[id] = { ...saved, peerId: fresh.peerId, peerRoom: fresh.peerRoom, at: fresh.at }
402
+ }
369
403
  return { keys, gone }
370
404
  }
371
405
  // A call key whose grant / finish answer is still out (connections.js postWithPendingKey — state machines pass 9, N#7): this device's
@@ -374,6 +408,36 @@ export const CONN_PENDING_KEY = 'space:connPending'
374
408
  export function loadPendingConnectionKeys() { try { const o = JSON.parse(lsGet(CONN_PENDING_KEY) || '{}'); return o && typeof o === 'object' && !Array.isArray(o) ? o : {} } catch { return {} } }
375
409
  export function savePendingConnectionKeys(o) { try { if (o && Object.keys(o).length) localStorage.setItem(CONN_PENDING_KEY, JSON.stringify(o)); else localStorage.removeItem(CONN_PENDING_KEY) } catch { /* private mode */ } }
376
410
  // stamped `at`: newer than a mark this device holds for the id, so a re-attach after a detach wins everywhere
411
+ const pendingKeyWrites = new Map()
412
+ export const readConnectionDisk = async name => (await import('./protectedLocal.js')).durableRead(name)
413
+ export function updatePendingConnectionKeys(change, readDisk = readConnectionDisk) {
414
+ const update = async () => {
415
+ const rows = JSON.parse(await readDisk(CONN_PENDING_KEY) || '{}')
416
+ if (!rows || typeof rows !== 'object' || Array.isArray(rows)) throw new Error('Pending connection keys could not be read')
417
+ await change(rows)
418
+ savePendingConnectionKeys(rows)
419
+ if (JSON.stringify(JSON.parse(await readDisk(CONN_PENDING_KEY) || '{}')) !== JSON.stringify(rows)) throw new Error('Could not save pending connection keys')
420
+ }
421
+ const run = () => globalThis.navigator?.locks ? navigator.locks.request('wb:pending-connection-keys', update) : update()
422
+ const scope = readDisk
423
+ const next = (pendingKeyWrites.get(scope) || Promise.resolve()).then(run)
424
+ const settled = next.catch(() => {})
425
+ pendingKeyWrites.set(scope, settled)
426
+ settled.then(() => { if (pendingKeyWrites.get(scope) === settled) pendingKeyWrites.delete(scope) })
427
+ return next
428
+ }
429
+ export function removePendingConnectionKey(id, callKey, readDisk = readConnectionDisk) {
430
+ return updatePendingConnectionKeys(rows => { if (rows[id]?.callKey === callKey) delete rows[id] }, readDisk)
431
+ }
432
+ export const appPendingConnectionStore = {
433
+ durable: true,
434
+ keep: (id, rec) => updatePendingConnectionKeys(async rows => {
435
+ for (const [key, entry] of Object.entries(rows)) if (Date.now() - Number(entry?.at || 0) >= PENDING_MS) delete rows[key]
436
+ checkConnectionCapacity(JSON.parse(await readConnectionDisk(CONNKEYS_KEY) || '{}'), rows, id)
437
+ rows[id] = { ...rec, at: Number(rec.at) || Date.now() }
438
+ }),
439
+ drop: (id, callKey) => removePendingConnectionKey(id, callKey),
440
+ }
377
441
  export function rememberConnectionKey(id, k, now = Date.now()) { return saveConnectionKeys({ ...loadConnectionKeys(), [id]: { ...k, at: Math.max(now, (loadConnGone()[id] || 0) + 1) } }) }
378
442
 
379
443
  // ── The Siri inbox (docs/siri-inbox.md): { token, defaultRoom, rooms: { [room]: { alias, label, pub:{x,y}, priv:{jwk}, at } } }.
@@ -419,14 +483,20 @@ export function mergeSiriRecords(cur, inc) {
419
483
  const gone = unionMarks(a.gone, b.gone, Infinity) // normSiri keeps the newest 64
420
484
  const token = siriKeyOf(a, b)
421
485
  const tokenHash = token ? '' : siriKeyOf({ rev: a.rev, token: a.tokenHash }, { rev: b.rev, token: b.tokenHash })
422
- const rooms = mergeSiriRooms(a.rooms, b.rooms, gone) // the newer entry (a tie: local) — and never one a mark took off
486
+ const rev = Math.max(a.rev || 0, b.rev || 0)
487
+ const eligible = [a, b].filter(s => (s.rev || 0) === rev)
488
+ const rooms = mergeSiriRooms(eligible[0].rooms, eligible[1]?.rooms || {}, gone) // the newer entry (a tie: local) — and never one a mark took off
423
489
  // a held stub never beats a whole copy of the SAME key (an older device's record still carries it)
424
- for (const [r, e] of Object.entries(rooms)) { const o = [a.rooms[r], b.rooms[r]].find((x) => x && x.priv && x.pub.x === e.pub.x && x.pub.y === e.pub.y); if (e.held && o) rooms[r] = o }
490
+ for (const [r, e] of Object.entries(rooms)) { const o = eligible.map(s => s.rooms[r]).find((x) => x && x.priv && x.pub.x === e.pub.x && x.pub.y === e.pub.y); if (e.held && o) { const { held, ...meta } = e; rooms[r] = { ...meta, priv: o.priv } } }
425
491
  // the other copy's default when this one's is gone (C3 — the keep's rule: it was blanked)
426
- return normSiri({ token, tokenHash, defaultRoom: siriDefaultOf(rooms, a.defaultRoom, b.defaultRoom), rooms, gone, rev: Math.max(a.rev || 0, b.rev || 0) })
492
+ return normSiri({ token, tokenHash, defaultRoom: siriDefaultOf(rooms, ...eligible.map(s => s.defaultRoom)), rooms, gone, rev })
427
493
  }
428
494
  export function loadSiri() { try { return normSiri(JSON.parse(lsGet(SIRI_KEY) || 'null')) } catch { return normSiri(null) } }
429
495
  export function saveSiri(o) { const n = normSiri(o); try { localStorage.setItem(SIRI_KEY, JSON.stringify(n)) } catch { /* private mode */ } try { dispatchEvent(new CustomEvent('wb-siri-changed')) } catch { /* no window (the SDK, tests) */ } return n } // the change event: the iPhone app's Siri list follows (siriHeld.js syncSiriToNative)
496
+ /** A Siri capture for `room` said BEFORE the Space was last taken off Siri (`gone[room]`, kept across a re-enable): Stop promised to
497
+ * discard it, so it is never posted — turning Siri back on before it expired posted the old words (side sweep: siri-intake-capture-
498
+ * survives-room-removal). No time on the capture, or never stopped: false (as before). */
499
+ export const siriCaptureStopped = (room, at, o = loadSiri()) => { const g = o && o.gone && Number(o.gone[room]); return !!(g && Number(at) > 0 && Number(at) <= g) }
430
500
  export const siriConfigured = (o = loadSiri()) => !!((o.token || o.tokenHash) && Object.keys(o.rooms).length)
431
501
  /** Union a synced/restored copy in — the newer entry per Space (mergeSiriRecords). Returns true on a change. */
432
502
  export function mergeSiri(incoming) {
@@ -434,7 +504,7 @@ export function mergeSiri(incoming) {
434
504
  const cur = loadSiri()
435
505
  const next = mergeSiriRecords(cur, inc)
436
506
  if (JSON.stringify(next) === JSON.stringify(cur)) return false
437
- saveSiri(next); return true
507
+ saveSiri(next); return JSON.stringify(loadSiri()) === JSON.stringify(next)
438
508
  }
439
509
  // ── A2A into a member's private lanes (docs/a2a-lanes.md): { lanes: { [laneRoom]: { handle, name, description, pub:{x,y},
440
510
  // priv:{jwk}, peers: [{ id, name, tokenHash, reply, created }] } } }. Each lane's INBOX KEYPAIR lives here and nowhere else
@@ -455,10 +525,29 @@ export function mergeA2A(incoming) {
455
525
  const cur = loadA2A()
456
526
  const next = mergeA2ARecords(cur, inc) // a2aCore.js: union, the newer copy leads, and a REMOVAL in either copy wins over a listing in the other (pass 9, K#3)
457
527
  if (JSON.stringify(next) === JSON.stringify(cur)) return false
458
- saveA2A(next); return true
528
+ saveA2A(next); return JSON.stringify(loadA2A()) === JSON.stringify(next)
459
529
  }
460
530
  /** A DETACH (connectionsSheet.js drop, after the Sentinel revoked it): the mark first — newer than the entry, and recorded even
461
531
  * when this device never held the key (attached elsewhere) — then the key. */
532
+ export async function forgetConnectionKeyDurably(id, readDisk) {
533
+ if (!CONN_ID.test(String(id))) throw new Error('Invalid connection')
534
+ const s = vaultConnStore()
535
+ if (!readDisk && s?.connForget) {
536
+ const receipt = await s.ask('connForget', { conn: id }, null, 8000)
537
+ if (!receipt?.forgotten) throw new Error('The vault could not save the removal')
538
+ return forgetConnectionKey(id)
539
+ }
540
+ const read = readDisk || (await import('./protectedLocal.js')).durableRead
541
+ const save = async () => {
542
+ const cur = loadConnectionKeys()
543
+ const at = Math.max(Date.now(), (Number(cur[id]?.at) || 0) + 1, (loadConnGone()[id] || 0) + 1)
544
+ saveConnGone(unionMarks(loadConnGone(), { [id]: at }))
545
+ if (!(Number(JSON.parse(await read(CONNGONE_KEY) || '{}')[id]) >= at)) throw new Error('Could not save the connection removal')
546
+ const rest = loadConnectionKeys(); delete rest[id]
547
+ return saveConnectionKeys(rest)
548
+ }
549
+ return globalThis.navigator?.locks ? navigator.locks.request('wb:connection-removals', save) : save()
550
+ }
462
551
  export function forgetConnectionKey(id, now = Date.now()) {
463
552
  const cur = loadConnectionKeys()
464
553
  if (CONN_ID.test(String(id))) saveConnGone(unionMarks(loadConnGone(), { [id]: Math.max(now, ((cur[id] && cur[id].at) || 0) + 1) }))
@@ -485,8 +574,17 @@ export function mergeContactLists(list, incoming) {
485
574
  const c = normContact(raw); if (!c) continue; const k = contactKey(c); const ex = byKey.get(k)
486
575
  if (!ex) { out.push(c); byKey.set(k, c); changed = true }
487
576
  else if (c.kind === 'agent') { if ((c.at || 0) >= (ex.at || 0)) { Object.assign(ex, c); changed = true } } // adopt a newer saved-assistant edit (LWW)
488
- else if ((c.at || 0) > (ex.at || 0)) { Object.assign(ex, c); changed = true } // person LWW: a newer edit / tombstone wins (equal-or-older at-less persons fall through to fill-name)
489
- else if (c.fn && !ex.fn) { ex.fn = c.fn; changed = true } // learned a name for a known address
577
+ else if ((c.at || 0) > (ex.at || 0)) { // person LWW: a newer edit / tombstone wins (equal-or-older at-less persons fall through to fill-name)
578
+ Object.assign(ex, c)
579
+ // A TOMBSTONE IS ONLY WHAT IT NAMES (side sweep cycle 165, contact-email-clear-rejoined-by-username): an edit that removed the
580
+ // email but kept the @username writes a tombstone for the email alone; kept here with the old row's username, the one-person
581
+ // merge (dedupePeople) joined it to the live row by that username and copied the removed email back onto it.
582
+ if (c.deleted) for (const f of ['email', 'username', 'handle', 'tel']) { if (!c[f]) delete ex[f] }
583
+ for (const f of c.cleared || []) { if (f === 'fn') ex.fn = ''; else delete ex[f] } // what that edit cleared goes here too
584
+ if (!c.cleared) delete ex.cleared
585
+ changed = true
586
+ }
587
+ else if (c.fn && !ex.fn && !isCleared(ex, 'fn')) { ex.fn = c.fn; changed = true } // learned a name for a known address — not one the person emptied
490
588
  }
491
589
  return { list: out, changed }
492
590
  }
@@ -517,13 +615,19 @@ export const personalAgentUI = () => { try { return localStorage.getItem('space:
517
615
  export const agentLinks = () => { try { const a = JSON.parse(localStorage.getItem(AGENT_LINKS_KEY) || '[]'); return Array.isArray(a) ? a : [] } catch { return [] } }
518
616
  export const inAgentLinks = (r) => agentLinks().includes(r)
519
617
  export const toggleAgentLink = (r) => { const s = new Set(agentLinks()); s.has(r) ? s.delete(r) : s.add(r); try { localStorage.setItem(AGENT_LINKS_KEY, JSON.stringify([...s].slice(0, 24))) } catch { /* */ } }
520
- export const saveName = (n) => { state.myName = String(n || '').trim().slice(0, 24); try { localStorage.setItem('space:myname', state.myName) } catch { /* */ } }
618
+ // WHEN THE NAME WAS SET (side sweep app-index-push-reverts-account-display-name): `at` = the time a person TYPED it (nameGate), or
619
+ // the account index's `nameAt` for a name taken from there. The index carries it as `nameAt`, so a device still holding an older
620
+ // name no longer writes it back over a rename made on another device. 0 = not known (an older device, a restored name).
621
+ const NAME_AT_KEY = 'space:myname-at'
622
+ export const loadNameAt = () => { try { const n = Number(localStorage.getItem(NAME_AT_KEY)); return Number.isFinite(n) && n > 0 ? n : 0 } catch { return 0 } }
623
+ export const saveName = (n, { at } = {}) => { state.myName = String(n || '').trim().slice(0, 24); try { localStorage.setItem('space:myname', state.myName); if (Number(at) > 0) localStorage.setItem(NAME_AT_KEY, String(Number(at))) } catch { /* */ } }
521
624
  /** A name learned from the account — the backup or the account's room list — not typed here: saved, and a "What's your name?"
522
625
  * already waiting is answered with it (nameGate.nameArrived, wired in space.js; the owner, 2026-10-25: "Why is your name still
523
- * required after restore?"). */
524
- export const adoptName = (n) => {
525
- const v = String(n || '').trim(); if (!v || state.myName) return false
526
- saveName(v)
626
+ * required after restore?"). `at`: the account's time for it — a NEWER one than this device's replaces a name held here. */
627
+ export const adoptName = (n, at = 0) => {
628
+ const v = String(n || '').trim(); if (!v) return false
629
+ if (state.myName && !(Number(at) > loadNameAt() && v !== state.myName)) return false
630
+ saveName(v, { at })
527
631
  try { if (typeof dispatchEvent === 'function' && typeof CustomEvent === 'function') dispatchEvent(new CustomEvent('wb-name-arrived', { detail: { name: state.myName } })) } catch { /* */ }
528
632
  return true
529
633
  }
@@ -568,11 +672,14 @@ export function plainProse(s) {
568
672
  .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)')
569
673
  .trim()
570
674
  }
571
- export const rememberCrossed = (r, text) => {
572
- const t = plainProse(text); if (!t) return
573
- try { localStorage.setItem(crossedKey(r), JSON.stringify([...crossedList(r).filter((x) => x !== t), t].slice(-50))) } catch { /* */ }
675
+ export const rememberCrossed = (room, id) => {
676
+ if (typeof id !== 'string' || !id.startsWith('cross:')) return
677
+ const entries = crossedList(room).filter(e => typeof e?.id === 'string' && e.id !== id)
678
+ try { localStorage.setItem(crossedKey(room), JSON.stringify([...entries, { id }].slice(-50))) } catch {}
574
679
  }
575
- export const wasCrossed = (r, text) => { const t = plainProse(text); return !!t && crossedList(r).some((x) => x === t || plainProse(x) === t) }
680
+ export const wasCrossed = (room, mirroredId) => typeof mirroredId === 'string' && mirroredId.startsWith('sh:cross:') &&
681
+ crossedList(room).some(entry => entry?.id === mirroredId.slice(3))
682
+
576
683
 
577
684
  // ── deleted-Space tombstones ────────────────────────────────────────────────────────────────────────────────────────
578
685
  // A delete is a TOMBSTONE, not a local forget: it rides the index doc to your other devices (roomSync publishes
package/sw-notif-core.js CHANGED
@@ -35,7 +35,7 @@ self.wbxIdbGet = (key) => new Promise((resolve) => {
35
35
  setTimeout(() => resolve(null), IDB_WAIT)
36
36
  try {
37
37
  const r = indexedDB.open('spaces', 1)
38
- r.onsuccess = () => { try { const rq = r.result.transaction('kv', 'readonly').objectStore('kv').get(key); rq.onsuccess = () => resolve(rq.result || null); rq.onerror = () => resolve(null) } catch { resolve(null) } }
38
+ r.onsuccess = () => { const db = r.result; db.onversionchange = () => db.close(); try { const rq = db.transaction('kv', 'readonly').objectStore('kv').get(key); rq.onsuccess = () => resolve(rq.result || null); rq.onerror = () => resolve(null) } catch { resolve(null) } }
39
39
  r.onerror = () => resolve(null)
40
40
  r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* already there */ } }
41
41
  } catch { resolve(null) }
@@ -44,7 +44,7 @@ self.wbxIdbSet = (key, value) => new Promise((resolve) => {
44
44
  setTimeout(() => resolve(false), IDB_WAIT)
45
45
  try {
46
46
  const r = indexedDB.open('spaces', 1)
47
- r.onsuccess = () => { try { const rq = r.result.transaction('kv', 'readwrite').objectStore('kv').put(value, key); rq.onsuccess = () => resolve(true); rq.onerror = () => resolve(false) } catch { resolve(false) } }
47
+ r.onsuccess = () => { const db = r.result; db.onversionchange = () => db.close(); try { const rq = db.transaction('kv', 'readwrite').objectStore('kv').put(value, key); rq.onsuccess = () => resolve(true); rq.onerror = () => resolve(false) } catch { resolve(false) } }
48
48
  r.onerror = () => resolve(false)
49
49
  r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* already there */ } }
50
50
  } catch { resolve(false) }
@@ -80,12 +80,12 @@ self.wbxNoteSw = (line) => {
80
80
  // `id` is THIS showing's own mark (the worker puts it in the notification's data too): iOS keeps GHOSTS of long-gone
81
81
  // notifications in getNotifications() — the owner's list held two stale 'space-test' entries for hours — so a fresh
82
82
  // notification that shares a ghost's TAG would read as "still showing" and a consumed tap could never be inferred.
83
- self.wbxNoteShown = async (room, tag, id) => {
84
- if (!room || !tag) return
83
+ self.wbxNoteShown = async (room, tag, id, dest = {}) => {
84
+ if (!tag || !(room || dest.code || dest.intake)) return
85
85
  try {
86
86
  const a = await self.wbxIdbGet('notifShown')
87
87
  const list = (Array.isArray(a) ? a : []).filter((x) => x && x.tag !== tag)
88
- list.push({ room, tag, id: id || '', at: Date.now() })
88
+ list.push({ room, tag, id: id || '', at: Date.now(), ...(dest.card ? { card: dest.card } : {}), ...(dest.code ? { code: dest.code } : {}), ...(dest.intake ? { intake: 1 } : {}) })
89
89
  while (list.length > 12) list.shift()
90
90
  await self.wbxIdbSet('notifShown', list)
91
91
  } catch { /* */ }
@@ -312,14 +312,16 @@ self.wbxWirePush = (cfg) => self.addEventListener('push', (e) => {
312
312
  if (p.remind || p.code) { // "WAITING FOR YOUR APPROVAL" — a room's card or a Code ask (wbxWaitingNotice)
313
313
  await self.wbxNoteSw('push remind ' + (p.code ? 'code' : room.slice(0, 10)))
314
314
  const w = (await self.wbxWaitingNotice(p)) || { title: 'Waiting for your approval', body: 'Open the app to answer.', tag: 'remind', data: {} }
315
- return self.registration.showNotification(w.title, { body: w.body, tag: w.tag, data: { ...w.data, id: idFor(w.tag) }, ...art, renotify: true })
315
+ const id = idFor(w.tag)
316
+ await self.wbxNoteShown(w.data.room || '', w.tag, id, w.data)
317
+ return self.registration.showNotification(w.title, { body: w.body, tag: w.tag, data: { ...w.data, id }, ...art, renotify: true })
316
318
  }
317
319
  // A MESSAGE WAITS IN THE ACCOUNT'S INTAKE (agent/messageIntake.mjs wake list; the owner, 2026-11-09: no notification when Claude Code
318
320
  // wrote to the private lane). Content-free by construction: the box is sealed to the account's devices and nobody on the way knows
319
321
  // who sent it. The tap opens the app (no room: the message room is not one to show), which collects it into its Space.
320
322
  if (p.intake) {
321
323
  await self.wbxNoteSw('push intake')
322
- const id = idFor('intake'); await self.wbxNoteShown('', 'intake', id)
324
+ const id = idFor('intake'); await self.wbxNoteShown('', 'intake', id, { intake: 1 })
323
325
  return self.registration.showNotification('New message for your assistant', { body: cfg.intakeBody || 'An agent you let in (or Siri) sent your assistant a message. Open the app to read it.', tag: 'intake', data: { intake: 1, id }, ...art, renotify: true })
324
326
  }
325
327
  const kind = p.test ? 'test' : p.invite ? 'invite' : p.call ? 'call' : 'message'
@@ -365,7 +367,8 @@ self.wbxWirePush = (cfg) => self.addEventListener('push', (e) => {
365
367
  await self.wbxNoteShown(room, tag, id)
366
368
  await self.registration.showNotification(d ? d.title : cfg.generic.title, { body: d ? d.body : cfg.generic.body, tag, data: { room, id }, ...art, silent, renotify: !silent })
367
369
  // …and iOS ignores `silent`: the room on screen is closed at once (it was shown, which is what iOS requires).
368
- if (viewing && await self.wbxQuietIfViewing(room, tag)) await self.wbxNoteSw('closed at once — the room is on screen')
370
+ // closed here, not by the person: forgotten, or the vault later reads it as a tap and reopens this room (side sweep 2026-11-28)
371
+ if (viewing && await self.wbxQuietIfViewing(room, tag)) { await self.wbxForgetShown(tag, id); await self.wbxNoteSw('closed at once — the room is on screen') }
369
372
  else if (room) await self.wbxBadgeAdd(room) // the number on the app's icon counts it until it is read (appBadge.js)
370
373
  // The push carried the preview, so describe() did not run: run it now for its PREFETCH — after the notification is up,
371
374
  // so a slow or refused fetch never delays or blanks what is shown.
package/tapTrail.js ADDED
@@ -0,0 +1,58 @@
1
+ // spaces/public/tapTrail.js — a device-only log of what happened to each tapped notification (2026-10-01).
2
+ //
3
+ // A tap crosses up to four hands — the service worker, the vault page, the app frame, the room opener — and every one
4
+ // of them failed SILENTLY: the owner's "I press it and it doesn't open the room" could be any of them, an iPhone push
5
+ // can't be reproduced off the device, and the only on-device log showed only when the app failed to boot. So each hand
6
+ // writes one line here, and the crash-trail view (Settings → five taps on the build line) shows them. The vault keeps
7
+ // its own copy under its own origin and hands it to the app on request. Never sent anywhere. Leaf: localStorage only.
8
+ export function makeTapTrail(key, max = 24) {
9
+ const read = () => { try { const a = JSON.parse(localStorage.getItem(key) || '[]'); return Array.isArray(a) ? a : [] } catch { return [] } }
10
+ // A REPEAT IS ONE LINE, COUNTED (the owner's boot log, 2026-10-20): "worker: index read: 7 rooms …" every few seconds filled
11
+ // the vault's 24 lines, so the slow launch the log was opened to explain had already rotated out. The same line again is
12
+ // folded into the last one — its first time kept, "×N, last <time>" appended — so what is different keeps its place.
13
+ const STAMP = /^\S+(?: [AP]M)? /
14
+ const REPEAT = / \(×(\d+), last [^)]*\)$/
15
+ const note = (line) => {
16
+ try {
17
+ const a = read()
18
+ const now = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
19
+ const msg = String(line).slice(0, 500) // 500: the boot line carries every mark of the open (bootReport) — at 200 the ones that explain a slow open (index sync, room entered, cache drawn) were cut off (2026-10-21)
20
+ const prev = a.length ? a[a.length - 1] : ''
21
+ const head = prev.match(STAMP)
22
+ const body = head ? prev.slice(head[0].length) : ''
23
+ if (head && body.replace(REPEAT, '') === msg) {
24
+ const m = body.match(REPEAT)
25
+ a[a.length - 1] = head[0] + msg + ` (×${m ? Number(m[1]) + 1 : 2}, last ${now})`
26
+ localStorage.setItem(key, JSON.stringify(a))
27
+ return
28
+ }
29
+ a.push(now + ' ' + msg)
30
+ while (a.length > max) a.shift()
31
+ localStorage.setItem(key, JSON.stringify(a))
32
+ } catch { /* a diagnostic must never be the thing that breaks the tap */ }
33
+ }
34
+ const clear = () => { try { localStorage.removeItem(key) } catch { /* */ } }
35
+ return { note, read, clear }
36
+ }
37
+
38
+ /** A room id as the trail shows it — enough to tell two rooms apart on a screenshot, not the whole id. */
39
+ export const roomTag = (r) => (r ? String(r).slice(0, 10) : '-')
40
+
41
+ /**
42
+ * Keep looking for a tapped room for a while after a launch or a foreground, instead of at one instant.
43
+ * On an iPhone, tapping a notification resumes the page (visibilitychange fires at once) and wakes the service worker in
44
+ * parallel; the worker writes the tapped room only once it has booted, often a beat AFTER the page looked. A single look
45
+ * missed it and the app stayed on its last room (the owner, 2026-10-01). `check()` resolves truthy once a tap was
46
+ * routed, which ends the watch; `start()` (re)opens a window of `forMs`, looking every `everyMs`.
47
+ */
48
+ export function watchForTap(check, { everyMs = 500, forMs = 15000, now = Date.now, setT = setTimeout } = {}) {
49
+ let until = 0, running = false
50
+ const tick = async () => {
51
+ let hit = false
52
+ try { hit = !!(await check()) } catch { /* a failed look is just a miss */ }
53
+ if (hit) until = 0
54
+ if (now() < until) setT(tick, everyMs); else running = false
55
+ }
56
+ const start = () => { until = now() + forMs; if (!running) { running = true; tick() } }
57
+ return { start }
58
+ }
package/turnVerdict.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // none of our codes: the API front door cut the request at ~30 s while the server finishes — the reply still comes;
7
7
  // never resend) · failed (a 5xx we raised) · no_answer
8
8
  export const CLOCK_REASON = 'This device’s clock is more than a minute off, so the confidential Space refused the request — set the clock to the right time (automatic), then try again.'
9
+ export const CONTINUATION_WINDOW_MS = 10 * 60 * 1000
9
10
  export const QUEUE_RETRY_MS = 1500
10
11
  export const QUEUE_MAX_TRIES = 640 // ~16 min of holding: longer than the longest turn (13 min since 2026-11-18; was 120 ≈ 180 s)
11
12
 
package/usageReceipts.js CHANGED
@@ -58,7 +58,10 @@ export async function receiptFor (key, room) { return key ? { drop: await dropFo
58
58
  // ── the sidecar: `usage-YYYY-MM` = { v:1, r: { <receipt id>: [day, payer, costMicros, in, out] } } ──
59
59
  export const monthOf = (ts) => { const d = new Date(ts); return d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0') }
60
60
  export const docNameFor = (month) => 'usage-' + month
61
- const row = (b) => [new Date(b.ts).getUTCDate(), Math.max(0, PAYERS.indexOf(b.payer)), Math.max(0, Math.round(Number(b.costMicros) || 0)), Math.max(0, Math.round(Number(b.in) || 0)), Math.max(0, Math.round(Number(b.out) || 0))]
61
+ // A sixth field, 1, when the reply's total counts only its priced calls (receipt `source` 'provider-partial' or 'none'): ADDITIVE —
62
+ // a reader that knows five fields reads the first five (side sweep: account-usage-drops-partial-price)
63
+ const unpricedSource = (s) => s === 'provider-partial' || s === 'none'
64
+ const row = (b) => [new Date(b.ts).getUTCDate(), Math.max(0, PAYERS.indexOf(b.payer)), Math.max(0, Math.round(Number(b.costMicros) || 0)), Math.max(0, Math.round(Number(b.in) || 0)), Math.max(0, Math.round(Number(b.out) || 0)), ...(unpricedSource(b.source) ? [1] : [])]
62
65
 
63
66
  /** Merge receipts into a month doc (idempotent by receipt id). */
64
67
  export function foldInto (doc, bodies) {
@@ -68,12 +71,14 @@ export function foldInto (doc, bodies) {
68
71
  }
69
72
  /** A month doc → totals: costMicros overall and by payer, replies, tokens, and per day. */
70
73
  export function usageTotals (doc) {
71
- const t = { costMicros: 0, replies: 0, in: 0, out: 0, byPayer: Object.fromEntries(PAYERS.map((p) => [p, 0])), byDay: {} }
74
+ // unpriced: replies whose cost counts only their priced calls — the total is then a floor, as the room's Usage says
75
+ const t = { costMicros: 0, replies: 0, in: 0, out: 0, unpriced: 0, byPayer: Object.fromEntries(PAYERS.map((p) => [p, 0])), byDay: {} }
72
76
  for (const v of Object.values((doc && doc.r) || {})) {
73
77
  if (!Array.isArray(v)) continue
74
- const [day, pi, cost, i, o] = v
78
+ const [day, pi, cost, i, o, partial] = v
75
79
  const payer = PAYERS[pi] || 'witbitz'
76
80
  t.costMicros += cost; t.replies++; t.in += i; t.out += o; t.byPayer[payer] += cost
81
+ if (partial === 1) t.unpriced++
77
82
  t.byDay[day] = (t.byDay[day] || 0) + cost
78
83
  }
79
84
  return t
@@ -127,10 +132,12 @@ export async function collectUsage ({ key, rooms, read, ack, readDoc, writeDoc,
127
132
  }
128
133
  }
129
134
  await Promise.all(Array.from({ length: Math.min(READS_AT_ONCE, rooms.length) }, (_, w) => worker(w)))
135
+ let unread = 0 // Spaces whose receipts could not be read now (no answer, a server error, a limit) — said to the reader, not passed over (side sweep: account-usage-unread-room-looks-current)
130
136
  for (const f of fetched) {
131
137
  if (!f) continue
132
138
  const { room, drop, ck, c, r } = f
133
- if (!r || r.status !== 200 || !Array.isArray(r.boxes)) continue
139
+ if (!r || r.status >= 500 || r.status === 429) { unread++; continue }
140
+ if (r.status !== 200 || !Array.isArray(r.boxes)) continue
134
141
  const items = []
135
142
  for (let i = 0; i < r.boxes.length; i++) {
136
143
  let b = null
@@ -172,5 +179,5 @@ export async function collectUsage ({ key, rooms, read, ack, readDoc, writeDoc,
172
179
  const pos = Number.isInteger(p.end) ? p.end : p.c.pos
173
180
  if (pos !== p.c.pos || keep.length !== p.c.pend.length) cursor.set(p.ck, { pos, pend: keep }) // a quiet room costs no write
174
181
  }
175
- return { folded, rooms: perRoom.filter((p) => p.items.length).length, cleared }
182
+ return { folded, rooms: perRoom.filter((p) => p.items.length).length, cleared, unread }
176
183
  }