Fix activity feed first load, sender names, and infinite scroll

- Treat contacts as loaded only once the kind 3 event exists, so the first
  home window is fetched with the follow list, and re-fetch the initial window
  when contacts arrive late.
- Resolve sender kind 0 profiles from the user's relays and the content's
  origin relays, and retry unresolved senders after the first load.
- Auto-load older pages while the end sentinel stays visible via a service-side
  loop, guarded by hasMore and a fetch lock, with an epoch token so a mode
  switch invalidates in-flight fetches.
- Deduplicate zap entries across window re-fetches.
This commit is contained in:
raucao committed 2026-11-17 00:31:06 +04:00
1 parent 5e19042ab5
commit 9a5517012c
9 files changed
+592 -48

No files matched your search

+4 -1
View File
@@ -88,7 +88,10 @@ export default class ActivityTimelineComponent extends Component {
<ActivityPhotoItem @item={{item}} @onSelect={{@onSelect}} />
{{/if}}
{{/each}}
<li class="activity-load-more" {{observeIntersection @onLoadMore}}>
<li
class="activity-load-more"
{{observeIntersection @onSentinelVisibility (not @hasMore)}}
>
{{#if @isLoadingMore}}
<div class="activity-load-more-spinner">
<Icon @name="loading-ring" @size={{24}} @color="#898989" />
+6 -2
View File
@@ -37,14 +37,18 @@ export default class ActivityController extends Controller {
return this.activity.isLoadingMore;
}
get hasMore() {
return this.activity.hasMore;
}
@action
setSourceMode(mode) {
this.activity.setSourceMode(mode);
}
@action
loadMore() {
this.activity.loadMore();
onSentinelVisibility(visible) {
this.activity.setSentinelVisible(visible);
}
@action
+15 -5
View File
@@ -1,17 +1,27 @@
import { modifier } from 'ember-modifier';
export default modifier((element, [callback, disabled]) => {
if (disabled) return;
// Reports the element's intersection state to `onVisibilityChange(isVisible)`
// whenever it changes (and once on first observe). `disabled` removes the
// observer entirely.
//
// This only reports visibility; it deliberately does not call a "load" callback
// on every intersection. The decision to load lives in the activity service,
// which keeps loading while the sentinel is visible instead of relying on
// modifier re-runs and IntersectionObserver initial callbacks.
export default modifier((element, [onVisibilityChange, disabled]) => {
if (disabled || typeof onVisibilityChange !== 'function') return;
let observer;
let cancelled = false;
let lastVisible = null;
observer = new IntersectionObserver(
(entries) => {
if (cancelled) return;
if (entries[0]?.isIntersecting) {
callback();
}
const isVisible = !!entries[0]?.isIntersecting;
if (isVisible === lastVisible) return;
lastVisible = isVisible;
onVisibilityChange(isVisible);
},
{
root: null,
+214 -13
View File
@@ -12,6 +12,17 @@ const SINCE_WINDOW = 30 * 24 * 60 * 60; // 30 days in seconds
const MIN_SINCE = Math.floor(new Date('2026-04-20').getTime() / 1000);
const MAX_WINDOW = 960 * 24 * 60 * 60; // 960 days in seconds
/**
* Stable identity key for a zap activity entry, used to deduplicate entries
* when the same time window is fetched more than once.
*
* @param {object} entry An `ActivityEntry` of type 'zap'
* @returns {string}
*/
function zapEntryKey(entry) {
return `${entry.photoEventId}:${entry.senderPubkey}:${entry.createdAt}`;
}
/**
* Orchestrates loading the user's incoming social activity (zaps received on
* their photos) and exposing it as a tracked `items` list for the activity
@@ -35,6 +46,9 @@ export default class ActivityService extends Service {
@tracked sourceMode = 'home';
@tracked isLoading = false;
@tracked isLoadingMore = false;
// Whether older activity may still be available. Used both to guard
// `loadMore` and to keep auto-loading while the end sentinel is visible.
@tracked hasMore = true;
_profileSubs = new Map();
_userPubkey = null;
@@ -42,9 +56,22 @@ export default class ActivityService extends Service {
_socialItems = [];
_lastSocialEvents = [];
_since = null;
_initialSince = null;
_sourceMode = 'home';
_isLoadingMore = false;
_cacheReadyCallback = null;
_contactsUnsub = null;
// Serializes window fetches so a late-contacts refetch can't interleave with
// `loadMore` and corrupt the `_since` bookkeeping.
_fetchLock = Promise.resolve();
// End-of-list visibility reported by the component. While it stays visible,
// older pages are loaded automatically.
_sentinelVisible = false;
_autoLoading = false;
// Bumped whenever the feed resets (new load, mode switch, stop). In-flight
// fetches and the auto-load loop from the previous state check this and bail
// instead of clobbering `_since` or appending stale items.
_epoch = 0;
/**
* Loads the user's incoming zap receipts and social photo activity.
@@ -64,16 +91,21 @@ export default class ActivityService extends Service {
if (this.items.length > 0) return;
this._userPubkey = pubkey || null;
this._since = Math.floor(Date.now() / 1000) - SINCE_WINDOW;
this._initialSince = this._since;
this.hasMore = true;
this._sentinelVisible = false;
this._epoch += 1;
this.isLoading = true;
this._cacheReadyCallback = () => {
this.isLoading = false;
};
try {
let contactsLoaded = true;
if (pubkey) {
await this.nostrData.loadMyContributions(pubkey);
await this.nostrData.loadProfile(pubkey);
await this.nostrData.whenContactsLoaded();
contactsLoaded = await this.nostrData.whenContactsLoaded();
}
this._socialItems = [];
@@ -82,13 +114,74 @@ export default class ActivityService extends Service {
this._mergeItems();
const now = Math.floor(Date.now() / 1000);
await this._fetchWithBackoff(this._since, now);
await this._withFetchLock(() => this._fetchWithBackoff(this._since, now));
// If contacts weren't ready for the first (current) window, the followee
// photos were missed. Fetch the window again once contacts arrive, since
// nothing else re-fetches the *current* window (loadMore only extends
// further back).
if (pubkey && !contactsLoaded) {
this._contactsUnsub?.();
this._contactsUnsub = this.nostrData.onContactsLoaded(() => {
this._contactsUnsub = null;
void this._refetchInitialWindow();
});
}
// If the end sentinel is visible for a short feed, make sure auto-loading
// kicked off even if its visibility callback fired before items landed.
if (this._sentinelVisible && this.hasMore) {
void this._autoLoadWhileVisible();
}
// Retry any sender profiles the loader couldn't resolve on the first
// pass (e.g. profiles that only live on the user's relays), so names
// appear without needing to re-enter the view.
void this.retryUnresolvedProfiles();
} finally {
this.isLoading = false;
this._cacheReadyCallback = null;
}
}
/**
* Re-fetches the initial (current) 30-day window and prepends any newly
* discovered items. Used when the follow list arrived after the initial
* window was fetched.
*
* @returns {Promise<void>}
*/
async _refetchInitialWindow() {
if (this._userPubkey === null || this._initialSince === null) return;
const epoch = this._epoch;
// Fetch just the initial window (no backoff) under the shared lock so it
// never interleaves with `loadMore` and leaves `_since` untouched.
await this._withFetchLock(() => {
if (this._epoch !== epoch) return;
return this._fetchAndProcessWindow(
this._initialSince,
Math.floor(Date.now() / 1000),
epoch
);
});
}
/**
* Runs `fn` after any in-flight window fetch finishes, serializing access to
* the shared `_since` bookkeeping.
*
* @param {() => Promise<unknown>} fn
* @returns {Promise<unknown>}
*/
_withFetchLock(fn) {
const result = this._fetchLock.then(fn, fn);
this._fetchLock = result.then(
() => {},
() => {}
);
return result;
}
/**
* Switches the activity source mode (e.g. 'home' for followee photos,
* 'explore' for all photos from trusted relays). Resets to a fresh
@@ -102,6 +195,10 @@ export default class ActivityService extends Service {
this.sourceMode = mode;
this._since = Math.floor(Date.now() / 1000) - SINCE_WINDOW;
this._initialSince = this._since;
this.hasMore = true;
this._sentinelVisible = false;
this._epoch += 1;
this._socialItems = [];
this._zapItems = [];
this._lastSocialEvents = [];
@@ -114,7 +211,7 @@ export default class ActivityService extends Service {
try {
const now = Math.floor(Date.now() / 1000);
await this._fetchWithBackoff(this._since, now);
await this._withFetchLock(() => this._fetchWithBackoff(this._since, now));
} finally {
this.isLoading = false;
this._cacheReadyCallback = null;
@@ -153,31 +250,96 @@ export default class ActivityService extends Service {
* @returns {Promise<void>}
*/
async loadMore() {
if (this._isLoadingMore || !this._since || !this.items.length) return;
if (
this._isLoadingMore ||
!this.hasMore ||
!this._since ||
!this.items.length
)
return;
this._isLoadingMore = true;
this.isLoadingMore = true;
const epoch = this._epoch;
try {
const startSince = this._since - SINCE_WINDOW;
await this._fetchWithBackoff(startSince, this._since);
await this._withFetchLock(() => {
// Bail if the feed was reset while we waited for the lock.
if (this._epoch !== epoch) return;
const startSince = this._since - SINCE_WINDOW;
return this._fetchWithBackoff(startSince, this._since, epoch);
});
} finally {
this._isLoadingMore = false;
this.isLoadingMore = false;
}
}
/**
* Reports whether the activity list's end sentinel is visible. While it
* stays visible, older pages are loaded automatically until the sentinel
* scrolls out of view or there is nothing left to load.
*
* @param {boolean} visible
*/
setSentinelVisible(visible) {
this._sentinelVisible = visible;
if (visible) {
void this._autoLoadWhileVisible();
}
}
/**
* Keeps loading older pages while the end sentinel is visible. Terminates
* when the sentinel scrolls out of view, `hasMore` becomes false, or a page
* fails to add anything (which would otherwise spin forever).
*
* @returns {Promise<void>}
*/
async _autoLoadWhileVisible() {
if (this._autoLoading) return;
this._autoLoading = true;
try {
let epoch = this._epoch;
for (;;) {
while (this._sentinelVisible && this.hasMore && this._epoch === epoch) {
const before = this.items.length;
await this.loadMore();
if (this._epoch !== epoch) break;
if (this.items.length === before) break;
}
// If the feed was reset (new load / mode switch) while we were busy,
// continue for the new state instead of dropping the request.
if (this._epoch !== epoch && this._sentinelVisible && this.hasMore) {
epoch = this._epoch;
continue;
}
break;
}
} finally {
this._autoLoading = false;
}
}
/**
* Stops subscriptions and clears the timeline. Called when leaving the
* activity route.
*/
stop() {
this._cleanupProfileSubs();
this._contactsUnsub?.();
this._contactsUnsub = null;
this._zapItems = [];
this._socialItems = [];
this._lastSocialEvents = [];
this.items = [];
this._userPubkey = null;
this._since = null;
this._initialSince = null;
this.hasMore = true;
this._sentinelVisible = false;
this._epoch += 1;
this._isLoadingMore = false;
this.isLoadingMore = false;
this.isLoading = false;
@@ -256,11 +418,24 @@ export default class ActivityService extends Service {
const newZapEntries = this._processZapEvents(events, this._userPubkey);
if (newZapEntries.length === 0) return false;
this._zapItems = [...this._zapItems, ...newZapEntries];
// Deduplicate against existing entries (and within this batch) so
// re-fetching a window (e.g. after contacts arrive late) doesn't append
// the same zaps twice.
const existing = new Set(this._zapItems.map(zapEntryKey));
const deduped = [];
for (const entry of newZapEntries) {
const key = zapEntryKey(entry);
if (existing.has(key)) continue;
existing.add(key);
deduped.push(entry);
}
if (deduped.length === 0) return false;
this._zapItems = [...this._zapItems, ...deduped];
this._mergeItems();
void this.placeNameResolver
.resolveInBackground(newZapEntries)
.resolveInBackground(deduped)
.then(() => this._mergeItems());
return true;
@@ -276,12 +451,13 @@ export default class ActivityService extends Service {
* @param {number} batchUntil End of the window (seconds)
* @returns {Promise<boolean>} True if any events were found
*/
async _fetchAndProcessWindow(batchSince, batchUntil) {
async _fetchAndProcessWindow(batchSince, batchUntil, epoch = this._epoch) {
const photoResult = await this.nostrData.fetchActivityPhotos(
batchSince,
batchUntil,
this._sourceMode
);
if (this._epoch !== epoch) return false;
let zapResult = {
cacheEvents: [],
@@ -293,6 +469,7 @@ export default class ActivityService extends Service {
batchSince,
batchUntil
);
if (this._epoch !== epoch) return false;
}
// Phase 1: Process cache events immediately
@@ -316,6 +493,7 @@ export default class ActivityService extends Service {
photoResult.networkEvents,
zapResult.networkEvents,
]);
if (this._epoch !== epoch) return false;
if (networkPhotos.length > 0) {
added = this._processPhotoEvents(networkPhotos) || added;
@@ -336,13 +514,14 @@ export default class ActivityService extends Service {
* @param {number} startUntil End of the first window (seconds)
* @returns {Promise<void>}
*/
async _fetchWithBackoff(startSince, startUntil) {
async _fetchWithBackoff(startSince, startUntil, epoch = this._epoch) {
let windowSize = SINCE_WINDOW;
let batchSince = startSince;
let batchUntil = startUntil;
while (true) {
if (this._since === null) return; // stopped
// Stopped, or the feed was reset (new load / mode switch).
if (this._since === null || this._epoch !== epoch) return;
// Clamp to MIN_SINCE — this is the final iteration if clamped
const isFinal = batchSince < MIN_SINCE;
@@ -350,8 +529,14 @@ export default class ActivityService extends Service {
batchSince = MIN_SINCE;
}
const found = await this._fetchAndProcessWindow(batchSince, batchUntil);
const found = await this._fetchAndProcessWindow(
batchSince,
batchUntil,
epoch
);
if (this._epoch !== epoch) return;
this._since = batchSince;
this.hasMore = !isFinal;
if (found || isFinal) break;
@@ -477,7 +662,7 @@ export default class ActivityService extends Service {
if (!this._profileSubs.has(pubkey)) {
const sub = this.nostrData.store
.model(ProfileModel, pubkey)
.model(ProfileModel, this._profilePointer(entry, pubkey))
.subscribe((profileContent) => {
this._applyProfileToPubkey(pubkey, profileContent);
});
@@ -487,6 +672,22 @@ export default class ActivityService extends Service {
this._applySenderProfile(entry, pubkey);
}
/**
* Builds the `ProfileModel` argument for a sender, adding the relay(s) the
* underlying content was seen on as relay hints. This lets the profile loader
* find metadata on the content's relay, not only the user's relays and the
* public directory relays.
*
* @param {object} entry An `ActivityEntry`
* @param {string} pubkey The sender pubkey
* @returns {string | { pubkey: string, relays: string[] }}
*/
_profilePointer(entry, pubkey) {
const eventId = entry.photo?.eventId || entry.photos?.[0]?.eventId;
const relays = eventId ? this.nostrData.getEventRelays(eventId) : [];
return relays.length > 0 ? { pubkey, relays } : pubkey;
}
_applySenderProfile(entry, pubkey) {
let profile = this.nostrData.getProfile(pubkey);
+67 -12
View File
@@ -1,7 +1,17 @@
import Service, { service } from '@ember/service';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { EMPTY, from, timeout, filter, connect, take, takeUntil } from 'rxjs';
import {
EMPTY,
from,
timeout,
filter,
connect,
take,
takeUntil,
defer,
of,
} from 'rxjs';
import { EventStore } from 'applesauce-core/event-store';
import { ProfileModel } from 'applesauce-core/models/profile';
import { MailboxesModel } from 'applesauce-core/models/mailboxes';
@@ -80,6 +90,11 @@ export default class NostrDataService extends Service {
// loadProfile, resolved in the ContactsModel callback.
_contactsResolver = null;
_contactsPromise = null;
// True once the kind 3 contacts event has actually been loaded. ContactsModel
// emits an empty array *before* the event arrives, so a truthy
// `_contactPubkeys` (e.g. an empty Set) does not mean contacts are ready.
_contactsLoaded = false;
_contactsLoadedCallbacks = new Set();
// Session-only reveal toggle for untrusted content. Not persisted.
@tracked showUntrustedContent = false;
@@ -130,6 +145,11 @@ export default class NostrDataService extends Service {
if (!this.cache) return EMPTY;
return from(this.cache.query(filters));
},
// Ask the user's own relays for missing metadata (profiles, relay lists,
// etc.) before falling back to the public directory relays. Without this,
// events that only exist on the user's relays (e.g. a sender's kind 0
// profile) are never resolved.
extraRelays: defer(() => of(this.activeReadRelays)),
lookupRelays: DIRECTORY_RELAYS,
});
@@ -1038,6 +1058,7 @@ export default class NostrDataService extends Service {
this.mailboxes = null;
this.contacts = null;
this._contactPubkeys = null;
this._contactsLoaded = false;
this.blossomServers = [];
// Create a deferred that resolves when contacts are first loaded
@@ -1066,9 +1087,23 @@ export default class NostrDataService extends Service {
.subscribe((contacts) => {
this.contacts = contacts;
this._contactPubkeys = new Set(contacts.map((c) => c.pubkey));
// Resolve the deferred so callers awaiting whenContactsLoaded proceed.
this._contactsResolver?.();
this._contactsResolver = null;
// ContactsModel emits an empty array before the kind 3 event is loaded,
// so only resolve "contacts loaded" once the event is actually present.
if (!this._contactsLoaded && this.store.getReplaceable(3, pubkey)) {
this._contactsLoaded = true;
// Resolve the deferred so callers awaiting whenContactsLoaded proceed.
this._contactsResolver?.();
this._contactsResolver = null;
for (const callback of this._contactsLoadedCallbacks) {
try {
callback();
} catch (e) {
console.debug('[nostr-data] contacts-loaded callback failed', e);
}
}
}
this._updatePlacePhotos();
// Re-trigger activity photo load now that contacts are available.
// If no activity load has been requested yet, _activityPhotosSince
@@ -1145,22 +1180,40 @@ export default class NostrDataService extends Service {
}
/**
* Returns a promise that resolves when contacts are first loaded, or
* immediately if already loaded. Times out after 5s so callers don't hang
* forever if contacts never arrive.
* Returns a promise that resolves once the user's contacts (kind 3) have
* actually loaded, or after `timeout` ms if they never arrive. Note that
* `ContactsModel` emits an empty array before the event is loaded, so this
* deliberately does not resolve based on `_contactPubkeys` alone.
*
* @param {number} [timeout=5000] Timeout in milliseconds
* @returns {Promise<void>}
* @returns {Promise<boolean>} True if contacts loaded, false on timeout
*/
whenContactsLoaded(timeout = 5000) {
if (this._contactPubkeys) return Promise.resolve();
if (!this._contactsPromise) return Promise.resolve();
if (this._contactsLoaded) return Promise.resolve(true);
if (!this._contactsPromise) return Promise.resolve(false);
return Promise.race([
this._contactsPromise,
new Promise((resolve) => setTimeout(resolve, timeout)),
this._contactsPromise.then(() => true),
new Promise((resolve) => setTimeout(() => resolve(false), timeout)),
]);
}
/**
* Registers a callback that fires once the user's contacts have loaded (or
* immediately if they already have). Useful for re-fetching data that
* depends on the follow list. Returns an unsubscribe function.
*
* @param {() => void} callback
* @returns {() => void}
*/
onContactsLoaded(callback) {
if (this._contactsLoaded) {
callback();
return () => {};
}
this._contactsLoadedCallbacks.add(callback);
return () => this._contactsLoadedCallbacks.delete(callback);
}
get userDisplayName() {
if (this.profile) {
if (this.profile.nip05) {
@@ -1314,6 +1367,7 @@ export default class NostrDataService extends Service {
this._contactsSub.unsubscribe();
this._contactsSub = null;
this._contactPubkeys = null;
this._contactsLoaded = false;
}
if (this._blossomSub) {
this._blossomSub.unsubscribe();
@@ -1344,6 +1398,7 @@ export default class NostrDataService extends Service {
this._cleanupSubscriptions();
this._clearProfileSubs();
this._attemptedProfilePubkeys.clear();
this._contactsLoadedCallbacks.clear();
if (this._deletionsSub) {
this._deletionsSub.unsubscribe();
+2 -1
View File
@@ -9,7 +9,8 @@ import ActivityTimeline from '#components/activity-timeline';
@sourceMode={{@controller.sourceMode}}
@onSetSourceMode={{@controller.setSourceMode}}
@isLoadingMore={{@controller.isLoadingMore}}
@onLoadMore={{@controller.loadMore}}
@hasMore={{@controller.hasMore}}
@onSentinelVisibility={{@controller.onSentinelVisibility}}
@scrollTop={{@controller.scrollTop}}
@onSelect={{@controller.selectItem}}
@onBack={{@controller.backToMenu}}
@@ -16,7 +16,6 @@ module('Integration | Component | activity-timeline', function (hooks) {
this.sourceMode = 'home';
this.onSetSourceMode = () => {};
this.isLoadingMore = false;
this.onLoadMore = () => {};
});
test('it renders a loading state', async function (assert) {
@@ -33,7 +32,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -56,7 +55,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -79,7 +78,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -105,7 +104,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -162,7 +161,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -193,7 +192,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -216,7 +215,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -247,7 +246,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -294,7 +293,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -320,7 +319,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -362,7 +361,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
@@ -404,7 +403,7 @@ module('Integration | Component | activity-timeline', function (hooks) {
@onClose={{this.noop}}
@onNostrConnected={{this.noop}}
@isLoadingMore={{this.isLoadingMore}}
@onLoadMore={{this.onLoadMore}}
@onSentinelVisibility={{this.noop}}
/>
</template>
);
+216 -1
View File
@@ -137,7 +137,12 @@ class MockNostrDataService extends Service {
loadMyContributions() {}
loadProfile() {}
whenContactsLoaded() {
return Promise.resolve();
return Promise.resolve(true);
}
onContactsLoaded(callback) {
callback();
return () => {};
}
async fetchActivityPhotos() {
@@ -152,6 +157,10 @@ class MockNostrDataService extends Service {
return this.profiles[pubkey];
}
getEventRelays() {
return [];
}
async loadIncomingZaps() {}
}
@@ -296,6 +305,71 @@ module('Unit | Service | activity', function (hooks) {
);
});
test('load re-fetches the initial window when contacts arrive late', async function (assert) {
const service = this.owner.lookup('service:activity');
service.nostrData.whenContactsLoaded = () => Promise.resolve(false);
let contactsCallback = null;
service.nostrData.onContactsLoaded = (callback) => {
contactsCallback = callback;
return () => {};
};
service._fetchWithBackoff = async () => {};
await service.load(USER_PUBKEY);
assert.ok(contactsCallback, 'registered a contacts-loaded callback');
let refetched = 0;
service._refetchInitialWindow = async () => {
refetched++;
};
contactsCallback();
assert.strictEqual(refetched, 1, 're-fetched after contacts load');
});
test('_refetchInitialWindow re-fetches just the initial window', async function (assert) {
const service = this.owner.lookup('service:activity');
service._userPubkey = USER_PUBKEY;
service._initialSince = 1000;
let calls = 0;
service._fetchAndProcessWindow = async (since) => {
calls++;
assert.strictEqual(since, 1000, 'fetches from the initial window');
};
await service._refetchInitialWindow();
assert.strictEqual(calls, 1, 're-fetched once');
});
test('_refetchInitialWindow does nothing without a connected user', async function (assert) {
const service = this.owner.lookup('service:activity');
service._userPubkey = null;
service._initialSince = 1000;
let calls = 0;
service._fetchAndProcessWindow = async () => {
calls++;
};
await service._refetchInitialWindow();
assert.strictEqual(calls, 0, 'no fetch without a user');
});
test('_processZapEventsIntoTimeline does not duplicate entries on re-fetch', function (assert) {
const service = this.owner.lookup('service:activity');
service._userPubkey = USER_PUBKEY;
service.nostrData.store.add(
makePhotoEvent({ id: PHOTO_EVENT_ID_1, placeIdentifier: 'osm:node:1' })
);
const receipt = makeZapReceiptEvent({ zappedEventId: PHOTO_EVENT_ID_1 });
service._processZapEventsIntoTimeline([receipt]);
service._processZapEventsIntoTimeline([receipt]);
assert.strictEqual(service.items.length, 1, 'zap not duplicated');
});
test('_resolveSender applies profile when available', function (assert) {
const service = this.owner.lookup('service:activity');
service.nostrData.profiles[SENDER_PUBKEY] = {
@@ -311,6 +385,30 @@ module('Unit | Service | activity', function (hooks) {
assert.false(entry.senderProfileLoading);
});
test('_resolveSender adds content relay hints for the sender profile', function (assert) {
const service = this.owner.lookup('service:activity');
service.nostrData.getEventRelays = () => ['wss://relay.example'];
let captured;
service.nostrData.store.model = (_constructor, pointer) => {
captured = pointer;
return {
subscribe() {
return { unsubscribe() {} };
},
};
};
const entry = parseZapReceipt(makeZapReceiptEvent(), USER_PUBKEY);
entry.photo = { eventId: PHOTO_EVENT_ID_1 };
service._resolveSender(entry);
assert.deepEqual(
captured,
{ pubkey: SENDER_PUBKEY, relays: ['wss://relay.example'] },
'relay hint passed to ProfileModel'
);
});
test('retryUnresolvedProfiles refreshes only unresolved sender pubkeys', async function (assert) {
const service = this.owner.lookup('service:activity');
service._userPubkey = USER_PUBKEY;
@@ -848,6 +946,123 @@ module('Unit | Service | activity', function (hooks) {
// Second 60-day window: batchSince = MIN_SINCE - 30d (< MIN_SINCE, clamped to MIN_SINCE for final fetch)
assert.strictEqual(callCount, 2, 'one normal + one clamped final fetch');
assert.false(service.isLoadingMore, 'isLoadingMore reset after exhaustion');
assert.false(service.hasMore, 'no more once the minimum window is reached');
});
test('loadMore does nothing when hasMore is false', async function (assert) {
const service = this.owner.lookup('service:activity');
service._userPubkey = USER_PUBKEY;
service._since = Math.floor(Date.now() / 1000);
service.items = [{ createdAt: 1 }];
service.hasMore = false;
let called = false;
service.nostrData.fetchActivityPhotos = async () => {
called = true;
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
};
await service.loadMore();
assert.false(called, 'no fetch when there is nothing older to load');
});
test('_fetchWithBackoff keeps hasMore true when a window returns events', async function (assert) {
const service = this.owner.lookup('service:activity');
service._userPubkey = USER_PUBKEY;
service._sourceMode = 'explore';
service._since = Math.floor(Date.now() / 1000);
service.nostrData.fetchActivityPhotos = async () => ({
cacheEvents: [],
networkEvents: Promise.resolve([
makePhotoEvent({
id: 'hm'.padEnd(64, '0'),
author: 'z'.repeat(64),
placeIdentifier: 'osm:node:300',
}),
]),
});
service.nostrData.isTrustedEvent = () => true;
const now = Math.floor(Date.now() / 1000);
await service._fetchWithBackoff(now - 1000, now);
assert.true(service.hasMore, 'older windows may still exist');
});
test('setSentinelVisible auto-loads pages while the sentinel is visible', async function (assert) {
const service = this.owner.lookup('service:activity');
service._since = Math.floor(Date.now() / 1000);
service.items = [{ createdAt: 1 }];
service.hasMore = true;
let pages = 0;
service.loadMore = async () => {
pages++;
service.items = [...service.items, { createdAt: 1 }];
if (pages >= 3) service.hasMore = false;
};
service.setSentinelVisible(true);
await new Promise((r) => setTimeout(r, 0));
assert.strictEqual(pages, 3, 'kept loading until hasMore became false');
});
test('setSentinelVisible stops auto-loading when the sentinel leaves view', async function (assert) {
const service = this.owner.lookup('service:activity');
service._since = Math.floor(Date.now() / 1000);
service.items = [{ createdAt: 1 }];
service.hasMore = true;
let pages = 0;
service.loadMore = async () => {
pages++;
service.items = [...service.items, { createdAt: 1 }];
service.setSentinelVisible(false);
};
service.setSentinelVisible(true);
await new Promise((r) => setTimeout(r, 0));
assert.strictEqual(pages, 1, 'stopped once the sentinel left view');
});
test('_autoLoadWhileVisible stops when a page adds nothing', async function (assert) {
const service = this.owner.lookup('service:activity');
service.items = [{ createdAt: 1 }];
service.hasMore = true;
let pages = 0;
service.loadMore = async () => {
pages++;
};
service.setSentinelVisible(true);
await new Promise((r) => setTimeout(r, 0));
assert.strictEqual(pages, 1, 'no infinite loop without progress');
});
test('_fetchWithBackoff aborts when the feed epoch changes mid-fetch', async function (assert) {
const service = this.owner.lookup('service:activity');
const now = Math.floor(Date.now() / 1000);
service._since = now;
const epoch = service._epoch;
let calls = 0;
service.nostrData.fetchActivityPhotos = async () => {
calls++;
// Simulate a mode switch / reset while the request is in flight.
service._epoch += 1;
return { cacheEvents: [], networkEvents: Promise.resolve([]) };
};
await service._fetchWithBackoff(now - 1000, now, epoch);
assert.strictEqual(calls, 1, 'stopped after the first stale window');
assert.strictEqual(service._since, now, '_since not clobbered');
});
test('loadMore guard prevents concurrent calls', async function (assert) {
+56
View File
@@ -257,6 +257,62 @@ module('Unit | Service | nostr-data | contacts', function (hooks) {
assert.true(true, 'resolved without hanging');
});
test('whenContactsLoaded does not resolve on an empty ContactsModel emission', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
const pubkey = makePubkey(1);
// loadProfile subscribes to ContactsModel, which emits an empty array
// *before* the kind 3 event exists. That must not count as "loaded".
await service.loadProfile(pubkey);
await new Promise((r) => setTimeout(r, 50));
assert.false(service._contactsLoaded, 'not marked as loaded');
assert.strictEqual(
service._contactPubkeys?.size ?? 0,
0,
'no contact pubkeys yet'
);
const loaded = await service.whenContactsLoaded(150);
assert.false(loaded, 'times out without contacts');
});
test('onContactsLoaded fires once the kind 3 event loads', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
const pubkey = makePubkey(1);
const contactA = makePubkey(2);
await service.loadProfile(pubkey);
let fired = 0;
const unsubscribe = service.onContactsLoaded(() => {
fired++;
});
assert.strictEqual(fired, 0, 'not fired before contacts load');
service.store.add(makeContactsEvent(pubkey, [contactA]));
await new Promise((r) => setTimeout(r, 50));
assert.strictEqual(fired, 1, 'fired after contacts load');
unsubscribe();
});
test('onContactsLoaded fires immediately when contacts already loaded', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
const pubkey = makePubkey(1);
const contactA = makePubkey(2);
service.store.add(makeContactsEvent(pubkey, [contactA]));
await service.loadProfile(pubkey);
await new Promise((r) => setTimeout(r, 50));
let fired = 0;
service.onContactsLoaded(() => {
fired++;
});
assert.strictEqual(fired, 1, 'fired synchronously');
});
test('kind 3 events are persisted to IDB cache', async function (assert) {
const service = this.owner.lookup('service:nostr-data');