@estiva-app/conversation 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/places.ts CHANGED
@@ -31,6 +31,7 @@ import { byOrder } from './order.js'
31
31
  import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, streamMarkerOf, threadContext } from './readState.js'
32
32
  import { peopleNamedInBody } from './strength.js'
33
33
  import { groupThreads } from './threads.js'
34
+ import { lightsIn, seenIn, type StreamJudge } from './unread.js'
34
35
 
35
36
  /** A team's own address kind: on it, a level or a member change is about the team's chat. */
36
37
  const KIND_TEAM = 39000
@@ -614,16 +615,28 @@ export function isUnreadOnPlace(
614
615
  judge: PlaceJudge,
615
616
  inConversationSince: number | undefined,
616
617
  ): boolean {
618
+ return lightsOnPlace(message, root, judge, inConversationSince) && newerThanItsMarker(message, root, merged, judge, startedOn(message, judge.following))
619
+ }
620
+
621
+ /** Whether `me` was in the place when the message was said. */
622
+ function startedOn(message: Pick<Message, 'created_at'>, following: Following): boolean {
623
+ return following.in && (following.since === undefined || message.created_at >= following.since)
624
+ }
625
+
626
+ /**
627
+ * Whether one message on a place lights it for `me` at all, read or not (§11.8 *What is unread on a place*, without the
628
+ * marker): a mention at any level; otherwise, unmuted and in the place, a new conversation, a reply in one `me` is in,
629
+ * and at All every message since All. Unread is this and newer than its marker.
630
+ */
631
+ function lightsOnPlace(message: Message, root: string | undefined, judge: PlaceJudge, inConversationSince: number | undefined): boolean {
617
632
  if (message.pubkey === judge.me) return false
633
+ if (peopleNamedInBody(message.content).has(judge.me)) return true
618
634
  const { following } = judge
619
- const mentioned = peopleNamedInBody(message.content).has(judge.me)
620
- const started = following.in && (following.since === undefined || message.created_at >= following.since)
621
635
  const levelLights =
622
636
  (following.level === 'all' && message.created_at >= (following.allSince ?? following.since ?? 0)) ||
623
637
  root === undefined ||
624
638
  (inConversationSince !== undefined && message.created_at >= inConversationSince)
625
- if (!mentioned && (judge.muted || !started || !levelLights)) return false
626
- return newerThanItsMarker(message, root, merged, judge, started)
639
+ return !judge.muted && startedOn(message, following) && levelLights
627
640
  }
628
641
 
629
642
  /** Whether a message that lights by its level is still unread: its stream's marker, or its thread's for a reply (§11.3). */
@@ -657,17 +670,118 @@ export function unreadOnListedFile<E extends Message>(
657
670
  merged: Readonly<Record<string, number>>,
658
671
  judge: PlaceJudge & { under?: boolean },
659
672
  ): E[] {
673
+ if (!judge.following.in) return []
674
+ // A root comment's `p` is the file's author, which says nothing of `P`: only a reply's counts (`eachMessage`).
675
+ return eachMessage(messages, judge.me, (message, root, inSince) =>
676
+ lightsOnListedFile(message, root, judge, inSince) && newerThanItsMarker(message, root, merged, judge, true),
677
+ )
678
+ }
679
+
680
+ /** Whether one message on a listed file lights the place for `me` at all, read or not ({@link unreadOnListedFile} without the marker). */
681
+ function lightsOnListedFile(message: Message, root: string | undefined, judge: PlaceJudge & { under?: boolean }, inSince: number | undefined): boolean {
660
682
  const { following, me } = judge
661
- if (!following.in) return []
683
+ if (!following.in || message.pubkey === me) return false
684
+ if (following.since !== undefined && message.created_at < following.since) return false
662
685
  const allFrom = following.level === 'all' && !judge.under && !judge.muted ? (following.allSince ?? following.since ?? 0) : undefined
663
- // A root comment's `p` is the file's author, which says nothing of `P`: only a reply's counts (`eachMessage`).
664
- return eachMessage(messages, me, (message, root, inSince) => {
665
- if (message.pubkey === me) return false
666
- if (following.since !== undefined && message.created_at < following.since) return false
667
- const mentioned = peopleNamedInBody(message.content).has(me)
668
- const inYours = !judge.muted && root !== undefined && inSince !== undefined && message.created_at >= inSince
669
- const atAll = allFrom !== undefined && message.created_at >= allFrom
670
- return (mentioned || inYours || atAll) && newerThanItsMarker(message, root, merged, judge, true)
686
+ const mentioned = peopleNamedInBody(message.content).has(me)
687
+ const inYours = !judge.muted && root !== undefined && inSince !== undefined && message.created_at >= inSince
688
+ const atAll = allFrom !== undefined && message.created_at >= allFrom
689
+ return mentioned || inYours || atAll
690
+ }
691
+
692
+ // ── What lit a stream, new and seen ─────────────────────────────────────────
693
+
694
+ /**
695
+ * One line of a stream's list (§11.8 *What lit a stream, new and seen*): a message, with why it lit
696
+ * ({@link UnreadReason}), or a reaction to `P`'s message (ACT-7; no line of this type is listed until a reaction's
697
+ * `orange:` mark is read, so none is today). `seen` is false for what is unread now: the New part of the list.
698
+ */
699
+ export type LitLine<E> =
700
+ | { type: 'message'; message: E; reason: UnreadReason; seen: boolean }
701
+ | { type: 'reaction'; reaction: E; seen: boolean }
702
+
703
+ /** Options for a stream's list. */
704
+ export interface LitLineOptions extends UnreadReasonOptions {
705
+ /**
706
+ * At most this many lines, except that every new line is kept: all the new ones, then the newest seen ones up to
707
+ * it. Each part is newest first, and the new part comes before the seen one. Unbounded when left out.
708
+ */
709
+ limit?: number
710
+ }
711
+
712
+ /** What stays in the list once seen: what was about `P` (Miky, 2026-11-11). A plain message read is in its conversation. */
713
+ const KEPT_ONCE_SEEN: ReadonlySet<UnreadReason> = new Set(['mention', 'reply-in-yours'])
714
+
715
+ function linesOf<E extends Message>(
716
+ messages: readonly E[],
717
+ me: string,
718
+ options: LitLineOptions,
719
+ judge: (message: E, root: string | undefined, inSince: number | undefined) => { lights: boolean; unread: boolean },
720
+ ): LitLine<E>[] {
721
+ const out: LitLine<E>[] = []
722
+ eachMessage(messages, me, (message, root, inSince) => {
723
+ const { lights, unread } = judge(message, root, inSince)
724
+ if (!lights) return false
725
+ const reason = unreadReason(message, root, inSince, me, options)
726
+ if (unread || KEPT_ONCE_SEEN.has(reason)) out.push({ type: 'message', message, reason, seen: !unread })
727
+ return false
728
+ })
729
+ return mergeLitLines([out], options)
730
+ }
731
+
732
+ const lineEvent = <E extends Message>(line: LitLine<E>): E => (line.type === 'message' ? line.message : line.reaction)
733
+
734
+ /**
735
+ * Several streams' lists as one (§11.8 *What lit a stream, new and seen*): a place's list is its own stream's and each
736
+ * listed file's, and a team's list is its places'. One line per message (the first list that has it wins), every new
737
+ * line before every seen one, each part newest first by §6.3's ordering, and `limit` bounds only the seen lines — the
738
+ * same order and limit as each stream's own list, so a file listed in two places is one line and a seen line never
739
+ * sits above a new one.
740
+ */
741
+ export function mergeLitLines<E extends Message>(lists: readonly (readonly LitLine<E>[])[], options: { limit?: number } = {}): LitLine<E>[] {
742
+ const byId = new Map<string, LitLine<E>>()
743
+ for (const list of lists) for (const line of list) if (!byId.has(lineEvent(line).id)) byId.set(lineEvent(line).id, line)
744
+ const out = [...byId.values()].sort((a, b) => byOrder(lineEvent(b), lineEvent(a)))
745
+ // New before seen; a limit never cuts a new line, since those are what light the dot: it bounds the seen ones.
746
+ const fresh = out.filter((line) => !line.seen)
747
+ const seen = out.filter((line) => line.seen)
748
+ return [...fresh, ...(options.limit === undefined ? seen : seen.slice(0, Math.max(0, options.limit - fresh.length)))]
749
+ }
750
+
751
+ /**
752
+ * A place's list, new then seen, each newest first (§11.8 *What lit a stream, new and seen*): every message that is unread on the place
753
+ * ({@link unreadOnPlace}), and every one that lit it and is seen now when it was about `me` — a mention of them or a
754
+ * reply in their conversation. The unseen lines are exactly {@link unreadOnPlace}'s; judged by today's following.
755
+ */
756
+ export function whatLitPlace<E extends Message>(messages: readonly E[], merged: Readonly<Record<string, number>>, judge: PlaceJudge, options: LitLineOptions = {}): LitLine<E>[] {
757
+ return linesOf(messages, judge.me, options, (message, root, inSince) => {
758
+ const lights = lightsOnPlace(message, root, judge, inSince)
759
+ return { lights, unread: lights && newerThanItsMarker(message, root, merged, judge, startedOn(message, judge.following)) }
760
+ })
761
+ }
762
+
763
+ /** A listed file's lines on the place that lists it, as {@link whatLitPlace}: the unseen ones are {@link unreadOnListedFile}'s. */
764
+ export function whatLitListedFile<E extends Message>(
765
+ messages: readonly E[],
766
+ merged: Readonly<Record<string, number>>,
767
+ judge: PlaceJudge & { under?: boolean },
768
+ options: LitLineOptions = {},
769
+ ): LitLine<E>[] {
770
+ if (!judge.following.in) return []
771
+ return linesOf(messages, judge.me, options, (message, root, inSince) => {
772
+ const lights = lightsOnListedFile(message, root, judge, inSince)
773
+ return { lights, unread: lights && newerThanItsMarker(message, root, merged, judge, true) }
774
+ })
775
+ }
776
+
777
+ /**
778
+ * A stream's lines by membership (a DM, with `{ dm: true }`, or a file `P` is a member of), as {@link whatLitPlace}: the
779
+ * unseen ones are {@link unreadIn}'s.
780
+ */
781
+ export function whatLitStream<E extends Message>(messages: readonly E[], merged: Readonly<Record<string, number>>, judge: StreamJudge, options: LitLineOptions = {}): LitLine<E>[] {
782
+ return linesOf(messages, judge.me, options, (message, root) => {
783
+ const lights = lightsIn(message, judge)
784
+ return { lights, unread: lights && !seenIn(message, root, merged, judge) }
671
785
  })
672
786
  }
673
787
 
@@ -0,0 +1,405 @@
1
+ /*
2
+ SPEC §11: marking things read and getting it onto the relay — the one queue
3
+ Ship and Leaf both use (TOPIC-3), so an app writes read state by
4
+ construction rather than by copying another app's queue.
5
+
6
+ One queue per tab, because a slot is one replaceable blob per installation:
7
+ two queues would each hold a partial context map and take turns overwriting
8
+ one another's markers.
9
+
10
+ Whole blob, always. The coordinate is replaced, not patched, so every
11
+ publish carries the complete map, and the slot is read back from the relay
12
+ before every write: every tab of this browser shares the slot, and a blob
13
+ read before another tab's publish would write over what that tab added. A
14
+ partial blob does not fail; it silently drops every context it left out, and
15
+ because the cross-slot merge is grow-only the loss stays invisible until
16
+ this is the last slot standing.
17
+
18
+ Debounced on marks, never on a poll: a refresh is not somebody reading
19
+ anything, and each publish costs an encrypt, a sign and a publish.
20
+
21
+ why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reply-is-read-only-when-its-thread-is-opened.md
22
+ */
23
+ import type { SignedEvent, UnsignedEvent } from '@estiva-app/protocol'
24
+ import type { QueryFn } from './decorations.js'
25
+ import { KIND_APP_DATA } from './kinds.js'
26
+ import {
27
+ REPLY_FLOOR_CONTEXT,
28
+ advanceContexts as advance,
29
+ loadSlotIdentity,
30
+ parseReadStateBlob,
31
+ publishReadState,
32
+ readStateDTag,
33
+ rotateSlotId,
34
+ toContextSeconds,
35
+ type Nip44,
36
+ type RandomBytes,
37
+ type SlotIdentity,
38
+ type SlotStorage,
39
+ } from './readState.js'
40
+
41
+ type Timer = unknown
42
+ const timers = globalThis as unknown as { setTimeout(run: () => void, ms: number): Timer; clearTimeout(id: Timer): void }
43
+ const consoleWarn = (...args: unknown[]): void => (globalThis as unknown as { console?: { warn(...a: unknown[]): void } }).console?.warn(...args)
44
+
45
+ /** Long enough to batch a few marks, short enough to survive a tab close. */
46
+ export const READ_STATE_PUBLISH_DEBOUNCE_MS = 3000
47
+
48
+ /** How long something must be on screen before it counts as read (Peek's, Ship's and Leaf's). */
49
+ export const READ_DWELL_MS = 1500
50
+
51
+ /** The longest wait between attempts while publishing keeps failing. */
52
+ export const READ_STATE_MAX_RETRY_MS = 60_000
53
+
54
+ /** The part of a browser's `document` the queue and the dwell listen to. */
55
+ export interface VisibilitySource {
56
+ readonly hidden: boolean
57
+ addEventListener(type: 'visibilitychange', listener: () => void): void
58
+ removeEventListener(type: 'visibilitychange', listener: () => void): void
59
+ }
60
+
61
+ /** What a flush did, for an app's diagnostic. */
62
+ export type ReadStateAttempt =
63
+ | 'nothing-pending'
64
+ | 'no-session'
65
+ | 'not-hydrated'
66
+ | 'unchanged'
67
+ | 'published'
68
+ | 'rejected'
69
+ | 'failed'
70
+
71
+ export interface ReadStateQueueOptions {
72
+ /** Where the slot id lives (`localStorage`); read when the slot is first needed. It may throw, or be absent. */
73
+ storage: () => SlotStorage | undefined
74
+ /** The app's own key (`ship.readstate.slot`, `leaf.readstate.slot`), so it keeps the slot it has. */
75
+ storageKey: string
76
+ /** Names the app in a new `client_id`: `ship` → `ship-1a2b3c4d`. */
77
+ clientPrefix: string
78
+ random: RandomBytes
79
+ /** Who is signed in now, or undefined. A mark made by nobody is dropped; a change of person drops the last one's queue. */
80
+ pubkey: () => string | undefined
81
+ /**
82
+ * Whether a write can go out now — false while an access token is being renewed. The markers wait and the
83
+ * queue comes back, backing off. Absent: always.
84
+ */
85
+ canWrite?: () => boolean
86
+ query: QueryFn
87
+ nip44: Nip44
88
+ sign: (event: UnsignedEvent) => Promise<SignedEvent>
89
+ publish: (event: SignedEvent) => Promise<{ ok: boolean; reason?: string }>
90
+ /** Each mark that moved a context, at once — before the publish — so a page can draw it read now. */
91
+ onMarked?: (contexts: Readonly<Record<string, number>>) => void
92
+ /** Each flush's outcome, for a diagnostic. */
93
+ onAttempt?: (outcome: ReadStateAttempt, detail?: string, contexts?: number) => void
94
+ debounceMs?: number
95
+ }
96
+
97
+ export interface ReadStateQueue {
98
+ /** Mark these contexts read at `atMs`; the publish follows, debounced. Contexts come from this package's builders. */
99
+ markRead(contexts: readonly (string | undefined)[], atMs?: number): void
100
+ /** Publish what is pending now. */
101
+ flush(): Promise<void>
102
+ /** This installation's slot, minted on first use. */
103
+ identity(): SlotIdentity
104
+ /** Publish before the tab goes away: `visibilitychange` is the one a phone fires. Returns the uninstall. */
105
+ installFlushOnHide(doc: VisibilitySource): () => void
106
+ /** What the queue holds now, copied, for a diagnostic: what can no probe outside the tab can see. */
107
+ state(): ReadStateQueueState
108
+ /** Drop the tab's state, timers included, so a test starts clean. */
109
+ reset(): void
110
+ }
111
+
112
+ export interface ReadStateQueueState {
113
+ /** Everything this slot believes it has read. */
114
+ known: Record<string, number>
115
+ /** Marked but not yet in an accepted publish. Non-empty for long is the smell. */
116
+ pending: Record<string, number>
117
+ /** What the relay is believed to hold for this slot. */
118
+ published: Record<string, number> | undefined
119
+ hydrated: boolean
120
+ /** The wait before the next retry, 0 when none is backing off. */
121
+ retryMs: number
122
+ }
123
+
124
+ export function createReadStateQueue(options: ReadStateQueueOptions): ReadStateQueue {
125
+ const { storageKey, clientPrefix, random, query, nip44 } = options
126
+ const debounceMs = options.debounceMs ?? READ_STATE_PUBLISH_DEBOUNCE_MS
127
+ const canWrite = options.canWrite ?? (() => true)
128
+ const attempt = (outcome: ReadStateAttempt, detail?: string, contexts?: number) => options.onAttempt?.(outcome, detail, contexts)
129
+
130
+ let identity: SlotIdentity | undefined
131
+ /** Whose read state this queue holds. */
132
+ let owner: string | undefined
133
+ /** Everything this slot holds: its own blob from the relay, plus what was marked here. */
134
+ let known: Record<string, number> = {}
135
+ /** Marked but not yet in an accepted publish. */
136
+ let pending: Record<string, number> = {}
137
+ /** What the relay is believed to hold, so an unchanged blob is not published again. */
138
+ let published: Record<string, number> | undefined
139
+ /** The last content seen at our coordinate and what it held, so an unchanged slot is not decrypted again. */
140
+ let ownCopy: { content: string; contexts: Record<string, number> } | undefined
141
+ let hydrated = false
142
+ /** When the copy of our slot read back was written (unix seconds), so the next publish is dated after it. */
143
+ let slotAt = 0
144
+ let timer: Timer | undefined
145
+ let retryMs = 0
146
+ let inFlight: Promise<void> = Promise.resolve()
147
+
148
+ function currentIdentity(): SlotIdentity {
149
+ identity ??= loadSlotIdentity({ storage: safe(options.storage), storageKey, clientPrefix, random })
150
+ return identity
151
+ }
152
+
153
+ function advanceContexts(current: Record<string, number>, updates: Record<string, number>): Record<string, number> {
154
+ const { contexts, evicted } = advance(current, updates)
155
+ if (evicted.length > 0) consoleWarn(`[read-state] over the byte cap; ${evicted.length} oldest markers dropped`)
156
+ return contexts
157
+ }
158
+
159
+ /** Another person in this tab: nothing of the last one's — what they read, what waits to be published — carries over. */
160
+ function forPerson(pubkey: string): void {
161
+ if (owner === pubkey) return
162
+ owner = pubkey
163
+ known = {}
164
+ pending = {}
165
+ published = undefined
166
+ ownCopy = undefined
167
+ hydrated = false
168
+ }
169
+
170
+ /**
171
+ * Read this installation's own blob back. Only our own coordinate: the write needs nothing of the other slots,
172
+ * and each would cost a `/nip44/decrypt` from the quota the rest of the app shares. Unreachable is not empty, and
173
+ * a slot that would not decrypt this time (a 429 above all) is not ours to write over: both throw, leaving the
174
+ * queue unhydrated so it comes back.
175
+ */
176
+ async function hydrate(pubkey: string): Promise<void> {
177
+ hydrated = false
178
+ const slot = currentIdentity()
179
+ const events = await query([{ kinds: [KIND_APP_DATA], authors: [pubkey], '#d': [readStateDTag(slot.slotId)] }])
180
+ const newest = events.filter((e) => e.pubkey === pubkey).sort((a, b) => b.created_at - a.created_at)[0]
181
+ let own: Record<string, number> = {}
182
+ slotAt = newest?.created_at ?? 0
183
+ if (newest && ownCopy?.content === newest.content) own = ownCopy.contexts
184
+ else if (newest) {
185
+ const blob = parseReadStateBlob(await nip44.decrypt(newest.content))
186
+ if (blob?.client_id === slot.clientId) {
187
+ own = blob.contexts
188
+ ownCopy = { content: newest.content, contexts: own }
189
+ } else {
190
+ // Another installation's blob at our coordinate (a copied profile), or one that will never decrypt (a rotated
191
+ // key): take a new slot id and start it empty, never writing over it.
192
+ identity = rotateSlotId(slot, { storage: safe(options.storage), storageKey, random })
193
+ ownCopy = undefined
194
+ }
195
+ }
196
+ if (owner !== pubkey) return
197
+ // Seeded from our own slot, never the merge: a slot is this installation's account of what it read, and seeding
198
+ // from the merge grows every slot to everything the person has read. The floor goes in as `current`, since
199
+ // `advanceContexts` refuses one among the updates.
200
+ const { [REPLY_FLOOR_CONTEXT]: floor, ...marked } = known
201
+ const held = floor === undefined ? own : { ...own, [REPLY_FLOOR_CONTEXT]: Math.max(floor, own[REPLY_FLOOR_CONTEXT] ?? 0) }
202
+ known = advanceContexts(held, marked)
203
+ published = own
204
+ hydrated = true
205
+ }
206
+
207
+ function schedule(ms: number): void {
208
+ timer = timers.setTimeout(() => {
209
+ timer = undefined
210
+ void flush()
211
+ }, ms)
212
+ }
213
+
214
+ /** Markers are still pending after a failed attempt: come back, backing off so an outage is not a busy loop. */
215
+ function retryLater(): void {
216
+ if (timer !== undefined) return
217
+ retryMs = retryMs === 0 ? debounceMs : Math.min(retryMs * 2, READ_STATE_MAX_RETRY_MS)
218
+ schedule(retryMs)
219
+ }
220
+
221
+ function flush(): Promise<void> {
222
+ if (timer !== undefined) {
223
+ timers.clearTimeout(timer)
224
+ timer = undefined
225
+ }
226
+ inFlight = inFlight.then(async () => {
227
+ if (Object.keys(pending).length === 0) return attempt('nothing-pending')
228
+ const pubkey = options.pubkey()
229
+ if (!pubkey || !canWrite()) {
230
+ attempt('no-session', 'retrying')
231
+ return retryLater()
232
+ }
233
+ // Marked by someone else who has since left this tab: theirs, never this person's.
234
+ forPerson(pubkey)
235
+ if (Object.keys(pending).length === 0) return attempt('nothing-pending')
236
+ try {
237
+ await hydrate(pubkey)
238
+ } catch (error) {
239
+ consoleWarn('[read-state] could not read the slot back:', error)
240
+ }
241
+ if (!hydrated) {
242
+ attempt('not-hydrated', 'relay unreachable, or our slot would not decrypt; retrying')
243
+ return retryLater()
244
+ }
245
+ const sending = pending
246
+ const contexts = { ...known }
247
+ pending = {}
248
+ if (published && sameContexts(published, contexts)) return attempt('unchanged')
249
+ try {
250
+ // Signed only as the person whose markers these are: a sign-in in another tab since the flush began would
251
+ // put them in that person's slot. What goes out is remembered, so reading it back costs no decrypt.
252
+ const result = await publishReadState(
253
+ {
254
+ sign: (event) => (options.pubkey() === pubkey ? options.sign(event) : Promise.reject(new Error('the person signed in changed'))),
255
+ publish: async (event) => {
256
+ const answer = await options.publish(event)
257
+ if (answer.ok) ownCopy = { content: event.content, contexts }
258
+ return answer
259
+ },
260
+ nip44,
261
+ },
262
+ pubkey,
263
+ currentIdentity(),
264
+ contexts,
265
+ // After the copy read back, never in the same second: on a tie the relay keeps the lower id and answers
266
+ // "duplicate" as accepted, so a larger blob published within the second (a flush on hide right after the
267
+ // debounced one) could lose to the smaller one with nothing to say so.
268
+ Math.max(Date.now(), (slotAt + 1) * 1000),
269
+ )
270
+ if (result.ok) {
271
+ published = contexts
272
+ retryMs = 0
273
+ return attempt('published', undefined, Object.keys(contexts).length)
274
+ }
275
+ consoleWarn('[read-state] publish refused:', result.reason)
276
+ attempt('rejected', result.reason)
277
+ } catch (error) {
278
+ consoleWarn('[read-state] publish failed:', error)
279
+ attempt('failed', error instanceof Error ? error.message : String(error))
280
+ }
281
+ pending = advanceContexts(pending, sending)
282
+ retryLater()
283
+ })
284
+ // A throw nobody expected (an app's callback) must not leave the chain rejected: every later flush would be skipped
285
+ // and nothing marked in this tab would reach the relay again.
286
+ const run = inFlight
287
+ inFlight = run.catch((error: unknown) => {
288
+ consoleWarn('[read-state] flush failed:', error)
289
+ if (Object.keys(pending).length > 0) retryLater()
290
+ })
291
+ return run
292
+ }
293
+
294
+ function markRead(contexts: readonly (string | undefined)[], atMs: number = Date.now()): void {
295
+ const pubkey = options.pubkey()
296
+ if (!pubkey) return
297
+ forPerson(pubkey)
298
+ const seconds = toContextSeconds(atMs)
299
+ const moved: Record<string, number> = {}
300
+ for (const context of contexts) {
301
+ if (!context) continue
302
+ const advanced = advanceContexts(known, { [context]: seconds })
303
+ // Not newer, or not a context the blob takes: nothing to publish.
304
+ if (advanced[context] === known[context]) continue
305
+ known = advanced
306
+ pending = advanceContexts(pending, { [context]: seconds })
307
+ moved[context] = seconds
308
+ }
309
+ if (Object.keys(moved).length === 0) return
310
+ options.onMarked?.(moved)
311
+ if (timer !== undefined) timers.clearTimeout(timer)
312
+ schedule(debounceMs)
313
+ }
314
+
315
+ function installFlushOnHide(doc: VisibilitySource): () => void {
316
+ const onHidden = () => {
317
+ if (doc.hidden) void flush()
318
+ }
319
+ doc.addEventListener('visibilitychange', onHidden)
320
+ return () => doc.removeEventListener('visibilitychange', onHidden)
321
+ }
322
+
323
+ function reset(): void {
324
+ if (timer !== undefined) timers.clearTimeout(timer)
325
+ timer = undefined
326
+ identity = undefined
327
+ owner = undefined
328
+ known = {}
329
+ pending = {}
330
+ published = undefined
331
+ ownCopy = undefined
332
+ hydrated = false
333
+ slotAt = 0
334
+ retryMs = 0
335
+ inFlight = Promise.resolve()
336
+ }
337
+
338
+ const state = (): ReadStateQueueState => ({
339
+ known: { ...known },
340
+ pending: { ...pending },
341
+ published: published ? { ...published } : undefined,
342
+ hydrated,
343
+ retryMs,
344
+ })
345
+
346
+ return { markRead, flush, identity: currentIdentity, installFlushOnHide, state, reset }
347
+ }
348
+
349
+ /**
350
+ * Mark `contexts` read once they have stayed on screen for {@link READ_DWELL_MS}: a conversation glanced past is not
351
+ * read. Only while the page is shown, and again when it comes back. `newestAtMs` is the newest message drawn for
352
+ * them: the mark never runs past it or past the clock, and a message dated ahead of the clock is read once the clock
353
+ * gets there, asked again at most a minute apart (a date far ahead would overflow the timer). With none drawn, the
354
+ * clock. Returns the cleanup — what a React effect returns.
355
+ */
356
+ export function watchDwell(
357
+ contexts: readonly string[],
358
+ newestAtMs: number | undefined,
359
+ mark: (contexts: readonly string[], atMs: number) => void,
360
+ doc: VisibilitySource,
361
+ dwellMs: number = READ_DWELL_MS,
362
+ ): () => void {
363
+ if (contexts.length === 0) return () => {}
364
+ let t: Timer | undefined
365
+ const fire = () => {
366
+ const now = Date.now()
367
+ mark(contexts, newestAtMs === undefined ? now : Math.min(newestAtMs, now))
368
+ if (newestAtMs !== undefined && newestAtMs > now) t = timers.setTimeout(fire, Math.min(newestAtMs - now, 60_000))
369
+ }
370
+ const arm = () => {
371
+ timers.clearTimeout(t)
372
+ if (!doc.hidden) t = timers.setTimeout(fire, dwellMs)
373
+ }
374
+ arm()
375
+ doc.addEventListener('visibilitychange', arm)
376
+ return () => {
377
+ timers.clearTimeout(t)
378
+ doc.removeEventListener('visibilitychange', arm)
379
+ }
380
+ }
381
+
382
+ /**
383
+ * The key a dwell restarts on: the set of contexts, not the array a render made. JSON, so it is never split back on a
384
+ * character an address may hold; {@link dwellContexts} turns it back.
385
+ */
386
+ export function dwellKey(contexts: readonly (string | undefined)[]): string {
387
+ return JSON.stringify(contexts.filter((c): c is string => Boolean(c)).sort())
388
+ }
389
+
390
+ export function dwellContexts(key: string): string[] {
391
+ return JSON.parse(key) as string[]
392
+ }
393
+
394
+ function safe(storage: () => SlotStorage | undefined): SlotStorage | undefined {
395
+ try {
396
+ return storage()
397
+ } catch {
398
+ return undefined
399
+ }
400
+ }
401
+
402
+ function sameContexts(a: Record<string, number>, b: Record<string, number>): boolean {
403
+ const keys = Object.keys(a)
404
+ return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k])
405
+ }
package/src/unread.ts CHANGED
@@ -73,10 +73,27 @@ export function unreadIn<E extends Message>(messages: readonly E[], merged: Read
73
73
 
74
74
  /** Whether one message is unread: §11.8's four conditions. `root` is its thread's root id when it is a reply. */
75
75
  export function isUnread(message: Message, root: string | undefined, merged: Readonly<Record<string, number>>, judge: StreamJudge): boolean {
76
+ return lightsIn(message, judge) && !seenIn(message, root, merged, judge)
77
+ }
78
+
79
+ /**
80
+ * Whether one message lights the stream for `P` at all, read or not: §11.8's first three conditions. A message that
81
+ * lights and is not {@link seenIn} is unread; one that lights and is seen is a line of the stream's list (§11.8 *What
82
+ * lit a stream, new and seen*).
83
+ */
84
+ export function lightsIn(message: Pick<Message, 'pubkey' | 'content' | 'created_at'>, judge: StreamJudge): boolean {
76
85
  if (message.pubkey === judge.me) return false
77
86
  const mentioned = peopleNamedInBody(message.content).has(judge.me)
78
87
  if (!mentioned && (!judge.member || judge.muted)) return false
79
- if (judge.since !== undefined && message.created_at < judge.since) return false
88
+ return judge.since === undefined || message.created_at >= judge.since
89
+ }
90
+
91
+ /** Whether a message that lights is seen: at or below its effective marker (§11.3), or below the reply floor or the floor (§11.6). */
92
+ export function seenIn(message: Pick<Message, 'created_at'>, root: string | undefined, merged: Readonly<Record<string, number>>, judge: StreamJudge): boolean {
93
+ return !newerThanMarker(message, root, merged, judge)
94
+ }
95
+
96
+ function newerThanMarker(message: Pick<Message, 'created_at'>, root: string | undefined, merged: Readonly<Record<string, number>>, judge: StreamJudge): boolean {
80
97
  const thread = root === undefined ? undefined : threadContext(root)
81
98
  const marker = thread === undefined ? streamMarkerOf(merged, judge.stream) : effectiveReadAt(merged, thread, judge.stream)
82
99
  if (marker !== undefined) return message.created_at > marker