Files
Chronos/src/Chronos.App/Jobs/JobListModel.cs
T
Alby96andClaude Opus 5.5 b95bc997d5 feat(jobs): show what mass passes do now on the desktop, the server section and the admin panel
A running job now says what it does now: "Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41". A paused or
failed job says where it stopped. The line appears in the Jobs table under the target, in the job bar (at most 60
characters, the item dropped first, the bar text also its tooltip), in the Archive's recent maintenance (refreshed at
most twice a second), in the editor's server-job line and in the sync tooltip. Byte jobs now count sizes in the bar.

While connected, the Server section lists the server's running and paused jobs, live through the jobs API and the
jobProgress events. Pause, Resume and Cancel are offered only to an account that manages the archive, which is what
the server requires to act on someone else's job; for any other account the list is read-only. The list hides while
nothing runs, and the capture gains a server-jobs scene.

The admin panel's Jobs page and dashboard show the same line under the target and update it with every progress event.
The steps, parts and sub-steps are in English and Italian, and an unknown step shows its counts only.

Refs #65

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:42:47 +01:00

185 lines
8.4 KiB
C#

using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.App.Jobs;
/// <summary>Filter chips of the Jobs screen (BRIEF §12.6).</summary>
public enum JobFilter
{
All,
Running,
Queued,
Done,
Failed,
}
/// <summary>One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs.</summary>
public sealed class JobEntry(Job job)
{
public Job Job { get; internal set; } = job;
/// <summary>Latest progress event of the running job; null once it stops.</summary>
public JobProgressInfo? Live { get; internal set; }
/// <summary><see cref="JobListModel.Stamp"/> of the last update.</summary>
internal long Stamp { get; set; }
public Guid Id => Job.Id;
public JobState State => Job.State;
public long Done => Live?.Done ?? Job.ProgressDone;
public long Total => Live?.Total ?? Job.ProgressTotal;
public double? ItemsPerSecond => Live?.ItemsPerSecond ?? Job.ItemsPerSecond;
public TimeSpan? Eta => Live?.Eta ?? Job.Eta;
public string? Message => Live?.Message;
/// <summary>
/// What the job does now (owner review 5, #65): the live detail while it runs, else the one stored with its last saved
/// progress (where a paused or failed job stopped); null when its handler reports none.
/// </summary>
public JobDetail? Detail => Live?.Detail ?? Job.Detail;
/// <summary>0…1, or null while the total is unknown.</summary>
public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null;
public bool IsFinished => State is JobState.Done or JobState.Failed or JobState.Cancelled;
}
/// <summary>
/// The job list behind the Jobs screen and the job bar: merges stored snapshots (<see cref="JobEngine.JobChanged"/>,
/// repository pages) with live progress (<see cref="JobEngine.Progress"/>), keeps queue order and answers the
/// filters. WPF-free and not thread-safe; feed it on the UI thread (through <see cref="JobUpdateBuffer"/>).
/// </summary>
public sealed class JobListModel
{
private readonly Dictionary<Guid, JobEntry> _entries = [];
private long _stamp;
public int Count => _entries.Count;
public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id);
/// <summary>
/// Change counter. Read it before requesting a page from the database and pass it to <see cref="ApplyLoaded"/>,
/// so a page that was read before an event cannot overwrite the newer state the event brought.
/// </summary>
public long Stamp => _stamp;
/// <summary>The priority queue the engine claims jobs by, which orders the queue here too (<see cref="JobPriorityQueue.ClaimsBefore"/>).</summary>
public JobPriorityQueue PriorityQueue { get; set; } = JobPriorityQueue.Off;
/// <summary>Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed.</summary>
public bool Apply(Job job) => Store(job, ++_stamp);
/// <summary>Inserts a snapshot read from the database; skipped when an event updated the job after <paramref name="readAt"/>.</summary>
public bool ApplyLoaded(Job job, long readAt)
{
if (_entries.TryGetValue(job.Id, out var entry) && entry.Stamp > readAt) return false;
return Store(job, readAt);
}
private bool Store(Job job, long stamp)
{
if (!_entries.TryGetValue(job.Id, out var entry))
{
_entries[job.Id] = new JobEntry(job) { Stamp = stamp };
return true;
}
entry.Stamp = Math.Max(entry.Stamp, stamp);
if (entry.Job == job) return false;
entry.Job = job;
if (job.State != JobState.Running) entry.Live = null;
return true;
}
/// <summary>Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed.</summary>
public bool Apply(JobProgressInfo progress)
{
if (!_entries.TryGetValue(progress.JobId, out var entry) || entry.State != JobState.Running) return false;
if (entry.Live == progress) return false;
entry.Live = progress;
return true;
}
/// <summary>Removes jobs no longer present (e.g. purged history).</summary>
public bool Remove(Guid id) => _entries.Remove(id);
/// <summary>
/// Display order: running (oldest start first), paused, queued in the order the engine claims them (the level of the
/// priority queue while it is on, priority, then age), then the history, newest finish first. Finished jobs before
/// <paramref name="clearedBefore"/> are hidden.
/// </summary>
public IReadOnlyList<JobEntry> Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null)
{
var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim();
return _entries.Values
.Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text)))
.OrderBy(Group)
.ThenBy(e => e.State == JobState.Queued && PriorityQueue.Enabled ? -(int)PriorityQueue.LevelOf(e.Job.Kind) : 0)
.ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0)
.ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks)
.ThenBy(e => e.Job.Created)
.ThenBy(e => e.Id)
.ToList();
}
/// <summary>Jobs per filter chip (after "Clear done").</summary>
public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) =>
_entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore));
/// <summary>1-based place of a queued job in the order workers claim jobs; 0 when it is not queued.</summary>
public int QueuePosition(Guid id)
{
if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0;
return _entries.Values.Count(e => e.State == JobState.Queued && PriorityQueue.ClaimsBefore(e.Job, entry.Job)) + 1;
}
/// <summary>The job the job bar mirrors: the running job with the most recent progress, else the first running one.</summary>
public JobEntry? Current =>
_entries.Values.Where(e => e.State == JobState.Running)
.OrderByDescending(e => e.Live is not null)
.ThenBy(e => (e.Job.Started ?? e.Job.Created).UtcTicks)
.FirstOrDefault();
public int RunningCount => _entries.Values.Count(e => e.State == JobState.Running);
/// <summary>Running jobs claimed by this machine's workers (<paramref name="localWorkerId"/>), not by render nodes or other PCs.</summary>
public int RunningOn(string localWorkerId) => _entries.Values.Count(e => e.State == JobState.Running && JobText.IsLocal(e.Job.NodeId, localWorkerId));
public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued);
/// <summary>
/// A job of <paramref name="kind"/> that the user waits for (not background work) is queued or running. Paused jobs
/// do not count: they wait for the user, or for an unmetered network, not for the queue.
/// </summary>
public bool IsBusy(JobKind kind) =>
_entries.Values.Any(e => e.Job.Kind == kind && e.Job.Priority != JobPriority.Background && e.State is JobState.Queued or JobState.Running);
/// <summary>Same order as <c>JobRepository.ClaimNextAsync</c> with the priority queue off: priority descending, then creation time and id.</summary>
public static bool ClaimsBefore(Job a, Job b) => JobPriorityQueue.Off.ClaimsBefore(a, b);
private static int Group(JobEntry e) => e.State switch
{
JobState.Running => 0,
JobState.Paused => 1,
JobState.Queued => 2,
_ => 3,
};
private static bool Matches(JobEntry e, JobFilter filter) => filter switch
{
JobFilter.Running => e.State is JobState.Running or JobState.Paused,
JobFilter.Queued => e.State == JobState.Queued,
JobFilter.Done => e.State == JobState.Done,
JobFilter.Failed => e.State is JobState.Failed or JobState.Cancelled,
_ => true,
};
private static bool Visible(JobEntry e, DateTimeOffset? clearedBefore) =>
clearedBefore is null || !e.IsFinished || (e.Job.Finished ?? e.Job.Created) > clearedBefore;
private static bool MatchesText(JobEntry e, string text) =>
(e.Job.TargetLabel?.Contains(text, StringComparison.CurrentCultureIgnoreCase) ?? false)
|| JobText.Kind(e.Job.Kind).Contains(text, StringComparison.CurrentCultureIgnoreCase);
}