@witbitz/sdk 4.4.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 (79) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +15 -0
  3. package/accountErase.js +9 -3
  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/awsKey.js +3 -1
  11. package/backupRecord.js +3 -0
  12. package/codeAttachments.js +1 -0
  13. package/codeCache.js +27 -3
  14. package/codeCloud.js +2 -0
  15. package/codeComputers.js +8 -0
  16. package/codeSent.js +43 -2
  17. package/codeTransport.js +24 -5
  18. package/connections.js +21 -3
  19. package/decrypt.html +69 -9
  20. package/eraseFile.js +15 -0
  21. package/idbSeal.js +5 -2
  22. package/inviteReceive.js +44 -0
  23. package/inviteSend.js +8 -2
  24. package/l1-worker-src.js +1 -1
  25. package/l1-worker.js +30 -14
  26. package/laneAssociation.js +11 -1
  27. package/laneLinkCore.js +9 -0
  28. package/ledgerView.js +30 -4
  29. package/manifest.json +78 -72
  30. package/offlineBundle.js +21 -0
  31. package/package.json +8 -2
  32. package/protectedLocal.js +34 -11
  33. package/reactionHolders.js +86 -0
  34. package/roomIntake.js +324 -0
  35. package/roomRoster.js +9 -2
  36. package/scheduleNext.js +60 -0
  37. package/sdkA2A.js +46 -8
  38. package/sdkAccount.js +71 -14
  39. package/sdkAccountDoc.js +3 -3
  40. package/sdkAccountSections.js +58 -18
  41. package/sdkAgui.js +33 -6
  42. package/sdkBackup.js +21 -6
  43. package/sdkBackupV2.js +15 -3
  44. package/sdkCloudDevice.js +12 -3
  45. package/sdkComputers.js +118 -17
  46. package/sdkDictation.js +1 -1
  47. package/sdkErase.js +3 -1
  48. package/sdkExports.js +15 -6
  49. package/sdkInvitations.js +4 -2
  50. package/sdkKeptAgent.js +19 -3
  51. package/sdkKeptIntake.js +100 -0
  52. package/sdkLaneLink.js +5 -6
  53. package/sdkRekey.js +72 -5
  54. package/sdkSchedules.js +8 -1
  55. package/sdkSpeech.js +14 -1
  56. package/sdkTemporaryRooms.js +2 -1
  57. package/sdkTurn.js +12 -4
  58. package/sharedViews.js +17 -1
  59. package/siri.js +29 -5
  60. package/spaceClient.js +96 -12
  61. package/spaceExport.js +50 -5
  62. package/spaceFork.js +15 -7
  63. package/spaceTemplates.js +2 -2
  64. package/speechOut.js +17 -3
  65. package/store.js +51 -13
  66. package/sw-notif-core.js +2 -1
  67. package/tapTrail.js +58 -0
  68. package/usageReceipts.js +12 -5
  69. package/vault-core.js +90 -16
  70. package/vault-kit.mjs +2 -2
  71. package/vault-screens.js +25 -11
  72. package/vaultAtRest.js +3 -2
  73. package/vaultCoreLock.js +3 -1
  74. package/vaultCorePush.js +58 -7
  75. package/vaultWorkerHost.js +9 -3
  76. package/witbitz-admin.d.ts +3 -0
  77. package/witbitz-admin.mjs +10 -10
  78. package/witbitz-sdk.d.ts +59 -23
  79. package/witbitz-sdk.js +271 -64
package/roomRoster.js CHANGED
@@ -155,7 +155,7 @@ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', s
155
155
  const key = email || '@' + norm(user)
156
156
  const byUser = !email && [...people.values()].find((x) => user && norm(x.user) === norm(user))
157
157
  if (byUser) continue
158
- add(key, { email, user, me: !!me && email === me, label: '' })
158
+ add(key, { email, user, me: !!me && email === me, label: '', ...(a.id ? { id: a.id } : {}) })
159
159
  }
160
160
  // You are a member the moment you are reading as your verified self, whether or not this device has announced.
161
161
  if (me && ![...people.values()].some((x) => x.me)) { if (people.has(me)) people.get(me).me = true; else add(me, { email: me, user: '', me: true, label: '' }) }
@@ -172,7 +172,7 @@ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', s
172
172
  const emails = Array.isArray(allow.emails) ? allow.emails.filter(Boolean) : []
173
173
  // an older room's @username entry: { handle, username } — the username it had THEN. A signed-in member whose handle it is
174
174
  // (seenHandles: the caller resolved the signed-in usernames) is that member under their new name, not a second person.
175
- const users = Array.isArray(allow.users) ? allow.users.filter((u) => !(u && typeof u === 'object' && u.handle && seenHandles.has(String(u.handle)))).map((u) => (u && typeof u === 'object' ? u.username : u)).filter(Boolean) : []
175
+ const users = Array.isArray(allow.users) ? allow.users.filter((u) => !(u && typeof u === 'object' && u.handle && (seenHandles.has(String(u.handle)) || seenHandles.has(String(u.handle).toLowerCase().trim())))).map((u) => (u && typeof u === 'object' ? u.username : u)).filter(Boolean) : []
176
176
  for (const e of emails) if (!covered.has(norm(e))) items.push({ label: e, tag: 'not yet opened', address: e })
177
177
  for (const u of users) if (!covered.has(norm('@' + u))) items.push({ label: '@' + u, tag: 'not yet opened', address: '@' + u, user: u })
178
178
  const domains = Array.isArray(allow.domains) ? allow.domains.filter(Boolean) : []
@@ -272,6 +272,9 @@ export function listRoster (roster, { attested = null } = {}) {
272
272
  verified,
273
273
  named: verified && !!e.name, // a name someone ATTESTED — the only kind that may be shown plain
274
274
  claimed: !verified && !!e.name, // a name its owner typed — shown, and the UI must mark it
275
+ // announced under a BROWSER PROFILE's id, not a key (selfRow's deviceId): one person on two browsers is two rows — counted
276
+ // per device, labelled "visitor" (the owner's rule, side sweep: open-room-device-rows-labelled-people)
277
+ visitor: !verified && !String(e.id || '').includes('.'),
275
278
  label: standalone[i] ? e.name : (e.name ? `${e.name} (${ordinal})` : ordinal),
276
279
  }
277
280
  })
@@ -289,6 +292,10 @@ export async function privateInvitationMatches(cfg, room, seen, { resolveUsers,
289
292
  let resolvedSeen = null
290
293
  const resolveSeen = async () => { if (resolvedSeen) return resolvedSeen; try { resolvedSeen = ((await within(resolveUsers(seenUsers))) || { resolved: [] }).resolved || [] } catch { resolvedSeen = [] } return resolvedSeen }
291
294
  if (seenUsers.length && legacyUsers.length) for (const r of await resolveSeen()) if (r && r.handle) seenHandles.add(String(r.handle))
295
+ // …and the handles the GATE recorded at their sign-in (roster_seen `entries`, 'u:<handle>' — agent/spaceOidc.mjs allowEntriesFor):
296
+ // a renamed member whose email door is closed resolves with no handle, and the old name was listed "not yet opened" beside them
297
+ // (side sweep 2026-11-28)
298
+ if (legacyUsers.length) for (const p of Object.values(seen)) for (const k of (p && Array.isArray(p.entries) ? p.entries : [])) if (typeof k === 'string' && k.startsWith('u:') && k.length > 2) seenHandles.add(k.slice(2))
292
299
  try {
293
300
  const mh = Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : []
294
301
  if (mh.length) { const got = new Set(); for (const p of Object.values(seen)) { if (p && p.email) { const h = await memberHash(p.email, room); if (h) got.add(h) } }
@@ -0,0 +1,60 @@
1
+ // scheduleNext.js — WHEN A DAILY SCHEDULE RUNS NEXT, for the always-on card and the SDK's schedules.list() (side sweep
2
+ // daily-schedule-display-omits-spring-gap-run-time). The cloud device runs a daily job at the first tick of a local day whose clock
3
+ // reads its time or later (schedulesDoc.js isDue): on the night the clocks skip that time, it becomes due the moment they jump.
4
+ // Computed from the time zone rules Intl holds on THIS device — display only. The turn enclave and the cloud device never read it.
5
+
6
+ const MIN = 60_000, DAY = 86_400_000, WINDOW = 48 * 3_600_000
7
+ const fmts = new Map()
8
+ const fmt = (tz) => {
9
+ let f = fmts.get(tz)
10
+ if (!f) { f = new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); fmts.set(tz, f) }
11
+ return f
12
+ }
13
+ function wall (ms, tz) {
14
+ const p = Object.fromEntries(fmt(tz).formatToParts(new Date(ms)).map((x) => [x.type, x.value]))
15
+ return { y: +p.year, mo: +p.month, d: +p.day, day: `${p.year}-${p.month}-${p.day}`, hm: `${p.hour}:${p.minute}`, h: +p.hour, mi: +p.minute }
16
+ }
17
+ /** The zone's offset at `ms` (wall clock − UTC, ms). */
18
+ const offset = (ms, tz) => { const w = wall(ms, tz), m = Math.floor(ms / MIN) * MIN; return Date.UTC(w.y, w.mo - 1, w.d, w.h, w.mi) - m }
19
+
20
+ /** The day's run: the first instant the local clock on that day reads `at` or later → { at (ms), skipped (the clocks jump past it),
21
+ * runsAt ('HH:MM' on the clock then) }, or null. */
22
+ function occurrence (y, mo, d, at, tz) {
23
+ const [h, mi] = at.split(':').map(Number), t0 = Date.UTC(y, mo - 1, d, h, mi), w0 = new Date(t0)
24
+ const day = `${w0.getUTCFullYear()}-${String(w0.getUTCMonth() + 1).padStart(2, '0')}-${String(w0.getUTCDate()).padStart(2, '0')}`
25
+ const cands = [...new Set([t0 - offset(t0 - DAY, tz), t0 - offset(t0 + DAY, tz)])].sort((a, b) => a - b)
26
+ const exact = cands.find((c) => { const w = wall(c, tz); return w.day === day && w.hm === at }) // the first, when the autumn clock repeats it
27
+ if (exact !== undefined) return { at: exact, skipped: false, runsAt: at }
28
+ const reached = (t) => { const w = wall(t, tz); return w.day > day || (w.day === day && w.hm >= at) }
29
+ let lo = cands[0], hi = cands[cands.length - 1]
30
+ if (lo === hi || reached(lo) || !reached(hi)) return null
31
+ while (hi - lo > MIN) { const mid = lo + Math.floor((hi - lo) / MIN / 2) * MIN; if (reached(mid)) hi = mid; else lo = mid } // the minute the clocks jump
32
+ return { at: hi, skipped: true, runsAt: wall(hi, tz).hm }
33
+ }
34
+ /** The runs of the next three local days still ahead of `now`, in order. */
35
+ function upcoming (when, now) {
36
+ if (!when || typeof when.at !== 'string' || !/^\d\d:\d\d$/.test(when.at) || !when.tz) return []
37
+ let today; try { today = wall(now, when.tz) } catch { return [] }
38
+ const out = []
39
+ for (let i = 0; i < 3; i++) {
40
+ const o = occurrence(today.y, today.mo, today.d + i, when.at, when.tz)
41
+ if (o && o.at > now) out.push({ ...o, i })
42
+ }
43
+ return out
44
+ }
45
+
46
+ /** When a daily job (`{ at, tz }`) runs next (ms), or null (not a daily job). */
47
+ export const nextDailyRun = (when, now = Date.now()) => { const u = upcoming(when, now); return u.length ? u[0].at : null }
48
+
49
+ /** The card's line when the clocks skip a daily job's time within the next 48 hours, else ''. */
50
+ export function skipNote (when, now = Date.now()) {
51
+ const o = upcoming(when, now).find((x) => x.skipped && x.at - now <= WINDOW)
52
+ if (!o) return ''
53
+ const label = o.i === 0 ? 'Today' : o.i === 1 ? 'Tomorrow' : 'On ' + new Intl.DateTimeFormat('en-US', { timeZone: when.tz, weekday: 'long' }).format(new Date(o.at))
54
+ return `${label} the clocks skip ${when.at} — it runs at ${o.runsAt}`
55
+ }
56
+
57
+ /** The SDK's list: each active daily job with its next run (`next`, ms) — new objects; anything else as it came. */
58
+ export const withNextRuns = (jobs, now = Date.now()) => (Array.isArray(jobs)
59
+ ? jobs.map((j) => { if (!j || j.paused || !j.when) return j; const next = nextDailyRun(j.when, now); return next === null ? j : { ...j, next } })
60
+ : jobs)
package/sdkA2A.js CHANGED
@@ -28,7 +28,7 @@ import { readAllPages } from './ledgerView.js'
28
28
  import { sealTo as sealToEnclave } from './sealShare.js'
29
29
  // The rules — the record, letting a peer in, the Sentinel calls, opening a collected message — are a2aCore.js, which the
30
30
  // Spaces app's a2aLane.js shares. This module is the SDK's classes and storage around them.
31
- import { A2A_COLLECT_WINDOW_MS, finishedTask, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, applyRemovals, removalIntents, pruneGoneIn, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, sentinelCalls, openItem, a2aMessage, a2aInstructions, isJobPeer } from './a2aCore.js'
31
+ import { A2A_COLLECT_WINDOW_MS, finishedTask, replyNotDelivered, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, applyRemovals, removalIntents, pruneGoneIn, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, withIntake, sentinelCalls, openItem, a2aMessage, a2aInstructions, isJobPeer } from './a2aCore.js'
32
32
  import { isLaneCopy } from './roomName.js' // a lane's copy of its shared room's line is never a draft
33
33
  import { A2A_PENDING_DOC, A2A_PEERS_DOC, peersFromDoc, pendingFromDoc, withoutShared } from './a2aShared.js'
34
34
  /** The Sentinel's answer for a task that already has its reply (infra/cloud-computer/sentinel/a2a.mjs). */
@@ -125,17 +125,37 @@ export class A2AAccount {
125
125
  _changed() { if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback */ } } }
126
126
  _calls() {
127
127
  const { post, auth, attest, seal } = this._d()
128
- return sentinelCalls({ post, auth, attest, seal, err: (kind, m, reply) => fail(kind === 'refused' ? 'sentinel_refused' : 'sentinel_unreachable', m, { definiteRefusal: kind === 'refused' && !!reply && (reply.ok === false || !!reply.error) && !(reply.status >= 500) && !['sentinel_unavailable', 'unreachable', 'timeout', 'busy'].includes(reply.error) }) })
128
+ return sentinelCalls({ post, auth, attest, seal, err: (kind, m, reply) => fail(kind === 'refused' ? 'sentinel_refused' : 'sentinel_unreachable', m, { definiteRefusal: kind === 'refused' && !!reply && (reply.ok === false || !!reply.error) && !(reply.status >= 500) && !['sentinel_unavailable', 'unreachable', 'timeout', 'busy'].includes(reply.error), ...(reply && typeof reply.state === 'string' ? { taskState: reply.state } : {}) }) })
129
129
  }
130
130
  _sealed(mode, obj) { return this._calls().sealed(mode, obj) }
131
131
  _plain(mode, extra = {}) { return this._calls().plain(mode, extra) }
132
- /** Send the whole record (it REPLACES what the Sentinel held) — this account's, or `s`, a changed copy (_change). */
133
- async _push(s = this._s, expectedGeneration = this._wb._archiveGeneration) {
132
+ // ⛔ A COPY THAT MISSES WHAT ANOTHER DEVICE ADDED IS NOT PUBLISHED (side sweep: outside-agent-stale-list-drops-pending-jobs): the
133
+ // grant REPLACES the Sentinel's record, and the Sentinel drops the waiting tasks of every agent it leaves out. A lane or an
134
+ // agent the Sentinel holds must be in this record, or closed / removed here (its tombstone, `gone` / `removed`); otherwise
135
+ // this device's copy is older than the account's — refused, nothing sent. A status that cannot be read refuses too.
136
+ async _assertCovers(candidate) {
137
+ const st = await this._plain('a2astatus')
138
+ for (const l of (st && Array.isArray(st.lanes) ? st.lanes : [])) {
139
+ if (!l || typeof l.handle !== 'string' || candidate.gone?.[l.handle]) continue
140
+ const mine = Object.values(candidate.lanes || {}).find((x) => x && x.handle === l.handle)
141
+ const missing = !mine || (Array.isArray(l.peers) ? l.peers : []).some((p) => p && p.id && !mine.peers.some((q) => q.id === p.id) && !mine.removed?.[p.id])
142
+ if (missing) throw fail('stale_record', 'another device changed this account’s outside agents — sync the account (or restore its latest wb.a2a.state) and try again')
143
+ }
144
+ }
145
+ /** Send the whole record (it REPLACES what the Sentinel held) — this account's, or `s`, a changed copy (_change). `intakeOf`
146
+ * (sdkKeptIntake.js): (record) → { room, pub, drops } — the record then names the account's message intake and those peers'
147
+ * drop addresses (a2aCore.withIntake), as the app's push does; without it the Sentinel keeps the intake it holds. */
148
+ async _push(s = this._s, expectedGeneration = this._wb._archiveGeneration, intakeOf = null) {
134
149
  const account = await this._account()
135
150
  if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
136
151
  const candidate = this._removals.length ? structuredClone(s) : s
137
152
  if (this._removals.length) applyRemovals(candidate, this._removals)
138
- const r = await this._sealed('a2agrant', { ...recordFor(candidate, account), preserveIntake: true })
153
+ await this._assertCovers(candidate)
154
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
155
+ const intake = intakeOf ? await intakeOf(candidate) : null
156
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
157
+ const rec = recordFor(candidate, account)
158
+ const r = await this._sealed('a2agrant', intake && intake.room && intake.pub ? withIntake(rec, intake) : { ...rec, preserveIntake: true })
139
159
  if (s === this._s) this._changed()
140
160
  return r
141
161
  }
@@ -146,7 +166,7 @@ export class A2AAccount {
146
166
  // One change at a time (each starts from the last one's result: two at once lost one). A restore() that landed while the
147
167
  // push was out (a vault applying the account's kept copy) is merged with the change, not overwritten (a2aCore.js rules).
148
168
  // `fn` returns NO_CHANGE when there is nothing to do (nothing pushed).
149
- _change(fn) {
169
+ _change(fn, { intake = null } = {}) {
150
170
  const generation = this._wb._archiveGeneration, email = this._wb._session?.email
151
171
  const changed = () => generation !== this._wb._archiveGeneration || email !== this._wb._session?.email
152
172
  const run = async () => {
@@ -161,7 +181,7 @@ export class A2AAccount {
161
181
  if (changed()) throw fail('account_changed', 'the account changed during the agent update')
162
182
  if (added.length) { this._removals.push(...added); this._changed() }
163
183
  const finish = await this._stageInbox?.(next)
164
- try { await this._push(next, generation) } catch (e) { if (!changed() && (e.definiteRefusal || (e.status >= 400 && e.status < 500))) { finish?.(false); if (added.length) { this._removals = previous; this._changed() } } throw e }
184
+ try { await this._push(next, generation, intake) } catch (e) { if (!changed() && (e.definiteRefusal || (e.status >= 400 && e.status < 500))) { finish?.(false); if (added.length) { this._removals = previous; this._changed() } } throw e }
165
185
  if (changed()) throw fail('account_changed', 'the account changed during the agent update')
166
186
  finish?.(true)
167
187
  this._removals = []
@@ -173,11 +193,25 @@ export class A2AAccount {
173
193
  this._q = p.catch(() => {})
174
194
  return p
175
195
  }
196
+ /** Send the record again, naming the account's message intake (`intakeOf`, see _push) — a kept assistant's peer then gets its
197
+ * jobs delivered to the cloud device (sdkKeptIntake.js). In the edit queue like every change; the record itself is unchanged. */
198
+ _pushIntake(intakeOf) { return this._change(() => true, { intake: intakeOf }) }
176
199
  /** What the Sentinel holds for this account (lanes, peers by name, open tasks). */
177
200
  status() { return this._plain('a2astatus') }
178
201
  /** Turn A2A off everywhere for this account: every lane's card and every token stop working. Each inbox is marked switched
179
202
  * off, so no other device's copy of the account's record switches one back on (pass 9, K#3). */
180
- async revoke() { const generation = this._wb._archiveGeneration; const r = await this._plain('a2arevoke'); if (this._wb._archiveGeneration !== generation) throw fail('account_changed', 'the account changed during revocation'); this._s = a2aStateOf(clearLanesIn(this._s)); this._removals = []; this._dropAllDrafts(); this._changed(); return r }
203
+ // in the edit queue, after any edit already on its way (side sweep 2026-11-28: an earlier addPeer could reach the Sentinel after the
204
+ // revocation and switch pairings back on) — as the Siri revoke is
205
+ revoke() {
206
+ const generation = this._wb._archiveGeneration
207
+ const run = async () => {
208
+ if (this._wb._archiveGeneration !== generation) throw fail('account_changed', 'the account changed before revocation')
209
+ const r = await this._plain('a2arevoke'); if (this._wb._archiveGeneration !== generation) throw fail('account_changed', 'the account changed during revocation'); this._s = a2aStateOf(clearLanesIn(this._s)); this._removals = []; this._dropAllDrafts(); this._changed(); return r
210
+ }
211
+ const p = (this._q || Promise.resolve()).then(run, run)
212
+ this._q = p.catch(() => {})
213
+ return p
214
+ }
181
215
  }
182
216
  const deliveryKey = (taskId, n, at) => JSON.stringify([taskId, Number(n) || 1, Number(at) || 0])
183
217
  const NO_CHANGE = Symbol('no change')
@@ -388,6 +422,10 @@ export class LaneA2A {
388
422
  // a task already answered (a resumed 'auto' task taken mid-send was re-sent on every resume, an error each time —
389
423
  // sync sweep backlog): it is done, not failed — dropped, never offered again
390
424
  if (!finishedTask(e)) throw e
425
+ if (replyNotDelivered(e, { reject })) { // the requester ended it: the reply never reached them — said so, not "sent" (side sweep 2026-11-28)
426
+ this._pending = this._pending.filter((p) => p.taskId !== taskId)
427
+ throw fail('task_ended', String(e.taskState).toUpperCase() === 'CANCELED' ? 'the peer canceled this task: the reply was not sent' : 'the task has already ended: this reply was not sent', { taskState: e.taskState })
428
+ }
391
429
  r = { state: 'completed' }
392
430
  }
393
431
  this._pending = this._pending.filter((p) => p.taskId !== taskId)
package/sdkAccount.js CHANGED
@@ -78,6 +78,16 @@ export function mergeIndex(a, b, maxRooms = 500) {
78
78
  if (assoc.detachedLane) { newer.detachedLane = true; delete newer.shared }
79
79
  else { delete newer.detachedLane; if (assoc.shared) newer.shared = assoc.shared; else delete newer.shared }
80
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
+ }
81
91
  rooms.set(r.room, pin.pinnedAt || pin.pinned ? { ...newer, pinned: !!pin.pinned, pinnedAt: num(pin.pinnedAt) } : newer)
82
92
  }
83
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
@@ -96,7 +106,9 @@ export function mergeIndex(a, b, maxRooms = 500) {
96
106
  const k = linkKey(l.a, l.b), prev = links.get(k)
97
107
  if (!prev || num(l.at) > num(prev.at)) links.set(k, l)
98
108
  }
99
- 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)
100
112
  return {
101
113
  rooms: reconcileAccountLanes([...rooms.values()]).sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
102
114
  tomb: [...tomb.entries()].map(([room, at]) => ({ room, at })).sort((x, y) => x.at - y.at).slice(-MAX_TOMBS),
@@ -153,8 +165,12 @@ export class AccountIndex {
153
165
  get enabled() { return this._backup.enabled }
154
166
  /** This device's id in the account (stable while its state is kept). */
155
167
  get deviceId() { return (this._backup._s && this._backup._s.device && this._backup._s.device.id) || '' }
156
- /** The account's rooms: [{ room, link, kind, label?, shared?, archived? }] — archived ones included, so filter as you like. */
157
- 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)) }
158
174
  /** The account's devices: [{ id, name, seenAt, signedOut, current }]. */
159
175
  get devices() {
160
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 } : {}) }))
@@ -169,26 +185,51 @@ export class AccountIndex {
169
185
  _usageKey() { const s = this._backup._s; return (s && normUsageKey(s.usage)) || null }
170
186
  _usageKeys() { const s = this._backup._s; return s ? [normUsageKey(s.usage), ...((s.usageOld || []).map(normUsageKey))].filter(Boolean) : [] }
171
187
 
172
- _noteLink(a, b, cap) {
188
+ _noteLink(a, b, cap, live = null) {
173
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)
174
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)
175
193
  const prev = (s.links || []).find((l) => linkKey(l.a, l.b) === k)
176
- if (prev && !prev.removed && prev.cap === cap) return
177
- 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)
178
198
  this._backup._changed(); this._schedule()
179
199
  }
180
- _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) {
181
212
  const s = this._backup._s; if (!s) return
182
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
+ }
183
224
  s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, removed: true, at: Date.now() }].slice(-200)
184
225
  this._backup._changed(); this._schedule()
185
226
  }
186
227
 
187
228
  /** Mark a room archived (or not) on every device. It stays in the account and in the backup. */
188
- 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) })) }
189
230
  pin(room, on = true) { return this._edit(room, (r) => ({ ...r, pinned: !!on, pinnedAt: Math.max(Date.now(), num(r.pinnedAt) + 1) })) }
190
231
  /** Rename a room in the account (the label a restore and your list show). */
191
- 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) })) }
192
233
  /** Drop a room from the account on EVERY device — the room itself is not deleted (that is wb.rooms.delete, for a
193
234
  * tenant). Opening its link again later brings it back. */
194
235
  forget(room) {
@@ -273,7 +314,8 @@ export class AccountIndex {
273
314
  * receipt address; the server seals each reply's cost to it, in the room. This folds the new receipts into the account's
274
315
  * monthly sidecar (kept in the index room, sealed like the index) and reads the month.
275
316
  * @param {object} [o] { month?: 'YYYY-MM' } (default this month, UTC)
276
- * → { 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 */
277
319
  async usage({ month } = {}) {
278
320
  if (!this.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore)')
279
321
  const m = month === undefined ? monthOf(Date.now()) : String(month)
@@ -352,7 +394,11 @@ export class AccountIndex {
352
394
  const s = this._backup._s
353
395
  const i = s ? s.rooms.findIndex((r) => r.room === room) : -1
354
396
  if (i < 0) throw fail('unknown_room', 'that room is not in this account')
355
- 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() }
356
402
  this._backup._schedule()
357
403
  return this
358
404
  }
@@ -428,6 +474,9 @@ export class AccountIndex {
428
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 } }
429
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: [] }
430
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
431
480
  const remote = { ...mergeIndex(old, fromApp), ...mergeUsage(old, fromApp) } // READ-THROUGH: both docs, the newer of each entry (one rule, mergeIndex)
432
481
  const s = this._backup._s
433
482
  const me = this._me()
@@ -436,12 +485,14 @@ export class AccountIndex {
436
485
  const outs = s.outs || {}
437
486
  const localDevices = { ...this._devices }
438
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 } }
439
- 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 } : {}) } } }
440
489
  const merged = mergeIndex(local, remote)
441
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
442
491
  Object.assign(merged, mergeUsage({ usage: s.usage, usageOld: s.usageOld }, remote))
443
492
  if (!merged.usage) merged.usage = await newUsageKey()
444
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]
445
496
  const self = merged.devices[me.id]
446
497
  if (self.out) return this._signedOut(['erased', 'moved'].includes(self.outWhy) ? self.outWhy : undefined)
447
498
  if (Date.now() - num(self.seenAt) > SEEN_EVERY) merged.devices[me.id] = { ...self, seenAt: Date.now() }
@@ -450,6 +501,7 @@ export class AccountIndex {
450
501
  const roomsBefore = canon({ rooms: s.rooms, tomb: s.tomb || [] })
451
502
  this._devices = merged.devices
452
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)
453
505
  const after = canon(merged)
454
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
455
507
  // the version read. A 409 on either re-reads both and merges again.
@@ -463,19 +515,24 @@ export class AccountIndex {
463
515
  }
464
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
465
517
  if (Object.keys(outs).length) {
466
- 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)))
467
522
  if (Object.keys(left).length) s.outs = left; else delete s.outs
468
523
  this._backup._changed()
469
524
  }
470
525
  if (canon({ rooms: merged.rooms, tomb: merged.tomb }) !== roomsBefore) this._backup._persist() // the vault copy holds rooms + tombs, not devices
471
526
  if (usageCanon(merged) !== usageBefore) this._backup._changed() // this device keeps the account's usage key
472
- 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 */ } } }
473
528
  this.lastError = null
529
+ try { this._backup._retryOwedSave?.() } catch { /* the backup keeps its own error */ } // a failed save is owed (sdkBackup.js)
474
530
  return { ok: true, rooms: this.rooms, devices: this.devices }
475
531
  }
476
532
  _signedOut(reason) {
477
533
  this.stop()
478
534
  this._devices = {}
535
+ this._keptMarks = null
479
536
  this._backup._drop()
480
537
  if (typeof this.onSignedOut === 'function') { try { this.onSignedOut(reason ? { reason } : undefined) } catch { /* the app's callback */ } }
481
538
  return { ok: true, signedOut: true, rooms: [], devices: [], ...(reason ? { reason } : {}) }
package/sdkAccountDoc.js CHANGED
@@ -25,7 +25,7 @@ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, u
25
25
  for (const r of rooms) {
26
26
  if (!r || !r.room || typeof r.link !== 'string' || !r.link) continue
27
27
  const mk = keyInLink(r.link) || (typeof r.mk === 'string' ? r.mk : '')
28
- 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
+ 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
29
  const association = preferredAssociation(r, obj(p.rooms)[r.room])
30
30
  const detached = !!association.detachedLane
31
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 } : {}) }
@@ -57,7 +57,7 @@ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, u
57
57
  if (erasedAt) signouts[ERASED_MARK] = Math.max(erasedAt, num(signouts[ERASED_MARK]))
58
58
  if (movedAt) signouts[MOVED_MARK] = Math.max(movedAt, num(signouts[MOVED_MARK]))
59
59
  const u = normUsageKey(usage)
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 }),
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)
61
61
  ...(Array.isArray(links) && links.length ? { links } : {}) }
62
62
  }
63
63
 
@@ -70,7 +70,7 @@ export function fromAppIndex (doc) {
70
70
  if (deletedAt) tomb.push({ room, at: deletedAt })
71
71
  if (typeof e.link !== 'string' || !e.link || e.deleted) continue
72
72
  const label = e.label !== undefined ? e.label : (e.title && e.title !== 'Space' && e.title !== room || e.manual ? e.title : undefined)
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 } : {}), link: e.link, kind: !e.detachedLane && e.kind === 'lane' ? 'lane' : 'space',
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
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 } : {}) })
75
75
  }
76
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