@estiva-app/conversation 0.39.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/CHANGELOG.md CHANGED
@@ -6,6 +6,29 @@ none. A change to how an event is read is a MINOR in `0.x` even when no
6
6
  signature moved, because two apps on different versions would then disagree
7
7
  about a conversation.
8
8
 
9
+ ## 0.40.0 — 2026-11-13
10
+
11
+ **SPEC: none changed.** The same blob goes to the same coordinate; this moves
12
+ the queue that writes it out of Ship and Leaf, which each held a copy
13
+ (TOPIC-3).
14
+
15
+ - `createReadStateQueue(options)`: one per tab. `markRead(contexts, atMs)`
16
+ debounces a whole-blob publish of this installation's slot; `flush()`,
17
+ `installFlushOnHide(document)`, `identity()`, `state()` (what is known,
18
+ pending and published, for a diagnostic), `reset()`. Before every write
19
+ it reads its own coordinate back (so two tabs of one browser never drop each
20
+ other's markers), skipping the decrypt when the content is the one it last
21
+ saw or published. It does not publish while the slot is unreachable or
22
+ refuses to decrypt, takes a new slot id when the coordinate holds another
23
+ installation's blob or one that will never decrypt, drops a queue whose
24
+ person signed out or changed, and backs off to a minute between failures.
25
+ `onMarked` and `onAttempt` let an app draw a mark at once and keep a
26
+ diagnostic.
27
+ - `watchDwell(contexts, newestAtMs, mark, document)`: marks what stayed on
28
+ screen for `READ_DWELL_MS` (1.5 s) while the page is shown, never past the
29
+ newest message drawn or the clock. `dwellKey` / `dwellContexts` give a React
30
+ effect a stable key for the set.
31
+
9
32
  ## 0.39.0 — 2026-11-11
10
33
 
11
34
  **SPEC §11.8: what lit a stream, new and seen** (ACT-4). Every app draws the same
package/README.md CHANGED
@@ -42,7 +42,7 @@ pass, the clock is a `createdAtMs` you pass, and drafts take their storage.
42
42
  | membership | §11.8 | `membershipOf`, `membersOf`, `streamOf`, `membershipFilters`, `candidateFilesOf`, `buildMembershipChange` |
43
43
  | muting | §11.8 | `parseMutedBlob`, `serializeMutedBlob`, `buildMutedEvent`, `mutedFilter`, `mutedFromFollowed` |
44
44
  | places and following | §11.8 *Places and following* | `followingOf`, `placeKindOf`, `placeFilters`, `unreadOnPlace`, `isUnreadOnPlace`, `buildLevelChange`, `parseTeamsBlob`, `serializeTeamsBlob`, `buildTeamsEvent`, `teamsFilter` |
45
- | read state | §11.1–§11.6 | `channelContext`, `fileContext`, `threadContext`, `loadSlotIdentity`, `advanceContexts`, `fetchReadState`, `publishReadState`, `mergeSlots`, `effectiveReadAt`, `THREAD_RULE_FROM`, `REPLY_FLOOR_CONTEXT`, `capReadStateContexts` |
45
+ | read state | §11.1–§11.6 | `channelContext`, `fileContext`, `threadContext`, `loadSlotIdentity`, `advanceContexts`, `fetchReadState`, `publishReadState`, `createReadStateQueue`, `watchDwell`, `mergeSlots`, `effectiveReadAt`, `THREAD_RULE_FROM`, `REPLY_FLOOR_CONTEXT`, `capReadStateContexts` |
46
46
  | unread | §11.3, §11.8 | `unreadIn`, `isUnread` |
47
47
  | a mention in a file's text | §11.8, §13.1 | `mentionAddsFor`, `newlyNamedPeople`, `peopleNamedInText` |
48
48
 
@@ -52,8 +52,11 @@ Chat, an edit, a reaction and a deletion are built with
52
52
 
53
53
  Read state takes its environment like the rest: slot storage and randomness
54
54
  (`loadSlotIdentity`), the relay query, the signer and NIP-44 (`fetchReadState`,
55
- `publishReadState`). When to write — the debounce, the dwell before a view
56
- counts as read — stays the app's.
55
+ `publishReadState`). When to write can come from here too:
56
+ `createReadStateQueue` is the one queue a tab marks read through (the
57
+ debounce, the read-back of its own slot before every whole-blob publish, the
58
+ backoff, a change of person), and `watchDwell` marks what stayed on screen for
59
+ `READ_DWELL_MS`. Ship and Leaf use both; an app may still write its own.
57
60
 
58
61
  **Light a dot from the files you already load, not from discovery alone.** A
59
62
  file's membership comes from `membershipOf` over that file's own events, which
package/dist/index.d.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 declare const CONVERSATION_VERSION = "0.39.0";
15
+ export declare const CONVERSATION_VERSION = "0.40.0";
16
16
  export { KIND_MESSAGE, KIND_COMMENT, KIND_EDIT, KIND_REACTION, KIND_DELETION, KIND_ASSERTION, isConversationKind, isEventId, } from './kinds.js';
17
17
  export { trustedTs, orderingMs, byOrder } from './order.js';
18
18
  export { namedInBody, isReply, anchorsOf, anchorIdsOf, isAbout, isCrossedComment, isCrossedCommentOn, isCommentOn, referencesAddress, strengthOn, threadStrength, referenceTagsFor, mentionTagsFor, peopleNamedInBody, MAX_MENTIONED_PEOPLE, type Strength, } from './strength.js';
@@ -31,6 +31,7 @@ export { FILE_TIER, fileReference, MESSAGE_TIER, messageCandidate, rankReference
31
31
  export { KIND_CHANGE, MEMBER_FIELD_PREFIX, FOLLOW_FIELD_PREFIX, isMembershipField, memberField, memberOfField, mentions, streamOf, membershipOf, membersOf, membershipFilters, candidateFilesOf, buildMembershipChange, MUTED_D_TAG, APPDATA_TAG, parseMutedBlob, serializeMutedBlob, buildMutedEvent, mutedFilter, mutedFromFollowed, type Membership, type MutedList, } from './membership.js';
32
32
  export { followingOf, teamMembersOf, placeKindOf, placeFilters, unreadOnPlace, unreadOnListedFile, unreadReason, unreadReasons, whatLitPlace, whatLitListedFile, whatLitStream, mergeLitLines, type LitLine, type LitLineOptions, type UnreadReason, type UnreadReasonOptions, isUnreadOnPlace, followField, buildLevelChange, TEAMS_D_TAG, parseTeamsBlob, serializeTeamsBlob, buildTeamsEvent, teamsFilter, placeListing, buildPlaceAdd, placeOffId, switchStateOf, switchWrites, withPlaceOff, type Listed, type SwitchChoice, type SwitchState, type SwitchWrites, type Level, type PlaceKind, type Place, type PlaceFacts, type WayIn, type Following, type PlaceJudge, type TeamsList, type TeamMember, } from './places.js';
33
33
  export { READ_STATE_TAG, READ_STATE_D_PREFIX, MAX_CONTEXTS, MAX_CONTEXT_ID_BYTES, MAX_TIMESTAMP, MAX_CLIENT_ID_BYTES, MAX_BLOB_BYTES, MAX_CONTEXTS_BYTES, READ_STATE_HORIZON_DAYS, channelContext, fileContext, fileIdContext, fileReadMarkers, streamMarkerOf, threadContext, messageContext, toContextSeconds, isPublishableContextId, loadSlotIdentity, rotateSlotId, readStateDTag, parseReadStateBlob, serializeReadStateBlob, capContextsToBytes, capReadStateContexts, THREAD_RULE_FROM, REPLY_FLOOR_CONTEXT, advanceContexts, buildReadStateEvent, allSlotsFilter, mergeSlots, classifyOwnSlots, effectiveReadAt, threadReadAt, belowReplyFloor, fetchReadState, createSlotCache, publishReadState, type SlotCache, type SlotIdentity, type SlotStorage, type SlotSource, type RandomBytes, type ReadStateBlob, type CappedContexts, type SlotBlob, type OwnSlotVerdict, type Nip44, type FetchedReadState, } from './readState.js';
34
+ export { createReadStateQueue, watchDwell, dwellKey, dwellContexts, READ_DWELL_MS, READ_STATE_PUBLISH_DEBOUNCE_MS, READ_STATE_MAX_RETRY_MS, type ReadStateQueue, type ReadStateQueueOptions, type ReadStateQueueState, type ReadStateAttempt, type VisibilitySource, } from './readStateQueue.js';
34
35
  export { unreadIn, isUnread, type StreamJudge } from './unread.js';
35
36
  export { streamHasUnread, MEMBERSHIP_LIMIT, HORIZON_SECONDS, membershipQueries, authorOfAddress, foldMemberships, streamTermsOf, membershipJudges, type StreamMessage, type StreamFrontier, type StreamTerms, type MembershipRead, } from './streamUnread.js';
36
37
  export { peopleNamedInText, newlyNamedPeople, mentionAddsFor, type FileText } from './textMentions.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,WAAW,CAAA;AAE5C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CA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, 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.40.0';
16
16
  export { KIND_MESSAGE, KIND_COMMENT, KIND_EDIT, KIND_REACTION, KIND_DELETION, KIND_ASSERTION, isConversationKind, isEventId, } from './kinds.js';
17
17
  export { trustedTs, orderingMs, byOrder } from './order.js';
18
18
  export { namedInBody, isReply, anchorsOf, anchorIdsOf, isAbout, isCrossedComment, isCrossedCommentOn, isCommentOn, referencesAddress, strengthOn, threadStrength, referenceTagsFor, mentionTagsFor, peopleNamedInBody, MAX_MENTIONED_PEOPLE, } from './strength.js';
@@ -31,6 +31,7 @@ export { FILE_TIER, fileReference, MESSAGE_TIER, messageCandidate, rankReference
31
31
  export { KIND_CHANGE, MEMBER_FIELD_PREFIX, FOLLOW_FIELD_PREFIX, isMembershipField, memberField, memberOfField, mentions, streamOf, membershipOf, membersOf, membershipFilters, candidateFilesOf, buildMembershipChange, MUTED_D_TAG, APPDATA_TAG, parseMutedBlob, serializeMutedBlob, buildMutedEvent, mutedFilter, mutedFromFollowed, } from './membership.js';
32
32
  export { followingOf, teamMembersOf, placeKindOf, placeFilters, unreadOnPlace, unreadOnListedFile, unreadReason, unreadReasons, whatLitPlace, whatLitListedFile, whatLitStream, mergeLitLines, isUnreadOnPlace, followField, buildLevelChange, TEAMS_D_TAG, parseTeamsBlob, serializeTeamsBlob, buildTeamsEvent, teamsFilter, placeListing, buildPlaceAdd, placeOffId, switchStateOf, switchWrites, withPlaceOff, } from './places.js';
33
33
  export { READ_STATE_TAG, READ_STATE_D_PREFIX, MAX_CONTEXTS, MAX_CONTEXT_ID_BYTES, MAX_TIMESTAMP, MAX_CLIENT_ID_BYTES, MAX_BLOB_BYTES, MAX_CONTEXTS_BYTES, READ_STATE_HORIZON_DAYS, channelContext, fileContext, fileIdContext, fileReadMarkers, streamMarkerOf, threadContext, messageContext, toContextSeconds, isPublishableContextId, loadSlotIdentity, rotateSlotId, readStateDTag, parseReadStateBlob, serializeReadStateBlob, capContextsToBytes, capReadStateContexts, THREAD_RULE_FROM, REPLY_FLOOR_CONTEXT, advanceContexts, buildReadStateEvent, allSlotsFilter, mergeSlots, classifyOwnSlots, effectiveReadAt, threadReadAt, belowReplyFloor, fetchReadState, createSlotCache, publishReadState, } from './readState.js';
34
+ export { createReadStateQueue, watchDwell, dwellKey, dwellContexts, READ_DWELL_MS, READ_STATE_PUBLISH_DEBOUNCE_MS, READ_STATE_MAX_RETRY_MS, } from './readStateQueue.js';
34
35
  export { unreadIn, isUnread } from './unread.js';
35
36
  export { streamHasUnread, MEMBERSHIP_LIMIT, HORIZON_SECONDS, membershipQueries, authorOfAddress, foldMemberships, streamTermsOf, membershipJudges, } from './streamUnread.js';
36
37
  export { peopleNamedInText, newlyNamedPeople, mentionAddsFor } from './textMentions.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,QAAQ,CAAA;AAE5C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE3D,OAAO,EACL,WAAW,EACX,OAAO,EACP,SAAS,EACT,WAAW,EACX,OAAO,EACP,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,EACX,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,oBAAoB,GAErB,MAAM,eAAe,CAAA;AAEtB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAiB,MAAM,cAAc,CAAA;AAEpE,OAAO,EAAE,YAAY,EA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f,eAAe,EACf,aAAa,EACb,gBAAgB,GAKjB,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,cAAc,EAAiB,MAAM,mBAAmB,CAAA;AAEtG,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAqB,MAAM,aAAa,CAAA;AAE3H,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAA4B,MAAM,mBAAmB,CAAA;AAEvG,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,eAAe,EACf,QAAQ,EACR,WAAW,EACX,aAAa,EACb,aAAa,GAGd,MAAM,eAAe,CAAA;AAEtB,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,GAIhB,MAAM,aAAa,CAAA"}
@@ -0,0 +1,86 @@
1
+ import type { SignedEvent, UnsignedEvent } from '@estiva-app/protocol';
2
+ import type { QueryFn } from './decorations.js';
3
+ import { type Nip44, type RandomBytes, type SlotIdentity, type SlotStorage } from './readState.js';
4
+ /** Long enough to batch a few marks, short enough to survive a tab close. */
5
+ export declare const READ_STATE_PUBLISH_DEBOUNCE_MS = 3000;
6
+ /** How long something must be on screen before it counts as read (Peek's, Ship's and Leaf's). */
7
+ export declare const READ_DWELL_MS = 1500;
8
+ /** The longest wait between attempts while publishing keeps failing. */
9
+ export declare const READ_STATE_MAX_RETRY_MS = 60000;
10
+ /** The part of a browser's `document` the queue and the dwell listen to. */
11
+ export interface VisibilitySource {
12
+ readonly hidden: boolean;
13
+ addEventListener(type: 'visibilitychange', listener: () => void): void;
14
+ removeEventListener(type: 'visibilitychange', listener: () => void): void;
15
+ }
16
+ /** What a flush did, for an app's diagnostic. */
17
+ export type ReadStateAttempt = 'nothing-pending' | 'no-session' | 'not-hydrated' | 'unchanged' | 'published' | 'rejected' | 'failed';
18
+ export interface ReadStateQueueOptions {
19
+ /** Where the slot id lives (`localStorage`); read when the slot is first needed. It may throw, or be absent. */
20
+ storage: () => SlotStorage | undefined;
21
+ /** The app's own key (`ship.readstate.slot`, `leaf.readstate.slot`), so it keeps the slot it has. */
22
+ storageKey: string;
23
+ /** Names the app in a new `client_id`: `ship` → `ship-1a2b3c4d`. */
24
+ clientPrefix: string;
25
+ random: RandomBytes;
26
+ /** Who is signed in now, or undefined. A mark made by nobody is dropped; a change of person drops the last one's queue. */
27
+ pubkey: () => string | undefined;
28
+ /**
29
+ * Whether a write can go out now — false while an access token is being renewed. The markers wait and the
30
+ * queue comes back, backing off. Absent: always.
31
+ */
32
+ canWrite?: () => boolean;
33
+ query: QueryFn;
34
+ nip44: Nip44;
35
+ sign: (event: UnsignedEvent) => Promise<SignedEvent>;
36
+ publish: (event: SignedEvent) => Promise<{
37
+ ok: boolean;
38
+ reason?: string;
39
+ }>;
40
+ /** Each mark that moved a context, at once — before the publish — so a page can draw it read now. */
41
+ onMarked?: (contexts: Readonly<Record<string, number>>) => void;
42
+ /** Each flush's outcome, for a diagnostic. */
43
+ onAttempt?: (outcome: ReadStateAttempt, detail?: string, contexts?: number) => void;
44
+ debounceMs?: number;
45
+ }
46
+ export interface ReadStateQueue {
47
+ /** Mark these contexts read at `atMs`; the publish follows, debounced. Contexts come from this package's builders. */
48
+ markRead(contexts: readonly (string | undefined)[], atMs?: number): void;
49
+ /** Publish what is pending now. */
50
+ flush(): Promise<void>;
51
+ /** This installation's slot, minted on first use. */
52
+ identity(): SlotIdentity;
53
+ /** Publish before the tab goes away: `visibilitychange` is the one a phone fires. Returns the uninstall. */
54
+ installFlushOnHide(doc: VisibilitySource): () => void;
55
+ /** What the queue holds now, copied, for a diagnostic: what can no probe outside the tab can see. */
56
+ state(): ReadStateQueueState;
57
+ /** Drop the tab's state, timers included, so a test starts clean. */
58
+ reset(): void;
59
+ }
60
+ export interface ReadStateQueueState {
61
+ /** Everything this slot believes it has read. */
62
+ known: Record<string, number>;
63
+ /** Marked but not yet in an accepted publish. Non-empty for long is the smell. */
64
+ pending: Record<string, number>;
65
+ /** What the relay is believed to hold for this slot. */
66
+ published: Record<string, number> | undefined;
67
+ hydrated: boolean;
68
+ /** The wait before the next retry, 0 when none is backing off. */
69
+ retryMs: number;
70
+ }
71
+ export declare function createReadStateQueue(options: ReadStateQueueOptions): ReadStateQueue;
72
+ /**
73
+ * Mark `contexts` read once they have stayed on screen for {@link READ_DWELL_MS}: a conversation glanced past is not
74
+ * read. Only while the page is shown, and again when it comes back. `newestAtMs` is the newest message drawn for
75
+ * them: the mark never runs past it or past the clock, and a message dated ahead of the clock is read once the clock
76
+ * gets there, asked again at most a minute apart (a date far ahead would overflow the timer). With none drawn, the
77
+ * clock. Returns the cleanup — what a React effect returns.
78
+ */
79
+ export declare function watchDwell(contexts: readonly string[], newestAtMs: number | undefined, mark: (contexts: readonly string[], atMs: number) => void, doc: VisibilitySource, dwellMs?: number): () => void;
80
+ /**
81
+ * 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
82
+ * character an address may hold; {@link dwellContexts} turns it back.
83
+ */
84
+ export declare function dwellKey(contexts: readonly (string | undefined)[]): string;
85
+ export declare function dwellContexts(key: string): string[];
86
+ //# sourceMappingURL=readStateQueue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readStateQueue.d.ts","sourceRoot":"","sources":["../src/readStateQueue.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACtE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAE/C,OAAO,EASL,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,WAAW,EACjB,MAAM,gBAAgB,CAAA;AAMvB,6EAA6E;AAC7E,eAAO,MAAM,8BAA8B,OAAO,CAAA;AAElD,iGAAiG;AACjG,eAAO,MAAM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,KAAK,IAAI,EACzD,GAAG,EAAE,gBAAgB,EACrB,OAAO,GAAE,MAAsB,GAC9B,MAAM,IAAI,CAkBZ;AAED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GAAG,MAAM,CAE1E;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAEnD"}
@@ -0,0 +1,288 @@
1
+ import { KIND_APP_DATA } from './kinds.js';
2
+ import { REPLY_FLOOR_CONTEXT, advanceContexts as advance, 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 { [REPLY_FLOOR_CONTEXT]: floor, ...marked } = known;
88
+ const held = floor === undefined ? own : { ...own, [REPLY_FLOOR_CONTEXT]: Math.max(floor, own[REPLY_FLOOR_CONTEXT] ?? 0) };
89
+ known = advanceContexts(held, marked);
90
+ published = own;
91
+ hydrated = true;
92
+ }
93
+ function schedule(ms) {
94
+ timer = timers.setTimeout(() => {
95
+ timer = undefined;
96
+ void flush();
97
+ }, ms);
98
+ }
99
+ /** Markers are still pending after a failed attempt: come back, backing off so an outage is not a busy loop. */
100
+ function retryLater() {
101
+ if (timer !== undefined)
102
+ return;
103
+ retryMs = retryMs === 0 ? debounceMs : Math.min(retryMs * 2, READ_STATE_MAX_RETRY_MS);
104
+ schedule(retryMs);
105
+ }
106
+ function flush() {
107
+ if (timer !== undefined) {
108
+ timers.clearTimeout(timer);
109
+ timer = undefined;
110
+ }
111
+ inFlight = inFlight.then(async () => {
112
+ if (Object.keys(pending).length === 0)
113
+ return attempt('nothing-pending');
114
+ const pubkey = options.pubkey();
115
+ if (!pubkey || !canWrite()) {
116
+ attempt('no-session', 'retrying');
117
+ return retryLater();
118
+ }
119
+ // Marked by someone else who has since left this tab: theirs, never this person's.
120
+ forPerson(pubkey);
121
+ if (Object.keys(pending).length === 0)
122
+ return attempt('nothing-pending');
123
+ try {
124
+ await hydrate(pubkey);
125
+ }
126
+ catch (error) {
127
+ consoleWarn('[read-state] could not read the slot back:', error);
128
+ }
129
+ if (!hydrated) {
130
+ attempt('not-hydrated', 'relay unreachable, or our slot would not decrypt; retrying');
131
+ return retryLater();
132
+ }
133
+ const sending = pending;
134
+ const contexts = { ...known };
135
+ pending = {};
136
+ if (published && sameContexts(published, contexts))
137
+ return attempt('unchanged');
138
+ try {
139
+ // Signed only as the person whose markers these are: a sign-in in another tab since the flush began would
140
+ // put them in that person's slot. What goes out is remembered, so reading it back costs no decrypt.
141
+ const result = await publishReadState({
142
+ sign: (event) => (options.pubkey() === pubkey ? options.sign(event) : Promise.reject(new Error('the person signed in changed'))),
143
+ publish: async (event) => {
144
+ const answer = await options.publish(event);
145
+ if (answer.ok)
146
+ ownCopy = { content: event.content, contexts };
147
+ return answer;
148
+ },
149
+ nip44,
150
+ }, pubkey, currentIdentity(), contexts,
151
+ // After the copy read back, never in the same second: on a tie the relay keeps the lower id and answers
152
+ // "duplicate" as accepted, so a larger blob published within the second (a flush on hide right after the
153
+ // debounced one) could lose to the smaller one with nothing to say so.
154
+ Math.max(Date.now(), (slotAt + 1) * 1000));
155
+ if (result.ok) {
156
+ published = contexts;
157
+ retryMs = 0;
158
+ return attempt('published', undefined, Object.keys(contexts).length);
159
+ }
160
+ consoleWarn('[read-state] publish refused:', result.reason);
161
+ attempt('rejected', result.reason);
162
+ }
163
+ catch (error) {
164
+ consoleWarn('[read-state] publish failed:', error);
165
+ attempt('failed', error instanceof Error ? error.message : String(error));
166
+ }
167
+ pending = advanceContexts(pending, sending);
168
+ retryLater();
169
+ });
170
+ // A throw nobody expected (an app's callback) must not leave the chain rejected: every later flush would be skipped
171
+ // and nothing marked in this tab would reach the relay again.
172
+ const run = inFlight;
173
+ inFlight = run.catch((error) => {
174
+ consoleWarn('[read-state] flush failed:', error);
175
+ if (Object.keys(pending).length > 0)
176
+ retryLater();
177
+ });
178
+ return run;
179
+ }
180
+ function markRead(contexts, atMs = Date.now()) {
181
+ const pubkey = options.pubkey();
182
+ if (!pubkey)
183
+ return;
184
+ forPerson(pubkey);
185
+ const seconds = toContextSeconds(atMs);
186
+ const moved = {};
187
+ for (const context of contexts) {
188
+ if (!context)
189
+ continue;
190
+ const advanced = advanceContexts(known, { [context]: seconds });
191
+ // Not newer, or not a context the blob takes: nothing to publish.
192
+ if (advanced[context] === known[context])
193
+ continue;
194
+ known = advanced;
195
+ pending = advanceContexts(pending, { [context]: seconds });
196
+ moved[context] = seconds;
197
+ }
198
+ if (Object.keys(moved).length === 0)
199
+ return;
200
+ options.onMarked?.(moved);
201
+ if (timer !== undefined)
202
+ timers.clearTimeout(timer);
203
+ schedule(debounceMs);
204
+ }
205
+ function installFlushOnHide(doc) {
206
+ const onHidden = () => {
207
+ if (doc.hidden)
208
+ void flush();
209
+ };
210
+ doc.addEventListener('visibilitychange', onHidden);
211
+ return () => doc.removeEventListener('visibilitychange', onHidden);
212
+ }
213
+ function reset() {
214
+ if (timer !== undefined)
215
+ timers.clearTimeout(timer);
216
+ timer = undefined;
217
+ identity = undefined;
218
+ owner = undefined;
219
+ known = {};
220
+ pending = {};
221
+ published = undefined;
222
+ ownCopy = undefined;
223
+ hydrated = false;
224
+ slotAt = 0;
225
+ retryMs = 0;
226
+ inFlight = Promise.resolve();
227
+ }
228
+ const state = () => ({
229
+ known: { ...known },
230
+ pending: { ...pending },
231
+ published: published ? { ...published } : undefined,
232
+ hydrated,
233
+ retryMs,
234
+ });
235
+ return { markRead, flush, identity: currentIdentity, installFlushOnHide, state, reset };
236
+ }
237
+ /**
238
+ * Mark `contexts` read once they have stayed on screen for {@link READ_DWELL_MS}: a conversation glanced past is not
239
+ * read. Only while the page is shown, and again when it comes back. `newestAtMs` is the newest message drawn for
240
+ * them: the mark never runs past it or past the clock, and a message dated ahead of the clock is read once the clock
241
+ * gets there, asked again at most a minute apart (a date far ahead would overflow the timer). With none drawn, the
242
+ * clock. Returns the cleanup — what a React effect returns.
243
+ */
244
+ export function watchDwell(contexts, newestAtMs, mark, doc, dwellMs = READ_DWELL_MS) {
245
+ if (contexts.length === 0)
246
+ return () => { };
247
+ let t;
248
+ const fire = () => {
249
+ const now = Date.now();
250
+ mark(contexts, newestAtMs === undefined ? now : Math.min(newestAtMs, now));
251
+ if (newestAtMs !== undefined && newestAtMs > now)
252
+ t = timers.setTimeout(fire, Math.min(newestAtMs - now, 60_000));
253
+ };
254
+ const arm = () => {
255
+ timers.clearTimeout(t);
256
+ if (!doc.hidden)
257
+ t = timers.setTimeout(fire, dwellMs);
258
+ };
259
+ arm();
260
+ doc.addEventListener('visibilitychange', arm);
261
+ return () => {
262
+ timers.clearTimeout(t);
263
+ doc.removeEventListener('visibilitychange', arm);
264
+ };
265
+ }
266
+ /**
267
+ * 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
268
+ * character an address may hold; {@link dwellContexts} turns it back.
269
+ */
270
+ export function dwellKey(contexts) {
271
+ return JSON.stringify(contexts.filter((c) => Boolean(c)).sort());
272
+ }
273
+ export function dwellContexts(key) {
274
+ return JSON.parse(key);
275
+ }
276
+ function safe(storage) {
277
+ try {
278
+ return storage();
279
+ }
280
+ catch {
281
+ return undefined;
282
+ }
283
+ }
284
+ function sameContexts(a, b) {
285
+ const keys = Object.keys(a);
286
+ return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k]);
287
+ }
288
+ //# 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,mBAAmB,EACnB,eAAe,IAAI,OAAO,EAC1B,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;AAE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,IAAI,CAAC,CAAC,CAAC,CAAA;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.40.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",
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.40.0'
16
16
 
17
17
  export {
18
18
  KIND_MESSAGE,
@@ -251,6 +251,21 @@ export {
251
251
  type FetchedReadState,
252
252
  } from './readState.js'
253
253
 
254
+ export {
255
+ createReadStateQueue,
256
+ watchDwell,
257
+ dwellKey,
258
+ dwellContexts,
259
+ READ_DWELL_MS,
260
+ READ_STATE_PUBLISH_DEBOUNCE_MS,
261
+ READ_STATE_MAX_RETRY_MS,
262
+ type ReadStateQueue,
263
+ type ReadStateQueueOptions,
264
+ type ReadStateQueueState,
265
+ type ReadStateAttempt,
266
+ type VisibilitySource,
267
+ } from './readStateQueue.js'
268
+
254
269
  export { unreadIn, isUnread, type StreamJudge } from './unread.js'
255
270
 
256
271
  export {
@@ -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
+ }