diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 019960a6..08b9c1ad 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -1193,4 +1193,57 @@ Show the videos of every sequence; the other filters stay Videos folder Where Copy to folder puts videos (the /videos volume in Docker); empty turns copying off + Listing folders + Checking + Indexing + Indexing photo {0} of {1} + Verifying + Verifying photo {0} of {1} + Drawing thumbnails + Thumbnail {0} of {1} + Making proxies + Proxy {0} of {1} + Analysing + Analysing photo {0} of {1} + Converting + Converting photo {0} of {1} + Replacing photos + Replacing photo {0} of {1} + Reorganizing + Copying photos + Copying photo {0} of {1} + Copying proxies + Copying proxy {0} of {1} + Copying originals + Copying original {0} of {1} + Copying video + Encoding + Encoding frame {0} of {1} + Uploading + Uploading photo {0} of {1} + Downloading + Downloading photo {0} of {1} + Erasing + Copying the index + Cleaning up + Maintenance + Queueing follow-ups + Processing + Processing photo {0} of {1} + Clearing stale leases + Removing temporary files + Compacting thumbnails + Flagging duplicates + Compacting the index + sequence {0} of {1} + folder {0} of {1} + video {0} of {1} + entry {0} of {1} + step {0} of {1} + {0} of {1} + Stopped at {0} + {0} fps + {0}/s + {0}/s + {0} left diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx index 53258a0a..007992f3 100644 --- a/i18n/en/Jobs.resx +++ b/i18n/en/Jobs.resx @@ -207,4 +207,53 @@ no media to remove just copied Copy videos + Listing folders + Checking + Indexing + Indexing photo {0} of {1} + Verifying + Verifying photo {0} of {1} + Drawing thumbnails + Thumbnail {0} of {1} + Making proxies + Proxy {0} of {1} + Analysing + Analysing photo {0} of {1} + Converting + Converting photo {0} of {1} + Replacing photos + Replacing photo {0} of {1} + Reorganizing + Copying photos + Copying photo {0} of {1} + Copying proxies + Copying proxy {0} of {1} + Copying originals + Copying original {0} of {1} + Copying video + Encoding + Encoding frame {0} of {1} + Uploading + Uploading photo {0} of {1} + Downloading + Downloading photo {0} of {1} + Erasing + Copying the index + Cleaning up + Maintenance + Queueing follow-ups + Processing + Processing photo {0} of {1} + Clearing stale leases + Removing temporary files + Compacting thumbnails + Flagging duplicates + Compacting the index + sequence {0} of {1} + folder {0} of {1} + video {0} of {1} + entry {0} of {1} + step {0} of {1} + {0} of {1} + Stopped at {0} diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 16dd7563..986c389d 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -129,6 +129,8 @@ The current password is wrong.long This upload belongs to a render job.long Servers found + Job not changed + Server jobs Keep proxies offline Account Server diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 3be6f60e..4a8fba67 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -692,6 +692,8 @@ SHA-256 fingerprint of the server certificate Forget this certificate; the next connection asks again Servers found on this network and used before + What runs or waits paused on the server now; pause, resume or cancel any of them + What runs or waits paused on the server now; only an account that manages the archive can pause or cancel them Keep the proxies of the server sequences you opened with proxies up to date on this PC, to edit without the originals; uses space in the cache folderlong Keep trusting this certificate Close without signing in · Esc diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index e7032d65..96ebc21d 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -1185,4 +1185,57 @@ Mostra i video di tutte le sequenze; gli altri filtri restano Cartella video Dove Copia in cartella mette i video (il volume /videos in Docker); vuota disattiva la copia + Elenco cartelle + Controllo + Indicizzazione + Indicizzazione foto {0} di {1} + Verifica + Verifica foto {0} di {1} + Creazione miniature + Miniatura {0} di {1} + Creazione proxy + Proxy {0} di {1} + Analisi + Analisi foto {0} di {1} + Conversione + Conversione foto {0} di {1} + Sostituzione foto + Sostituzione foto {0} di {1} + Riorganizzazione + Copia foto + Copia foto {0} di {1} + Copia proxy + Copia proxy {0} di {1} + Copia originali + Copia originale {0} di {1} + Copia video + Codifica + Codifica fotogramma {0} di {1} + Invio + Invio foto {0} di {1} + Download + Download foto {0} di {1} + Eliminazione + Copia dell'indice + Pulizia + Manutenzione + Accodamento seguiti + Elaborazione + Elaborazione foto {0} di {1} + Pulizia lease scaduti + Rimozione file temporanei + Compattazione miniature + Marcatura duplicati + Compattazione indice + sequenza {0} di {1} + cartella {0} di {1} + video {0} di {1} + voce {0} di {1} + passo {0} di {1} + {0} di {1} + Fermo a {0} + {0} fps + {0}/s + {0}/s + {0} rimanenti diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx index 7a70891f..2fd006cd 100644 --- a/i18n/it/Jobs.it.resx +++ b/i18n/it/Jobs.it.resx @@ -205,4 +205,53 @@ nessun media da rimuovere appena copiato Copia video + Elenco cartelle + Controllo + Indicizzazione + Indicizzazione foto {0} di {1} + Verifica + Verifica foto {0} di {1} + Creazione miniature + Miniatura {0} di {1} + Creazione proxy + Proxy {0} di {1} + Analisi + Analisi foto {0} di {1} + Conversione + Conversione foto {0} di {1} + Sostituzione foto + Sostituzione foto {0} di {1} + Riorganizzazione + Copia foto + Copia foto {0} di {1} + Copia proxy + Copia proxy {0} di {1} + Copia originali + Copia originale {0} di {1} + Copia video + Codifica + Codifica fotogramma {0} di {1} + Invio + Invio foto {0} di {1} + Download + Download foto {0} di {1} + Eliminazione + Copia dell'indice + Pulizia + Manutenzione + Accodamento seguiti + Elaborazione + Elaborazione foto {0} di {1} + Pulizia lease scaduti + Rimozione file temporanei + Compattazione miniature + Marcatura duplicati + Compattazione indice + sequenza {0} di {1} + cartella {0} di {1} + video {0} di {1} + voce {0} di {1} + passo {0} di {1} + {0} di {1} + Fermo a {0} diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 7002d187..264fc26b 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -127,6 +127,8 @@ La password attuale è errata. Questo caricamento appartiene a un job di rendering. Server trovati + Lavoro non modificato + Lavori del server Proxy disponibili offline Account Server diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 4a6a5ca8..bdcb1a80 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -762,6 +762,8 @@ Impronta SHA-256 del certificato del server Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo Server trovati in questa rete e usati in precedenza + Ciò che il server esegue o tiene in pausa ora; metti in pausa, riprendi o annulla qualsiasi lavoro + Ciò che il server esegue o tiene in pausa ora; solo un account che gestisce l'archivio può metterli in pausa o annullarli Mantieni aggiornati su questo PC i proxy delle sequenze del server aperte con i proxy, per lavorare senza gli originali; usa spazio nella cartella cache Continua a considerare attendibile questo certificato Chiude senza accedere · Esc diff --git a/src/Chronos.App/Archive/MaintenanceReports.cs b/src/Chronos.App/Archive/MaintenanceReports.cs index 06ac494a..527a94ad 100644 --- a/src/Chronos.App/Archive/MaintenanceReports.cs +++ b/src/Chronos.App/Archive/MaintenanceReports.cs @@ -3,6 +3,7 @@ using Chronos.App.Jobs; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Data.Archiving; +using Chronos.Data.Jobs; using Chronos.Data.Repositories; using Chronos.Ui.Controls; @@ -30,9 +31,15 @@ public enum OrphanKind /// One line of the orphans report and the target of its fix. public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId); -/// A line of "Recent maintenance": date, operation and outcome. -public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State) +/// +/// A line of "Recent maintenance": date, operation and outcome; , the muted second line of a running +/// job (what it does now) or of a paused or failed one (where it stopped), owner review 5, #65; empty otherwise, with +/// the line whole plus the speed and time left. +/// +public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State, string Detail = "", string DetailToolTip = "") { + public bool HasDetail => Detail.Length > 0; + /// The outcome's glyph and colour, as on the Jobs screen (paired with the word, never colour alone). public StatusKind StateKind => State switch { @@ -102,18 +109,23 @@ public static class MaintenanceReports return rows; } - public static IReadOnlyList Recent(IEnumerable jobs, int count) => + /// + /// The latest jobs as "Recent maintenance" lines; a running one shows its percentage and what it + /// does now from its progress when there is some (owner review 5, #65), else from its stored snapshot. + /// + public static IReadOnlyList Recent(IEnumerable jobs, int count, IReadOnlyDictionary? live = null) => [ .. jobs.OrderByDescending(j => j.Finished ?? j.Started ?? j.Created).Take(count).Select(j => { var when = j.Finished ?? j.Started ?? j.Created; var text = string.IsNullOrWhiteSpace(j.TargetLabel) ? JobText.Kind(j.Kind) : Loc.L("Archive.Recent.Line", JobText.Kind(j.Kind), j.TargetLabel); + var entry = new JobEntry(j) { Live = j.State == JobState.Running ? live?.GetValueOrDefault(j.Id) : null }; var state = j.State switch { - JobState.Running when j.ProgressTotal > 0 => Formatting.Percent(j.ProgressDone / (double)j.ProgressTotal), + JobState.Running when entry.Fraction is { } fraction => Formatting.Percent(fraction), _ => Loc.L("Jobs.State." + j.State), }; - return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State); + return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State, JobText.RowStatus(entry), JobText.RowStatusToolTip(entry)); }), ]; } diff --git a/src/Chronos.App/DesignTime/SampleJobDetails.cs b/src/Chronos.App/DesignTime/SampleJobDetails.cs new file mode 100644 index 00000000..83129e2c --- /dev/null +++ b/src/Chronos.App/DesignTime/SampleJobDetails.cs @@ -0,0 +1,36 @@ +using Chronos.Core.Model; + +namespace Chronos.App.DesignTime; + +/// +/// What the sample's running and paused jobs do now (owner review 5, #65), for the design view, the screenshots and the +/// visual tests: a pass over many photos says which photo of which sequence; a job of another kind, or one that is queued or +/// finished, is left as it is. +/// +public static class SampleJobDetails +{ + /// with the sample detail of its kind while it runs or is paused; unchanged otherwise. + public static Job Apply(Job job) + { + ArgumentNullException.ThrowIfNull(job); + if (job.State is not (JobState.Running or JobState.Paused) || job.Detail is not null) return job; + var title = string.IsNullOrWhiteSpace(job.TargetLabel) ? null : job.TargetLabel; + JobDetail? detail = job.Kind switch + { + JobKind.Scan or JobKind.Rebuild => new JobDetail(JobStep.Index, "2024/2024-09-27 Harbour sunset", 1_240, 3_600, 12, 340, JobPartUnit.Folder), + JobKind.Verify => new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence), + JobKind.Thumbs => new JobDetail(JobStep.Thumbs, title, 1_240, 3_600, 2, 7, JobPartUnit.Sequence), + JobKind.Proxies => new JobDetail(JobStep.Proxies, title, 1_240, 3_600, 2, 7, JobPartUnit.Sequence), + JobKind.LightAnalyse => new JobDetail(JobStep.Analyse, title, Part: 120, Parts: 4_812, PartUnit: JobPartUnit.Sequence), + JobKind.DeepAnalyse => new JobDetail(JobStep.Analyse, title, job.ProgressDone, job.ProgressTotal), + JobKind.Render or JobKind.WorkspaceRender => new JobDetail(JobStep.Encode, null, job.ProgressDone, job.ProgressTotal), + JobKind.Convert => new JobDetail(JobStep.Convert, title, 412, 1_200, 4, 9, JobPartUnit.Sequence), + JobKind.Import => new JobDetail(JobStep.CopyPhoto, "IMG_4812.CR3", 1_240, 4_812), + JobKind.UploadCommit => new JobDetail(JobStep.Upload, title, job.ProgressDone, job.ProgressTotal), + JobKind.Download => new JobDetail(JobStep.Download, title, job.ProgressDone, job.ProgressTotal), + JobKind.Maintenance => new JobDetail(JobStep.Maintenance, "packs", Part: 3, Parts: 5, PartUnit: JobPartUnit.Step), + _ => null, + }; + return detail is null ? job : job with { Detail = detail }; + } +} diff --git a/src/Chronos.App/DesignTime/SampleServerJobs.cs b/src/Chronos.App/DesignTime/SampleServerJobs.cs new file mode 100644 index 00000000..938ca1f2 --- /dev/null +++ b/src/Chronos.App/DesignTime/SampleServerJobs.cs @@ -0,0 +1,89 @@ +using System.Runtime.CompilerServices; +using Chronos.App.Server; +using Chronos.Core.Model; +using Chronos.Data.Jobs; +using Chronos.Protocol; + +namespace Chronos.App.DesignTime; + +/// +/// The sample server's jobs for the Server section's job list (owner review 5, #65), for the screenshots: empty until +/// , then a verification and a thumbnail pass running with what each does now, and a proxy pass paused. +/// Pause, resume and cancel change the list; no event ever comes. Thread-safe; disposing it does nothing, so it can be reused. +/// +public sealed class SampleServerJobs : IServerJobsApi +{ + private readonly Lock _gate = new(); + private List _jobs = []; + + /// The sample's running and paused jobs. + public void Fill() + { + var now = SampleData.Now; + lock (_gate) + { + _jobs = + [ + Job(JobKind.Verify, "Harbour sunset", JobState.Running, 812, 2_400, 38.5, 41, now.AddMinutes(-6), + new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence)), + Job(JobKind.Thumbs, "Sunrise over Superga", JobState.Running, 1_240, 3_600, 52.0, 45, now.AddMinutes(-3), + new JobDetail(JobStep.Thumbs, "Sunrise over Superga", 1_240, 3_600, 2, 7, JobPartUnit.Sequence)), + Job(JobKind.Proxies, "Alpine lake, winter", JobState.Paused, 300, 1_800, null, null, now.AddMinutes(-40), + new JobDetail(JobStep.Proxies, "Alpine lake, winter", 300, 1_800, 1, 2, JobPartUnit.Sequence)), + ]; + } + } + + /// Nothing runs on the server again. + public void Clear() + { + lock (_gate) _jobs = []; + } + + public Task> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken) + { + lock (_gate) + { + var items = _jobs.Where(j => j.State == state).ToList(); + return Task.FromResult(new Page(items, null, items.Count)); + } + } + + public Task GetJobAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) return Task.FromResult(_jobs.Single(j => j.Id == id)); + } + + public Task PauseJobAsync(Guid id, CancellationToken cancellationToken) => SetState(id, JobState.Paused); + + public Task ResumeJobAsync(Guid id, CancellationToken cancellationToken) => SetState(id, JobState.Running); + + public Task CancelJobAsync(Guid id, CancellationToken cancellationToken) => SetState(id, JobState.Cancelled); + + public async IAsyncEnumerable EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + yield break; + } + + public void Dispose() + { + } + + private Task SetState(Guid id, JobState state) + { + lock (_gate) + { + var index = _jobs.FindIndex(j => j.Id == id); + var job = _jobs[index] with { State = JobWire.State(state) }; + if (state is JobState.Running or JobState.Paused) _jobs[index] = job; + else _jobs.RemoveAt(index); + return Task.FromResult(job); + } + } + + private static JobDto Job(JobKind kind, string target, JobState state, long done, long total, double? rate, double? eta, DateTimeOffset started, + JobDetail detail) => + new(Guid.NewGuid(), JobWire.Kind(kind), [Guid.NewGuid()], target, JobWire.State(state), JobWire.Priority(JobPriority.Background), done, total, + rate, eta, null, null, 1, null, started, started, null, null, JobWire.Detail(detail)); +} diff --git a/src/Chronos.App/Editor/EditorText.cs b/src/Chronos.App/Editor/EditorText.cs index 273f2af3..ce5e6998 100644 --- a/src/Chronos.App/Editor/EditorText.cs +++ b/src/Chronos.App/Editor/EditorText.cs @@ -44,7 +44,10 @@ public static class EditorText }; } - /// "Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left"; "Render waiting on Studio NAS". + /// + /// "Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left"; with what the job does now in place of the + /// counter ("… · Encoding frame 1,240 of 3,600 · 11.3 fps · 3 min left", owner review 5, #65); "Render waiting on Studio NAS". + /// public static string ServerJobDetail(Job job, string server) { ArgumentNullException.ThrowIfNull(job); @@ -55,7 +58,8 @@ public static class EditorText _ => "Tooltips.Editor.ServerJob", }; var parts = new List { Loc.L(key, JobText.Kind(job.Kind), server) }; - if (JobText.Counter(job.ProgressDone, job.ProgressTotal) is { Length: > 0 } counter) parts.Add(counter); + if (job.State == JobState.Running && JobText.Status(job.Detail) is { Length: > 0 } status) parts.Add(status); + else if (JobText.Counter(job.Kind, job.ProgressDone, job.ProgressTotal) is { Length: > 0 } counter) parts.Add(counter); if (JobText.Speed(job.Kind, job.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed); if (job.Eta is { } eta) parts.Add(Loc.L("Editor.ServerJob.Left", Formatting.Duration(eta))); return string.Join(Separator, parts); diff --git a/src/Chronos.App/Editor/ServerJobs.cs b/src/Chronos.App/Editor/ServerJobs.cs index 90f779c1..cbad697c 100644 --- a/src/Chronos.App/Editor/ServerJobs.cs +++ b/src/Chronos.App/Editor/ServerJobs.cs @@ -180,6 +180,8 @@ internal sealed class ServerJobs : IAsyncDisposable ProgressTotal = progress.Total, ItemsPerSecond = progress.ItemsPerSecond, Eta = JobEta.FromSeconds(progress.EtaSeconds), + // What it does now (owner review 5, #65); an older server sends none, and the last one stays. + Detail = JobWire.FromDto(progress.Detail) ?? job.Detail, }); break; case JobProgressEvent: diff --git a/src/Chronos.App/Jobs/JobListModel.cs b/src/Chronos.App/Jobs/JobListModel.cs index 34f91ecc..fe87772b 100644 --- a/src/Chronos.App/Jobs/JobListModel.cs +++ b/src/Chronos.App/Jobs/JobListModel.cs @@ -32,6 +32,12 @@ public sealed class JobEntry(Job job) public TimeSpan? Eta => Live?.Eta ?? Job.Eta; public string? Message => Live?.Message; + /// + /// 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. + /// + public JobDetail? Detail => Live?.Detail ?? Job.Detail; + /// 0…1, or null while the total is unknown. public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null; diff --git a/src/Chronos.App/Jobs/JobRowViewModel.cs b/src/Chronos.App/Jobs/JobRowViewModel.cs index 4d7e3f53..459522cf 100644 --- a/src/Chronos.App/Jobs/JobRowViewModel.cs +++ b/src/Chronos.App/Jobs/JobRowViewModel.cs @@ -36,6 +36,17 @@ public sealed class JobRowViewModel : ObservableObject public string Target => _entry.Job.TargetLabel ?? string.Empty; + /// + /// What a running job does now, or where a paused or failed job stopped (owner review 5, #65), under the target; empty + /// otherwise. Not announced: a screen reader hears state changes only (DECISIONS row 158). + /// + public string StatusText => JobText.RowStatus(_entry); + + public bool HasStatus => StatusText.Length > 0; + + /// The status line whole, then the speed and time left of a running job. + public string StatusToolTip => JobText.RowStatusToolTip(_entry); + /// A schedule queued the job (owner review 2, R10): the row shows a "Scheduled" pill. public bool IsScheduled => _entry.Job.ScheduleId is not null; @@ -136,6 +147,9 @@ public sealed class JobRowViewModel : ObservableObject return; } OnPropertyChanged(nameof(Progress)); + OnPropertyChanged(nameof(StatusText)); + OnPropertyChanged(nameof(HasStatus)); + OnPropertyChanged(nameof(StatusToolTip)); OnPropertyChanged(nameof(PercentText)); OnPropertyChanged(nameof(SpeedText)); OnPropertyChanged(nameof(LeftText)); diff --git a/src/Chronos.App/Jobs/JobText.cs b/src/Chronos.App/Jobs/JobText.cs index d748456b..c6064590 100644 --- a/src/Chronos.App/Jobs/JobText.cs +++ b/src/Chronos.App/Jobs/JobText.cs @@ -29,6 +29,141 @@ public static class JobText public static string Counter(long done, long total) => total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty; + /// "1,240 / 3,600", or "52 GB / 1.1 TB" for a job that counts bytes; empty while the total is unknown. + public static string Counter(JobKind kind, long done, long total) => total <= 0 ? string.Empty + : CountsBytes(kind) ? Loc.L("Jobs.Counter", Formatting.Bytes(done), Formatting.Bytes(total)) + : Counter(done, total); + + /// The longest status line the job bar shows (); the item goes first, the full line is in the Jobs table. + public const int BarStatusLength = 60; + + /// + /// What a job does now (owner review 5, #65), from its : the step ("Verifying photo 812 of 2,400"), + /// the item ("Harbour sunset", a folder kept left to right) and the part ("sequence 3 of 41"), each left out when empty; + /// a clean-up or maintenance sub-step names itself in place of the step. A step this build does not know (a newer server) + /// shows its counts only. Empty for no detail. + /// + public static string Status(JobDetail? detail) => Status(detail, int.MaxValue); + + /// + /// in at most characters: a longer line drops the item + /// first, then is cut with an ellipsis. + /// + public static string Status(JobDetail? detail, int maxLength) + { + if (detail is null) return string.Empty; + var (step, consumed) = StepPhrase(detail); + var item = consumed ? null : ItemText(detail.Item); + var part = PartPhrase(detail); + var full = JoinParts(step, item, part); + if (full.Length <= maxLength) return full; + if (item is not null && JoinParts(step, null, part) is { Length: > 0 } shorter) full = shorter; + return Cut(full, maxLength); + } + + /// + /// The status line of a Jobs row: what a running job does now; "Stopped at …" with where a paused or failed job stopped; + /// empty for queued and finished jobs, and for a job whose handler reports no detail. + /// + public static string RowStatus(JobEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + return entry.State switch + { + JobState.Running => Status(entry.Detail), + JobState.Paused or JobState.Failed when Status(entry.Job.Detail) is { Length: > 0 } status => Loc.L("Jobs.Detail.StoppedAt", status), + _ => string.Empty, + }; + } + + /// The tooltip of a row's status line: the line whole, then the speed and the time left while the job runs. + public static string RowStatusToolTip(JobEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + var parts = new List(3); + if (RowStatus(entry) is { Length: > 0 } status) parts.Add(status); + if (entry.State == JobState.Running) + { + if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed); + if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta))); + } + return string.Join(Loc.Separator, parts); + } + + /// + /// The step phrase, counted when the item is ("Verifying photo 812 of 2,400"), and whether it took the item's place (the + /// named sub-step of a clean-up or maintenance). + /// + private static (string? Phrase, bool ConsumedItem) StepPhrase(JobDetail detail) + { + var counted = detail.ItemTotal > 0; + var done = Formatting.Count(Math.Clamp(detail.ItemDone, 0, detail.ItemTotal)); + var total = Formatting.Count(detail.ItemTotal); + var counts = counted ? Loc.L("Jobs.Detail.Count", done, total) : null; + // A clean-up step ("job-history") and a maintenance step ("packs") name themselves. + var named = detail.Step switch + { + JobStep.Cleanup => Known("Jobs.Schedule.Step." + Pascal(detail.Item)), + JobStep.Maintenance => Known("Jobs.Maintenance.Step." + Pascal(detail.Item)), + _ => null, + }; + if (named is not null) return (JoinParts(Loc.L(named), counts, null), true); + if (detail.Step == JobStep.None) return (counts, false); + var key = "Jobs.Step." + detail.Step; + // The item of a clean-up or maintenance step is a key, not data: one this build does not know is never shown. + if (detail.Step is JobStep.Cleanup or JobStep.Maintenance) return (JoinParts(Known(key) is { } step ? Loc.L(step) : null, counts, null), true); + if (counted && Known(key + ".Count") is { } countKey) return (Loc.L(countKey, done, total), false); + if (Known(key) is null) return (counts, false); + return (JoinParts(Loc.L(key), counts, null), false); + } + + /// "sequence 3 of 41" when the job has more than one part; null otherwise. + private static string? PartPhrase(JobDetail detail) + { + if (detail.Parts <= 1) return null; + var part = Formatting.Count(Math.Clamp(detail.Part, 0, detail.Parts)); + var parts = Formatting.Count(detail.Parts); + return detail.PartUnit != JobPartUnit.None && Known("Jobs.Part." + detail.PartUnit) is { } key + ? Loc.L(key, part, parts) + : Loc.L("Jobs.Detail.Count", part, parts); + } + + /// The item as data: a folder or a path kept left to right inside right-to-left text (DECISIONS row 218). + private static string? ItemText(string? item) + { + if (string.IsNullOrWhiteSpace(item)) return null; + return item.Contains('/') || item.Contains('\\') ? Formatting.LeftToRight(item) : item; + } + + /// "job-history" → "JobHistory"; null for a key that is not one (data from a newer peer). + private static string? Pascal(string? key) + { + if (string.IsNullOrEmpty(key) || key.Length > 40 || !key.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')) return null; + return string.Concat(key.Split('-', '_', StringSplitOptions.RemoveEmptyEntries).Select(p => char.ToUpperInvariant(p[0]) + p[1..])); + } + + /// The key when the catalog has it (the step, unit or sub-step of a newer peer may have none); null otherwise. + private static string? Known(string? key) => key is not null && !key.EndsWith('.') && Loc.Get(key, Loc.Culture) is not null ? key : null; + + private static string JoinParts(string? a, string? b, string? c) + { + var pieces = new List(3); + if (!string.IsNullOrEmpty(a)) pieces.Add(a); + if (!string.IsNullOrEmpty(b)) pieces.Add(b); + if (!string.IsNullOrEmpty(c)) pieces.Add(c); + return string.Join(Loc.Separator, pieces); + } + + /// Cuts to characters with an ellipsis, closing a left-to-right island it cut into. + private static string Cut(string text, int max) + { + if (text.Length <= max) return text; + var length = Math.Max(1, max - 1); + if (char.IsHighSurrogate(text[length - 1])) length--; + var cut = text[..length] + "…"; + return cut.Count(c => c == '‪') > cut.Count(c => c == '‬') ? cut + "‬" : cut; + } + /// /// The "Left" column: time left while running, "after n" while queued, the finish time of the history. /// @@ -71,13 +206,17 @@ public static class JobText } /// - /// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left". + /// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left"; with a detail, what the + /// job does now in place of the counter ("Scan · Archive 2024 · Indexing photo 1,240 of 3,600 · folder 12 of 340 · 41/s · + /// 3 min left", at most characters of it); a job that counts bytes shows sizes. /// public static string Bar(JobEntry entry) { + ArgumentNullException.ThrowIfNull(entry); var parts = new List(5) { Kind(entry.Job.Kind) }; if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!); - if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter); + if (Status(entry.Detail, BarStatusLength) is { Length: > 0 } status) parts.Add(status); + else if (Counter(entry.Job.Kind, entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter); if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed); if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta))); return string.Join(Loc.Separator, parts); diff --git a/src/Chronos.App/Sections/ArchiveView.xaml b/src/Chronos.App/Sections/ArchiveView.xaml index 79fa8630..063e4275 100644 --- a/src/Chronos.App/Sections/ArchiveView.xaml +++ b/src/Chronos.App/Sections/ArchiveView.xaml @@ -299,14 +299,20 @@ - + - + + + + + diff --git a/src/Chronos.App/Sections/ArchiveViewModel.cs b/src/Chronos.App/Sections/ArchiveViewModel.cs index 56cc369d..14c5c6ad 100644 --- a/src/Chronos.App/Sections/ArchiveViewModel.cs +++ b/src/Chronos.App/Sections/ArchiveViewModel.cs @@ -34,6 +34,7 @@ namespace Chronos.App.Sections; public sealed class ArchiveViewModel : SectionViewModel { private const int RecentCount = 6; + private static readonly TimeSpan RecentInterval = TimeSpan.FromMilliseconds(500); private const int PageSize = 1000; private static readonly TimeSpan ReloadDelay = TimeSpan.FromSeconds(2); @@ -72,6 +73,13 @@ public sealed class ArchiveViewModel : SectionViewModel private IReadOnlyList _formats = []; private IReadOnlyList _health = []; private IReadOnlyList _recent = []; + + /// The jobs behind , their running ones' latest progress, and the ids whose progress counts here. + private IReadOnlyList _recentJobs = []; + private readonly Dictionary _recentLive = []; + private readonly System.Collections.Concurrent.ConcurrentDictionary _recentPending = new(); + private HashSet _recentRunning = []; + private CoalescingThrottle? _recentThrottle; private IReadOnlyList? _duplicates; private IReadOnlyList? _orphans; private bool _findingDuplicates; @@ -524,7 +532,12 @@ public sealed class ArchiveViewModel : SectionViewModel { _reloadDelay.Stop(); _search?.Cancel(); - if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged; + if (_jobEvents && Services.Jobs is { } jobs) + { + jobs.JobChanged -= OnJobChanged; + jobs.Progress -= OnProgress; + } + _recentThrottle?.Dispose(); _waitingReorganize = null; _dialog?.Dispose(); base.Dispose(); @@ -663,6 +676,10 @@ public sealed class ArchiveViewModel : SectionViewModel foreach (var kind in MaintenanceReports.MaintenanceKinds) jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id))); if (!IsShowing(archive)) return; + _recentJobs = jobs; + _recentLive.Clear(); + _recentPending.Clear(); + Volatile.Write(ref _recentRunning, [.. jobs.Where(j => j.State == JobState.Running).Select(j => j.Id)]); Recent = MaintenanceReports.Recent(jobs, RecentCount); var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null }) .MaxBy(j => j.Finished); @@ -675,9 +692,33 @@ public sealed class ArchiveViewModel : SectionViewModel { if (_jobEvents || Services.Jobs is not { } jobs) return; jobs.JobChanged += OnJobChanged; + // A running Recent line follows its job (owner review 5, #65), at most twice a second. + _recentThrottle = new CoalescingThrottle(RecentInterval, SynchronizationContext.Current, FlushRecent); + jobs.Progress += OnProgress; _jobEvents = true; } + /// Progress of a running job of "Recent maintenance" (any thread): kept until the next flush. + private void OnProgress(JobProgressInfo progress) + { + if (!Volatile.Read(ref _recentRunning).Contains(progress.JobId)) return; + _recentPending[progress.JobId] = progress; + _recentThrottle?.Signal(); + } + + /// The running Recent lines with their latest progress (UI thread). + private void FlushRecent() + { + var changed = false; + foreach (var id in _recentPending.Keys) + { + if (!_recentPending.TryRemove(id, out var progress) || !_recentRunning.Contains(id)) continue; + _recentLive[id] = progress; + changed = true; + } + if (changed) Recent = MaintenanceReports.Recent(_recentJobs, RecentCount, _recentLive); + } + /// /// A finished job on this archive or its sequences changes the figures: read them again once the jobs settle (a /// burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business. diff --git a/src/Chronos.App/Sections/JobsView.xaml b/src/Chronos.App/Sections/JobsView.xaml index d0586c09..35b2a686 100644 --- a/src/Chronos.App/Sections/JobsView.xaml +++ b/src/Chronos.App/Sections/JobsView.xaml @@ -187,13 +187,20 @@ ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}" ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleName}" /> - + - + + + + diff --git a/src/Chronos.App/Sections/ServerView.xaml b/src/Chronos.App/Sections/ServerView.xaml index 3e039e1c..2f8b9af0 100644 --- a/src/Chronos.App/Sections/ServerView.xaml +++ b/src/Chronos.App/Sections/ServerView.xaml @@ -42,9 +42,10 @@ - + + @@ -166,8 +167,11 @@ + + + - + diff --git a/src/Chronos.App/Sections/ServerViewModel.cs b/src/Chronos.App/Sections/ServerViewModel.cs index c2d33220..3ca37e84 100644 --- a/src/Chronos.App/Sections/ServerViewModel.cs +++ b/src/Chronos.App/Sections/ServerViewModel.cs @@ -14,7 +14,8 @@ namespace Chronos.App.Sections; /// /// Server (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with trust-on-first-use and login, /// status (name, version, latency, certificate), account and quota, sign out, the options of this PC (render node, -/// proxies kept offline, automatic project sync, uploads paused on metered networks) and the sync table (). +/// proxies kept offline, automatic project sync, uploads paused on metered networks), the server's running and paused jobs +/// () and the sync table (). /// The rail badge counts the settings conflicts waiting for a choice. /// public sealed class ServerViewModel : SectionViewModel @@ -41,11 +42,19 @@ public sealed class ServerViewModel : SectionViewModel Sync = new SyncTableViewModel(shell); _conflicts = Sync.Chips.Single(c => c.Filter == SyncFilter.Conflicts); _conflicts.PropertyChanged += OnConflictsChanged; + Jobs = new ServerJobsViewModel(() => ServerJobsViewModel.AccountOf(Session), () => JobsConnection(Session), SynchronizationContext.Current, + (title, message) => Shell.Notify(title, message, isError: true)); } /// Sequences of this PC and of the server, where they stand and what can be done. public SyncTableViewModel Sync { get; } + /// The server's running and paused jobs, live (owner review 5, #65). + public ServerJobsViewModel Jobs { get; } + + /// Opens the job list's connection for a session; the screenshots put the sample server's jobs here. + internal Func JobsConnection { get; set; } = ServerJobsViewModel.ConnectionOf; + public ShellViewModel Shell { get; } private ServerSession Session => _session ?? Shell.Services.Server; @@ -212,6 +221,7 @@ public sealed class ServerViewModel : SectionViewModel if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery(); Shell.Settings.Encoders.CollectionChanged += OnEncodersChanged; Sync.Attach(); + Jobs.Refresh(); await _session.RestoreAsync(); if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error, _session.Flow.Address); } @@ -222,6 +232,7 @@ public sealed class ServerViewModel : SectionViewModel if (_session is not null) _session.PropertyChanged -= OnSessionChanged; Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged; Sync.Dispose(); + Jobs.Dispose(); base.Dispose(); } @@ -278,6 +289,7 @@ public sealed class ServerViewModel : SectionViewModel { OnAllPropertiesChanged(); CommandManager.InvalidateRequerySuggested(); + Jobs.Refresh(); } /// The name of a server role, or null for a role this build does not know. diff --git a/src/Chronos.App/Server/ServerJobsApi.cs b/src/Chronos.App/Server/ServerJobsApi.cs new file mode 100644 index 00000000..769aacd5 --- /dev/null +++ b/src/Chronos.App/Server/ServerJobsApi.cs @@ -0,0 +1,44 @@ +using Chronos.Protocol; +using Chronos.Protocol.Client; + +namespace Chronos.App.Server; + +/// +/// What the Server section's job list needs from the signed-in server (owner review 5, #65): its jobs by state, one job, +/// pause, resume and cancel, and its events (, ). Owns its connection. +/// +public interface IServerJobsApi : IDisposable +{ + /// A page of the server's jobs in (a wire name: running, paused…), newest first. + Task> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken); + + Task GetJobAsync(Guid id, CancellationToken cancellationToken); + + Task PauseJobAsync(Guid id, CancellationToken cancellationToken); + + Task ResumeJobAsync(Guid id, CancellationToken cancellationToken); + + Task CancelJobAsync(Guid id, CancellationToken cancellationToken); + + /// Server events until cancelled or the socket closes. + IAsyncEnumerable EventsAsync(CancellationToken cancellationToken); +} + +/// over a signed-in , which it owns. +public sealed class ChronosServerJobsApi(ChronosClient client) : IServerJobsApi +{ + public Task> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken) => + client.ListJobsAsync(state, null, cursor, cancellationToken); + + public Task GetJobAsync(Guid id, CancellationToken cancellationToken) => client.GetJobAsync(id, cancellationToken); + + public Task PauseJobAsync(Guid id, CancellationToken cancellationToken) => client.PauseJobAsync(id, cancellationToken); + + public Task ResumeJobAsync(Guid id, CancellationToken cancellationToken) => client.ResumeJobAsync(id, cancellationToken); + + public Task CancelJobAsync(Guid id, CancellationToken cancellationToken) => client.CancelJobAsync(id, cancellationToken); + + public IAsyncEnumerable EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken); + + public void Dispose() => client.Dispose(); +} diff --git a/src/Chronos.App/Server/ServerJobsView.xaml b/src/Chronos.App/Server/ServerJobsView.xaml new file mode 100644 index 00000000..6f9245a2 --- /dev/null +++ b/src/Chronos.App/Server/ServerJobsView.xaml @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `; @@ -23,6 +23,8 @@ function archiveProblemChip(problem) { export async function render(root, { api, setMeta, actions, onEvent }) { let timer = null; + // The active jobs drawn, by id, so a progress event updates the bar and the status line in place. + let activeJobs = new Map(); const refresh = () => { clearTimeout(timer); timer = setTimeout(load, 1500); @@ -53,6 +55,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) { const uploads = lastThirtyDays(d.uploads); const totalUploads = uploads.reduce((s, u) => s + u.value, 0); const peak = Math.max(0, ...uploads.map((u) => u.value)); + activeJobs = new Map(d.activeJobs.map((j) => [j.id, j])); root.innerHTML = `
@@ -111,7 +114,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
${d.activeJobs.map((j) => `
${escapeHtml(kindLabel(j.kind))} - ${escapeHtml(j.targetLabel ?? "")} + ${targetCell(j)} ${escapeHtml(nodeLabel(j, d.nodes))} ${progressCell(j)}${stateCell(j.state)} ${j.scheduleId ? `` : ""} - ${escapeHtml(j.targetLabel ?? "")} + ${targetCell(j)} ${escapeHtml(nodeLabel(j, nodes))} ${progressCell(j)} ${stateCell(j.state)} @@ -231,8 +231,14 @@ async function renderQueue(root, { api, setMeta, onEvent }, focusJob) { if (job) { job.progressDone = e.done; job.progressTotal = e.total; - const cell = root.querySelector(`[data-key="${CSS.escape(e.jobId)}"] .progress`); + job.itemsPerSecond = e.itemsPerSecond; + job.etaSeconds = e.etaSeconds; + // An older server sends no detail: the line keeps what the list said. + if (e.detail) job.detail = e.detail; + const row = root.querySelector(`[data-key="${CSS.escape(e.jobId)}"]`); + const cell = row?.querySelector(".progress"); if (cell) cell.innerHTML = progressCell(job); + updateStatus(row, job); } } else if (e.type === "jobState" || e.type === "nodeState") { clearTimeout(timer); diff --git a/tests/Chronos.App.Tests/Editor/RemoteSequenceSourceTests.cs b/tests/Chronos.App.Tests/Editor/RemoteSequenceSourceTests.cs index 2340294e..f4babcb7 100644 --- a/tests/Chronos.App.Tests/Editor/RemoteSequenceSourceTests.cs +++ b/tests/Chronos.App.Tests/Editor/RemoteSequenceSourceTests.cs @@ -386,6 +386,35 @@ public sealed class RemoteSequenceSourceTests(TestContext context) Assert.True(api.Disposed, "closing the editor closes its connection"); } + [Test] + public async Task TheServersJobSaysWhatItDoesNow() + { + Loc.SetCulture(System.Globalization.CultureInfo.GetCultureInfo("en")); + var (source, api, _) = Open(); + await using (source) + { + await source.LoadAsync(context.Cancellation); + var seen = new List(); + source.JobChanged += job => + { + lock (seen) seen.Add(job); + }; + var id = Guid.CreateVersion7(); + api.Jobs[id] = api.Job(id, "render", "running"); + api.Publish(new JobStateEvent(id, "running", null)); + await WaitAsync(() => Last(seen).Id == id); + + // Owner review 5, #65: the progress event carries the step, and an older server's event without one keeps it. + api.Publish(new JobProgressEvent(id, 40, 300, 11.3, 20, new JobDetailDto("encode", null, 40, 300))); + await WaitAsync(() => Last(seen).ProgressDone == 40); + Assert.Equal(new JobDetail(JobStep.Encode, null, 40, 300), Last(seen).Detail); + Assert.Contains("Encoding frame 40 of 300", EditorText.ServerJobDetail(Last(seen), "Studio NAS")); + api.Publish(new JobProgressEvent(id, 41, 300, 11.3, 19)); + await WaitAsync(() => Last(seen).ProgressDone == 41); + Assert.Equal(JobStep.Encode, Last(seen).Detail?.Step); + } + } + [Test] public async Task ASequenceGoneFromTheServerReadsAsMissing() { diff --git a/tests/Chronos.App.Tests/Jobs/JobTextTests.cs b/tests/Chronos.App.Tests/Jobs/JobTextTests.cs new file mode 100644 index 00000000..fd110116 --- /dev/null +++ b/tests/Chronos.App.Tests/Jobs/JobTextTests.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using Chronos.App.Infrastructure; +using Chronos.App.Jobs; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Data.Jobs; +using Chronos.Testing; + +namespace Chronos.App.Tests.Jobs; + +/// The status line of a running job (owner review 5, #65): what it does now, in the job bar, the Jobs table and the tooltips. +public sealed class JobTextTests +{ + private static readonly DateTimeOffset T0 = new(2026, 9, 28, 10, 0, 0, TimeSpan.Zero); + + [Test] + public void TheStatusLineSaysStepItemAndPart() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence); + Assert.Equal("Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41", JobText.Status(verify)); + // Not counted: the step word alone; a single part is not said. + Assert.Equal("Listing folders", JobText.Status(new JobDetail(JobStep.List))); + Assert.Equal("Encoding frame 10 of 300", JobText.Status(new JobDetail(JobStep.Encode, null, 10, 300, 1, 1, JobPartUnit.Render))); + // A part without a unit is counted plainly. + Assert.Equal("Analysing · Lake · 120 of 4,812", JobText.Status(new JobDetail(JobStep.Analyse, "Lake", Part: 120, Parts: 4_812))); + Assert.Equal(string.Empty, JobText.Status(null)); + } + + [Test] + public void EveryStepAndPartHasItsWordsInEnglishAndItalian() + { + foreach (var culture in new[] { "en", "it" }) + { + var c = CultureInfo.GetCultureInfo(culture); + foreach (var step in Enum.GetValues().Where(s => s != JobStep.None)) + Assert.True(Loc.Get("Jobs.Step." + step, c) is not null, $"{culture} {step}"); + foreach (var unit in Enum.GetValues().Where(u => u != JobPartUnit.None)) + Assert.True(Loc.Get("Jobs.Part." + unit, c) is not null, $"{culture} {unit}"); + foreach (var sub in new[] { "Leases", "Temp", "Packs", "Duplicates", "Vacuum" }) + Assert.True(Loc.Get("Jobs.Maintenance.Step." + sub, c) is not null, $"{culture} {sub}"); + } + } + + + [Test] + public void SubStepsNameThemselvesAndUnknownOnesShowCountsOnly() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + Assert.Equal("Compacting thumbnails · step 3 of 5", JobText.Status(new JobDetail(JobStep.Maintenance, "packs", Part: 3, Parts: 5, PartUnit: JobPartUnit.Step))); + Assert.Equal("Job history", JobText.Status(new JobDetail(JobStep.Cleanup, "job-history"))); + // A sub-step key of a newer server is never shown as text. + Assert.Equal("Maintenance · step 6 of 6", JobText.Status(new JobDetail(JobStep.Maintenance, "re-index", Part: 6, Parts: 6, PartUnit: JobPartUnit.Step))); + // A step this build does not know (JobStep.None from the wire) shows its counts and item only. + Assert.Equal("4 of 10 · Lake", JobText.Status(new JobDetail(JobStep.None, "Lake", 4, 10))); + Assert.Equal(JobStep.None, JobWire.FromDto(new Chronos.Protocol.JobDetailDto("teleport", "Lake", 4, 10))!.Step); + } + + [Test] + public void FoldersStayLeftToRight() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var status = JobText.Status(new JobDetail(JobStep.Index, "2024/2024-09-27 Harbour", 1, 2)); + Assert.Contains(Formatting.LeftToRight("2024/2024-09-27 Harbour"), status); + } + + [Test] + public void ALongLineDropsTheItemFirstThenIsCut() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var detail = new JobDetail(JobStep.Verify, new string('x', 120), 812, 2_400, 3, 41, JobPartUnit.Sequence); + Assert.Equal("Verifying photo 812 of 2,400 · sequence 3 of 41", JobText.Status(detail, JobText.BarStatusLength)); + var cut = JobText.Status(detail, 20); + Assert.Equal(20, cut.Length); + Assert.True(cut.EndsWith('…')); + // A cut folder island is closed again. + var folder = JobText.Status(new JobDetail(JobStep.Index, "2024/" + new string('y', 80)), 30); + Assert.Equal(folder.Count(c => c == '‪'), folder.Count(c => c == '‬')); + } + + [Test] + public void TheBarSaysWhatTheJobDoesNow() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var job = Job(JobKind.Verify, JobState.Running, "Harbour sunset") with + { + Detail = new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence), + }; + // The bar keeps 60 characters of the line: the item (already the target here) goes first. + var entry = new JobEntry(job); + Assert.Equal("Verify · Harbour sunset · Verifying photo 812 of 2,400 · sequence 3 of 41", JobText.Bar(entry)); + + // Without a detail the counter stays, in bytes for a byte job. + var bytes = new JobEntry(Job(JobKind.Import, JobState.Running, "Card") with { ProgressDone = 2_000_000, ProgressTotal = 8_000_000 }); + Assert.Equal($"Import · Card · {Formatting.Bytes(2_000_000)} / {Formatting.Bytes(8_000_000)}", JobText.Bar(bytes)); + Assert.Equal("3 / 9", JobText.Counter(JobKind.Scan, 3, 9)); + } + + [Test] + public void LiveDetailWinsAndStoppedJobsSayWhere() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var job = Job(JobKind.Thumbs, JobState.Running, "Lake") with { Detail = new JobDetail(JobStep.Thumbs, "Lake", 1, 10) }; + var entry = new JobEntry(job) + { + Live = new JobProgressInfo(job.Id, job.Kind, "Lake", 5, 10, 2.5, TimeSpan.FromMinutes(2), null, new JobDetail(JobStep.Thumbs, "Lake", 5, 10)), + }; + Assert.Equal("Thumbnail 5 of 10 · Lake", JobText.RowStatus(entry)); + Assert.Equal("Thumbnail 5 of 10 · Lake · 2.5 fps · 2 min left", JobText.RowStatusToolTip(entry)); + + var paused = new JobEntry(job with { State = JobState.Paused }); + Assert.Equal("Stopped at Thumbnail 1 of 10 · Lake", JobText.RowStatus(paused)); + Assert.Equal(string.Empty, JobText.RowStatus(new JobEntry(job with { State = JobState.Queued }))); + Assert.Equal(string.Empty, JobText.RowStatus(new JobEntry(job with { State = JobState.Done }))); + } + + [Test] + public void RecentMaintenanceFollowsLiveProgress() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var verify = Job(JobKind.Verify, JobState.Running, "ChronosArchive") with { ProgressDone = 10, ProgressTotal = 100 }; + var scan = Job(JobKind.Scan, JobState.Paused, "Archive") with { Detail = new JobDetail(JobStep.Index, null, 4, 9) }; + var live = new Dictionary + { + [verify.Id] = new(verify.Id, verify.Kind, null, 71, 100, null, null, null, new JobDetail(JobStep.Verify, "Harbour sunset", 3, 9)), + // Progress of a job that is not running is not shown. + [scan.Id] = new(scan.Id, scan.Kind, null, 99, 100, null, null, null, new JobDetail(JobStep.Index, null, 8, 9)), + }; + var recent = Chronos.App.Archiving.MaintenanceReports.Recent([verify, scan], 5, live); + var running = recent.Single(r => r.JobId == verify.Id); + Assert.Equal("71 %", running.StateText); + Assert.Equal("Verifying photo 3 of 9 · Harbour sunset", running.Detail); + Assert.True(running.HasDetail); + var paused = recent.Single(r => r.JobId == scan.Id); + Assert.Equal("Stopped at Indexing photo 4 of 9", paused.Detail); + // Without live progress the stored snapshot speaks. + Assert.Equal("10 %", Chronos.App.Archiving.MaintenanceReports.Recent([verify], 5).Single().StateText); + } + + private static Job Job(JobKind kind, JobState state, string label) => new() + { + Id = Guid.CreateVersion7(), + Kind = kind, + State = state, + TargetLabel = label, + Created = T0, + Started = state == JobState.Queued ? null : T0, + }; +} + +/// The status line in Italian. It switches the process-wide UI language, so the class is serial. +[Serial] +public sealed class JobTextLanguageTests +{ + [Test] + public void ItalianWordsTheSameLine() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("it")); + try + { + var verify = new JobDetail(JobStep.Verify, "Tramonto", 812, 2_400, 3, 41, JobPartUnit.Sequence); + Assert.Equal($"Verifica foto 812 di {Formatting.Count(2_400)} · Tramonto · sequenza 3 di 41", JobText.Status(verify)); + Assert.Equal("Elaborazione foto 5 di 9", JobText.Status(new JobDetail(JobStep.Process, null, 5, 9))); + Assert.Equal("Fermo a Miniatura 1 di 10", Loc.L("Jobs.Detail.StoppedAt", JobText.Status(new JobDetail(JobStep.Thumbs, null, 1, 10)))); + } + finally + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + } + } +} diff --git a/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs b/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs new file mode 100644 index 00000000..7c549bbf --- /dev/null +++ b/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.cs @@ -0,0 +1,221 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Chronos.App.Server; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Data.Jobs; +using Chronos.Protocol; +using Chronos.Testing; + +namespace Chronos.App.Tests.Jobs; + +/// The Server section's list of the server's jobs (owner review 5, #65, the owner's answer to Q2). +public sealed class ServerJobsListTests +{ + private static readonly DateTimeOffset T0 = new(2026, 9, 28, 10, 0, 0, TimeSpan.Zero); + + [Test] + public async Task AReadOnlyAccountSeesRunningAndPausedJobsWithoutActions() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var api = new FakeJobsApi(); + var verify = api.Add("verify", "Harbour sunset", "running", new JobDetailDto("verify", "Harbour sunset", 812, 2_400, 3, 41, "sequence")); + api.Add("proxies", "Lake", "paused", new JobDetailDto("proxies", "Lake", 300, 1_800)); + api.Add("thumbs", "Queued one", "queued"); + using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", CanControl: false), () => api, new IdleContext()); + + await UpdatedAsync(vm, vm.Refresh); + Assert.True(vm.IsWatching); + Assert.False(vm.CanControl); + Assert.Equal(Loc.L("Tooltips.Server.Jobs.ReadOnly"), vm.TitleToolTip); + Assert.Equal(2, vm.Rows.Count); + Assert.True(vm.HasRows); + var running = vm.Rows[0]; + Assert.Equal(verify, running.Id); + Assert.Equal("Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41", running.StatusText); + Assert.Equal(StatusKindOf(JobState.Running), running.StateKind); + Assert.Empty(running.Actions); + Assert.Equal("Stopped at Proxy 300 of 1,800 · Lake", vm.Rows[1].StatusText); + Assert.Empty(vm.Rows[1].Actions); + // Without the right, nothing reaches the server. + await vm.ActAsync(verify, (a, id, ct) => a.PauseJobAsync(id, ct)); + Assert.Equal(0, api.Actions); + } + + [Test] + public async Task ProgressEventsMoveTheLineAndAFinishedJobLeaves() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var api = new FakeJobsApi(); + var id = api.Add("verify", "Harbour sunset", "running", new JobDetailDto("verify", "Harbour sunset", 1, 2_400, 3, 41, "sequence")); + using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", false), () => api, new IdleContext()); + await UpdatedAsync(vm, vm.Refresh); + + await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobProgressEvent(id, 900, 2_400, 52, 60, + new JobDetailDto("verify", "Alpine lake", 20, 100, 4, 41, "sequence")))); + var row = vm.Rows.Single(); + Assert.Equal("Verifying photo 20 of 100 · Alpine lake · sequence 4 of 41", row.StatusText); + Assert.Equal(900d / 2_400, row.Progress); + Assert.Equal("1 min", row.LeftText); + + await UpdatedAsync(vm, () => api.Events.Writer.TryWrite(new JobStateEvent(id, "done", null))); + Assert.Empty(vm.Rows); + Assert.False(vm.HasRows); + } + + [Test] + public async Task AManagingAccountPausesResumesAndCancels() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var api = new FakeJobsApi(); + var id = api.Add("thumbs", "Lake", "running"); + using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", CanControl: true), () => api, new IdleContext()); + await UpdatedAsync(vm, vm.Refresh); + Assert.True(vm.CanControl); + Assert.Equal(Loc.L("Tooltips.Server.Jobs"), vm.TitleToolTip); + Assert.SequenceEqual(new[] { Loc.L("Jobs.Action.Pause"), Loc.L("Jobs.Action.Cancel") }, vm.Rows.Single().Actions.Select(a => a.Text)); + + await vm.ActAsync(id, (a, job, ct) => a.PauseJobAsync(job, ct)); + Assert.Equal(StatusKindOf(JobState.Paused), vm.Rows.Single().StateKind); + Assert.SequenceEqual(new[] { Loc.L("Jobs.Action.Resume"), Loc.L("Jobs.Action.Cancel") }, vm.Rows.Single().Actions.Select(a => a.Text)); + + await vm.ActAsync(id, (a, job, ct) => a.CancelJobAsync(job, ct)); + Assert.Empty(vm.Rows); + Assert.Equal(2, api.Actions); + } + + [Test] + public async Task ARefusedActionIsSaidAndTheListStays() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var api = new FakeJobsApi { Refuse = true }; + var id = api.Add("thumbs", "Lake", "running"); + string? said = null; + using var vm = new ServerJobsViewModel(() => new ServerJobsAccount("a", true), () => api, new IdleContext(), (title, reason) => said = $"{title}: {reason}"); + await UpdatedAsync(vm, vm.Refresh); + + await vm.ActAsync(id, (a, job, ct) => a.PauseJobAsync(job, ct)); + Assert.Equal($"{Loc.L("Server.Jobs.NotChanged")}: The job cannot do that in its current state.", said); + Assert.Equal(StatusKindOf(JobState.Running), vm.Rows.Single().StateKind); + } + + [Test] + public async Task SigningOutEmptiesTheListAndClosesTheConnection() + { + var api = new FakeJobsApi(); + api.Add("verify", "Harbour sunset", "running"); + ServerJobsAccount? account = new("a", false); + using var vm = new ServerJobsViewModel(() => account, () => api, new IdleContext()); + await UpdatedAsync(vm, vm.Refresh); + Assert.Equal(1, vm.Rows.Count); + + account = null; + vm.Refresh(); + Assert.False(vm.IsWatching); + Assert.Empty(vm.Rows); + await api.Disposed.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + // Without an account nothing is opened. + var opened = 0; + using var signedOut = new ServerJobsViewModel(() => null, () => { opened++; return api; }, new IdleContext()); + signedOut.Refresh(); + Assert.Equal(0, opened); + Assert.False(signedOut.HasRows); + } + + private static Chronos.Ui.Controls.StatusKind StatusKindOf(JobState state) => + state == JobState.Paused ? Chronos.Ui.Controls.StatusKind.Paused : Chronos.Ui.Controls.StatusKind.Running; + + /// Runs , waits for the listener to post what follows, then applies it as the UI would. + private static async Task UpdatedAsync(ServerJobsViewModel vm, Action act) + { + var posted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + void OnPosted() => posted.TrySetResult(); + vm.Posted += OnPosted; + try + { + act(); + await posted.Task.WaitAsync(TimeSpan.FromSeconds(10)); + } + finally + { + vm.Posted -= OnPosted; + } + vm.Flush(); + } + + /// A UI context that never runs what is posted to it: the test applies the updates itself. + private sealed class IdleContext : SynchronizationContext + { + public override void Post(SendOrPostCallback d, object? state) + { + } + } + + private sealed class FakeJobsApi : IServerJobsApi + { + private readonly List _jobs = []; + + public Channel Events { get; } = Channel.CreateUnbounded(); + + public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool Refuse { get; init; } + + public int Actions { get; private set; } + + public Guid Add(string kind, string target, string state, JobDetailDto? detail = null) + { + var id = Guid.CreateVersion7(); + lock (_jobs) + { + _jobs.Add(new JobDto(id, kind, [], target, state, "background", 10, 100, null, null, null, null, 1, null, T0, T0.AddMinutes(_jobs.Count), null, null, + detail)); + } + return id; + } + + public Task> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken) + { + lock (_jobs) + { + var items = _jobs.Where(j => j.State == state).ToList(); + return Task.FromResult(new Page(items, null, items.Count)); + } + } + + public Task GetJobAsync(Guid id, CancellationToken cancellationToken) + { + lock (_jobs) return Task.FromResult(_jobs.Single(j => j.Id == id)); + } + + public Task PauseJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "paused"); + + public Task ResumeJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "running"); + + public Task CancelJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "cancelled"); + + public async IAsyncEnumerable EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var e in Events.Reader.ReadAllAsync(cancellationToken)) yield return e; + } + + public void Dispose() => Disposed.TrySetResult(); + + private Task Set(Guid id, string state) + { + if (Refuse) + throw new Chronos.Protocol.Client.ChronosApiException(System.Net.HttpStatusCode.Conflict, + new ApiError("invalid_state", "The job cannot do that in its current state.", null)); + Actions++; + lock (_jobs) + { + var index = _jobs.FindIndex(j => j.Id == id); + var job = _jobs[index] with { State = state }; + _jobs[index] = job; + return Task.FromResult(job); + } + } + } +} diff --git a/tests/Chronos.Server.Tests/Hosting/AdminJobDetailTests.cs b/tests/Chronos.Server.Tests/Hosting/AdminJobDetailTests.cs new file mode 100644 index 00000000..37346407 --- /dev/null +++ b/tests/Chronos.Server.Tests/Hosting/AdminJobDetailTests.cs @@ -0,0 +1,60 @@ +using System.Net.Http.Json; +using System.Text.RegularExpressions; +using Chronos.Core.Model; +using Chronos.Data.Jobs; +using Chronos.Protocol; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Hosting; + +/// +/// What a job does now in the admin panel (owner review 5, #65; Admin/web/jobs.js): the Jobs page and the dashboard +/// draw the status line under the target and move it with every progress event, and every step, part and sub-step the +/// server can send is worded in English and Italian. +/// +[Category("server")] +public sealed class AdminJobDetailTests(TestContext context) +{ + private static readonly string[] MaintenanceSteps = ["Leases", "Temp", "Packs", "Duplicates", "Vacuum"]; + + [Test] + public async Task TheJobsPageAndTheDashboardShowTheStatusLine() + { + await using var server = await TestServer.StartAsync(context); + var jobs = await server.Client.GetStringAsync("/admin/jobs.js"); + foreach (var helper in new[] { "statusText(detail)", "rowStatus(job)", "speedText(kind, rate)", "leftText(seconds)", "targetCell(job)", "statusLine(job)", "updateStatus(row, job)" }) + Assert.Contains($"export function {helper}", jobs); + // Items are data: they read in their own direction, and the whole line is the tooltip. + Assert.Contains(@"", jobs); + foreach (var page in new[] { "/admin/pages/jobs.js", "/admin/pages/dashboard.js" }) + { + var text = await server.Client.GetStringAsync(page); + Assert.Contains(@"${targetCell(j)}", text); + Assert.Contains("if (e.detail) job.detail = e.detail;", text); + Assert.Contains("updateStatus(row, job);", text); + Assert.True(!text.Contains(" style=", StringComparison.Ordinal), "inline style"); + } + Assert.Contains(".progress-detail {", await server.Client.GetStringAsync("/admin/admin.css")); + } + + [Test] + public async Task EveryStepAndPartIsInEnglishAndItalian() + { + await using var server = await TestServer.StartAsync(context); + var jobs = await server.Client.GetStringAsync("/admin/jobs.js"); + var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString)); + var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString)); + var keys = Regex.Matches(jobs, @"""(Admin\.[A-Za-z]+(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value).ToList(); + Assert.Contains("Admin.Job.Detail.StoppedAt", keys); + // The keys built from what the server sends. + keys.AddRange(Enum.GetValues().Where(s => s != JobStep.None).Select(s => $"Admin.Job.Step.{s}")); + keys.AddRange(Enum.GetValues().Where(u => u != JobPartUnit.None).Select(u => $"Admin.Job.Part.{u}")); + keys.AddRange(MaintenanceSteps.Select(s => $"Admin.Job.Maintenance.Step.{s}")); + foreach (var key in keys.Distinct()) + Assert.True(en.ContainsKey(key) && it.ContainsKey(key), key); + // The step and the unit keys are the wire names in PascalCase, as the panel builds them. + Assert.Equal("copy-photo", JobWire.Step(JobStep.CopyPhoto)); + Assert.Equal("Copia foto {0} di {1}", it["Admin.Job.Step.CopyPhoto.Count"]); + Assert.Equal("Verifying photo {0} of {1}", en["Admin.Job.Step.Verify.Count"]); + } +}