Files
Chronos/src/Titano.App/Sections/JobsViewModel.cs
T
Claude d80cb5f8a7 fix(app): Server, Jobs, Settings, About and Welcome after the accessibility and RTL review
- Keyboard: Tab follows the visual order (toolbars, section list, dialog
  buttons), reaches every Jobs row button, stays inside the Welcome dialog
  (which opens focused); the Settings section list shows a focus ring.
- Screen readers: sync and job rows read as their sequence or job with the
  state as item status; row buttons name their row; filter chips are radio
  buttons; the connection state, errors, sync retries, update checks and
  self-test results are announced; Auto values are text, not dead buttons.
- Right to left: paths, addresses, templates, fingerprints, the job log, sizes
  and the logo stay left to right; numbers stay right-aligned.
- Layout: Jobs and sync headers line up with their rows (shared padding,
  shared actions column, constant scroll-bar gutter); toolbars wrap before
  anything is cut; Settings labels share a column as wide as the longest one;
  path rows give way instead of wrapping; conflict rows use the warning tint.
- Behaviour: Settings reloads the archive folder and default server set
  elsewhere; forgetting a certificate in Settings asks first and disconnects
  the session on it; transfers count in the Local only and Remote chips; the
  Workers readout counts this PC's workers; badge, status strip and Running
  chip agree; the admin link shows for administrators only; Reset section is
  gone from Advanced; empty states carry one action; shorter labels; the
  encoders a render node offers and the presets each encoder serves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-03 17:23:59 +00:00

398 lines
14 KiB
C#

using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Jobs;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>A filter chip of the Jobs toolbar ("Running · 4").</summary>
public sealed class JobFilterChip(JobFilter filter, Action<JobFilter> select) : ObservableObject
{
private int _count;
private bool _isSelected;
public JobFilter Filter { get; } = filter;
public string Text => Loc.L("Jobs.Filter." + Filter, Formatting.Count(_count));
public string ToolTip => Loc.L("Tooltips.Jobs.Filter." + Filter);
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
public bool IsSelected
{
get => _isSelected;
set => Set(ref _isSelected, value);
}
public int Count
{
get => _count;
set
{
if (Set(ref _count, value)) OnPropertyChanged(nameof(Text));
}
}
internal void Refresh() => OnAllPropertiesChanged();
}
/// <summary>
/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
/// shell's job bar, the status strip and the rail badge.
/// </summary>
public sealed class JobsViewModel : SectionViewModel
{
private static readonly TimeSpan FlushInterval = TimeSpan.FromMilliseconds(100);
private const int PageSize = 200;
private readonly JobListModel _model = new();
private readonly JobUpdateBuffer _buffer = new();
private readonly Dictionary<Guid, JobRowViewModel> _rows = [];
private readonly JobActions _actions;
private CoalescingThrottle? _throttle;
private IJobQueue? _queue;
private JobFilter _filter = JobFilter.All;
private string _searchText = string.Empty;
private string? _cursor;
private bool _hasMore;
private bool _loading;
private bool _hasLoaded;
public JobsViewModel(ShellViewModel shell)
: base(SectionKey.Jobs, "Icon.Jobs")
{
Shell = shell;
_actions = new JobActions(this);
Chips = [.. Enum.GetValues<JobFilter>().Select(f => new JobFilterChip(f, SelectFilter) { IsSelected = f == JobFilter.All })];
PauseCurrentCommand = new AsyncRelayCommand(PauseCurrentAsync, () => _model.Current is not null);
PauseAllCommand = new AsyncRelayCommand(PauseAllAsync, () => _model.RunningCount > 0);
ClearDoneCommand = new RelayCommand(ClearDone, () => _model.CountOf(JobFilter.Done, ClearedAt) + _model.CountOf(JobFilter.Failed, ClearedAt) > 0);
RenderingSettingsCommand = new RelayCommand(() =>
{
Shell.Settings.Page = SettingsPage.Rendering;
Shell.Navigate(SectionKey.Settings);
});
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
ImportCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
}
public ShellViewModel Shell { get; }
/// <summary>Rows in display order for the current filter and search.</summary>
public ObservableCollection<JobRowViewModel> Rows { get; } = [];
public IReadOnlyList<JobFilterChip> Chips { get; }
public ICommand PauseCurrentCommand { get; }
public ICommand PauseAllCommand { get; }
public ICommand ClearDoneCommand { get; }
public ICommand RenderingSettingsCommand { get; }
public ICommand LoadMoreCommand { get; }
/// <summary>The empty state's one action: jobs start with an import.</summary>
public ICommand ImportCommand { get; }
public JobFilter Filter
{
get => _filter;
set
{
if (!Set(ref _filter, value)) return;
foreach (var chip in Chips) chip.IsSelected = chip.Filter == value;
SyncRows();
}
}
public string SearchText
{
get => _searchText;
set
{
if (Set(ref _searchText, value ?? string.Empty)) SyncRows();
}
}
/// <summary>"Workers 1 / 4": jobs this PC's workers run out of its workers.</summary>
public string WorkersText => Loc.L("Jobs.Workers", _queue is { } queue ? _model.RunningOn(queue.WorkerId) : 0, _queue?.Workers ?? 0);
/// <summary>The engine of this PC runs workers (it has none before it starts).</summary>
public bool HasWorkers => _queue is { Workers: > 0 };
/// <summary>"History keeps 90 days".</summary>
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
public bool IsEmpty => _hasLoaded && Rows.Count == 0;
public bool HasRows => Rows.Count > 0;
internal IJobQueue? Queue => _queue;
internal JobListModel Model => _model;
private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
/// <summary>Subscribes to the engine and loads the first page of jobs.</summary>
public void Attach()
{
_queue = Shell.Services.Jobs;
if (_queue is null)
{
_hasLoaded = true;
RaiseState();
return;
}
_throttle = new CoalescingThrottle(FlushInterval, SynchronizationContext.Current, Flush);
_queue.JobChanged += OnJobChanged;
_queue.Progress += OnProgress;
_ = LoadMoreAsync();
}
public override void Dispose()
{
if (_queue is not null)
{
_queue.JobChanged -= OnJobChanged;
_queue.Progress -= OnProgress;
}
_throttle?.Dispose();
base.Dispose();
}
/// <summary>Reads the job list again from the first page (after jobs were written outside the engine).</summary>
public Task ReloadAsync()
{
_cursor = null;
_hasMore = true;
_hasLoaded = false;
return LoadMoreAsync();
}
/// <summary>Next page of the history (newest first); the view calls it when the list scrolls near its end.</summary>
public async Task LoadMoreAsync()
{
if (_queue is null || _loading || (_hasLoaded && !_hasMore)) return;
_loading = true;
try
{
var stamp = _model.Stamp;
var page = await _queue.ListAsync(_cursor, PageSize);
foreach (var job in page.Items) _model.ApplyLoaded(job, stamp);
_cursor = page.NextCursor;
_hasMore = page.NextCursor is not null;
}
catch (DatabaseException ex)
{
Log.Warning("jobs", "Job list unavailable", ex);
_hasMore = false;
}
finally
{
_loading = false;
_hasLoaded = true;
}
Flush();
}
/// <summary>Applies everything buffered since the last flush (UI thread).</summary>
internal void Flush()
{
var (jobs, progress) = _buffer.Drain();
foreach (var job in jobs) _model.Apply(job);
foreach (var p in progress) _model.Apply(p);
SyncRows();
UpdateShell();
}
private void OnJobChanged(Job job)
{
_buffer.Post(job);
_throttle?.Signal();
}
private void OnProgress(JobProgressInfo progress)
{
_buffer.Post(progress);
_throttle?.Signal();
}
private void SelectFilter(JobFilter filter) => Filter = filter;
/// <summary>Brings <see cref="Rows"/> to the model's order with moves (rows keep their expanded log).</summary>
private void SyncRows()
{
var ordered = _model.Ordered(_filter, _searchText, ClearedAt);
var wanted = new HashSet<Guid>(ordered.Select(e => e.Id));
for (var i = Rows.Count - 1; i >= 0; i--)
{
if (!wanted.Contains(Rows[i].Id)) Rows.RemoveAt(i);
}
for (var i = 0; i < ordered.Count; i++)
{
var entry = ordered[i];
var position = entry.State == JobState.Queued ? _model.QueuePosition(entry.Id) : 0;
if (!_rows.TryGetValue(entry.Id, out var row))
{
row = new JobRowViewModel(entry, position, _actions);
_rows[entry.Id] = row;
}
else
{
row.Update(entry, position);
}
if (i < Rows.Count && ReferenceEquals(Rows[i], row)) continue;
var existing = Rows.IndexOf(row);
if (existing >= 0) Rows.Move(existing, i);
else Rows.Insert(i, row);
}
foreach (var chip in Chips) chip.Count = _model.CountOf(chip.Filter, ClearedAt);
RaiseState();
}
private void UpdateShell()
{
if (_model.Current is { } current)
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null);
else
Shell.SetJob(null, 0);
// The rail badge, the status strip and the Running chip count the same jobs: running or paused (Jobs.html).
var active = _model.CountOf(JobFilter.Running);
Shell.SetJobCount(active, _model.QueuedCount);
Badge = active;
OnPropertyChanged(nameof(WorkersText));
OnPropertyChanged(nameof(HasWorkers));
CommandManager.InvalidateRequerySuggested();
}
private void RaiseState()
{
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
}
private async Task PauseCurrentAsync()
{
if (_model.Current is { } current && _queue is not null) await _queue.PauseAsync(current.Id);
}
private async Task PauseAllAsync()
{
if (_queue is null) return;
foreach (var entry in _model.Ordered(JobFilter.Running).Where(e => e.State == JobState.Running).ToList()) await _queue.PauseAsync(entry.Id);
}
private void ClearDone()
{
Shell.Services.Settings.JobsClearedAt = DateTimeOffset.UtcNow;
Shell.Services.SaveSettings();
SyncRows();
}
/// <summary>Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen.</summary>
internal async Task OpenTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id);
else Shell.Navigate(SectionKey.Archive);
}
/// <summary>Shows the folder of what a job worked on in Explorer.</summary>
internal async Task RevealTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
var id = job.TargetIds[0];
if (await db.Sequences.GetAsync(id) is { } sequence && await db.Archives.GetAsync(sequence.ArchiveId) is { } owner)
ShellActions.Reveal(Path.Combine(owner.RootPath, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
else if (await db.Archives.GetAsync(id) is { } archive)
ShellActions.Reveal(archive.RootPath);
}
}
/// <summary>Row actions per job state (Jobs.html) and their commands.</summary>
internal sealed class JobActions(JobsViewModel owner)
{
public string WorkerId => owner.Queue?.WorkerId ?? Environment.MachineName;
public IReadOnlyList<JobAction> For(JobEntry entry)
{
var job = entry.Job;
var row = JobText.Name(job);
return entry.State switch
{
JobState.Running =>
[
OnQueue("Jobs.Action.Pause", "Tooltips.Jobs.Pause", row, q => q.PauseAsync(job.Id)),
OnQueue("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", row, q => q.CancelAsync(job.Id)),
],
JobState.Paused =>
[
OnQueue("Jobs.Action.Resume", "Tooltips.Jobs.Resume", row, q => q.ResumeAsync(job.Id)),
OnQueue("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", row, q => q.CancelAsync(job.Id)),
],
JobState.Queued when job.Priority < JobPriority.User =>
[
OnQueue("Jobs.Action.MoveUp", "Tooltips.Jobs.MoveUp", row, q => q.RaisePriorityAsync(job.Id)),
OnQueue("Jobs.Action.Remove", "Tooltips.Jobs.Remove", row, q => q.CancelAsync(job.Id)),
],
JobState.Queued =>
[
OnQueue("Jobs.Action.Pause", "Tooltips.Jobs.PauseQueued", row, q => q.PauseAsync(job.Id)),
OnQueue("Jobs.Action.Remove", "Tooltips.Jobs.Remove", row, q => q.CancelAsync(job.Id)),
],
JobState.Failed =>
[
OnQueue("Jobs.Action.Retry", "Tooltips.Jobs.Retry", row, q => q.ResumeAsync(job.Id)),
Action("Jobs.Action.Show", "Tooltips.Jobs.Show", row, () => owner.OpenTargetAsync(job)),
],
JobState.Cancelled =>
[
OnQueue("Jobs.Action.Retry", "Tooltips.Jobs.Retry", row, q => q.ResumeAsync(job.Id)),
],
_ =>
[
Action("Jobs.Action.Open", "Tooltips.Jobs.Open", row, () => owner.OpenTargetAsync(job)),
Action("Jobs.Action.Folder", "Tooltips.Jobs.Folder", row, () => owner.RevealTargetAsync(job)),
],
};
}
/// <summary>Reads the stored log tail of a row (persisted with each checkpoint).</summary>
public async Task LoadLogAsync(JobRowViewModel row)
{
if (owner.Queue is not { } queue) return;
try
{
if (await queue.GetAsync(row.Id) is { } job) row.SetLog(job.LogTail);
}
catch (DatabaseException ex)
{
Log.Warning("jobs", "Job log unavailable", ex);
}
}
/// <summary>A row button named with its row for screen readers ("Pause: Render · Harbour sunset").</summary>
private static JobAction Action(string textKey, string toolTipKey, string row, Func<Task> run)
{
var text = Loc.L(textKey);
return new JobAction(text, Loc.L(toolTipKey), Loc.L("Jobs.ActionFor", text, row), new AsyncRelayCommand(run));
}
private JobAction OnQueue(string textKey, string toolTipKey, string row, Func<IJobQueue, Task> run) =>
Action(textKey, toolTipKey, row, async () =>
{
if (owner.Queue is { } queue) await run(queue);
});
}