D1, prima parte: Dashboard al posto di Attività e «Cosa scaricare prima» generale

Richiesta di Alberto (#59): decidere cosa scaricare prima, una Dashboard compatta come
pagina iniziale da guardare mentre il motore lavora, e le miniature di ciò che è arrivato.

- Dashboard (§7.9, §10.2): /dashboard è la pagina iniziale e la prima voce della barra;
  /, /attivita, «Ho finito» del browser, il riquadro di stato e il ritorno dopo l'accesso
  portano lì. In alto l'anteprima del browser sempre visibile, chiesta ogni secondo mentre
  il motore lavora (LiveBrowserPreview cattura al più un fotogramma al secondo), accanto
  cosa sta facendo e i quattro tetti; poi la striscia più bassa, la cronologia con le
  miniature e la coda ridotta alle prime righe con «Mostra tutta». Sotto i 1000 px una
  colonna sola.
- Miniature della cronologia: /api/activity/arrived dà gli elementi che una ricetta ha
  salvato (account, inizio e fine della ricetta), chiesti solo quando la riga entra in
  vista, al più otto con «+N». Un clic apre un'anteprima leggera con foto o video senza
  audio, frecce fra i file della riga, Esc, «Apri nella Libreria» e «Apri l'account».
- «Cosa scaricare prima» (§7.2, §6.5): ordine generale dei tipi in Impostazioni → Limiti
  e comportamento (trascinare, «Su» e «Giù», nota sulle storie che scadono), predefinito
  storie, evidenza, post, reel, taggati. Dopo il giro, il lavoro dovuto si estrae con il
  peso dell'account per il peso del tipo (16, 8, 4, 2, 1): pesa, non rende fisso. La coda
  dei file segue lo stesso ordine.
- Prove: DownloadOrderTests (ordine, pesi, coda, motore con seme fisso: il primo tipo
  viene più spesso ma non sempre, il giro resta primo, un tipo senza lavoro non si
  visita), DashboardApiTests, una prova dell'interfaccia per / e /attivita.

Non ancora fatto: ordine per account e segno del reel (serve una migrazione da concordare
con E1), «Raggruppa i post» / «Tutte le foto», confronto con i mockup, revisione del
resto della guida che nomina ancora Attività.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 14:53:03 +01:00
1 parent 2068dd28f3
commit d6c0ef851d
38 files changed
+1468 -479

No files matched your search

@@ -242,7 +242,9 @@ public sealed class DownloadQueue
var now = _clock.Now;
var waiting = _retryAt.Count(r => r.Value > now);
var window = (int)Math.Min(10_000L, (long)_options.BatchSize + attempted.Count + waiting);
var batch = (await _storage.Media.ListPendingDownloadsAsync(window, ct).ConfigureAwait(false))
// «Cosa scaricare prima» (spec §6.5, §7.2), read at every batch so that a change counts from the next one.
var order = await Febe.Core.Engine.DownloadOrder.LoadAsync(_storage.Settings, ct).ConfigureAwait(false);
var batch = (await _storage.Media.ListPendingDownloadsAsync(window, order.EntryKinds(), ct).ConfigureAwait(false))
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now))
.Take(_options.BatchSize)
.ToList();
+160
View File
@@ -0,0 +1,160 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>A type of «Cosa scaricare prima» (spec §7.2): the kinds of recipes of §6.3, grouped as Alberto names them.</summary>
public enum DownloadKind
{
/// <summary>«Storie»: Storie di un account.</summary>
Stories,
/// <summary>«Evidenza»: Raccolta in evidenza.</summary>
Highlights,
/// <summary>«Post»: Controllo del profilo and Storico, profile pictures included.</summary>
Posts,
/// <summary>«Reel»: Reel.</summary>
Reels,
/// <summary>«Taggati»: Taggati.</summary>
Tagged,
}
/// <summary>
/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in <see cref="SettingKey"/> as their
/// Italian names separated by commas. It weighs the next visit after the Giro dei seguiti (the weight of a kind is
/// <see cref="Weight"/>, multiplied by the weight of the account) and the order of the queue of the files (spec §6.5). It
/// never adds a visit, never brings one forward and never makes the order fixed: it only weighs the choices the engine
/// already makes among the work that is due and allowed.
/// </summary>
public sealed class DownloadOrder
{
/// <summary>The general order (Impostazioni → Limiti e comportamento).</summary>
public const string SettingKey = "scaricamento.ordine";
/// <summary>The weights of the positions, first to last (spec §7.4 table, «Peso di un tipo nella scelta»).</summary>
public static readonly IReadOnlyList<double> Weights = [16, 8, 4, 2, 1];
private static readonly (DownloadKind Kind, string Name)[] Names =
[
(DownloadKind.Stories, "storie"),
(DownloadKind.Highlights, "evidenza"),
(DownloadKind.Posts, "post"),
(DownloadKind.Reels, "reel"),
(DownloadKind.Tagged, "taggati"),
];
private DownloadOrder(IReadOnlyList<DownloadKind> kinds) => Kinds = kinds;
/// <summary>Storie, evidenza, post, reel, taggati (spec §7.2, §16 question 19).</summary>
public static DownloadOrder Default { get; } = new([DownloadKind.Stories, DownloadKind.Highlights, DownloadKind.Posts, DownloadKind.Reels, DownloadKind.Tagged]);
/// <summary>The five kinds, first to last.</summary>
public IReadOnlyList<DownloadKind> Kinds { get; }
/// <summary>True when this is the order of <see cref="Default"/>.</summary>
public bool IsDefault => Kinds.SequenceEqual(Default.Kinds);
/// <summary>The Italian name of a kind, as stored and as the interface sends it.</summary>
public static string NameOf(DownloadKind kind) => Names.First(n => n.Kind == kind).Name;
/// <summary>
/// Reads a stored order. Unknown names are left out, a kind named twice counts once and the kinds missing are added
/// at the end in the default order, so any text gives the five kinds; null or empty gives <see cref="Default"/>.
/// </summary>
public static DownloadOrder Parse(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return Default;
}
var kinds = new List<DownloadKind>();
foreach (var part in text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
foreach (var (kind, name) in Names)
{
if (string.Equals(name, part, StringComparison.OrdinalIgnoreCase) && !kinds.Contains(kind))
{
kinds.Add(kind);
}
}
}
kinds.AddRange(Default.Kinds.Where(k => !kinds.Contains(k)));
return new DownloadOrder(kinds);
}
/// <summary>Builds an order from the names the interface sends; the same rules as <see cref="Parse"/>.</summary>
public static DownloadOrder From(IEnumerable<string> names) => Parse(string.Join(',', names));
/// <summary>The stored text: the five names, comma separated.</summary>
public override string ToString() => string.Join(',', Kinds.Select(NameOf));
/// <summary>0 for the first kind, 4 for the last.</summary>
public int Position(DownloadKind kind)
{
for (var i = 0; i < Kinds.Count; i++)
{
if (Kinds[i] == kind)
{
return i;
}
}
return Kinds.Count - 1;
}
/// <summary>16, 8, 4, 2 or 1 by the position of the kind.</summary>
public double Weight(DownloadKind kind) => Weights[Position(kind)];
/// <summary>
/// The kind of a task of the engine (spec §7.2); null for the work that no kind weighs: the Giro dei seguiti, which
/// stays first, and the reading of the following list.
/// </summary>
public static DownloadKind? KindOf(EngineTaskKind task) => task switch
{
EngineTaskKind.AccountStories => DownloadKind.Stories,
EngineTaskKind.HighlightCheck => DownloadKind.Highlights,
EngineTaskKind.ProfileCheck or EngineTaskKind.Backfill or EngineTaskKind.SinglePost => DownloadKind.Posts,
EngineTaskKind.ReelsCheck => DownloadKind.Reels,
EngineTaskKind.TaggedCheck => DownloadKind.Tagged,
_ => null,
};
/// <summary>
/// The kind of a file in the queue (spec §6.5): profile pictures go with the posts; a reel counts as a post until Febe
/// keeps whether a post is a reel (spec §8.3, the flag of <c>entry</c> of D1).
/// </summary>
public static DownloadKind KindOf(EntryKind entry) => entry switch
{
EntryKind.Story => DownloadKind.Stories,
EntryKind.Highlight => DownloadKind.Highlights,
EntryKind.Tagged => DownloadKind.Tagged,
_ => DownloadKind.Posts,
};
/// <summary>The entry kinds in the order of the queue: the position of each <see cref="EntryKind"/>, first to last.</summary>
public IReadOnlyList<EntryKind> EntryKinds()
{
var all = Enum.GetValues<EntryKind>();
return [.. all.OrderBy(e => Position(KindOf(e))).ThenBy(e => Array.IndexOf(all, e))];
}
/// <summary>The general order stored in the settings.</summary>
public static async Task<DownloadOrder> LoadAsync(ISettingsStore settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
return Parse(await settings.GetAsync(SettingKey, ct).ConfigureAwait(false));
}
/// <summary>Stores the general order; the default is stored as no value («come le impostazioni predefinite»).</summary>
public static Task SaveAsync(ISettingsStore settings, DownloadOrder order, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(order);
return settings.SetAsync(SettingKey, order.IsDefault ? null : order.ToString(), ct);
}
}
+10 -1
View File
@@ -524,7 +524,16 @@ public sealed class EngineMonitor : IEngineMonitor
var recent = _host.RecentActions(10);
if (recent.Count > 0)
{
views.AddRange(recent.Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false)));
views.AddRange(recent.Select(r => new RecentActionView(
r.At,
ItalianText.Clock(r.At, zone),
r.Title,
r.Detail,
r.Badge,
false,
r.NewEntries > 0 ? r.AccountId : null,
r.NewEntries > 0 ? r.StartedAt : null,
r.NewEntries)));
return views;
}
+15 -2
View File
@@ -136,8 +136,21 @@ public sealed record BudgetView(
/// <param name="Suspended">The engine is stopped or paused.</param>
public sealed record QueueItem(long TaskId, EngineTaskKind Kind, long? AccountId, string Title, string Detail, DateTimeOffset? Around, string When, bool IsManual, bool Suspended);
/// <summary>A line of «Appena fatto».</summary>
public sealed record RecentActionView(DateTimeOffset At, string Time, string Title, string Detail, string? Badge, bool InProgress);
/// <summary>A line of the history of the Dashboard («Appena fatto»).</summary>
/// <param name="AccountId">Account of the recipe, when it has one and saved something: with <see cref="From"/> and
/// <see cref="At"/> it tells the page which entries arrived, for their thumbnails (spec §7.9, tappa D1).</param>
/// <param name="From">When the recipe started.</param>
/// <param name="NewEntries">Entries saved by the recipe.</param>
public sealed record RecentActionView(
DateTimeOffset At,
string Time,
string Title,
string Detail,
string? Badge,
bool InProgress,
long? AccountId = null,
DateTimeOffset? From = null,
int NewEntries = 0);
/// <summary>A recipe suspended after repeated unrecognized formats.</summary>
public sealed record SuspendedRecipeView(RecipeKind Recipe, string Name, DateTimeOffset Since);
+4 -1
View File
@@ -8,6 +8,8 @@ namespace Febe.Core.Engine;
/// <param name="Detail">«2 storie nuove», «Nessuna novità».</param>
/// <param name="Status">How it ended.</param>
/// <param name="NewEntries">New entries found.</param>
/// <param name="StartedAt">When it started: the entries of the account discovered from then to <see cref="At"/> are
/// the ones it saved (thumbnails of the Dashboard, spec §7.9).</param>
public sealed record RecentAction(
DateTimeOffset At,
RecipeKind Recipe,
@@ -15,7 +17,8 @@ public sealed record RecentAction(
string Title,
string Detail,
RecipeStatus Status,
int NewEntries)
int NewEntries,
DateTimeOffset? StartedAt = null)
{
/// <summary>Short label of the outcome for a badge («Scaricato», «Rimandato»...); null when nothing to say.</summary>
public string? Badge => Status switch
+32 -31
View File
@@ -84,23 +84,39 @@ internal sealed class SessionComposer
await RunSweepAsync(sweepTask, accounts, state, ct).ConfigureAwait(false);
}
// 3. Stories: flagged by the stories bar first, then the due ones (visits of profiles not followed included).
// 3. The work that is due: stories flagged by the stories bar first, then, drawn one after the other with the
// weight of the account times the weight of its kind in «Cosa scaricare prima» (spec §7.2, tappa D1), the other
// stories (visits of profiles not followed included) and, except in a light session, the expired profile checks,
// highlight collections and other planned work. The order weighs the choices, it does not add any.
if (!Over(state, ct))
{
var now = Clock.Now;
var window = await WindowLengthAsync(now, ct).ConfigureAwait(false);
var order = await DownloadOrder.LoadAsync(Store.Settings, ct).ConfigureAwait(false);
due = await Store.Tasks.PeekDueAsync(now, 1000, ct).ConfigureAwait(false);
await RunManualTasksAsync(due, accounts, state, ct).ConfigureAwait(false);
var storyWork = due.Where(t => !t.IsManual && IsStoryWork(t, accounts, now)).ToList();
var flagged = storyWork.Where(t => t.Priority >= Options.FlaggedStoriesPriority);
var rest = storyWork.Where(t => t.Priority < Options.FlaggedStoriesPriority);
foreach (var task in Weighted(flagged, accounts, now, window).Concat(Weighted(rest, accounts, now, window)))
var rest = storyWork.Where(t => t.Priority < Options.FlaggedStoriesPriority).ToList();
var other = light
? []
: due.Where(t => !t.IsManual
&& t.Kind is not (EngineTaskKind.FollowingSweep or EngineTaskKind.Backfill or EngineTaskKind.AccountStories)
&& !storyWork.Contains(t)).ToList();
var storyIds = rest.Select(t => t.Id).ToHashSet();
foreach (var task in Weighted(flagged, accounts, now, window, order).Concat(Weighted(rest.Concat(other), accounts, now, window, order)))
{
if (Over(state, ct))
{
break;
}
// A profile already opened in this session is not opened again for the other work: it waits for the next one.
if (!storyIds.Contains(task.Id) && task.Priority < Options.FlaggedStoriesPriority && task.AccountId is { } visited && state.Visited.Contains(visited))
{
continue;
}
await RunScheduledAsync(task, accounts, state, ct).ConfigureAwait(false);
}
@@ -133,28 +149,7 @@ internal sealed class SessionComposer
}
}
// 4. Expired profile checks, highlight collections and other planned work.
if (!light && !Over(state, ct))
{
var now = Clock.Now;
var window = await WindowLengthAsync(now, ct).ConfigureAwait(false);
due = await Store.Tasks.PeekDueAsync(now, 1000, ct).ConfigureAwait(false);
await RunManualTasksAsync(due, accounts, state, ct).ConfigureAwait(false);
var other = due.Where(t => !t.IsManual
&& t.Kind is not (EngineTaskKind.FollowingSweep or EngineTaskKind.Backfill or EngineTaskKind.AccountStories)
&& !(t.AccountId is { } id && state.Visited.Contains(id)));
foreach (var task in Weighted(other, accounts, now, window))
{
if (Over(state, ct))
{
break;
}
await RunScheduledAsync(task, accounts, state, ct).ConfigureAwait(false);
}
}
// 5. A few pages of history on one account.
// 4. A few pages of history on one account.
if (!light && !Over(state, ct))
{
await RunBackfillAsync(state, ct).ConfigureAwait(false);
@@ -470,21 +465,26 @@ internal sealed class SessionComposer
&& (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now);
}
private IEnumerable<EngineTask> Weighted(IEnumerable<EngineTask> tasks, Dictionary<long, Account> accounts, DateTimeOffset now, TimeSpan window)
private IEnumerable<EngineTask> Weighted(IEnumerable<EngineTask> tasks, Dictionary<long, Account> accounts, DateTimeOffset now, TimeSpan window, DownloadOrder order)
{
var items = new List<(EngineTask, double)>();
foreach (var task in tasks)
{
// The visit of a profile not followed whose stories are due is story work (spec §7.2): it weighs as stories.
var kind = task.Kind == EngineTaskKind.ProfileCheck && IsStoryWork(task, accounts, now)
? DownloadKind.Stories
: DownloadOrder.KindOf(task.Kind);
var kindWeight = kind is { } k ? order.Weight(k) : 1;
if (task.AccountId is { } id && accounts.TryGetValue(id, out var account))
{
var interval = task.Kind == EngineTaskKind.AccountStories
? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay)
: VisitInterval(account, window);
items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval)));
items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval) * kindWeight));
}
else
{
items.Add((task, 2));
items.Add((task, 2 * kindWeight));
}
}
@@ -907,6 +907,7 @@ internal sealed class SessionComposer
}
state.Recipes++;
var startedAt = Clock.Now;
_s.Runtime.Activity = ActivityText(request.Kind, account);
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
RecipeOutcome outcome;
@@ -946,7 +947,7 @@ internal sealed class SessionComposer
await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false);
await ApplyOutcomeAsync(task, request, account, outcome, state, startedAt).ConfigureAwait(false);
}
finally
{
@@ -978,7 +979,7 @@ internal sealed class SessionComposer
}
}
private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state)
private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state, DateTimeOffset startedAt)
{
// Bookkeeping always completes, even when the session has just been cancelled. Independent writes are queued
// together (the single writer keeps their order and commits them in one transaction).
@@ -1132,7 +1133,7 @@ internal sealed class SessionComposer
}
var (title, detail) = Describe(kind, account, outcome);
_recent.Add(new RecentAction(now, kind, account?.Id, title, detail, outcome.Status, outcome.NewEntries));
_recent.Add(new RecentAction(now, kind, account?.Id, title, detail, outcome.Status, outcome.NewEntries, startedAt));
var severity = outcome.Status switch
{
RecipeStatus.Completed => outcome.NewEntries > 0 ? EventSeverity.Success : EventSeverity.Info,
+9
View File
@@ -60,6 +60,12 @@ public interface IEntryStore
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
/// <summary>
/// What a recipe saved (spec §7.9, thumbnails of the history of the Dashboard): the entries of the account discovered
/// in [from, to], newest first, at most <paramref name="limit"/>, with how many there are in all.
/// </summary>
Task<ArrivedEntries> ListDiscoveredAsync(long accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default);
/// <summary>Entries of (account, kind) discovered in [from, to): per-account daily backfill limit.</summary>
Task<int> CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default);
@@ -74,3 +80,6 @@ public interface IEntryStore
/// <summary>Tiles for given entries, in the given order (e.g. the items of a highlight collection).</summary>
Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
}
/// <summary>Entries saved by a recipe: the first ones, newest first, and how many in all.</summary>
public sealed record ArrivedEntries(IReadOnlyList<long> EntryIds, int Total);
+7
View File
@@ -30,6 +30,13 @@ public interface IMediaStore
/// </summary>
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, CancellationToken ct = default);
/// <summary>
/// Files waiting to be downloaded in the order of «Cosa scaricare prima» (spec §6.5, §7.2): the files of the entry kind
/// that comes first in <paramref name="kindOrder"/>, then the other kinds in that order, and within a kind the ones
/// that expire first, then the oldest waiting. A kind left out of the list goes last.
/// </summary>
Task<IReadOnlyList<PendingDownload>> ListPendingDownloadsAsync(int limit, IReadOnlyList<EntryKind> kindOrder, CancellationToken ct = default);
/// <summary>Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»).</summary>
Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default);