Files
Chronos/tests/Chronos.App.Tests/Jobs/ServerJobsListTests.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

222 lines
9.4 KiB
C#

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;
/// <summary>The Server section's list of the server's jobs (owner review 5, #65, the owner's answer to Q2).</summary>
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;
/// <summary>Runs <paramref name="act"/>, waits for the listener to post what follows, then applies it as the UI would.</summary>
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();
}
/// <summary>A UI context that never runs what is posted to it: the test applies the updates itself.</summary>
private sealed class IdleContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object? state)
{
}
}
private sealed class FakeJobsApi : IServerJobsApi
{
private readonly List<JobDto> _jobs = [];
public Channel<ServerEvent> Events { get; } = Channel.CreateUnbounded<ServerEvent>();
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<Page<JobDto>> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken)
{
lock (_jobs)
{
var items = _jobs.Where(j => j.State == state).ToList();
return Task.FromResult(new Page<JobDto>(items, null, items.Count));
}
}
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
{
lock (_jobs) return Task.FromResult(_jobs.Single(j => j.Id == id));
}
public Task<JobDto> PauseJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "paused");
public Task<JobDto> ResumeJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "running");
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => Set(id, "cancelled");
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var e in Events.Reader.ReadAllAsync(cancellationToken)) yield return e;
}
public void Dispose() => Disposed.TrySetResult();
private Task<JobDto> 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);
}
}
}
}