@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/sdkAccount.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { preferredAssociation, reconcileAccountLanes } from './laneAssociation.js'
1
2
  // spaces/public/sdkAccount.js — `wb.account`: the account's LIVE index for a builder's app (2026-10-03; the owner, on what
2
3
  // the SDK lacked next to the Spaces app: "And what about the index room etc." → "Yes"). wb.backup puts the room list in
3
4
  // the vault for a RESTORE on a new device; this keeps two LIVE devices in step, the way the app's own index room does:
@@ -68,8 +69,25 @@ export function mergeIndex(a, b, maxRooms = 500) {
68
69
  for (const r of [...(a.rooms || []), ...(b.rooms || [])]) {
69
70
  if (!r || !r.room) continue
70
71
  const prev = rooms.get(r.room)
71
- const newer = !prev || num(r.at) > num(prev.at) ? r : prev
72
+ const latest = !prev || num(r.at) > num(prev.at) ? r : prev
73
+ const assoc = preferredAssociation(prev, r)
74
+ const newer = { ...latest, kind: assoc.kind, ...(assoc.associationAt ? { associationAt: assoc.associationAt } : {}) }
75
+ if (assoc.mintedFor || prev?.mintedFor || r.mintedFor) newer.mintedFor = assoc.mintedFor || prev?.mintedFor || r.mintedFor
76
+ if (assoc.laneOrigin === 'minted' && !assoc.detachedLane) newer.laneOrigin = 'minted'
77
+ else delete newer.laneOrigin
78
+ if (assoc.detachedLane) { newer.detachedLane = true; delete newer.shared }
79
+ else { delete newer.detachedLane; if (assoc.shared) newer.shared = assoc.shared; else delete newer.shared }
72
80
  const pin = !prev || num(r.pinnedAt) > num(prev.pinnedAt) ? r : prev
81
+ // THE LABEL AND THE ARCHIVE MARK EACH BY ITS OWN CLOCK, as the app keeps them (side sweep 2026-11-28: a rename on one device and an
82
+ // archive of the same room on another, before they synced — the later edit's whole entry replaced both). An entry without the
83
+ // field's clock (an older SDK's) counts by its `at`, as before.
84
+ if (prev) {
85
+ const lab = (x) => num(x.labelAt) || num(x.at), arc = (x) => num(x.archivedAt) || num(x.at)
86
+ const L = lab(r) > lab(prev) ? r : prev, A = arc(r) > arc(prev) ? r : prev
87
+ for (const k of ['label', 'renamed', 'labelAt']) { if (L[k] !== undefined) newer[k] = L[k]; else delete newer[k] }
88
+ if (A.archived) newer.archived = true; else delete newer.archived
89
+ if (num(A.archivedAt)) newer.archivedAt = A.archivedAt; else delete newer.archivedAt
90
+ }
73
91
  rooms.set(r.room, pin.pinnedAt || pin.pinned ? { ...newer, pinned: !!pin.pinned, pinnedAt: num(pin.pinnedAt) } : newer)
74
92
  }
75
93
  for (const [room, r] of rooms) if (tomb.has(room) && tomb.get(room) >= num(r.at)) rooms.delete(room) // only a TOMBSTONE removes — an entry from a backup made before `at` existed has none
@@ -88,9 +106,11 @@ export function mergeIndex(a, b, maxRooms = 500) {
88
106
  const k = linkKey(l.a, l.b), prev = links.get(k)
89
107
  if (!prev || num(l.at) > num(prev.at)) links.set(k, l)
90
108
  }
91
- const keepDevices = Object.entries(devices).sort((x, y) => num(y[1].seenAt) - num(x[1].seenAt)).slice(0, MAX_DEVICES)
109
+ // the newest kept: seen, or signed out — a fresh sign-out mark must reach the device it signs out
110
+ const lastOf = (d) => Math.max(num(d.seenAt), num(d.out))
111
+ const keepDevices = Object.entries(devices).sort((x, y) => lastOf(y[1]) - lastOf(x[1])).slice(0, MAX_DEVICES)
92
112
  return {
93
- rooms: [...rooms.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
113
+ rooms: reconcileAccountLanes([...rooms.values()]).sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
94
114
  tomb: [...tomb.entries()].map(([room, at]) => ({ room, at })).sort((x, y) => x.at - y.at).slice(-MAX_TOMBS),
95
115
  devices: Object.fromEntries(keepDevices),
96
116
  links: [...links.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-200),
@@ -145,8 +165,12 @@ export class AccountIndex {
145
165
  get enabled() { return this._backup.enabled }
146
166
  /** This device's id in the account (stable while its state is kept). */
147
167
  get deviceId() { return (this._backup._s && this._backup._s.device && this._backup._s.device.id) || '' }
148
- /** The account's rooms: [{ room, link, kind, label?, shared?, archived? }] — archived ones included, so filter as you like. */
149
- get rooms() { return this._backup.rooms }
168
+ /** The account's rooms: [{ room, link, kind, label?, shared?, archived?, alwaysOn? }] — archived ones included, so filter as you like.
169
+ * `alwaysOn: true`: the account's saved Always on mark, as of the last sync (side sweep: sdk-always-on-status-omits-saved-choice —
170
+ * the list carried nothing, though people and private assistants are refused on it). A view: never written from here. */
171
+ get rooms() { const k = this._keptMarks; return k && k.size ? this._backup.rooms.map((r) => (r && k.has(r.room) ? { ...r, alwaysOn: true } : r)) : this._backup.rooms }
172
+ /** @private the account index's always-on marks (sync, and sdkCloudDevice.js markKept after it writes one) */
173
+ _noteKeptMarks(doc) { this._keptMarks = new Set(Object.entries((doc && doc.rooms && typeof doc.rooms === 'object' && doc.rooms) || {}).filter(([, e]) => e && typeof e === 'object' && e.alwaysOn === true && !e.deleted).map(([room]) => room)) }
150
174
  /** The account's devices: [{ id, name, seenAt, signedOut, current }]. */
151
175
  get devices() {
152
176
  return Object.entries(this._devices).map(([id, d]) => ({ id, name: d.name || '', seenAt: num(d.seenAt), signedOut: !!d.out, current: id === this.deviceId, ...(typeof d.sdk === 'string' && d.sdk ? { sdk: d.sdk } : {}) }))
@@ -161,29 +185,59 @@ export class AccountIndex {
161
185
  _usageKey() { const s = this._backup._s; return (s && normUsageKey(s.usage)) || null }
162
186
  _usageKeys() { const s = this._backup._s; return s ? [normUsageKey(s.usage), ...((s.usageOld || []).map(normUsageKey))].filter(Boolean) : [] }
163
187
 
164
- _noteLink(a, b, cap) {
188
+ _noteLink(a, b, cap, live = null) {
165
189
  const s = this._backup._s; if (!s) return
190
+ if (live) (this._liveLinks = this._liveLinks || new Set()).add(live) // a link open on this device: stopped when the account drops it (side sweep 2026-11-28)
166
191
  const k = linkKey(a, b)
192
+ if (live) (this._latestLink = this._latestLink || new Map()).set(k, live) // the newest handle for the pair here: an older one is retired (side sweep round 2)
167
193
  const prev = (s.links || []).find((l) => linkKey(l.a, l.b) === k)
168
- if (prev && !prev.removed && prev.cap === cap) return
169
- s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, cap, at: Date.now() }].slice(-200)
194
+ if (prev && !prev.removed && prev.cap === cap) { if (live) live._linkAt = num(prev.at); return }
195
+ const at = Date.now()
196
+ if (live) live._linkAt = at // which saved link this handle stands for: a later one is a replacement it may not remove
197
+ s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, cap, at }].slice(-200)
170
198
  this._backup._changed(); this._schedule()
171
199
  }
172
- _dropLink(a, b) {
200
+ /** @private ANOTHER DEVICE'S UNLINK STOPS THE LINK OPEN HERE (side sweep 2026-11-28): the sync removed the saved link, but two lanes open
201
+ * on this device kept their live tool and went on carrying asks and answers between the assistants. */
202
+ _stopDroppedLinks(links) {
203
+ if (!this._liveLinks || !this._liveLinks.size) return
204
+ const byKey = new Map((links || []).map((l) => [linkKey(l.a, l.b), l]))
205
+ for (const live of [...this._liveLinks]) {
206
+ if (live._dead) { this._liveLinks.delete(live); continue }
207
+ const e = byKey.get(linkKey(live.a.room, live.b.room))
208
+ if (e && e.removed) { this._liveLinks.delete(live); try { live._stop() } catch { /* */ } }
209
+ }
210
+ }
211
+ _dropLink(a, b, handle = null) {
173
212
  const s = this._backup._s; if (!s) return
174
213
  const k = linkKey(a, b)
214
+ // A RETIRED HANDLE'S UNLINK (side sweep: retired-sdk-link-unlinks-replacement): the saved link is already removed, or a newer link of
215
+ // the same pair replaced the one this handle stood for — a fresh removal keyed only by the pair would supersede that replacement.
216
+ if (handle) {
217
+ // …or the pair was linked again on this device by a newer handle — a lane that closed and reopened reuses the saved link's time,
218
+ // so the time alone cannot tell them apart (side sweep round 2)
219
+ const latest = this._latestLink && this._latestLink.get(k)
220
+ if (latest && latest !== handle) return
221
+ const cur = (s.links || []).find((l) => linkKey(l.a, l.b) === k)
222
+ if (cur && (cur.removed || (handle._linkAt != null && num(cur.at) > num(handle._linkAt)))) return
223
+ }
175
224
  s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, removed: true, at: Date.now() }].slice(-200)
176
225
  this._backup._changed(); this._schedule()
177
226
  }
178
227
 
179
228
  /** Mark a room archived (or not) on every device. It stays in the account and in the backup. */
180
- archive(room, on = true) { return this._edit(room, (r) => ({ ...r, archived: !!on })) }
229
+ archive(room, on = true) { return this._edit(room, (r) => ({ ...r, archived: !!on, archivedAt: Math.max(Date.now(), num(r.archivedAt) + 1) })) }
181
230
  pin(room, on = true) { return this._edit(room, (r) => ({ ...r, pinned: !!on, pinnedAt: Math.max(Date.now(), num(r.pinnedAt) + 1) })) }
182
231
  /** Rename a room in the account (the label a restore and your list show). */
183
- rename(room, label) { return this._edit(room, (r) => ({ ...r, label: String(label || '').slice(0, 120), renamed: true })) }
232
+ rename(room, label) { return this._edit(room, (r) => ({ ...r, label: String(label || '').slice(0, 120), renamed: true, labelAt: Math.max(Date.now(), num(r.labelAt) + 1) })) }
184
233
  /** Drop a room from the account on EVERY device — the room itself is not deleted (that is wb.rooms.delete, for a
185
234
  * tenant). Opening its link again later brings it back. */
186
- forget(room) { this._backup.remove(room); return this }
235
+ forget(room) {
236
+ for (const child of this._backup.rooms || []) if (child.shared === room) this._backup._detachLane(child.room, room)
237
+ this._backup.remove(room)
238
+ this._pruneAgents?.()
239
+ return this
240
+ }
187
241
  async repairNames() { return this._repairNames(this._readName) }
188
242
  async _repairNames(read) {
189
243
  const state = this._backup._s
@@ -260,7 +314,8 @@ export class AccountIndex {
260
314
  * receipt address; the server seals each reply's cost to it, in the room. This folds the new receipts into the account's
261
315
  * monthly sidecar (kept in the index room, sealed like the index) and reads the month.
262
316
  * @param {object} [o] { month?: 'YYYY-MM' } (default this month, UTC)
263
- * → { month, replies, costMicros, costUsd, byPayer: { you, admin, app, witbitz } (micros), byDay, in, out } */
317
+ * → { month, replies, costMicros, costUsd, byPayer: { you, admin, app, witbitz } (micros), byDay, in, out, unpriced } — `unpriced`: replies
318
+ * whose cost counts only their priced calls (a call reported no price), so costMicros is a floor */
264
319
  async usage({ month } = {}) {
265
320
  if (!this.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore)')
266
321
  const m = month === undefined ? monthOf(Date.now()) : String(month)
@@ -295,7 +350,7 @@ export class AccountIndex {
295
350
  if (!this._again) this._again = this._running.catch(() => null).then(() => { this._again = null; return this.enabled ? this.sync() : { ok: false, rooms: this.rooms, devices: this.devices } })
296
351
  return this._again
297
352
  }
298
- this._running = this._sync().finally(() => { this._running = null; this._syncSettled?.() })
353
+ this._running = this._sync().finally(() => { this._running = null; this._syncSettled?.(); this._pruneAgents?.() })
299
354
  return this._running
300
355
  }
301
356
 
@@ -339,7 +394,11 @@ export class AccountIndex {
339
394
  const s = this._backup._s
340
395
  const i = s ? s.rooms.findIndex((r) => r.room === room) : -1
341
396
  if (i < 0) throw fail('unknown_room', 'that room is not in this account')
342
- s.rooms[i] = { ...fn(s.rooms[i]), at: Date.now() }
397
+ // the label's and the archive mark's own clocks are kept as they were before this edit (mergeIndex: an edit of one field is not
398
+ // a newer value of the other — side sweep 2026-11-28)
399
+ const r = s.rooms[i], base = { ...r, labelAt: num(r.labelAt) || num(r.at), archivedAt: num(r.archivedAt) || num(r.at) }
400
+ for (const k of ['labelAt', 'archivedAt']) if (!base[k]) delete base[k]
401
+ s.rooms[i] = { ...fn(base), at: Date.now() }
343
402
  this._backup._schedule()
344
403
  return this
345
404
  }
@@ -415,6 +474,9 @@ export class AccountIndex {
415
474
  if (!gotX.ok) { this.lastError = fail(gotX.unopenable ? 'unopenable' : 'unreadable', gotX.unopenable ? 'the account index could not be opened' : 'the account index could not be read', { status: gotX.status }); return { ok: false, rooms: this.rooms, devices: this.devices } }
416
475
  const old = got.doc ? { rooms: got.doc.rooms || [], tomb: got.doc.tomb || [], links: got.doc.links || [], devices: got.doc.devices || {}, usage: normUsageKey(got.doc.usage), usageOld: (got.doc.usageOld || []).map(normUsageKey).filter(Boolean) } : { rooms: [], tomb: [], links: [], devices: {}, usage: null, usageOld: [] }
417
476
  const fromApp = fromAppIndex(gotX.doc)
477
+ const marksBefore = [...(this._keptMarks || [])].sort().join('\n')
478
+ this._noteKeptMarks(gotX.doc)
479
+ const marksChanged = [...this._keptMarks].sort().join('\n') !== marksBefore // another device kept or stopped a Space: onChange tells the app
418
480
  const remote = { ...mergeIndex(old, fromApp), ...mergeUsage(old, fromApp) } // READ-THROUGH: both docs, the newer of each entry (one rule, mergeIndex)
419
481
  const s = this._backup._s
420
482
  const me = this._me()
@@ -423,12 +485,14 @@ export class AccountIndex {
423
485
  const outs = s.outs || {}
424
486
  const localDevices = { ...this._devices }
425
487
  for (const [id, at] of Object.entries(outs)) { const d = localDevices[id] || remote.devices[id]; if (d && num(d.out) < at) localDevices[id] = { ...d, out: at } }
426
- const local = { rooms: s.rooms, tomb: s.tomb || [], links: s.links || [], devices: { ...localDevices, [me.id]: { ...mine, name: me.name || mine.name || '', seenAt: num(mine.seenAt), ...(typeof this._spk === 'string' && this._spk ? { spk: this._spk } : {}), ...(this._version ? { sdk: this._version } : {}) } } }
488
+ const local = { rooms: s.rooms, tomb: s.tomb || [], links: s.links || [], devices: { ...localDevices, [me.id]: { ...mine, name: me.name || mine.name || '', seenAt: num(mine.seenAt) || Date.now(), ...(typeof this._spk === 'string' && this._spk ? { spk: this._spk } : {}), ...(this._version ? { sdk: this._version } : {}) } } }
427
489
  const merged = mergeIndex(local, remote)
428
490
  // the usage key: made by the first device that finds none — only after this DEFINITIVE read, so two keys meet only in a race
429
491
  Object.assign(merged, mergeUsage({ usage: s.usage, usageOld: s.usageOld }, remote))
430
492
  if (!merged.usage) merged.usage = await newUsageKey()
431
493
  if (moved()) return stopped()
494
+ // this device is never trimmed out of its own list (a full account kept the newest 50 without it)
495
+ if (!merged.devices[me.id]) merged.devices[me.id] = local.devices[me.id]
432
496
  const self = merged.devices[me.id]
433
497
  if (self.out) return this._signedOut(['erased', 'moved'].includes(self.outWhy) ? self.outWhy : undefined)
434
498
  if (Date.now() - num(self.seenAt) > SEEN_EVERY) merged.devices[me.id] = { ...self, seenAt: Date.now() }
@@ -437,6 +501,7 @@ export class AccountIndex {
437
501
  const roomsBefore = canon({ rooms: s.rooms, tomb: s.tomb || [] })
438
502
  this._devices = merged.devices
439
503
  s.rooms = merged.rooms; s.tomb = merged.tomb; s.links = merged.links; s.usage = merged.usage; s.usageOld = merged.usageOld
504
+ this._stopDroppedLinks(merged.links)
440
505
  const after = canon(merged)
441
506
  // DUAL WRITE: the old doc for every older release, then the app's; each only when it differs from what it holds, each over
442
507
  // the version read. A 409 on either re-reads both and merges again.
@@ -450,19 +515,24 @@ export class AccountIndex {
450
515
  }
451
516
  // the index now carries each kept sign-out (written above, or it already had it) — or the device is gone from it: let go
452
517
  if (Object.keys(outs).length) {
453
- const left = Object.fromEntries(Object.entries(outs).filter(([id, at]) => merged.devices[id] && num(merged.devices[id].out) < at))
518
+ // from the CURRENT list: a sign-out made while the write was out (not in `outs`, or newer) stays for the next pass (side sweep:
519
+ // sdk-signout-completion-clears-newer-request — the snapshot overwrote it, and a page closed before the follow-up sync lost it)
520
+ const carried = (id, at) => Object.prototype.hasOwnProperty.call(outs, id) && outs[id] === at && !(merged.devices[id] && num(merged.devices[id].out) < at)
521
+ const left = Object.fromEntries(Object.entries(s.outs || {}).filter(([id, at]) => !carried(id, at)))
454
522
  if (Object.keys(left).length) s.outs = left; else delete s.outs
455
523
  this._backup._changed()
456
524
  }
457
525
  if (canon({ rooms: merged.rooms, tomb: merged.tomb }) !== roomsBefore) this._backup._persist() // the vault copy holds rooms + tombs, not devices
458
526
  if (usageCanon(merged) !== usageBefore) this._backup._changed() // this device keeps the account's usage key
459
- if (after !== before) { if (canon({ links: merged.links }) !== canon({ links: local.links })) this._backup._changed(); if (typeof this.onChange === 'function') { try { this.onChange({ rooms: this.rooms, devices: this.devices }) } catch { /* the app's callback */ } } }
527
+ if (after !== before || marksChanged) { if (after !== before && canon({ links: merged.links }) !== canon({ links: local.links })) this._backup._changed(); if (typeof this.onChange === 'function') { try { this.onChange({ rooms: this.rooms, devices: this.devices }) } catch { /* the app's callback */ } } }
460
528
  this.lastError = null
529
+ try { this._backup._retryOwedSave?.() } catch { /* the backup keeps its own error */ } // a failed save is owed (sdkBackup.js)
461
530
  return { ok: true, rooms: this.rooms, devices: this.devices }
462
531
  }
463
532
  _signedOut(reason) {
464
533
  this.stop()
465
534
  this._devices = {}
535
+ this._keptMarks = null
466
536
  this._backup._drop()
467
537
  if (typeof this.onSignedOut === 'function') { try { this.onSignedOut(reason ? { reason } : undefined) } catch { /* the app's callback */ } }
468
538
  return { ok: true, signedOut: true, rooms: [], devices: [], ...(reason ? { reason } : {}) }
package/sdkAccountDoc.js CHANGED
@@ -8,6 +8,7 @@
8
8
  // hold, a split room's ASSEMBLED key (decision 5). A forgotten room is `forgot: <at>` — the SDK's RE-OPENABLE mark — never the
9
9
  // app's final `deleted` (decision 4). Devices: { name, seenAt, out } ↔ { label, lastSeenAt } + `signouts`; `sdk` (the release a
10
10
  // device runs) rides along. Entries the SDK cannot read (no link, no mark) are carried over as they were.
11
+ import { preferredAssociation } from './laneAssociation.js'
11
12
  import { indexDoc, indexRoomEntry } from './accountIndexDoc.js'
12
13
  import { keyInLink, roomPin } from './accountRecord.js'
13
14
  import { normUsageKey } from './usageReceipts.js'
@@ -24,8 +25,15 @@ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, u
24
25
  for (const r of rooms) {
25
26
  if (!r || !r.room || typeof r.link !== 'string' || !r.link) continue
26
27
  const mk = keyInLink(r.link) || (typeof r.mk === 'string' ? r.mk : '')
27
- const at = num(r.at), e = indexRoomEntry({ room: r.room, title: r.label || '', titleAt: at, ...roomPin(r), renamed: typeof r.renamed === 'boolean' ? r.renamed : !!(r.label && r.label !== 'Space' && r.label !== r.room), at, archived: !!r.archived, archivedAt: at }, obj(p.rooms)[r.room] || undefined, mk ? { mk } : {}) // prev: the app's per-field rules, and the "always on" mark it keeps (sync sweep 2026-11-23 #13 — every SDK write dropped it)
28
- map[r.room] = { ...e, link: r.link, kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.kind === 'lane' && r.shared ? { shared: r.shared } : {}), ...(r.label && e.title !== r.label ? { label: r.label } : {}) }
28
+ const at = num(r.at), e = indexRoomEntry({ room: r.room, title: r.label || '', titleAt: num(r.labelAt) || at, ...roomPin(r), renamed: typeof r.renamed === 'boolean' ? r.renamed : !!(r.label && r.label !== 'Space' && r.label !== r.room), at, archived: !!r.archived, archivedAt: num(r.archivedAt) || at }, obj(p.rooms)[r.room] || undefined, mk ? { mk } : {}) // prev: the app's per-field rules, and the "always on" mark it keeps (sync sweep 2026-11-23 #13 — every SDK write dropped it)
29
+ const association = preferredAssociation(r, obj(p.rooms)[r.room])
30
+ const detached = !!association.detachedLane
31
+ map[r.room] = { ...e, ...(num(association.associationAt) ? { associationAt: association.associationAt } : {}), ...(detached ? { detachedLane: true } : {}), link: r.link, kind: !detached && association.kind === 'lane' ? 'lane' : 'space', ...(association.kind === 'lane' && association.shared ? { shared: association.shared } : {}), ...(r.label && e.title !== r.label ? { label: r.label } : {}) }
32
+ if (association.mintedFor || r.mintedFor || e.mintedFor) map[r.room].mintedFor = association.mintedFor || r.mintedFor || e.mintedFor
33
+ if (association.laneOrigin === 'minted' && !detached) map[r.room].laneOrigin = 'minted'
34
+ else delete map[r.room].laneOrigin
35
+ if (detached) delete map[r.room].shared
36
+ else delete map[r.room].detachedLane
29
37
  }
30
38
  for (const t of tomb) if (t && t.room) map[t.room] = { ...(map[t.room] || {}), forgot: Math.max(num(t.at), num((map[t.room] || {}).forgot)) || 1 }
31
39
  for (const [room, e] of Object.entries(obj(p.rooms))) if (!(room in map) && e && typeof e === 'object' && !e.link && !e.forgot) map[room] = e
@@ -49,7 +57,7 @@ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, u
49
57
  if (erasedAt) signouts[ERASED_MARK] = Math.max(erasedAt, num(signouts[ERASED_MARK]))
50
58
  if (movedAt) signouts[MOVED_MARK] = Math.max(movedAt, num(signouts[MOVED_MARK]))
51
59
  const u = normUsageKey(usage)
52
- return { ...indexDoc({ rooms: map, devices: devs, signouts, name: typeof p.name === 'string' ? p.name : '', seen: p.seen, vseen: p.vseen, inviteKey: p.inviteKey, usageKey: u, usageKeysOld: (usageOld || []).map(normUsageKey).filter(Boolean), pipesRoom: p.pipesRoom, msgsRoom: p.msgsRoom }),
60
+ return { ...indexDoc({ rooms: map, devices: devs, signouts, name: typeof p.name === 'string' ? p.name : '', seen: p.seen, vseen: p.vseen, inviteKey: p.inviteKey, usageKey: u, usageKeysOld: (usageOld || []).map(normUsageKey).filter(Boolean), pipesRoom: p.pipesRoom, msgsRoom: p.msgsRoom, nameAt: num(p.nameAt) }), // nameAt carried: dropping it let an app device's older name win the tie (side sweep: app-index-push-reverts-account-display-name)
53
61
  ...(Array.isArray(links) && links.length ? { links } : {}) }
54
62
  }
55
63
 
@@ -62,8 +70,8 @@ export function fromAppIndex (doc) {
62
70
  if (deletedAt) tomb.push({ room, at: deletedAt })
63
71
  if (typeof e.link !== 'string' || !e.link || e.deleted) continue
64
72
  const label = e.label !== undefined ? e.label : (e.title && e.title !== 'Space' && e.title !== room || e.manual ? e.title : undefined)
65
- rooms.push({ room, ...roomPin(e), ...(num(e.at) ? { at: e.at } : {}), ...(e.archived ? { archived: true } : {}), link: e.link, kind: e.kind === 'lane' ? 'lane' : 'space',
66
- ...(label ? { label } : {}), ...(label && !e.manual ? { renamed: false } : e.manual && (label === 'Space' || label === room) ? { renamed: true } : {}), ...(e.kind === 'lane' && e.shared ? { shared: e.shared } : {}), ...(typeof e.mk === 'string' && e.mk && e.mk !== keyInLink(e.link) ? { mk: e.mk } : {}) })
73
+ rooms.push({ room, ...roomPin(e), ...(e.mintedFor ? { mintedFor: e.mintedFor } : {}), ...(e.laneOrigin === 'minted' && !e.detachedLane ? { laneOrigin: 'minted' } : {}), ...(num(e.associationAt) ? { associationAt: e.associationAt } : {}), ...(e.detachedLane ? { detachedLane: true } : {}), ...(num(e.at) ? { at: e.at } : {}), ...(e.archived ? { archived: true } : {}), ...(num(e.archivedAt) && num(e.archivedAt) !== num(e.at) ? { archivedAt: e.archivedAt } : {}), ...(num(e.titleAt) && num(e.titleAt) !== num(e.at) ? { labelAt: e.titleAt } : {}), link: e.link, kind: !e.detachedLane && e.kind === 'lane' ? 'lane' : 'space',
74
+ ...(label ? { label } : {}), ...(label && !e.manual ? { renamed: false } : e.manual && (label === 'Space' || label === room) ? { renamed: true } : {}), ...(!e.detachedLane && e.kind === 'lane' && e.shared ? { shared: e.shared } : {}), ...(typeof e.mk === 'string' && e.mk && e.mk !== keyInLink(e.link) ? { mk: e.mk } : {}) })
67
75
  }
68
76
  // …and the app's ERASED mark is the SDK's reason (#8): an SDK device whose stamp is no newer than the mark was signed out by Delete my
69
77
  // account in the app — its onSignedOut hears { reason: 'erased' }, as when the SDK deleted it
@@ -18,7 +18,7 @@ import { mergeContactLists, normContact, dedupePeople, contactKey } from './stor
18
18
  import { cleanRoomDefaults, writeRoomDefaults, ROOM_DEFAULTS_DOC } from './roomDefaultPrefs.js'
19
19
  import { sealDoc } from './accountSeal.js'
20
20
  import { BLOCKS_DOC, cleanBlocks, mergeBlocks, isBlocked } from './blocks.js' // blocks: the app's list and its rules
21
- import { CHAT_LOCKS_DOC, cleanChatLocks, mergeChatLocks, validPin, newSalt, newLockId, stretchPin, pinIdFor, addLock, dropLock, lockOfTarget, liveLocks, accountTries, wrongTryIn } from './chatLock.js'
21
+ import { CHAT_LOCKS_DOC, cleanChatLocks, mergeChatLocks, validPin, newSalt, saltsOf, newLockId, stretchPin, pinIdFor, addLock, dropLock, lockOfTarget, liveLocks, accountTries, wrongTryIn, deleteLockedTargets } from './chatLock.js'
22
22
 
23
23
  const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
24
24
  const canon = (x) => JSON.stringify(x === undefined ? null : x)
@@ -27,7 +27,7 @@ const obj = (x) => (x && typeof x === 'object' && !Array.isArray(x) ? x : null)
27
27
 
28
28
  class Section {
29
29
  /** @param {object} spec { doc, of(doc) → value, apply(doc, change) → the doc to write, or null when nothing moves, calls } */
30
- constructor (ix, spec) { this._ix = ix; this._spec = spec; this._calls = spec.calls; this._val = null; this._master = null; this._used = false; this._fns = new Set(); this._remote = false }
30
+ constructor (ix, spec) { this._ix = ix; this._spec = spec; this._calls = spec.calls; this._val = null; this._master = null; this._used = false; this._fns = new Set(); this._remote = false; this._have = false }
31
31
  /** What this device last read (null before the first read, and for another account). */
32
32
  get value () { if (this._remote) return copy(this._val); const s = this._ix._backup._s; return s && s.master === this._master ? copy(this._val) : null }
33
33
  /** Read it now. */
@@ -36,7 +36,7 @@ class Section {
36
36
  on (ev, fn) { if (ev === 'change' && typeof fn === 'function') { this._fns.add(fn); if (!this._used && this._ix.enabled) this._pass(null).catch(() => null) } return this }
37
37
  off (ev, fn) { this._fns.delete(fn); return this }
38
38
  _seen (v, fire = false) { const was = this._val; this._remote = true; this._val = v; if (fire && canon(was) !== canon(v)) this._fire(v) } // in a vault: what the vault read
39
- _fire (v) { for (const fn of this._fns) { try { fn(copy(v)) } catch { /* the app's callback */ } } }
39
+ _fire (v) { for (const fn of [...this._fns]) { try { fn(copy(v)) } catch { /* the app's callback */ } } } // a copy of the set: a listener that rebinds itself must not hear this change twice
40
40
  async _pass (change) {
41
41
  const ix = this._ix, d = this._spec.doc
42
42
  if (!ix.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore)')
@@ -44,26 +44,60 @@ class Section {
44
44
  const s0 = ix._backup._s, moved = () => { if (ix._backup._s !== s0) throw fail('account_changed', 'the account changed on this device during the call') }
45
45
  for (let i = 0; i < 5; i++) {
46
46
  const loc = await ix._where(); moved()
47
- if (this._master !== loc.master) { this._master = loc.master; this._val = null }
47
+ if (this._master !== loc.master) { this._master = loc.master; this._val = null; this._have = false }
48
48
  if (!loc.made && !(s0.device && s0.device.made)) { await ix._ensureRoom(loc); moved() } // the index room, made once (as the sync does)
49
49
  const got = await ix._read(loc, d, loc.app); moved()
50
50
  if (!got.ok) throw fail(got.unopenable ? 'unopenable' : 'unreadable', `the account's ${d} could not be ${got.unopenable ? 'opened' : 'read'}`, { status: got.status })
51
51
  const next = change === null ? null : this._spec.apply(got.doc, change)
52
52
  if (next) {
53
- const w = await ix._client().state(loc.room, loc.mk, d, await sealDoc(loc.app, next), 'account ' + d, 'device', got.v); moved()
53
+ const sealed = await sealDoc(loc.app, next)
54
+ // a dropped connection is a failed save too, with the same code as a refused one (side sweep 2026-11-28: it threw uncoded / vault_error)
55
+ let w; try { w = await ix._client().state(loc.room, loc.mk, d, sealed, 'account ' + d, 'device', got.v) } catch (e) { moved(); if (e && e.code) throw e; throw fail('save_failed', `the account's ${d} could not be saved`, { status: 0 }) } // a coded refusal (sign_in_required, …) stays itself; only a dropped transport becomes save_failed
56
+ moved()
54
57
  if (w && w.status === 409) { await new Promise((r) => setTimeout(r, 10 + Math.floor(Math.random() * 40) * (i + 1))); continue } // another device wrote: merge over it
55
58
  if (!w || w.status !== 200) throw fail('save_failed', `the account's ${d} could not be saved`, { status: w && w.status })
56
- this._val = this._spec.of(next); return copy(this._val)
59
+ this._val = this._spec.of(next); this._have = true; return copy(this._val)
57
60
  }
58
- const was = this._val, now = this._spec.of(got.doc)
59
- this._val = now
60
- if (was !== null && canon(was) !== canon(now)) this._fire(now)
61
+ const was = this._val, had = this._have, now = this._spec.of(got.doc)
62
+ this._val = now; this._have = true
63
+ // after a first read, even of an empty section (null), another device's first value is a change (side sweep 2026-11-28: it arrived silently)
64
+ if (had && canon(was) !== canon(now)) this._fire(now)
61
65
  return copy(now)
62
66
  }
63
67
  throw fail('save_failed', `the account's ${d} kept changing under this device — try again`, { status: 409 })
64
68
  }
65
69
  }
66
70
 
71
+ export function codeAgentPreference(ix, agent) {
72
+ const pref = new Section(ix, {
73
+ doc: 'xindex2',
74
+ of: doc => String(doc?.code?.agent || ''),
75
+ apply(doc, name) {
76
+ const code = doc?.code || {}
77
+ if ((code.agent || '') === name) return null
78
+ return { ...doc, code: { ...code, agent: name, mod: Math.max(Date.now(), (Number(code.mod) || 0) + 1) } }
79
+ },
80
+ })
81
+ return pref._pass(agent === undefined ? null : agent)
82
+ }
83
+
84
+ export function computerModelPreference(ix, computer, model) {
85
+ const pref = new Section(ix, {
86
+ doc: 'xindex2',
87
+ of: doc => String(doc?.code?.models?.[computer] || ''),
88
+ apply(doc, ref) {
89
+ const code = doc?.code || {}, models = { ...code.models }
90
+ if ((models[computer] || '') === ref) return null
91
+ if (ref) {
92
+ if (!(computer in models) && Object.keys(models).length >= 32) throw fail('too_many_models', 'the account already keeps 32 computer model choices')
93
+ models[computer] = ref
94
+ } else delete models[computer]
95
+ return { ...doc, code: { ...code, models, mod: Math.max(Date.now(), (Number(code.mod) || 0) + 1) } }
96
+ },
97
+ })
98
+ return pref._pass(model === undefined ? null : model)
99
+ }
100
+
67
101
  // ── contacts: xindex2.contacts ──
68
102
  const contactsOf = (doc) => dedupePeople(((obj(doc) && Array.isArray(doc.contacts)) ? doc.contacts : []).map(normContact).filter(Boolean))
69
103
  const withContacts = (doc, rows) => {
@@ -72,8 +106,11 @@ const withContacts = (doc, rows) => {
72
106
  }
73
107
  const live = (list) => list && list.filter((c) => !c.deleted).map(({ deleted: _d, ...c }) => c)
74
108
  // one row, stamped against the list each try read: newer than any copy of it (the app's LWW), a removal its tombstone
109
+ // the same person by either address: a row keyed by its email is found by its @username too, as the app's forgetContact finds it
110
+ // (side sweep 2026-11-28: remove({ username }) of a row with an email wrote no tombstone)
111
+ const samePerson = (x, c) => contactKey(x) === contactKey(c) || (x.kind !== 'agent' && c.kind !== 'agent' && ((!!c.username && x.username === c.username) || (!!c.email && x.email === c.email)))
75
112
  const stamped = (c, gone) => (cur) => {
76
- const ex = cur.find((x) => contactKey(x) === contactKey(c))
113
+ const ex = cur.find((x) => samePerson(x, c))
77
114
  if (gone && !ex) return []
78
115
  return [{ ...(gone ? ex : c), ...(gone ? { deleted: true } : {}), at: Math.max(Date.now(), ((ex && ex.at) || 0) + 1) }]
79
116
  }
@@ -82,7 +119,7 @@ class Contacts extends Section {
82
119
  constructor (ix) { super(ix, { doc: 'xindex2', of: contactsOf, calls: ['get', 'set', 'remove', 'merge'], apply: (doc, rows) => withContacts(doc, typeof rows === 'function' ? rows(contactsOf(doc)) : rows) }) }
83
120
  get value () { return live(super.value) }
84
121
  async get () { return live(await super.get()) }
85
- _fire (v) { super._fire(live(v)) } // the app keeps a removal as a row; the builder sees the people
122
+ _fire (v) { super._fire(live(v) || []) } // the app keeps a removal as a row; the builder sees the people (a sign-out: [] — side sweep 2026-11-28, it sent null)
86
123
  /** Add or edit one contact ({ email | username, fn?, tel? } or a saved assistant { kind: 'agent', id, fn, persona? }); it wins over older copies. */
87
124
  async set (contact) { return live(await this._pass(stamped(oneContact(contact), false))) }
88
125
  /** Remove one (by its email, @username or assistant id) on every device — the app's tombstone row. */
@@ -94,7 +131,8 @@ class Contacts extends Section {
94
131
  // ── name: xindex.name ──
95
132
  class Name extends Section {
96
133
  constructor (ix) { super(ix, { doc: 'xindex', of: (doc) => (obj(doc) && typeof doc.name === 'string' ? doc.name : ''), calls: ['get', 'set'],
97
- apply: (doc, name) => (obj(doc) && doc.name === name ? null : { v: 2, rooms: {}, devices: {}, signouts: {}, ...(obj(doc) || {}), name, at: Date.now() }) }) }
134
+ apply: (doc, name) => (obj(doc) && doc.name === name ? null : { v: 2, rooms: {}, devices: {}, signouts: {}, ...(obj(doc) || {}), name, nameAt: Date.now(), at: Date.now() }) }) } // nameAt: when the name was typed — the app keeps the newer name by it (side sweep: app-index-push-reverts-account-display-name)
135
+ _fire (v) { super._fire(typeof v === 'string' ? v : '') } // a sign-out clears it to '' (side sweep 2026-11-28: null, which the type excludes)
98
136
  /** The person's name, for every device of the account (the app keeps 24 characters). An empty name is refused, as the app never writes one over a name. */
99
137
  async set (name) { const n = String(typeof name === 'string' ? name : '').trim().slice(0, 24); if (!n) throw fail('invalid_argument', 'a name is needed'); return this._pass(n) }
100
138
  }
@@ -104,7 +142,12 @@ const memStore = (v) => { const m = new Map(v ? [['space:default-room', JSON.str
104
142
  const optionsOf = (doc) => { const c = cleanRoomDefaults(doc); if (!c) return null; const { v: _v, mods: _m, ...o } = c; return o }
105
143
  class RoomDefaults extends Section {
106
144
  constructor (ix) { super(ix, { doc: 'x' + ROOM_DEFAULTS_DOC, of: optionsOf, calls: ['get', 'set'],
107
- apply: (doc, patch) => { const cur = cleanRoomDefaults(doc), next = writeRoomDefaults(patch, {}, memStore(cur), Date.now()); return next && canon(optionsOf(next)) !== canon(optionsOf(cur)) ? next : null } }) }
145
+ apply: (doc, patch) => {
146
+ const cur = cleanRoomDefaults(doc)
147
+ // a doc this SDK cannot read (a newer app's version) is never replaced by the patch alone (side sweep 2026-11-28), as the app's sync refuses it
148
+ // — nor one whose version is not 1 at all (0, a string): only a v:1 doc with no options is an empty one to fill
149
+ if (!cur && obj(doc) && doc.v !== 1 && Object.keys(doc).length) throw fail('unreadable', "the account's room defaults are in a format this app cannot read — nothing was written")
150
+ const next = writeRoomDefaults(patch, {}, memStore(cur), Date.now()); return next && canon(optionsOf(next)) !== canon(optionsOf(cur)) ? next : null } }) }
108
151
  /** Change some of the New-Space defaults ({ quick, enclave, verified, lanes, temporary }: booleans; { assistant, model }: strings).
109
152
  * `verified` is kept for older apps: today's app makes every new Space verified and ignores it (sync sweep 11-21 #11). */
110
153
  async set (patch) {
@@ -126,7 +169,7 @@ class Blocks extends Section {
126
169
  constructor (ix) { super(ix, { doc: 'x' + BLOCKS_DOC, of: blocksOf, calls: ['get', 'block', 'unblock', 'merge'], apply: (doc, add) => withBlocks(doc, typeof add === 'function' ? add(blocksOf(doc)) : add) }) }
127
170
  get value () { return liveBlocks(super.value) }
128
171
  async get () { return liveBlocks(await super.get()) }
129
- _fire (v) { super._fire(liveBlocks(v)) } // the app keeps an unblock as a row; the builder sees who is blocked
172
+ _fire (v) { super._fire(liveBlocks(v) || []) } // the app keeps an unblock as a row; the builder sees who is blocked (a sign-out: [])
130
173
  /** Block a person on every device of the account ({ email?, user?, room?, sid?, name? } — space.blockIdentity(message), plus the name to show). */
131
174
  async block (who) { const w = oneWho(who); return liveBlocks(await this._pass((cur) => [{ ...w, at: nextAt(cur) }])) }
132
175
  /** Unblock: every live entry that names them by any proof goes, kept as a tombstone so another device does not bring them back. */
@@ -142,16 +185,27 @@ class Blocks extends Section {
142
185
 
143
186
  /** Puts the sections on the account index (`ix.contacts`, `ix.name`, `ix.roomDefaults`, `ix.blocks`) and keeps them in `ix._sections`. */
144
187
  class ChatLocks extends Section {
145
- constructor(ix) { super(ix, { doc: 'x' + CHAT_LOCKS_DOC, of: cleanChatLocks, calls: ['get', 'merge', 'set', 'remove', 'check', 'changePin'], apply: (doc, incoming) => { const next = typeof incoming === 'function' ? incoming(cleanChatLocks(doc)) : mergeChatLocks(doc, incoming); return canon(next) === canon(cleanChatLocks(doc)) ? null : next } }) }
188
+ constructor(ix) { super(ix, { doc: 'x' + CHAT_LOCKS_DOC, of: cleanChatLocks, calls: ['get', 'merge', 'set', 'remove', 'check', 'match', 'changePin', 'previewDeleteAll', 'deleteAll'], apply: (doc, incoming) => { const next = typeof incoming === 'function' ? incoming(cleanChatLocks(doc)) : mergeChatLocks(doc, incoming); return canon(next) === canon(cleanChatLocks(doc)) ? null : next } }) }
146
189
  async merge(doc) {
147
190
  const clean = cleanChatLocks(doc); if (!clean) throw fail('invalid_argument', 'chatLocks.merge needs a chat-locks document')
148
- return this._write(clean)
191
+ return this._write(clean, { retryMarker: true }) // the presence mark retried at the next sync, as the removal does (side sweep 2026-11-28)
149
192
  }
150
193
  async set({ kind, target, pin, title } = {}) {
151
194
  if (!['room', 'code'].includes(kind) || typeof target !== 'string' || !target || target.length > 300 || !validPin(pin)) throw fail('invalid_argument', 'chatLocks.set needs kind, target and a PIN of 4–12 digits')
152
- const s0 = this._ix._backup._s, salt = newSalt(), fingerprint = await pinIdFor(await stretchPin(pin, salt)), id = newLockId()
195
+ const s0 = this._ix._backup._s, salt = saltsOf(await this.get())[0] || newSalt(), fingerprint = await pinIdFor(await stretchPin(pin, salt)), id = newLockId()
153
196
  if (this._ix._backup._s !== s0) throw fail('account_changed', 'the account changed during PIN setup')
154
- return this._write((doc) => { if (lockOfTarget(doc, kind, target)) throw fail('locked', 'this chat is already locked'); return addLock(doc, id, { kind, target, salt, pin: fingerprint, title }) })
197
+ try {
198
+ return await this._write((doc) => { if (lockOfTarget(doc, kind, target)) throw fail('locked', 'this chat is already locked'); return addLock(doc, id, { kind, target, salt, pin: fingerprint, title }) }, { retryMarker: true }) // a failed mark: retried at the next sync, not a failed setup that then says 'locked'
199
+ } catch (error) {
200
+ // ALREADY LOCKED: the presence mark is (re)written too (side sweep: sdk-first-chat-lock-marker-retry) — a lock an older release saved
201
+ // without its mark, and with nothing pending, otherwise left every other device's sync skipping the lock document for good
202
+ if (error && error.code === 'locked' && this._ix._backup._s === s0 && s0) {
203
+ s0.chatLockMarkPending = Math.max(Date.now(), (s0.chatLockMarkPending || 0) + 1)
204
+ this._ix._backup._changed?.()
205
+ await this._mark(s0).catch(() => {}) // failed: retried at the next sync (refreshSections)
206
+ }
207
+ throw error
208
+ }
155
209
  }
156
210
  async remove({ lockId } = {}) {
157
211
  if (typeof lockId !== 'string' || !/^lk_[A-Za-z0-9_-]{22}$/.test(lockId)) throw fail('invalid_argument', 'chatLocks.remove needs a lockId')
@@ -169,8 +223,88 @@ class ChatLocks extends Section {
169
223
  const current = liveLocks(cur).find((l) => l.lockId === lockId)
170
224
  if (!current || current.pin !== lock.pin || current.salt !== lock.salt) throw fail('changed_meanwhile', 'the display lock changed; try again')
171
225
  return addLock(cur, lockId, { kind: current.kind, target: current.target, salt: current.salt, title: current.title, pin: fingerprint })
226
+ }, { retryMarker: true })
227
+ }
228
+ _mintedAssistants(targets) {
229
+ const parents = new Set(targets.filter(t => t.kind === 'room').map(t => t.target))
230
+ return (this._ix._backup.rooms || []).filter(r => r.shared && parents.has(r.shared) && !r.detachedLane && r.laneOrigin === 'minted')
231
+ }
232
+ async previewDeleteAll() {
233
+ const plan = await this._planDeleteAll()
234
+ this._shown = { owner: this._ix._backup._s, lockIds: plan.targets.map(t => t.lockId) } // what the caller was shown (deleteAll below)
235
+ return plan
236
+ }
237
+ async _planDeleteAll() {
238
+ const owner = this._ix._backup._s
239
+ if (!(await this._ix.sync())?.ok || this._ix._backup._s !== owner) throw fail('index_unavailable', 'the account could not be synced')
240
+ const targets = liveLocks(await this.get()).map(({ kind, target, lockId }) => ({ kind, target, lockId }))
241
+ if (this._ix._backup._s !== owner) throw fail('account_changed', 'the account changed')
242
+ const locked = new Set(targets.filter(t => t.kind === 'room').map(t => t.target))
243
+ const privateAssistants = this._mintedAssistants(targets).filter(r => !locked.has(r.room))
244
+ .map(r => ({ room: r.room, parent: r.shared, title: r.label || '' }))
245
+ return { targets, privateAssistants }
246
+ }
247
+ // `lockIds` (side sweep: sdk-bulk-preview): the locks previewDeleteAll showed — a lock added since (another device) is not deleted
248
+ async deleteAll({ includePrivateAssistants = false, privateAssistantRooms, lockIds } = {}) {
249
+ if (privateAssistantRooms !== undefined && (!Array.isArray(privateAssistantRooms) || !privateAssistantRooms.every(r => typeof r === 'string'))) throw fail('invalid_argument', 'privateAssistantRooms must contain room IDs')
250
+ if (lockIds !== undefined && (!Array.isArray(lockIds) || !lockIds.every(id => typeof id === 'string'))) throw fail('invalid_argument', 'lockIds must contain lock IDs from previewDeleteAll')
251
+ // A bare deleteAll() right after previewDeleteAll() on this handle: a lock added since (another device) was never shown, so
252
+ // it is refused, not deleted (side sweep: sdk-bulk-preview) — preview again, or pass lockIds. The preview is used once; with
253
+ // no preview, deleteAll() stays "every live lock", as documented.
254
+ const shown = this._shown; this._shown = null
255
+ const owner = this._ix._backup._s, { targets: live, privateAssistants } = await this._planDeleteAll()
256
+ if (!lockIds && shown && shown.owner === owner) {
257
+ const added = live.filter(t => !shown.lockIds.includes(t.lockId))
258
+ if (added.length) throw fail('changed_meanwhile', 'a display lock was added after previewDeleteAll; preview again or pass lockIds', { added: added.map(t => t.target) })
259
+ }
260
+ const targets = lockIds ? live.filter(t => lockIds.includes(t.lockId)) : live
261
+ const approved = privateAssistants.filter(r => privateAssistantRooms ? privateAssistantRooms.includes(r.room) : includePrivateAssistants === true).map(r => r.room)
262
+ return this._deleteTargets(targets, owner, undefined, approved)
263
+ }
264
+ async _deleteTargets(targets, owner, afterRemoval, assistants = []) {
265
+ const ix = this._ix
266
+ const current = () => !!owner && ix._backup._s === owner
267
+ const approved = new Set([...assistants, ...targets.filter(t => t.kind === 'room').map(t => t.target)])
268
+ return deleteLockedTargets(targets, {
269
+ stillLocked: async (id, kind, target) => {
270
+ if (!current()) return false
271
+ const lock = lockOfTarget(await this.get(), kind, target)
272
+ return current() && lock?.lockId === id
273
+ },
274
+ removeTarget: async (kind, target) => {
275
+ if (!current() || !await ix._deleteLockTarget(kind, target, current, approved, afterRemoval) || !current()) return false
276
+ if (afterRemoval) await afterRemoval(kind, target)
277
+ return current()
278
+ },
279
+ removeLock: async (id, kind, target) => {
280
+ if (!current()) throw fail('account_changed', 'the account changed')
281
+ await this._write(doc => lockOfTarget(doc, kind, target)?.lockId === id ? dropLock(doc, id) : doc, { retryMarker: true })
282
+ },
172
283
  })
173
284
  }
285
+ async match({ pin } = {}) {
286
+ if (!validPin(pin)) throw fail('invalid_argument', 'a PIN is 4–12 digits')
287
+ const owner = this._ix._backup._s, doc = await this.get(), dev = this._ix.deviceId
288
+ if (!dev) throw fail('not_enabled', 'this account has no device id for synced PIN attempts')
289
+ const before = accountTries(doc), salts = saltsOf(doc)
290
+ if (before.next > Date.now() || !salts.length) return { ok: false, matches: [], next: before.next }
291
+ const fingerprints = new Map()
292
+ for (const salt of salts) fingerprints.set(salt, await pinIdFor(await stretchPin(pin, salt)))
293
+ if (this._ix._backup._s !== owner) throw fail('account_changed', 'the account changed during PIN checking')
294
+ let matches = [], next = 0
295
+ await this._write(cur => {
296
+ const now = Date.now(), tries = accountTries(cur), locks = liveLocks(cur)
297
+ matches = []; next = tries.next
298
+ if (next > now || !locks.length) return cur
299
+ if (locks.some(l => !fingerprints.has(l.salt))) throw fail('changed_meanwhile', 'display locks changed; try again')
300
+ matches = locks.filter(l => fingerprints.get(l.salt) === l.pin)
301
+ .map(({ lockId, kind, target, title }) => ({ lockId, kind, target, title: title || '' }))
302
+ const result = matches.length ? cur : wrongTryIn(cur, dev, now)
303
+ next = accountTries(result, now).next
304
+ return result
305
+ })
306
+ return { ok: !!matches.length, matches, next }
307
+ }
174
308
  async check({ lockId, pin } = {}) {
175
309
  if (!validPin(pin)) throw fail('invalid_argument', 'a PIN is 4–12 digits')
176
310
  const s0 = this._ix._backup._s, doc = await this.get(), lock = liveLocks(doc).find((l) => l.lockId === lockId)
@@ -194,9 +328,19 @@ class ChatLocks extends Section {
194
328
  })
195
329
  return { ok, next }
196
330
  }
197
- async _write(change) {
198
- const ix = this._ix, s0 = ix._backup._s, merged = await this._pass(change)
199
- // The app reads this optional doc only after the account index advertises its presence.
331
+ async _write(change, { retryMarker = false } = {}) {
332
+ const ix = this._ix, owner = ix._backup._s, merged = await this._pass(change)
333
+ if (retryMarker && owner === ix._backup._s) {
334
+ owner.chatLockMarkPending = Math.max(Date.now(), (owner.chatLockMarkPending || 0) + 1)
335
+ ix._backup._changed?.()
336
+ }
337
+ try { await this._mark(owner) } catch (error) {
338
+ if (!retryMarker || owner !== ix._backup._s) throw error
339
+ }
340
+ return merged
341
+ }
342
+ async _mark(s0) {
343
+ const ix = this._ix, pending = s0.chatLockMarkPending
200
344
  for (let i = 0; i < 5; i++) {
201
345
  const loc = await ix._where(), got = await ix._read(loc, 'xindex', loc.app)
202
346
  if (ix._backup._s !== s0) throw fail('account_changed', 'the account changed during chatLocks.merge')
@@ -206,7 +350,8 @@ class ChatLocks extends Section {
206
350
  const r = await ix._client().state(loc.room, loc.mk, 'xindex', await sealDoc(loc.app, next), 'chat locks present', 'device', got.v)
207
351
  if (r && r.status === 409) continue
208
352
  if (!r || r.status !== 200) throw fail('save_failed', 'the chat-lock presence mark could not be saved')
209
- return merged
353
+ if (pending && ix._backup._s === s0 && s0.chatLockMarkPending === pending) { delete s0.chatLockMarkPending; ix._backup._changed?.() }
354
+ return
210
355
  }
211
356
  throw fail('save_failed', 'the account index kept changing; retry chatLocks.merge')
212
357
  }
@@ -219,5 +364,9 @@ export function attachSections (ix) {
219
364
  }
220
365
  /** After an account sync: the sections the app uses are read again (a change another device made fires 'change'). */
221
366
  export async function refreshSections (ix) {
222
- for (const s of Object.values(ix._sections || {})) if (s._used && !s._remote) await s._pass(null).catch(() => null)
367
+ for (const s of Object.values(ix._sections || {})) if (s._used && !s._remote) {
368
+ await s._pass(null).catch(() => null)
369
+ }
370
+ const owner = ix._backup._s
371
+ if (owner?.chatLockMarkPending && ix.chatLocks && !ix.chatLocks._remote) await ix.chatLocks._mark(owner).catch(() => {})
223
372
  }