Use asset first latest releases

This commit is contained in:
franzap
2026-06-07 18:36:00 -03:00
parent c7398c8413
commit 8ccc6e4c6b
2 changed files with 141 additions and 107 deletions
+96 -107
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:models/models.dart'; import 'package:models/models.dart';
import 'package:zapstore/services/package_manager/package_manager.dart';
import 'package:zapstore/services/updates_service.dart'; import 'package:zapstore/services/updates_service.dart';
import 'package:zapstore/utils/extensions.dart'; import 'package:zapstore/utils/extensions.dart';
import 'app_card.dart'; import 'app_card.dart';
@@ -15,9 +16,9 @@ const _kPageSize = 5;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class LatestReleasesState { class LatestReleasesState {
final List<Release> firstPage; final List<SoftwareAsset> firstPage;
final List<Release> olderPages; final List<SoftwareAsset> olderPages;
final Map<String, App> appsByIdentifier; final Map<String, App> appsByAssetId;
final bool isLoadingMore; final bool isLoadingMore;
final bool hasMore; final bool hasMore;
final Object? error; final Object? error;
@@ -25,7 +26,7 @@ class LatestReleasesState {
const LatestReleasesState({ const LatestReleasesState({
required this.firstPage, required this.firstPage,
required this.olderPages, required this.olderPages,
required this.appsByIdentifier, required this.appsByAssetId,
required this.isLoadingMore, required this.isLoadingMore,
required this.hasMore, required this.hasMore,
this.error, this.error,
@@ -34,7 +35,7 @@ class LatestReleasesState {
factory LatestReleasesState.loading() => const LatestReleasesState( factory LatestReleasesState.loading() => const LatestReleasesState(
firstPage: [], firstPage: [],
olderPages: [], olderPages: [],
appsByIdentifier: {}, appsByAssetId: {},
isLoadingMore: false, isLoadingMore: false,
hasMore: true, hasMore: true,
); );
@@ -42,19 +43,19 @@ class LatestReleasesState {
bool get isLoading => bool get isLoading =>
firstPage.isEmpty && olderPages.isEmpty && error == null; firstPage.isEmpty && olderPages.isEmpty && error == null;
List<Release> get allReleases => [...firstPage, ...olderPages]; List<SoftwareAsset> get allAssets => [...firstPage, ...olderPages];
LatestReleasesState copyWith({ LatestReleasesState copyWith({
List<Release>? firstPage, List<SoftwareAsset>? firstPage,
List<Release>? olderPages, List<SoftwareAsset>? olderPages,
Map<String, App>? appsByIdentifier, Map<String, App>? appsByAssetId,
bool? isLoadingMore, bool? isLoadingMore,
bool? hasMore, bool? hasMore,
Object? error, Object? error,
}) => LatestReleasesState( }) => LatestReleasesState(
firstPage: firstPage ?? this.firstPage, firstPage: firstPage ?? this.firstPage,
olderPages: olderPages ?? this.olderPages, olderPages: olderPages ?? this.olderPages,
appsByIdentifier: appsByIdentifier ?? this.appsByIdentifier, appsByAssetId: appsByAssetId ?? this.appsByAssetId,
isLoadingMore: isLoadingMore ?? this.isLoadingMore, isLoadingMore: isLoadingMore ?? this.isLoadingMore,
hasMore: hasMore ?? this.hasMore, hasMore: hasMore ?? this.hasMore,
error: error, error: error,
@@ -68,14 +69,14 @@ class LatestReleasesState {
/// Local-first, reactive notifier for the "Latest Releases" home section. /// Local-first, reactive notifier for the "Latest Releases" home section.
/// ///
/// Design: /// Design:
/// - The outer `query<Release>(...)` subscription carries an `and:` chain that /// - The outer `query<SoftwareAsset>(...)` subscription carries an `and:` chain
/// loads `release.app` (+ nested `app.author`) and `release.softwareAssets` /// that loads `asset.app`
/// in the background via `NestedQueryManager`. Relationship queries are /// in the background via `NestedQueryManager`. Relationship queries are
/// fire-and-forget; they NEVER block the state update. /// fire-and-forget; they NEVER block the state update.
/// - The listener reacts to every emission — `StorageLoading(localReleases)` /// - The listener reacts to every emission — `StorageLoading(localAssets)`
/// during `awaitingRemote` and `StorageData` once EOSE lands. Local Releases /// during `awaitingRemote` and `StorageData` once EOSE lands. Local assets
/// are displayed within one frame regardless of network state. /// are displayed within one frame regardless of network state.
/// - `appsByIdentifier` is computed synchronously from local storage /// - `appsByAssetId` is computed synchronously from local storage
/// (`storage.querySync`) on every emission. As the `and:` relationship /// (`storage.querySync`) on every emission. As the `and:` relationship
/// queries populate storage in the background, subsequent emissions pick /// queries populate storage in the background, subsequent emissions pick
/// up the newly-available Apps. /// up the newly-available Apps.
@@ -85,36 +86,27 @@ class LatestReleasesState {
/// - Remote failures degrade gracefully; rows without a resolved App are /// - Remote failures degrade gracefully; rows without a resolved App are
/// simply skipped by the consumer widget. /// simply skipped by the consumer widget.
class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> { class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
LatestReleasesNotifier(this.ref) : super(LatestReleasesState.loading()) { LatestReleasesNotifier(this.ref, {required this.platform})
: super(LatestReleasesState.loading()) {
_subscribe(); _subscribe();
} }
final Ref ref; final Ref ref;
ProviderSubscription<StorageState<Release>>? _sub; final String platform;
ProviderSubscription<StorageState<SoftwareAsset>>? _sub;
void _subscribe() { void _subscribe() {
_sub?.close(); _sub?.close();
_sub = ref.listen( _sub = ref.listen(
query<Release>( query<SoftwareAsset>(
tags: {
'#f': {platform},
},
limit: _kPageSize, limit: _kPageSize,
source: const LocalAndRemoteSource(relays: 'AppCatalog', stream: true), source: const LocalAndRemoteSource(relays: 'AppCatalog', stream: true),
subscriptionPrefix: 'app-latest-releases', subscriptionPrefix: 'app-latest-releases',
and: (release) => { and: (asset) => {
release.app.query( asset.app.query(
source: const LocalAndRemoteSource(
relays: 'AppCatalog',
stream: false,
),
and: (app) => {
app.author.query(
source: const LocalAndRemoteSource(
relays: {'vertex', 'social'},
cachedFor: Duration(hours: 2),
),
),
},
),
release.softwareAssets.query(
source: const LocalAndRemoteSource( source: const LocalAndRemoteSource(
relays: 'AppCatalog', relays: 'AppCatalog',
stream: false, stream: false,
@@ -123,7 +115,7 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
}, },
), ),
(_, next) { (_, next) {
if (next is StorageError<Release>) { if (next is StorageError<SoftwareAsset>) {
state = state.copyWith(error: next.exception); state = state.copyWith(error: next.exception);
return; return;
} }
@@ -133,34 +125,31 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
); );
} }
void _applyFirstPage(List<Release> releases) { void _applyFirstPage(List<SoftwareAsset> assets) {
final storage = ref.read(storageNotifierProvider.notifier); final storage = ref.read(storageNotifierProvider.notifier);
final liveIds = releases.map((r) => r.id).toSet(); final liveIds = assets.map((asset) => asset.id).toSet();
final filteredOlder = state.olderPages final filteredOlder = state.olderPages
.where((r) => !liveIds.contains(r.id)) .where((asset) => !liveIds.contains(asset.id))
.toList(); .toList();
final keepIds = { final keepAssets = [...assets, ...filteredOlder];
...releases.map((r) => r.appIdentifier),
...filteredOlder.map((r) => r.appIdentifier),
}..removeWhere((id) => id.isEmpty);
final appsByIdentifier = _resolveAppsFromLocal(storage, keepIds); final appsByAssetId = _resolveAppsFromLocal(storage, keepAssets);
state = state.copyWith( state = state.copyWith(
firstPage: releases, firstPage: assets,
olderPages: filteredOlder, olderPages: filteredOlder,
appsByIdentifier: appsByIdentifier, appsByAssetId: appsByAssetId,
error: null, error: null,
); );
} }
Future<void> loadMore() async { Future<void> loadMore() async {
final all = state.allReleases; final all = state.allAssets;
if (state.isLoadingMore || !state.hasMore || all.isEmpty) return; if (state.isLoadingMore || !state.hasMore || all.isEmpty) return;
final oldest = all final oldest = all
.map((r) => r.event.createdAt) .map((asset) => asset.event.createdAt)
.reduce((a, b) => a.isBefore(b) ? a : b) .reduce((a, b) => a.isBefore(b) ? a : b)
.subtract(const Duration(milliseconds: 1)); .subtract(const Duration(milliseconds: 1));
@@ -168,16 +157,21 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
try { try {
final storage = ref.read(storageNotifierProvider.notifier); final storage = ref.read(storageNotifierProvider.notifier);
final req = final req = RequestFilter<SoftwareAsset>(
RequestFilter<Release>(until: oldest, limit: _kPageSize).toRequest(); tags: {
'#f': {platform},
},
until: oldest,
limit: _kPageSize,
).toRequest();
// Local-first: read whatever is already cached, so offline scroll // Local-first: read whatever is already cached, so offline scroll
// shows older items immediately without waiting on the relay. // shows older items immediately without waiting on the relay.
final localReleases = storage.querySync(req); final localAssets = storage.querySync(req);
List<Release> releases; List<SoftwareAsset> assets;
if (localReleases.isNotEmpty) { if (localAssets.isNotEmpty) {
releases = localReleases; assets = localAssets;
// Background hydrate: bring in any older items the relay has that // Background hydrate: bring in any older items the relay has that
// aren't cached yet. Results land via the live subscription's // aren't cached yet. Results land via the live subscription's
// general storage-update path; next scroll picks them up. // general storage-update path; next scroll picks them up.
@@ -191,11 +185,11 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
), ),
subscriptionPrefix: 'app-latest-releases-older', subscriptionPrefix: 'app-latest-releases-older',
) )
.catchError((_) => const <Release>[]), .catchError((_) => const <SoftwareAsset>[]),
); );
} else { } else {
// Nothing local. Try remote with a short timeout; fall back to empty. // Nothing local. Try remote with a short timeout; fall back to empty.
releases = await storage assets = await storage
.query( .query(
req, req,
source: const LocalAndRemoteSource( source: const LocalAndRemoteSource(
@@ -206,85 +200,84 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
) )
.timeout( .timeout(
const Duration(seconds: 5), const Duration(seconds: 5),
onTimeout: () => const <Release>[], onTimeout: () => const <SoftwareAsset>[],
) )
.catchError((_) => const <Release>[]); .catchError((_) => const <SoftwareAsset>[]);
} }
if (releases.isEmpty) { if (assets.isEmpty) {
state = state.copyWith(isLoadingMore: false, hasMore: false); state = state.copyWith(isLoadingMore: false, hasMore: false);
return; return;
} }
final existingIds = all.map((r) => r.id).toSet(); final existingIds = all.map((asset) => asset.id).toSet();
final unique = releases final unique = assets
.where((r) => !existingIds.contains(r.id)) .where((asset) => !existingIds.contains(asset.id))
.toList(); .toList();
// Fire relationship queries for the older page in the background. // Fire relationship queries for the older page in the background.
// The first-page subscription's general-update path will refresh // The first-page subscription's general-update path will refresh
// `appsByIdentifier` as apps/authors/assets land in storage. // `appsByAssetId` as apps land in storage.
_hydrateOlderPageRelationships(unique); _hydrateOlderPageRelationships(unique);
final keepIds = { final keepAssets = [...state.firstPage, ...state.olderPages, ...unique];
...state.firstPage.map((r) => r.appIdentifier),
...state.olderPages.map((r) => r.appIdentifier),
...unique.map((r) => r.appIdentifier),
}..removeWhere((id) => id.isEmpty);
state = state.copyWith( state = state.copyWith(
olderPages: [...state.olderPages, ...unique], olderPages: [...state.olderPages, ...unique],
appsByIdentifier: _resolveAppsFromLocal(storage, keepIds), appsByAssetId: _resolveAppsFromLocal(storage, keepAssets),
isLoadingMore: false, isLoadingMore: false,
hasMore: releases.length >= _kPageSize, hasMore: assets.length >= _kPageSize,
); );
} catch (_) { } catch (_) {
state = state.copyWith(isLoadingMore: false); state = state.copyWith(isLoadingMore: false);
} }
} }
/// Synchronously map app identifiers → App using local storage only. /// Synchronously map asset IDs -> parent App using local storage only.
/// Never awaits network; returns an empty entry for ids not yet in cache. /// Never awaits network; returns an empty entry for ids not yet in cache.
Map<String, App> _resolveAppsFromLocal( Map<String, App> _resolveAppsFromLocal(
StorageNotifier storage, StorageNotifier storage,
Set<String> appIds, List<SoftwareAsset> assets,
) { ) {
final result = <String, App>{}; final result = <String, App>{};
for (final id in appIds) { for (final asset in assets) {
if (asset.appIdentifier.isEmpty) continue;
final matches = storage.querySync( final matches = storage.querySync(
RequestFilter<App>( RequestFilter<App>(
authors: {asset.event.pubkey},
tags: { tags: {
'#d': {id}, '#d': {asset.appIdentifier},
'#f': {platform},
}, },
limit: 1, limit: 1,
).toRequest(), ).toRequest(),
); );
if (matches.isNotEmpty) { if (matches.isNotEmpty) {
result[id] = matches.first; result[asset.id] = matches.first;
} }
} }
return result; return result;
} }
/// Fire-and-forget relationship hydration for older-page Releases. /// Fire-and-forget relationship hydration for older-page SoftwareAssets.
/// Results land in local storage and trigger a refresh via the outer /// Results land in local storage and trigger a refresh via the outer
/// subscription's `handleStorageUpdate`. /// subscription's `handleStorageUpdate`.
void _hydrateOlderPageRelationships(List<Release> releases) { void _hydrateOlderPageRelationships(List<SoftwareAsset> assets) {
if (releases.isEmpty) return; if (assets.isEmpty) return;
final storage = ref.read(storageNotifierProvider.notifier); final storage = ref.read(storageNotifierProvider.notifier);
final appIds = releases final appFilters = <RequestFilter<App>>[];
.map((r) => r.appIdentifier) for (final asset in assets) {
.where((id) => id.isNotEmpty) final filters = asset.app.req?.filters;
.toSet(); if (filters != null && filters.isNotEmpty) {
final assetIds = releases appFilters.add(filters.first);
.expand((r) => r.event.getTagSetValues('e')) }
.toSet(); }
if (appIds.isNotEmpty) { if (appFilters.isNotEmpty) {
unawaited( unawaited(
storage.query( storage.query(
RequestFilter<App>(tags: {'#d': appIds}).toRequest(), Request<App>(appFilters),
source: const LocalAndRemoteSource( source: const LocalAndRemoteSource(
relays: 'AppCatalog', relays: 'AppCatalog',
stream: false, stream: false,
@@ -293,18 +286,6 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
), ),
); );
} }
if (assetIds.isNotEmpty) {
unawaited(
storage.query(
RequestFilter<SoftwareAsset>(ids: assetIds).toRequest(),
source: const LocalAndRemoteSource(
relays: 'AppCatalog',
stream: false,
),
subscriptionPrefix: 'app-latest-releases-older-assets',
),
);
}
} }
@override @override
@@ -316,7 +297,8 @@ class LatestReleasesNotifier extends StateNotifier<LatestReleasesState> {
final latestReleasesProvider = final latestReleasesProvider =
StateNotifierProvider<LatestReleasesNotifier, LatestReleasesState>((ref) { StateNotifierProvider<LatestReleasesNotifier, LatestReleasesState>((ref) {
return LatestReleasesNotifier(ref); final platform = ref.read(packageManagerProvider.notifier).platform;
return LatestReleasesNotifier(ref, platform: platform);
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -336,8 +318,8 @@ class LatestReleasesContainer extends HookConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final state = showSkeleton ? null : ref.watch(latestReleasesProvider); final state = showSkeleton ? null : ref.watch(latestReleasesProvider);
final releases = state?.allReleases ?? []; final assets = state?.allAssets ?? [];
final appsById = state?.appsByIdentifier ?? const {}; final appsByAssetId = state?.appsByAssetId ?? const {};
final categorized = ref.watch(categorizedUpdatesProvider); final categorized = ref.watch(categorizedUpdatesProvider);
final pinnedApps = [ final pinnedApps = [
@@ -348,8 +330,8 @@ class LatestReleasesContainer extends HookConsumerWidget {
final seenAppIds = <String>{...pinnedIds}; final seenAppIds = <String>{...pinnedIds};
final dedupedApps = <App>[]; final dedupedApps = <App>[];
for (final release in releases) { for (final asset in assets) {
final app = appsById[release.appIdentifier]; final app = appsByAssetId[asset.id];
if (app != null && seenAppIds.add(app.identifier)) { if (app != null && seenAppIds.add(app.identifier)) {
dedupedApps.add(app); dedupedApps.add(app);
} }
@@ -360,6 +342,7 @@ class LatestReleasesContainer extends HookConsumerWidget {
useEffect(() { useEffect(() {
if (state == null) return null; if (state == null) return null;
void onScroll() { void onScroll() {
if (!scrollController.hasClients) return;
final s = ref.read(latestReleasesProvider); final s = ref.read(latestReleasesProvider);
if (s.isLoadingMore || !s.hasMore) return; if (s.isLoadingMore || !s.hasMore) return;
if (scrollController.position.pixels >= if (scrollController.position.pixels >=
@@ -368,21 +351,27 @@ class LatestReleasesContainer extends HookConsumerWidget {
} }
} }
void checkInitialLoad() { void checkContentExtent() {
if (!scrollController.hasClients) return; if (!scrollController.hasClients) return;
final position = scrollController.position; final position = scrollController.position;
final s = ref.read(latestReleasesProvider); final s = ref.read(latestReleasesProvider);
if (s.isLoadingMore || !s.hasMore) return; if (s.isLoadingMore || !s.hasMore) return;
if (position.maxScrollExtent <= position.viewportDimension) { if (position.maxScrollExtent <= 0 ||
position.pixels >= position.maxScrollExtent - 300) {
ref.read(latestReleasesProvider.notifier).loadMore(); ref.read(latestReleasesProvider.notifier).loadMore();
} }
} }
WidgetsBinding.instance.addPostFrameCallback((_) => checkInitialLoad()); WidgetsBinding.instance.addPostFrameCallback((_) => checkContentExtent());
scrollController.addListener(onScroll); scrollController.addListener(onScroll);
return () => scrollController.removeListener(onScroll); return () => scrollController.removeListener(onScroll);
}, [scrollController, state]); }, [
scrollController,
combinedApps.length,
state?.isLoadingMore,
state?.hasMore,
]);
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -0,0 +1,45 @@
# WORK-012 - Latest Releases Asset-First Pagination
**Feature:** FEAT-004 asset-first queries
**Status:** Implemented
## Context
The home screen "Latest Releases" section can miss newly published apps/releases
and pagination appears not to fire.
Diagnosis:
- `LatestReleasesNotifier` queries `Release` kind `30063`, but current app-card
freshness is driven by `SoftwareAsset` kind `3063`.
- The query has no platform filter, then resolves Apps after the fact.
- The UI dedupes by App after fetching only five raw Release rows, so duplicate
releases for the same app can hide other apps until pagination runs.
- The viewport-fill pagination check is tied to a one-frame scroll extent check
and should use the actual scroll extent after each render.
## Tasks
- [x] Switch Latest Releases first page to `SoftwareAsset` (`3063`) with platform filtering.
- [x] Keep local-first relationship resolution and avoid awaiting network on render.
- [x] Page older SoftwareAssets by asset `createdAt`.
- [x] Make initial/fill pagination trigger from actual scroll extent.
- [x] Attempt analyzer and focused tests where available.
## Verification
- [ ] `fvm flutter analyze`
- [x] Manual/code review: first page uses `SoftwareAsset`, `#f` platform filter,
and no awaited network call in the render/listener path.
Analyzer could not run in this environment:
- `fvm dart format lib/widgets/latest_releases_container.dart` failed with
`Operation not permitted` from the fvm shim.
- `dart format ...` failed trying to create/read files under the user pub/cache
paths.
- `flutter analyze` failed with `operation not permitted: flutter`.
## Spec Issues
_None_