1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552 | ;; ported-from: src/room.ts
;;
;; Room boot: crypto → libp2p transport → chat store → UI. This namespace is the
;; :room module's only entry (shadow-cljs.edn), loaded via shadow.lazy from
;; sueta.main once a room secret is known — so the lobby stays a small chunk and
;; the libp2p/OrbitDB stack only downloads when entering a room. That is the TS
;; build's `await import("./room")` boundary, kept real.
;;
;; THIS FILE OWNS THE PROMESA BOUNDARY. `p/let` is required here and below —
;; never from sueta.main, which is the :main module and therefore first paint.
;; test/module-split.test.mjs asserts that in both directions over the require
;; graph, because a stray require is invisible until someone measures the
;; bundle. Why promesa at all: `shadow.cljs.modern/js-await` is pure `.then`
;; sugar — it expands to `(-> thenable (.then (fn [name] body)))`, with no
;; `async`/`await` anywhere — so a boot with sixteen sequential awaits could
;; only be written as sixteen nested closures. It was: one expression, 29 paren
;; levels deep, closing on a run of 26. `p/let` is the same `.then` chain with
;; the nesting spent in a binding vector instead of in indentation.
;;
;; TWO RULES THAT COME WITH IT:
;;
;; a. ONLY GENUINELY ASYNC WORK GOES IN A BINDING. `p/let` coerces every
;; binding value, and coercion assimilates anything with a `.then` — so a
;; synchronous value is safe there only while it is not thenable. Nothing
;; in this tree or in the kits defines a `then` member (grep it before you
;; doubt it), which is what makes the plain constructors below legal
;; neighbours of the awaits. It is also why they are all *named*: a reader
;; can see which lines wait.
;;
;; b. A `p/let` BODY AWAITS EVERY EXPRESSION IN IT, one microtask each. The
;; synchronous blocks in this file are therefore each ONE call to a named
;; `!`-suffixed function, whose body is an ordinary `do` and runs in one
;; tick — exactly as the js-await ladder's bodies did. Spreading those
;; statements across a multi-expression `p/let` body would interleave
;; microtasks between lines the mailbox replay/deposit order depends on
;; (PROTOCOL.md §9).
;;
;; TWO BEHAVIOURS THIS APP HAS AND THE GAMES DO NOT:
;;
;; 1. NEVER AUTO-ADOPT ON IDENTITY CONFLICT. game1's id/boot.cljs calls
;; `adoptBridgeSeed` the moment the bridge reports a different suite seed,
;; because nothing in a game is bound to the old key. Here the replicated
;; log's authorship and every grant ARE bound to it, so the conflict is
;; surfaced to the identity sheet and the human chooses
;; (adoptSuiteIdentity / keepLocalIdentity below). This file therefore uses
;; IdBridge directly and deliberately does NOT vendor game1's id/boot.
;;
;; 2. onEntry IS WIRED BEFORE REPLICATION STARTS. RoomLog.open starts sync, and
;; `emit` marks hashes as seen, so a handler attached afterwards loses those
;; entries permanently. The store needs the log to exist, so the callback is
;; installed at open() time and buffers into `pending` until the store is
;; constructed. Both callbacks go to RoomLog.open — never assigned after.
(ns sueta.room
(:require [ardegazu.id.bridge-client :refer (IdBridge)]
[promesa.core :as p]
[sueta.app.call :as call]
[sueta.app.chat :as chat]
[sueta.app.migrate :as migrate]
[sueta.app.rooms :as rooms]
[sueta.app.ui :as ui]
[sueta.config :as config]
[sueta.fx :as fx]
[sueta.i18n :as i18n :refer (t tn)]
[ardegazu.rooms.js :as j]
[ardegazu.rooms.lib.crypto :as rc]
[ardegazu.rooms.lib.descriptor :as descriptor]
[ardegazu.rooms.lib.log :as rlog]
[sueta.lib.mailbox :as mbx]
[sueta.lib.media :as media]
[ardegazu.rooms.lib.net :as net]
[sueta.lib.selftest :as selftest]
[ardegazu.rooms.lib.turn :as turn]
[sueta.stores :as stores]
[shadow.lazy :as lazy]))
(def ^:private social-loadable (lazy/loadable sueta.social/attach!))
(declare setup-mailbox finish-boot)
(def ^:private DEFAULTS
(let [o (j/ordered "relayMultiaddr" config/RELAY-MULTIADDR
"turnCredsUrl" config/TURN-CREDS-URL
"discoveryTopic" config/DISCOVERY-TOPIC)]
;; offline mailbox: production discovers it via the descriptor; the env pair
;; is the dev/self-host path (a dev ip4 multiaddr skips the descriptor fetch)
(when (and (some? config/MAILBOX-URL) (some? config/MAILBOX-CREDS-URL))
(unchecked-set o "mailbox" (j/ordered "baseUrl" config/MAILBOX-URL
"credsUrl" config/MAILBOX-CREDS-URL
"maxMessageKb" 64)))
o))
;; ---- the cell: three slots that do not exist yet ----------------------------
;;
;; `store`, `ui` and `call` are built in that order, and every one of them is
;; referenced by callbacks installed BEFORE it exists: net's event bag needs all
;; three, the log's onEntry needs the store, the mailbox's notices need the UI.
;; That is a fixpoint, and the TypeScript wrote it as `let ui!: UI` — mutable
;; slots plus the discipline of never reading one before its owner filled it.
;;
;; Here it is one atom over a Clojure map. A slot read is `(:ui @cell)` and "not
;; filled yet" is `nil`, which `when-some` already knows what to do with. What
;; it replaces is a `js-obj` used as a mutable box with three accessor closures
;; (`store-of` / `ui-of` / `call-of`) written over it; those closures existed
;; only because `(unchecked-get cell "ui")` needed hiding, and a keyword does
;; not need hiding.
(defn- my-name-fn
"net's `myName`: whatever this device currently calls itself. The store owns
the answer once it exists; until then the stored name is the best there is."
[cell nm]
(fn []
(let [s (:store @cell)]
(cond
(j/truthy? s) (chat/my-name s)
(j/truthy? nm) nm
:else "?"))))
(defn- net-events
"net's callback bag. Each of these can fire before, between or after the cell's
slots are filled, so every one reads its slot at call time and does nothing
while it is still empty."
[cell]
(j/ordered
"peerState" (fn [peer state name]
(when-some [u (:ui @cell)] (ui/set-peer u peer state name))
(when-some [c (:call @cell)] (call/on-peer-state c peer state))
js/undefined)
"peerGone" (fn [peer]
(when-some [u (:ui @cell)] (ui/remove-peer u peer))
(when-some [c (:call @cell)] (call/on-peer-gone c peer))
js/undefined)
"message" (fn [from payload]
(if (identical? "call" (when (j/truthy? payload)
(unchecked-get payload "kind")))
(when-some [c (:call @cell)] (call/on-wire c from payload))
(when-some [s (:store @cell)] (chat/on-message s from payload)))
js/undefined)
;; chat images ride the log; call signaling has its own protocol
"binary" (fn [_from _data] js/undefined)
"peerReady" (fn [peer]
(when-some [s (:store @cell)] (chat/on-channel-open s peer))
(when-some [c (:call @cell)] (call/on-channel-open c peer))
js/undefined)
"status" (fn [up]
(when-some [u (:ui @cell)] (ui/set-signaling u up))
js/undefined)))
(defn- entry-sink
"The log's `onEntry`, and the flush that replays what arrived too early.
onEntry MUST exist before sync starts (see the ns docs) and the store does
not exist at that point, so everything that lands early is buffered and
replayed — in arrival order — by the returned flush. Returns
[on-entry flush!]."
[cell]
(let [pending (array)
on-entry (fn [e]
(let [s (:store @cell)]
(if (j/truthy? s)
(do (chat/apply-entry s e)
;; live backfill may unblock deferred mailbox entries
(when-some [m (:mbx @cell)] (mbx/on-live-entry m)))
(.push pending e)))
js/undefined)]
[on-entry
(fn flush! []
(doseq [e (array-seq (.splice pending 0))] (on-entry e))
js/undefined)]))
;; ---- the pieces boot awaits -------------------------------------------------
(defn- dev-self-test!
"The dev-only crypto contract check (TS: `if (import.meta.env.DEV)` in
main.ts). It lives here rather than in sueta.main because lib/selftest
reaches lib/access, which imports @orbitdb/core — that must not land in the
:main module and break the lobby/room chunk split.
Returns nil ON PURPOSE. run-self-test returns a promise and boot has never
waited on it; a `p/let` binding awaits whatever it is given, so handing back
the promise here would newly block every dev boot on the self test."
[]
(when ^boolean goog.DEBUG (selftest/run-self-test))
nil)
(defn- assert-self
"This device's assertion that it holds the suite identity, for the roster:
FOUR keys {pub, sig, hue, glyph}, or nil when there is no suite identity."
[suite-id room-crypto profile]
(if-not (j/truthy? suite-id)
(p/resolved nil)
(p/let [sig (.assert ^js suite-id config/APP-SALT
(unchecked-get room-crypto "roomId")
(unchecked-get room-crypto "peerId"))]
(j/ordered "pub" (unchecked-get suite-id "publicKeyB64")
"sig" sig
"hue" (unchecked-get profile "hue")
"glyph" (unchecked-get profile "glyph")))))
(defn- self-info
"What the identity sheet is shown: FIVE keys {seed, fp, pub, profile,
conflict}. A NON-NULL `conflict` means the suite bridge holds a DIFFERENT
identity — it is surfaced, never adopted automatically (see the ns docs)."
[id-boot suite-id profile]
(when (j/truthy? suite-id)
(j/ordered "seed" (j/nn (unchecked-get id-boot "seed") "")
"fp" (unchecked-get suite-id "fingerprint")
"pub" (unchecked-get suite-id "publicKeyB64")
"profile" profile
"conflict" (unchecked-get id-boot "conflict"))))
(defn- stored-name
"The name this device already goes by: the suite profile's, else this app's
own `<ns>:name` mirror, else nil. (localStorage throws in Safari private
mode, which is not an error — it means \"no name\".)"
[profile]
(let [n (unchecked-get profile "name")]
(if (j/truthy? n)
n
(try
(js/localStorage.getItem (config/ns-key "name"))
(catch :default _ nil)))))
(defn- persist-storage!
"Ask Safari & friends not to evict the blockstore. Best effort in the strict
sense: a browser with no StorageManager, or one that simply says no, is the
expected case and not a failure."
[]
(p/do
(let [st (unchecked-get js/navigator "storage")]
(when (and (j/truthy? st) (j/truthy? (.-persist ^js st)))
(.persist ^js st)))))
;; ---- boot -------------------------------------------------------------------
(defn boot-room [root secret force-relay]
(let [cell (atom {})]
(p/let [_ (dev-self-test!)
room-entry (rooms/touch-room secret)
;; network id first: per-sender keys and AADs bind to the libp2p PeerId
session (net/new-session-key)
room-crypto (rc/create secret config/APP-SALT (unchecked-get session "peerId"))
;; persistent identity: one Ed25519 seed for the WHOLE suite, picked
;; up via the identity bridge (ardegazu.ro/id/) and mirrored in this
;; app's storage so offline boots never wait on the iframe (id-kit
;; bridge-client). The mirror keys are the same `<ns>:id` / `<ns>:name`
;; this app always used.
bridge (IdBridge. (j/ordered "ns" config/NS "bridgeUrl" config/ID-BRIDGE-URL))
id-boot (.boot ^js bridge)
profile (unchecked-get id-boot "profile")
;; a language picked anywhere in the suite follows you here — before
;; the UI renders
_ (i18n/absorb-suite-lang (unchecked-get profile "lang"))
suite-id (unchecked-get id-boot "identity")
assertion (assert-self suite-id room-crypto profile)
info (self-info id-boot suite-id profile)
nm (stored-name profile)
cfg (descriptor/resolve-relay-config DEFAULTS)
ice (turn/IceConfig. (unchecked-get cfg "turnCredsUrl") force-relay)
net-obj (net/create
(j/ordered
"privateKey" (unchecked-get session "privateKey")
"crypto" room-crypto
"ice" ice
"relayMultiaddr" (unchecked-get cfg "relayMultiaddr")
"discoveryTopic" (unchecked-get cfg "discoveryTopic")
"myName" (my-name-fn cell nm)
"events" (net-events cell)))
;; the replicated log: Helia over the same libp2p node + OrbitDB
;; events DB
helia (stores/open-idb-helia (unchecked-get net-obj "libp2p")
(j/ordered "blocks" (config/ns-db "blocks")
"data" (config/ns-db "data")))
_ (fx/drop-silently (persist-storage!))
;; onEntry MUST exist before sync starts (see the ns docs)
[on-entry flush-pending!] (entry-sink cell)
log (rlog/open helia room-crypto suite-id
(j/ordered
"onEntry" on-entry
;; undecryptable garbage from non-members — expected
;; noise
"onError" (fn [_] js/undefined)))
store (chat/ChatStore.
net-obj log (j/nn nm "")
(j/ordered "appSalt" config/APP-SALT
"roomId" (unchecked-get room-crypto "roomId"))
assertion)
_ (swap! cell assoc :store store)
ctx {:cell cell
:root root
:secret secret
:room-entry room-entry
:room-crypto room-crypto
:bridge bridge
:id-boot id-boot
:suite-id suite-id
:self-info info
:stored-name nm
:cfg cfg
:ice ice
:net net-obj
:log log
:store store}
_ (setup-mailbox ctx)
;; flush the entries that arrived while the store did not exist yet
_ (flush-pending!)]
(finish-boot ctx))))
;; ---- mailbox (PROTOCOL.md §9) ----------------------------------------------
(defn- setup-mailbox
"A second transport for the same sealed blocks, so history reaches members who
are never online together. Constructed only when the descriptor (or env)
advertises one."
[{:keys [cell cfg room-crypto log suite-id store]}]
(let [mailbox (unchecked-get cfg "mailbox")]
(if-not (j/truthy? mailbox)
(p/resolved nil)
(p/let [mbx-room-id (rc/mailbox-room-id room-crypto)
cipher (rc/mbx-cipher room-crypto)]
(let [room-id (unchecked-get room-crypto "roomId")
k (fn [prefix] (config/ns-key (str prefix ":" room-id)))
sync (mbx/MailboxSync.
(j/ordered
"log" log
"client" (mbx/MailboxClient. (unchecked-get mailbox "baseUrl") mbx-room-id
(mbx/MailboxAuth. (unchecked-get mailbox "credsUrl")
mbx-room-id))
"cipher" cipher
"maxMessageKb" (unchecked-get mailbox "maxMessageKb")
"keys" (j/ordered "cursor" (k "mbx-cursor")
"queue" (k "mbx-queue")
"sent" (k "mbx-sent")
"retry" (k "mbx-retry")
"ident" (k "mbx-ident"))
"hasIdentity" (not (nil? suite-id))
"onDisplayOnly" (fn [e] (chat/apply-entry store e) js/undefined)
;; lib/ stays i18n-free; the mailbox emits exactly one
;; notice (expired offline messages), so the app boundary
;; swaps in the translation
"onNotice" (fn [_]
(when-some [u (:ui @cell)]
(ui/toast u (str "⌛ " (t "toast.mailbox-expired"))))
js/undefined)
"onReplayed" (fn [n]
(when-some [u (:ui @cell)]
(ui/toast u (tn "toast.offline-delivered" n)))
js/undefined)))]
(swap! cell assoc :mbx sync)
(unchecked-set log "onAppended" (fn [h] (mbx/enqueue-entry sync h) js/undefined))
(unchecked-set log "onImageStored" (fn [c] (mbx/enqueue-image sync c) js/undefined))
;; every unixfs block must fit one mailbox frame (envelope ≈ 40 bytes)
(unchecked-set log "imageChunkBytes"
(js/Math.min (* (- (unchecked-get mailbox "maxMessageKb") 1) 1024) 61440))
js/undefined)))))
;; ---- the rest of the boot ---------------------------------------------------
(defn- make-media
"calls: membership on the room topic, media on dedicated media-only pcs"
[{:keys [cell room-crypto ice store] net-obj :net}]
(media/Media.
(j/ordered "crypto" room-crypto
"ice" ice
"net" net-obj
"myName" (fn [] (chat/my-name store))
"events"
(j/ordered
"track" (fn [peer stream]
(when-some [c (:call @cell)] (call/on-track c peer stream))
js/undefined)
;; media transport class (direct/relayed) — unused here since the
;; video cap is uniform (coturn allows full rate); a fork can
;; drive UI with it
"mediaState" (fn [_peer _state] js/undefined)))))
(defn- make-ui
"The UI, and the one place the whole boot's capabilities are handed to it."
[{:keys [root secret store bridge room-entry] info :self-info call-obj :call}]
(ui/UI.
root store
(j/ordered
"send" (fn [text thread] (chat/send-text store text thread))
"sendImage" (fn [file thread] (chat/send-image store file thread))
"react" (fn [id emoji] (chat/toggle-reaction store id emoji))
"rename" (fn [name]
(chat/set-name store name)
;; suite-wide: writes the local mirror (same `<ns>:name` key as
;; before) and pushes to the bridge so every other app renames too
(.putProfile ^js bridge (j/ordered "name" name))
js/undefined)
"inviteURL" (fn [] (str (.-origin js/location) (.-pathname js/location) "#" secret))
"roomLabel" (fn [] (unchecked-get room-entry "label"))
"goLobby" (fn []
(.replaceState js/history nil "" (.-pathname js/location))
(.reload js/location)
js/undefined)
"joinCall" (fn [video] (call/join call-obj video))
"leaveCall" (fn [] (call/leave call-obj))
"toggleMic" (fn [] (call/toggle-mic call-obj))
"toggleCam" (fn [] (call/toggle-cam call-obj))
"identity" (fn [] info)
"importIdentity"
(fn [seed]
(if-not (.test (js/RegExp. "^[A-Za-z0-9_-]{43}$") seed)
false
(let [ok (try (js/localStorage.setItem (config/ns-key "id") seed) true
(catch :default _ false))]
(when ok
;; app-local switch; if it differs from the suite identity, the next
;; boot surfaces the chooser (adopt suite-wide vs keep local)
(.reload js/location))
ok)))
;; Conflict chooser: make the SUITE identity this app's too. Only ever
;; reached from an explicit two-tap in the identity sheet — chat NEVER
;; adopts on its own (see the ns docs).
"adoptSuiteIdentity"
(fn []
(let [conflict (when (j/truthy? info) (unchecked-get info "conflict"))]
(when (j/truthy? conflict)
(.adoptBridgeSeed ^js bridge conflict)
(.reload js/location)))
js/undefined)
;; Conflict chooser: keep the app-local identity, stop asking.
"keepLocalIdentity"
(fn []
(let [conflict (when (j/truthy? info) (unchecked-get info "conflict"))]
(when (j/truthy? conflict)
(.keepLocalSeed ^js bridge conflict)
(unchecked-set info "conflict" nil)))
js/undefined))))
(defn- wire-callbacks!
"Everything the store and the call manager say, said to the UI. Installed once
both exist, never reassigned. One tick, no awaits."
[{:keys [secret store log] net-obj :net ui-obj :ui call-obj :call}]
;; the AUTHOR id (durable log identity), not the session peerId — the UI
;; compares it against reaction author sets
(ui/bind-self ui-obj (unchecked-get log "myAuthorId"))
(unchecked-set store "onPeerName" (fn [peer name] (ui/set-peer-name ui-obj peer name)))
(unchecked-set store "onPeerIdentity" (fn [peer id] (ui/set-peer-identity ui-obj peer id)))
(unchecked-set store "onIncoming" (fn [m] (ui/notify-incoming ui-obj m)))
;; same-identity device sync: directed only (never broadcast — every member
;; could decrypt a broadcast; the directed stream is pairwise-encrypted)
(unchecked-set store "onSelfDevice"
(fn [peer]
(let [payload (j/ordered "kind" "roomsync")
rs (rooms/build-room-sync)]
(unchecked-set payload "rooms" (unchecked-get rs "rooms"))
(unchecked-set payload "gone" (unchecked-get rs "gone"))
;; the peer may already be gone — that is the normal case,
;; not a defect
(fx/drop-silently (js/Promise.resolve (net/send-to net-obj peer payload))))
js/undefined))
(unchecked-set store "onRoomSync"
(fn [_peer payload]
(let [n (rooms/merge-rooms payload secret)]
(when (pos? n) (ui/toast ui-obj (tn "toast.rooms-synced" n))))
js/undefined))
(unchecked-set call-obj "onRoster"
(fn [st members] (ui/update-call ui-obj st members (call/local-stream call-obj))))
(unchecked-set call-obj "onError" (fn [m] (ui/toast ui-obj m)))
(unchecked-set call-obj "onNotice" (fn [m] (ui/toast ui-obj m)))
js/undefined)
(defn- announce-live!
"Everything that happens the instant the local replay is in: one tick, no
awaits, in exactly this order."
[{:keys [cell secret store log room-crypto] info :self-info
net-obj :net ui-obj :ui call-obj :call media-obj :media} restored]
;; one-shot import of v1 device history into the log (no-op when done/absent)
(fx/tolerate
"history migration failed"
(p/let [n (migrate/migrate-legacy-history secret config/APP-SALT log store)]
(when (pos? n) (ui/toast ui-obj (tn "toast.migrated" n)))
js/undefined))
(chat/mark-live store)
(when (pos? restored) (ui/toast ui-obj (tn "toast.restored" restored)))
;; mailbox catch-up: replay deposits from members who came and went while we
;; were offline, then flush our own queue (non-blocking; live chat never waits)
(when-some [m (:mbx @cell)] (mbx/start m))
;; console/debug handle — grants nothing an open console doesn't have
(unchecked-set js/window "__sueta"
(j/ordered "net" net-obj "log" log "store" store "media" media-obj
"call" call-obj "roomCrypto" room-crypto
"identity" info "mbx" (:mbx @cell)))
nil)
(defn- join-room!
"The name is settled: adopt it, tell the suite, bring the social layer up and
arrange to leave cleanly. One tick, no awaits."
[{:keys [cell secret store bridge id-boot log] net-obj :net ui-obj :ui
call-obj :call media-obj :media} chosen asked]
(chat/set-name store chosen)
(try (js/localStorage.setItem (config/ns-key "name") chosen) (catch :default _ nil))
;; a first-run name goes suite-wide too (the rename path already does)
(when (and asked (j/truthy? (unchecked-get id-boot "identity")))
(.putProfile ^js bridge (j/ordered "name" chosen)))
;; the social side: presence to friends + live invite toasts, riding this
;; node's pubsub. Its own chunk; must never delay or break the room — but a
;; chunk that will not load is ours, not weather, so it says so.
(when (and (j/truthy? (unchecked-get id-boot "identity"))
(j/truthy? (unchecked-get id-boot "seed")))
(fx/tolerate
"social layer failed to attach"
(p/let [attach (lazy/load social-loadable)]
(attach (j/ordered "net" net-obj
"idBoot" id-boot
"bridge" bridge
"store" store
"ui" ui-obj
"secret" secret)))))
(.addEventListener js/window "beforeunload"
(fn []
(call/leave call-obj)
(media/close media-obj)
(when-some [m (:mbx @cell)] (mbx/stop m))
(rlog/close log)
(net/close net-obj)
js/undefined))
js/undefined)
(defn- finish-boot
"Media, calls, the UI, and then the two awaits that end a boot: the local
replay and the name."
[ctx]
(let [{:keys [cell store log]} ctx
media-obj (make-media ctx)
call-obj (call/CallManager. (:net ctx) media-obj (fn [] (chat/my-name store)))
ctx (assoc ctx :media media-obj :call call-obj)]
(swap! cell assoc :call call-obj)
(unchecked-set call-obj "onStartedCall"
(fn []
;; a call LogOp: {t, ts, name} — three keys
(fx/tolerate "call marker not appended"
(.append ^js log (j/ordered "t" "call" "ts" (js/Date.now)
"name" (chat/my-name store))))
js/undefined))
(let [ui-obj (make-ui ctx)
ctx (assoc ctx :ui ui-obj)]
(swap! cell assoc :ui ui-obj)
(wire-callbacks! ctx)
;; returning users are not re-asked: a stored name joins silently (rename
;; lives in the identity sheet)
(let [trimmed (if (j/truthy? (:stored-name ctx)) (.trim ^string (:stored-name ctx)) "")
asked (not (j/truthy? trimmed))]
;; replay this device's copy of the log (works fully offline), then go live
(p/let [restored (rlog/load-tail log 500)
_ (announce-live! ctx restored)
chosen (if asked (ui/ask-name ui-obj nil) trimmed)]
(join-room! ctx chosen asked))))))
|