@estiva-app/conversation 0.39.0 → 0.41.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.
@@ -0,0 +1,292 @@
1
+ import { KIND_APP_DATA } from './kinds.js';
2
+ import { advanceContexts as advance, splitFloors, loadSlotIdentity, parseReadStateBlob, publishReadState, readStateDTag, rotateSlotId, toContextSeconds, } from './readState.js';
3
+ const timers = globalThis;
4
+ const consoleWarn = (...args) => globalThis.console?.warn(...args);
5
+ /** Long enough to batch a few marks, short enough to survive a tab close. */
6
+ export const READ_STATE_PUBLISH_DEBOUNCE_MS = 3000;
7
+ /** How long something must be on screen before it counts as read (Peek's, Ship's and Leaf's). */
8
+ export const READ_DWELL_MS = 1500;
9
+ /** The longest wait between attempts while publishing keeps failing. */
10
+ export const READ_STATE_MAX_RETRY_MS = 60_000;
11
+ export function createReadStateQueue(options) {
12
+ const { storageKey, clientPrefix, random, query, nip44 } = options;
13
+ const debounceMs = options.debounceMs ?? READ_STATE_PUBLISH_DEBOUNCE_MS;
14
+ const canWrite = options.canWrite ?? (() => true);
15
+ const attempt = (outcome, detail, contexts) => options.onAttempt?.(outcome, detail, contexts);
16
+ let identity;
17
+ /** Whose read state this queue holds. */
18
+ let owner;
19
+ /** Everything this slot holds: its own blob from the relay, plus what was marked here. */
20
+ let known = {};
21
+ /** Marked but not yet in an accepted publish. */
22
+ let pending = {};
23
+ /** What the relay is believed to hold, so an unchanged blob is not published again. */
24
+ let published;
25
+ /** The last content seen at our coordinate and what it held, so an unchanged slot is not decrypted again. */
26
+ let ownCopy;
27
+ let hydrated = false;
28
+ /** When the copy of our slot read back was written (unix seconds), so the next publish is dated after it. */
29
+ let slotAt = 0;
30
+ let timer;
31
+ let retryMs = 0;
32
+ let inFlight = Promise.resolve();
33
+ function currentIdentity() {
34
+ identity ??= loadSlotIdentity({ storage: safe(options.storage), storageKey, clientPrefix, random });
35
+ return identity;
36
+ }
37
+ function advanceContexts(current, updates) {
38
+ const { contexts, evicted } = advance(current, updates);
39
+ if (evicted.length > 0)
40
+ consoleWarn(`[read-state] over the byte cap; ${evicted.length} oldest markers dropped`);
41
+ return contexts;
42
+ }
43
+ /** Another person in this tab: nothing of the last one's — what they read, what waits to be published — carries over. */
44
+ function forPerson(pubkey) {
45
+ if (owner === pubkey)
46
+ return;
47
+ owner = pubkey;
48
+ known = {};
49
+ pending = {};
50
+ published = undefined;
51
+ ownCopy = undefined;
52
+ hydrated = false;
53
+ }
54
+ /**
55
+ * Read this installation's own blob back. Only our own coordinate: the write needs nothing of the other slots,
56
+ * and each would cost a `/nip44/decrypt` from the quota the rest of the app shares. Unreachable is not empty, and
57
+ * a slot that would not decrypt this time (a 429 above all) is not ours to write over: both throw, leaving the
58
+ * queue unhydrated so it comes back.
59
+ */
60
+ async function hydrate(pubkey) {
61
+ hydrated = false;
62
+ const slot = currentIdentity();
63
+ const events = await query([{ kinds: [KIND_APP_DATA], authors: [pubkey], '#d': [readStateDTag(slot.slotId)] }]);
64
+ const newest = events.filter((e) => e.pubkey === pubkey).sort((a, b) => b.created_at - a.created_at)[0];
65
+ let own = {};
66
+ slotAt = newest?.created_at ?? 0;
67
+ if (newest && ownCopy?.content === newest.content)
68
+ own = ownCopy.contexts;
69
+ else if (newest) {
70
+ const blob = parseReadStateBlob(await nip44.decrypt(newest.content));
71
+ if (blob?.client_id === slot.clientId) {
72
+ own = blob.contexts;
73
+ ownCopy = { content: newest.content, contexts: own };
74
+ }
75
+ else {
76
+ // Another installation's blob at our coordinate (a copied profile), or one that will never decrypt (a rotated
77
+ // key): take a new slot id and start it empty, never writing over it.
78
+ identity = rotateSlotId(slot, { storage: safe(options.storage), storageKey, random });
79
+ ownCopy = undefined;
80
+ }
81
+ }
82
+ if (owner !== pubkey)
83
+ return;
84
+ // Seeded from our own slot, never the merge: a slot is this installation's account of what it read, and seeding
85
+ // from the merge grows every slot to everything the person has read. The floor goes in as `current`, since
86
+ // `advanceContexts` refuses one among the updates.
87
+ const { floors, markers: marked } = splitFloors(known);
88
+ const held = { ...own };
89
+ for (const [floor, at] of Object.entries(floors))
90
+ held[floor] = Math.max(at, own[floor] ?? 0);
91
+ known = advanceContexts(held, marked);
92
+ published = own;
93
+ hydrated = true;
94
+ }
95
+ function schedule(ms) {
96
+ timer = timers.setTimeout(() => {
97
+ timer = undefined;
98
+ void flush();
99
+ }, ms);
100
+ }
101
+ /** Markers are still pending after a failed attempt: come back, backing off so an outage is not a busy loop. */
102
+ function retryLater() {
103
+ if (timer !== undefined)
104
+ return;
105
+ retryMs = retryMs === 0 ? debounceMs : Math.min(retryMs * 2, READ_STATE_MAX_RETRY_MS);
106
+ schedule(retryMs);
107
+ }
108
+ function flush() {
109
+ if (timer !== undefined) {
110
+ timers.clearTimeout(timer);
111
+ timer = undefined;
112
+ }
113
+ inFlight = inFlight.then(async () => {
114
+ if (Object.keys(pending).length === 0)
115
+ return attempt('nothing-pending');
116
+ const pubkey = options.pubkey();
117
+ if (!pubkey || !canWrite()) {
118
+ attempt('no-session', 'retrying');
119
+ return retryLater();
120
+ }
121
+ // Marked by someone else who has since left this tab: theirs, never this person's.
122
+ forPerson(pubkey);
123
+ if (Object.keys(pending).length === 0)
124
+ return attempt('nothing-pending');
125
+ try {
126
+ await hydrate(pubkey);
127
+ }
128
+ catch (error) {
129
+ consoleWarn('[read-state] could not read the slot back:', error);
130
+ }
131
+ if (!hydrated) {
132
+ attempt('not-hydrated', 'relay unreachable, or our slot would not decrypt; retrying');
133
+ return retryLater();
134
+ }
135
+ const sending = pending;
136
+ const contexts = { ...known };
137
+ // Our slot as read back: what it holds is carried verbatim, keys this version does not know included (§11.1).
138
+ const slot = ownCopy?.contexts;
139
+ pending = {};
140
+ if (published && sameContexts(published, contexts))
141
+ return attempt('unchanged');
142
+ try {
143
+ // Signed only as the person whose markers these are: a sign-in in another tab since the flush began would
144
+ // put them in that person's slot. What goes out is remembered, so reading it back costs no decrypt.
145
+ const result = await publishReadState({
146
+ sign: (event) => (options.pubkey() === pubkey ? options.sign(event) : Promise.reject(new Error('the person signed in changed'))),
147
+ publish: async (event) => {
148
+ const answer = await options.publish(event);
149
+ if (answer.ok)
150
+ ownCopy = { content: event.content, contexts };
151
+ return answer;
152
+ },
153
+ nip44,
154
+ }, pubkey, currentIdentity(), contexts,
155
+ // After the copy read back, never in the same second: on a tie the relay keeps the lower id and answers
156
+ // "duplicate" as accepted, so a larger blob published within the second (a flush on hide right after the
157
+ // debounced one) could lose to the smaller one with nothing to say so.
158
+ Math.max(Date.now(), (slotAt + 1) * 1000), slot);
159
+ if (result.ok) {
160
+ published = contexts;
161
+ retryMs = 0;
162
+ return attempt('published', undefined, Object.keys(contexts).length);
163
+ }
164
+ consoleWarn('[read-state] publish refused:', result.reason);
165
+ attempt('rejected', result.reason);
166
+ }
167
+ catch (error) {
168
+ consoleWarn('[read-state] publish failed:', error);
169
+ attempt('failed', error instanceof Error ? error.message : String(error));
170
+ }
171
+ pending = advanceContexts(pending, sending);
172
+ retryLater();
173
+ });
174
+ // A throw nobody expected (an app's callback) must not leave the chain rejected: every later flush would be skipped
175
+ // and nothing marked in this tab would reach the relay again.
176
+ const run = inFlight;
177
+ inFlight = run.catch((error) => {
178
+ consoleWarn('[read-state] flush failed:', error);
179
+ if (Object.keys(pending).length > 0)
180
+ retryLater();
181
+ });
182
+ return run;
183
+ }
184
+ function markRead(contexts, atMs = Date.now()) {
185
+ const pubkey = options.pubkey();
186
+ if (!pubkey)
187
+ return;
188
+ forPerson(pubkey);
189
+ const seconds = toContextSeconds(atMs);
190
+ const moved = {};
191
+ for (const context of contexts) {
192
+ if (!context)
193
+ continue;
194
+ const advanced = advanceContexts(known, { [context]: seconds });
195
+ // Not newer, or not a context the blob takes: nothing to publish.
196
+ if (advanced[context] === known[context])
197
+ continue;
198
+ known = advanced;
199
+ pending = advanceContexts(pending, { [context]: seconds });
200
+ moved[context] = seconds;
201
+ }
202
+ if (Object.keys(moved).length === 0)
203
+ return;
204
+ options.onMarked?.(moved);
205
+ if (timer !== undefined)
206
+ timers.clearTimeout(timer);
207
+ schedule(debounceMs);
208
+ }
209
+ function installFlushOnHide(doc) {
210
+ const onHidden = () => {
211
+ if (doc.hidden)
212
+ void flush();
213
+ };
214
+ doc.addEventListener('visibilitychange', onHidden);
215
+ return () => doc.removeEventListener('visibilitychange', onHidden);
216
+ }
217
+ function reset() {
218
+ if (timer !== undefined)
219
+ timers.clearTimeout(timer);
220
+ timer = undefined;
221
+ identity = undefined;
222
+ owner = undefined;
223
+ known = {};
224
+ pending = {};
225
+ published = undefined;
226
+ ownCopy = undefined;
227
+ hydrated = false;
228
+ slotAt = 0;
229
+ retryMs = 0;
230
+ inFlight = Promise.resolve();
231
+ }
232
+ const state = () => ({
233
+ known: { ...known },
234
+ pending: { ...pending },
235
+ published: published ? { ...published } : undefined,
236
+ hydrated,
237
+ retryMs,
238
+ });
239
+ return { markRead, flush, identity: currentIdentity, installFlushOnHide, state, reset };
240
+ }
241
+ /**
242
+ * Mark `contexts` read once they have stayed on screen for {@link READ_DWELL_MS}: a conversation glanced past is not
243
+ * read. Only while the page is shown, and again when it comes back. `newestAtMs` is the newest message drawn for
244
+ * them: the mark never runs past it or past the clock, and a message dated ahead of the clock is read once the clock
245
+ * gets there, asked again at most a minute apart (a date far ahead would overflow the timer). With none drawn, the
246
+ * clock. Returns the cleanup — what a React effect returns.
247
+ */
248
+ export function watchDwell(contexts, newestAtMs, mark, doc, dwellMs = READ_DWELL_MS) {
249
+ if (contexts.length === 0)
250
+ return () => { };
251
+ let t;
252
+ const fire = () => {
253
+ const now = Date.now();
254
+ mark(contexts, newestAtMs === undefined ? now : Math.min(newestAtMs, now));
255
+ if (newestAtMs !== undefined && newestAtMs > now)
256
+ t = timers.setTimeout(fire, Math.min(newestAtMs - now, 60_000));
257
+ };
258
+ const arm = () => {
259
+ timers.clearTimeout(t);
260
+ if (!doc.hidden)
261
+ t = timers.setTimeout(fire, dwellMs);
262
+ };
263
+ arm();
264
+ doc.addEventListener('visibilitychange', arm);
265
+ return () => {
266
+ timers.clearTimeout(t);
267
+ doc.removeEventListener('visibilitychange', arm);
268
+ };
269
+ }
270
+ /**
271
+ * 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
272
+ * character an address may hold; {@link dwellContexts} turns it back.
273
+ */
274
+ export function dwellKey(contexts) {
275
+ return JSON.stringify(contexts.filter((c) => Boolean(c)).sort());
276
+ }
277
+ export function dwellContexts(key) {
278
+ return JSON.parse(key);
279
+ }
280
+ function safe(storage) {
281
+ try {
282
+ return storage();
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ }
288
+ function sameContexts(a, b) {
289
+ const keys = Object.keys(a);
290
+ return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k]);
291
+ }
292
+ //# sourceMappingURL=readStateQueue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readStateQueue.js","sourceRoot":"","sources":["../src/readStateQueue.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAC1C,OAAO,EACL,eAAe,IAAI,OAAO,EAC1B,WAAW,EACX,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,gBAAgB,GAKjB,MAAM,gBAAgB,CAAA;AAGvB,MAAM,MAAM,GAAG,UAA0G,CAAA;AACzH,MAAM,WAAW,GAAG,CAAC,GAAG,IAAe,EAAQ,EAAE,CAAE,UAAuE,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,CAAA;AAEjJ,6EAA6E;AAC7E,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAA;AAElD,iGAAiG;AACjG,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAA;AAEjC,wEAAwE;AACxE,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAA;AAwE7C,MAAM,UAAU,oBAAoB,CAAC,OAA8B;IACjE,MAAM,EAAE,UAAU,EAAE,YA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AAA;IAC3B,OAAO,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAClF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/conversation",
3
- "version": "0.39.0",
3
+ "version": "0.41.0",
4
4
  "description": "The conversation rules of the Estiva SPEC (§6.2–§6.8, §11): comment and mention strengths, threading, one shape for a message and a thread, resolving a thread, the line rule, the edit, reaction and attachment folds, NIP-22 comment and reply builders, drafts, NIP-RS read state, membership and unread. A convenience an app adopts, never a requirement.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,10 +47,10 @@
47
47
  "prepublishOnly": "npm run build"
48
48
  },
49
49
  "peerDependencies": {
50
- "@estiva-app/protocol": ">=0.51.0"
50
+ "@estiva-app/protocol": ">=0.58.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@estiva-app/protocol": ">=0.51.0",
53
+ "@estiva-app/protocol": ">=0.58.0",
54
54
  "typescript": "~5.9.3"
55
55
  }
56
56
  }
package/src/builders.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  *
5
5
  * Chat, an edit, a reaction and a deletion are `@estiva-app/protocol`'s
6
6
  * `buildMessage`, `buildEdit`, `buildReaction` and `buildDeletion`, which are
7
- * already Buzz-shaped and byte-pinned. What is conversation-specific is the
7
+ * byte-pinned there (a reaction also names its target's author, which upstream
8
+ * Buzz does not write: SPEC §6.6). What is conversation-specific is the
8
9
  * NIP-22 pair below, whose shape the SPEC decided rather than Buzz.
9
10
  */
10
11
  import { fileIdFormOf, fileIdOf, imetaTag, toNostrSeconds, type Imeta, type NostrTag, type UnsignedEvent } from '@estiva-app/protocol'
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  * apps: it imports no app's data layer, opens no socket, and takes every
13
13
  * environment touch — the relay read, the clock, storage — as a parameter.
14
14
  */
15
- export const CONVERSATION_VERSION = '0.39.0'
15
+ export const CONVERSATION_VERSION = '0.41.0'
16
16
 
17
17
  export {
18
18
  KIND_MESSAGE,
@@ -59,9 +59,15 @@ export {
59
59
  reactionEventsOf,
60
60
  foldReactions,
61
61
  groupReactions,
62
+ REACTIONS_TO_ME_FROM,
63
+ reactionsToMeFilter,
64
+ reactionTakeBackFilter,
65
+ keepReactionToMe,
66
+ reactionsToMe,
62
67
  type ReactionHorizon,
63
68
  type ReactionEvent,
64
69
  type Reaction,
70
+ type ReactionToMe,
65
71
  } from './reactions.js'
66
72
 
67
73
  export { decorationsOf, type Decoration, type Decorations, type QueryFn } from './decorations.js'
@@ -166,6 +172,10 @@ export {
166
172
  whatLitListedFile,
167
173
  whatLitStream,
168
174
  mergeLitLines,
175
+ reactionStreamOf,
176
+ newReactionsIn,
177
+ reactionsSeenWrites,
178
+ type ReactionJudge,
169
179
  type LitLine,
170
180
  type LitLineOptions,
171
181
  type UnreadReason,
@@ -218,6 +228,10 @@ export {
218
228
  messageContext,
219
229
  toContextSeconds,
220
230
  isPublishableContextId,
231
+ isCarriedContextId,
232
+ REACTIONS_FLOOR_CONTEXT,
233
+ reactionsContext,
234
+ reactionsSeenOf,
221
235
  loadSlotIdentity,
222
236
  rotateSlotId,
223
237
  readStateDTag,
@@ -251,6 +265,21 @@ export {
251
265
  type FetchedReadState,
252
266
  } from './readState.js'
253
267
 
268
+ export {
269
+ createReadStateQueue,
270
+ watchDwell,
271
+ dwellKey,
272
+ dwellContexts,
273
+ READ_DWELL_MS,
274
+ READ_STATE_PUBLISH_DEBOUNCE_MS,
275
+ READ_STATE_MAX_RETRY_MS,
276
+ type ReadStateQueue,
277
+ type ReadStateQueueOptions,
278
+ type ReadStateQueueState,
279
+ type ReadStateAttempt,
280
+ type VisibilitySource,
281
+ } from './readStateQueue.js'
282
+
254
283
  export { unreadIn, isUnread, type StreamJudge } from './unread.js'
255
284
 
256
285
  export {
package/src/places.ts CHANGED
@@ -25,11 +25,23 @@
25
25
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-team-has-members-and-followers-and-a-place-is-followed-at-a-level.md
26
26
  */
27
27
  import { fileIdOf, KIND, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
28
- import { FILE_ADDRESS, FOLDER_ID, KIND_APP_DATA, KIND_CHANGE } from './kinds.js'
28
+ import { FILE_ADDRESS, FOLDER_ID, KIND_APP_DATA, KIND_CHANGE, KIND_COMMENT, KIND_MESSAGE } from './kinds.js'
29
29
  import { APPDATA_TAG, FOLLOW_FIELD_PREFIX, buildMembershipChange, memberOfField } from './membership.js'
30
30
  import { byOrder } from './order.js'
31
- import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, streamMarkerOf, threadContext } from './readState.js'
32
- import { peopleNamedInBody } from './strength.js'
31
+ import { REACTIONS_TO_ME_FROM, type ReactionToMe } from './reactions.js'
32
+ import {
33
+ REPLY_FLOOR_CONTEXT,
34
+ belowReplyFloor,
35
+ channelContext,
36
+ effectiveReadAt,
37
+ fileContext,
38
+ fileIdContext,
39
+ reactionsContext,
40
+ reactionsSeenOf,
41
+ streamMarkerOf,
42
+ threadContext,
43
+ } from './readState.js'
44
+ import { anchorIdsOf, anchorsOf, peopleNamedInBody } from './strength.js'
33
45
  import { groupThreads } from './threads.js'
34
46
  import { lightsIn, seenIn, type StreamJudge } from './unread.js'
35
47
 
@@ -693,12 +705,12 @@ function lightsOnListedFile(message: Message, root: string | undefined, judge: P
693
705
 
694
706
  /**
695
707
  * 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.
708
+ * ({@link UnreadReason}), or a reaction to `P`'s message (ACT-7), new until its conversation's `reactions:` key is
709
+ * written past it. `seen` is false for what is unread now: the New part of the list.
698
710
  */
699
711
  export type LitLine<E> =
700
712
  | { type: 'message'; message: E; reason: UnreadReason; seen: boolean }
701
- | { type: 'reaction'; reaction: E; seen: boolean }
713
+ | { type: 'reaction'; reaction: ReactionToMe; seen: boolean }
702
714
 
703
715
  /** Options for a stream's list. */
704
716
  export interface LitLineOptions extends UnreadReasonOptions {
@@ -707,6 +719,12 @@ export interface LitLineOptions extends UnreadReasonOptions {
707
719
  * it. Each part is newest first, and the new part comes before the seen one. Unbounded when left out.
708
720
  */
709
721
  limit?: number
722
+ /**
723
+ * The reactions to `P`'s messages in this stream ({@link reactionsToMe}, mapped to it by {@link reactionStreamOf}):
724
+ * each is a line, new by {@link newReactionsIn}, else seen. A reaction to `P` is always about `P`, so a seen one
725
+ * stays in the list.
726
+ */
727
+ reactions?: readonly ReactionToMe[]
710
728
  }
711
729
 
712
730
  /** What stays in the list once seen: what was about `P` (Miky, 2026-11-11). A plain message read is in its conversation. */
@@ -717,6 +735,7 @@ function linesOf<E extends Message>(
717
735
  me: string,
718
736
  options: LitLineOptions,
719
737
  judge: (message: E, root: string | undefined, inSince: number | undefined) => { lights: boolean; unread: boolean },
738
+ reactions: { merged: Readonly<Record<string, number>>; judge: ReactionJudge },
720
739
  ): LitLine<E>[] {
721
740
  const out: LitLine<E>[] = []
722
741
  eachMessage(messages, me, (message, root, inSince) => {
@@ -726,10 +745,12 @@ function linesOf<E extends Message>(
726
745
  if (unread || KEPT_ONCE_SEEN.has(reason)) out.push({ type: 'message', message, reason, seen: !unread })
727
746
  return false
728
747
  })
729
- return mergeLitLines([out], options)
748
+ return mergeLitLines([out, reactionLines<E>(options.reactions ?? [], reactions.merged, reactions.judge)], options)
730
749
  }
731
750
 
732
- const lineEvent = <E extends Message>(line: LitLine<E>): E => (line.type === 'message' ? line.message : line.reaction)
751
+ /** What a line is ordered and told apart by: its message, or its reaction as an event of that id and time. */
752
+ const lineEvent = <E extends Message>(line: LitLine<E>): Pick<Message, 'id' | 'created_at' | 'tags'> =>
753
+ line.type === 'message' ? line.message : { id: line.reaction.id, created_at: line.reaction.at, tags: [] }
733
754
 
734
755
  /**
735
756
  * 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
@@ -754,10 +775,16 @@ export function mergeLitLines<E extends Message>(lists: readonly (readonly LitLi
754
775
  * reply in their conversation. The unseen lines are exactly {@link unreadOnPlace}'s; judged by today's following.
755
776
  */
756
777
  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
- })
778
+ return linesOf(
779
+ messages,
780
+ judge.me,
781
+ options,
782
+ (message, root, inSince) => {
783
+ const lights = lightsOnPlace(message, root, judge, inSince)
784
+ return { lights, unread: lights && newerThanItsMarker(message, root, merged, judge, startedOn(message, judge.following)) }
785
+ },
786
+ { merged, judge: { contexts: [judge.stream], following: judge.following, muted: judge.muted } },
787
+ )
761
788
  }
762
789
 
763
790
  /** A listed file's lines on the place that lists it, as {@link whatLitPlace}: the unseen ones are {@link unreadOnListedFile}'s. */
@@ -768,10 +795,16 @@ export function whatLitListedFile<E extends Message>(
768
795
  options: LitLineOptions = {},
769
796
  ): LitLine<E>[] {
770
797
  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
- })
798
+ return linesOf(
799
+ messages,
800
+ judge.me,
801
+ options,
802
+ (message, root, inSince) => {
803
+ const lights = lightsOnListedFile(message, root, judge, inSince)
804
+ return { lights, unread: lights && newerThanItsMarker(message, root, merged, judge, true) }
805
+ },
806
+ { merged, judge: { contexts: [judge.stream], following: judge.following, muted: judge.muted } },
807
+ )
775
808
  }
776
809
 
777
810
  /**
@@ -779,10 +812,124 @@ export function whatLitListedFile<E extends Message>(
779
812
  * unseen ones are {@link unreadIn}'s.
780
813
  */
781
814
  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) }
785
- })
815
+ return linesOf(
816
+ messages,
817
+ judge.me,
818
+ options,
819
+ (message, root) => {
820
+ const lights = lightsIn(message, judge)
821
+ return { lights, unread: lights && !seenIn(message, root, merged, judge) }
822
+ },
823
+ // Not a member: no reaction lights, as no message but a mention does.
824
+ { merged, judge: { contexts: [judge.stream], following: null, muted: judge.muted || !judge.member, since: judge.since } },
825
+ )
826
+ }
827
+
828
+ // ── A reaction to your message — §11.8, ACT-7 ───────────────────────────────
829
+
830
+ /**
831
+ * The §11.1 contexts of the stream a reacted message is in, where its reactions are seen: a reaction on a reply counts
832
+ * in its root's stream. A chat message (`kind:9`, root or reply) is in its channel's general stream, the bare uuid of
833
+ * its `h`. A comment (`kind:1111`, root or reply) is in its file's stream: the address its thread is about and
834
+ * `file:<d>`, both where the comment or the address gives them. Empty for anything else, and for a comment §6.4
835
+ * ignores.
836
+ *
837
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-is-seen-once-in-its-conversation.md
838
+ */
839
+ export function reactionStreamOf(target: Pick<SignedEvent, 'kind' | 'tags'>): string[] {
840
+ if (target.kind === KIND_MESSAGE) {
841
+ const channel = channelContext(tag(target, 'h'))
842
+ return channel === undefined ? [] : [channel]
843
+ }
844
+ if (target.kind !== KIND_COMMENT) return []
845
+ const out = new Set<string>()
846
+ for (const address of anchorsOf(target)) {
847
+ const context = fileContext(address)
848
+ if (context === undefined) continue
849
+ out.add(context)
850
+ const byId = fileIdContext(fileIdOf(address))
851
+ if (byId !== undefined) out.add(byId)
852
+ }
853
+ for (const id of anchorIdsOf(target)) {
854
+ const byId = fileIdContext(id)
855
+ if (byId !== undefined) out.add(byId)
856
+ }
857
+ return [...out]
858
+ }
859
+
860
+ /** Who is judging the reactions in one conversation stream, and on what terms. */
861
+ export interface ReactionJudge {
862
+ /** The stream's §11.1 contexts ({@link reactionStreamOf}): a file named both ways passes both. */
863
+ contexts: readonly string[]
864
+ /** {@link followingOf} for `P` on the place the stream is on or listed by; `null` for a DM or a stream `P` is a member of. */
865
+ following: Following | null
866
+ /** Whether `P` muted the place (or the stream): a reaction is not a mention, so nothing lights. */
867
+ muted?: boolean
868
+ /** For a DM or a member stream, unix seconds `P` came in; with a `following`, the later of this and its `since` counts. */
869
+ since?: number
870
+ }
871
+
872
+ /** When a reaction in the stream starts to count for `P`: the later of `P`'s start and {@link REACTIONS_TO_ME_FROM}; undefined when nothing does. */
873
+ function reactionsStartOf(judge: ReactionJudge): number | undefined {
874
+ if (judge.muted) return undefined
875
+ if (judge.following !== null && !judge.following.in) return undefined
876
+ return Math.max(judge.following?.since ?? 0, judge.since ?? 0, REACTIONS_TO_ME_FROM)
877
+ }
878
+
879
+ function reactionLines<E>(reactions: readonly ReactionToMe[], merged: Readonly<Record<string, number>>, judge: ReactionJudge): LitLine<E>[] {
880
+ const start = reactionsStartOf(judge)
881
+ if (start === undefined) return []
882
+ const seenTo = reactionsSeenOf(merged, judge.contexts)
883
+ return reactions
884
+ .filter((reaction) => reaction.at >= start)
885
+ .map((reaction): LitLine<E> => ({ type: 'reaction', reaction, seen: reaction.at <= seenTo }))
886
+ }
887
+
888
+ /**
889
+ * The reactions to `P`'s messages in one conversation stream that are new (§11.8, ACT-7): `reactions` are already
890
+ * mapped to the stream ({@link reactionStreamOf}); each is new when it is at or after `P`'s start there (following's
891
+ * `since`, or a DM's or a member stream's) and {@link REACTIONS_TO_ME_FROM}, and later than the stream's `reactions:`
892
+ * key and the reactions floor ({@link reactionsSeenOf}). Not in the place, or a muted one: none. Newest first, as given.
893
+ *
894
+ * Nothing but this conversation's `reactions:` key and the reactions floor clears one: opening the conversation reads
895
+ * its messages, and only writing its {@link reactionsSeenWrites} sees its reactions.
896
+ *
897
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-is-seen-once-in-its-conversation.md
898
+ */
899
+ export function newReactionsIn(reactions: readonly ReactionToMe[], merged: Readonly<Record<string, number>>, judge: ReactionJudge): ReactionToMe[] {
900
+ return reactionLines<never>(reactions, merged, judge).flatMap((line) => (line.type === 'reaction' && !line.seen ? [line.reaction] : []))
901
+ }
902
+
903
+ /**
904
+ * What showing reactions to `P` writes (ACT-7): for each conversation, the `reactions:` key at the newest reaction
905
+ * shown — its `created_at`, never the clock, so a reaction that arrives meanwhile stays new — and never later than
906
+ * `nowMs`, so a reaction dated ahead of the clock cannot mark later ones seen. Written under the stream's write
907
+ * context: `file:<d>` for a file named by its id, else its address; the bare uuid for a chat. `contexts` is the
908
+ * reaction's stream ({@link reactionStreamOf}). Each is ready for the read-state queue: `markRead([context], atMs)`.
909
+ * Resting on a row whose card listed them, and opening a conversation that draws them, both write it.
910
+ *
911
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-is-seen-once-in-its-conversation.md
912
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/reactions-seen-is-kept-under-reactions-and-opening-it-sees-it.md
913
+ */
914
+ export function reactionsSeenWrites(
915
+ lines: readonly { reaction: ReactionToMe; contexts: readonly string[] }[],
916
+ nowMs: number = Date.now(),
917
+ ): { context: string; atMs: number }[] {
918
+ const newest = new Map<string, number>()
919
+ for (const { reaction, contexts } of lines) {
920
+ const write = writeContextOf(contexts)
921
+ if (write === undefined) continue
922
+ const key = reactionsContext(write)
923
+ const atMs = Math.min(reaction.at * 1000, nowMs)
924
+ if ((newest.get(key) ?? -1) < atMs) newest.set(key, atMs)
925
+ }
926
+ return [...newest].map(([context, atMs]) => ({ context, atMs }))
927
+ }
928
+
929
+ /** Where a stream's reactions are written: its `file:<d>` (named, or from an address whose `d` is an id), else its address or channel. */
930
+ function writeContextOf(contexts: readonly string[]): string | undefined {
931
+ const byId = contexts.find((c) => c.startsWith('file:')) ?? contexts.map((c) => fileIdContext(FILE_ADDRESS.test(c) ? fileIdOf(c) : undefined)).find((c) => c !== undefined)
932
+ return byId ?? contexts[0]
786
933
  }
787
934
 
788
935
  /**