fix(sync): resolve conflicts against the versions shown, isolate failures, renders on request

- Conflicts are settled against the versions the user was shown; a later change on
  either side refuses the choice and compares again. Title, tags, rating and notes
  changed differently on both sides are a conflict too (no silent tag union).
- Links are written under the engine's gate and forgotten only after a 404; linked
  local copies are read by id; unlinked copies with the same originals are linked
  by content.
- A failure on one sequence is recorded on its link; the others are still compared.
- Downloads hash unverified local copies first and restore originals missing here.
- Background proxy downloads give way to the user's requests; "Keep proxies offline"
  refreshes the caches of sequences opened with proxies, checks free space and backs
  off after a failure.
- Renders travel on request: Send exports (chunked, hash-verified upload keeping the
  render id; new POST /sequences/{id}/renders endpoints) and Get exports.
- Server screen: stable row buttons, mockup column grid, Tab through rows, conflict
  rows first on the card colour, localised conflict detail, Save both confirmation,
  Pause metered uploads, culture switch, Library one-word sync glyphs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:26:56 +00:00
1 parent 3601e0a47f
commit 2d40a613b9
48 files changed
+2498 -465

No files matched your search

+115 -56
View File
@@ -1,6 +1,6 @@
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Net;
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Infrastructure;
@@ -10,7 +10,6 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Sync;
using Titano.Protocol.Client;
using Titano.Ui.Mvvm;
namespace Titano.App.Server;
@@ -26,7 +25,7 @@ public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select)
public string ToolTip => Loc.L("Tooltips.Server.Sync.Filter." + Filter);
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
/// <summary>Conflicts waiting for a choice: the chip is drawn in the warning colour.</summary>
/// <summary>Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one.</summary>
public bool NeedsAttention => Filter == SyncFilter.Conflicts && _count > 0;
public bool IsSelected
@@ -45,22 +44,33 @@ public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select)
OnPropertyChanged(nameof(NeedsAttention));
}
}
/// <summary>Texts in the current language.</summary>
public void Relabel()
{
OnPropertyChanged(nameof(Text));
OnPropertyChanged(nameof(ToolTip));
}
}
/// <summary>
/// The sync table of the Server screen (BRIEF §12.7, Server.html): every sequence of this PC and of the signed-in
/// server with what each side holds, where it stands and what can be done (upload, download originals, open with
/// proxies, settle a settings conflict, pause or resume a transfer), filter chips, search, "Upload all local" and the
/// footer (last comparison, server archive, admin panel). Reloads when the sync engine reports a change; transfer
/// progress is applied at most a few times a second. Runs on the UI thread.
/// proxies, get or send exports, settle a conflict, pause or resume a transfer), filter chips, search, "Upload all
/// local" and the footer (last comparison, server archive, admin panel). Reloads when the sync engine reports a change;
/// transfer progress is applied at most a few times a second. Runs on the UI thread.
/// </summary>
public sealed class SyncTableViewModel : ObservableObject, IDisposable
{
private readonly ShellViewModel _shell;
private readonly IReadOnlyList<SyncFilterChip> _chips;
private readonly HashSet<Guid> _openWhenCached = [];
/// <summary>"Open with proxies" waiting for its proxy download: server id → the job that fills the cache.</summary>
private readonly Dictionary<Guid, Guid> _openWhenCached = [];
private readonly ConcurrentDictionary<Guid, JobProgressInfo> _progress = new();
private readonly SemaphoreSlim _reloading = new(1, 1);
private readonly AsyncRelayCommand _uploadAll;
private IReadOnlyList<SyncEntry> _entries = [];
private SyncFilter _filter = SyncFilter.All;
private string _search = string.Empty;
@@ -72,7 +82,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
{
_shell = shell;
_chips = [.. Enum.GetValues<SyncFilter>().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })];
UploadAllCommand = new AsyncRelayCommand(UploadAllAsync, () => Rights.CanUpload && LocalOnly.Any());
_uploadAll = new AsyncRelayCommand(UploadAllAsync, () => IsActive && Rights.CanUpload && LocalOnly.Any());
OpenAdminCommand = new RelayCommand(() =>
{
if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
@@ -81,7 +91,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
public ObservableCollection<SyncRow> Rows { get; } = [];
public IReadOnlyList<SyncFilterChip> Chips => _chips;
public ICommand UploadAllCommand { get; }
public ICommand UploadAllCommand => _uploadAll;
public ICommand OpenAdminCommand { get; }
public string SearchText
@@ -89,7 +99,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
get => _search;
set
{
if (Set(ref _search, value ?? string.Empty)) ApplyFilter();
if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true);
}
}
@@ -104,7 +114,12 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
: _entries.Count == 0 ? Loc.L("Server.Sync.Empty")
: Loc.L("Server.Sync.NoMatch");
public string UploadAllToolTip => Loc.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(LocalOnly.Count()), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
/// <summary>What "Upload all local" sends, or why it is disabled.</summary>
public string UploadAllToolTip =>
!IsActive ? Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected")
: !Rights.CanUpload ? Loc.L("Tooltips.Server.Sync.UploadAll.NoRight")
: !LocalOnly.Any() ? Loc.L("Tooltips.Server.Sync.UploadAll.Nothing")
: Loc.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(LocalOnly.Count()), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
/// <summary>"Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison.</summary>
public string? LastSyncText => Host.Agent?.Snapshot is { } s
@@ -128,12 +143,13 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
/// <summary>Starts following the sync engine and the transfer jobs.</summary>
/// <summary>Starts following the sync engine, the transfer jobs and the language.</summary>
public void Attach()
{
if (_attached) return;
_attached = true;
Host.Changed += OnChanged;
Loc.CultureChanged += OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
jobs.JobChanged += OnJobChanged;
@@ -168,7 +184,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
public void Dispose()
{
if (!_attached) return;
_attached = false;
Host.Changed -= OnChanged;
Loc.CultureChanged -= OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
jobs.JobChanged -= OnJobChanged;
@@ -180,16 +198,15 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
{
_filter = filter;
foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter;
ApplyFilter();
ApplyFilter(rebuild: true);
}
/// <summary>Counts, rows, footer and the Library's sync glyphs after a reload.</summary>
private void Refresh()
{
foreach (var chip in _chips) chip.Count = _entries.Count(e => SyncText.Matches(e, chip.Filter, string.Empty));
ApplyFilter();
ApplyFilter(rebuild: false);
UpdateLibrary();
OpenCachedProxies();
OnPropertyChanged(nameof(IsActive));
OnPropertyChanged(nameof(UploadAllToolTip));
OnPropertyChanged(nameof(LastSyncText));
@@ -197,34 +214,52 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
OnPropertyChanged(nameof(ErrorText));
OnPropertyChanged(nameof(ErrorToolTip));
OnPropertyChanged(nameof(CanOpenAdmin));
CommandManager.InvalidateRequerySuggested();
_uploadAll.RaiseCanExecuteChanged();
}
/// <summary>Updates the rows in place (scroll position and recycled containers survive), adding and removing as needed.</summary>
private void ApplyFilter()
/// <summary>
/// Shows the entries the filter and search keep. A reload updates the rows in place (scroll position, focus and
/// recycled containers survive); a new filter or search lays the rows out again.
/// </summary>
private void ApplyFilter(bool rebuild)
{
var rights = Rights;
var wanted = _entries.Where(e => SyncText.Matches(e, _filter, _search.Trim())).ToList();
var byId = Rows.ToDictionary(r => r.Id);
for (var i = 0; i < wanted.Count; i++)
if (rebuild)
{
var entry = wanted[i];
if (byId.Remove(entry.Id, out var row))
Rows.Clear();
foreach (var entry in wanted) Rows.Add(Row(entry, rights, byId));
}
else
{
for (var i = 0; i < wanted.Count; i++)
{
row.Update(entry, rights);
var at = Rows.IndexOf(row);
if (at != i) Rows.Move(at, i);
var entry = wanted[i];
if (i < Rows.Count && Rows[i].Id == entry.Id)
{
Rows[i].Update(entry, rights);
continue;
}
var row = Row(entry, rights, byId);
var at = byId.ContainsKey(entry.Id) ? Rows.IndexOf(row) : -1;
if (at >= 0) Rows.Move(at, i);
else Rows.Insert(i, row);
}
else
{
Rows.Insert(i, new SyncRow(entry, rights, ActAsync));
}
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
}
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(EmptyText));
}
/// <summary>The existing row of an entry, updated, or a new one.</summary>
private SyncRow Row(SyncEntry entry, SyncRights rights, Dictionary<Guid, SyncRow> existing)
{
if (!existing.TryGetValue(entry.Id, out var row)) return new SyncRow(entry, rights, ActAsync);
row.Update(entry, rights);
return row;
}
/// <summary>The Library shows each local copy's sync state: rows it has loaded take the fresh state.</summary>
private void UpdateLibrary()
{
@@ -235,15 +270,6 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
}
}
/// <summary>"Open with proxies" waits for the proxy download; the editor opens once it is in the cache.</summary>
private void OpenCachedProxies()
{
foreach (var entry in _entries)
{
if (entry.Status == SyncStatus.ProxiesOnly && _openWhenCached.Remove(entry.Id)) _shell.OpenSequence(entry.Id);
}
}
private async Task ActAsync(SyncRow row, SyncAction action)
{
if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
@@ -253,6 +279,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
case SyncAction.Upload:
await service.EnqueueUploadAsync(engine, server, entry.Local!);
break;
case SyncAction.SendExports:
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
break;
case SyncAction.DownloadOriginals:
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
{
@@ -261,12 +290,18 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
}
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
break;
case SyncAction.GetExports:
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
break;
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
_shell.OpenSequence(entry.Id);
return;
case SyncAction.OpenWithProxies:
_openWhenCached.Add(entry.Id);
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
var job = await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
_openWhenCached[entry.Id] = job.Id;
// A download that finished before it was recorded here opens at once.
if (await _shell.Services.Database!.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
OpenWhenCached(ended);
break;
case SyncAction.Pause:
await _shell.Services.Jobs!.PauseAsync(entry.Transfer!.Id);
@@ -275,7 +310,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
await _shell.Services.Jobs!.ResumeAsync(entry.Transfer!.Id);
break;
case SyncAction.SyncSettings when Host.Remote is { } remote:
await service.SyncSettingsAsync(remote, entry.Id, CancellationToken.None);
await service.SyncSettingsAsync(remote, entry.Id, Host.Policy, CancellationToken.None);
break;
case SyncAction.KeepMine or SyncAction.TakeServer or SyncAction.SaveBoth when Host.Remote is { } remote:
await ResolveAsync(service, remote, entry, action);
@@ -284,40 +319,43 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
await ReloadAsync();
}
/// <summary>Settles a conflict; overwriting one side is confirmed first with the settings that differ (the dry run).</summary>
/// <summary>Settles a conflict once the user confirmed the plan: the settings that differ and what each choice overwrites.</summary>
private async Task ResolveAsync(SyncService service, ISyncRemote remote, SyncEntry entry, SyncAction action)
{
if (!_shell.Services.Dialogs.Confirm(ConflictRequest(entry, action))) return;
var resolution = action switch
{
SyncAction.KeepMine => SyncResolution.KeepMine,
SyncAction.TakeServer => SyncResolution.TakeServer,
_ => SyncResolution.SaveBoth,
};
if (resolution != SyncResolution.SaveBoth && !_shell.Services.Dialogs.Confirm(OverwriteRequest(entry, action))) return;
try
{
await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None);
if (await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None) is { } saved)
{
_shell.Notify(Loc.L("Server.Sync.SavedBoth"), Path.GetFileName(saved), Loc.L("Server.Sync.ShowCopy"), Loc.L("Tooltips.Server.Sync.ShowCopy"),
() => ShellActions.Reveal(saved));
}
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
catch (SyncConflictChangedException ex)
{
// The server copy changed again meanwhile: compare again and let the user choose on fresh content.
_shell.Notify(Loc.L("Server.Sync.ChangedAgain"));
await service.RefreshSequencesAsync(remote, [entry.Id], Host.Policy, CancellationToken.None);
// One side changed after the choice was shown: the row now shows the fresh content.
_shell.Notify(ex.Message);
}
}
/// <summary>"Keep this PC's settings?" with the settings that differ: one side's edits are about to be overwritten.</summary>
private static ConfirmRequest OverwriteRequest(SyncEntry entry, SyncAction action) => new()
/// <summary>The dry run of a resolution: what is replaced, by which side's values, and where "Save both" keeps this PC's.</summary>
internal static ConfirmRequest ConflictRequest(SyncEntry entry, SyncAction action) => new()
{
Heading = Loc.L("Server.Conflict." + action + ".Title"),
Message = Loc.L("Server.Conflict." + action + ".Message", entry.Title),
Detail = SyncText.Conflict(entry),
Detail = string.Join(Environment.NewLine, SyncText.Conflict(entry, 10)),
DetailToolTip = Loc.L("Tooltips.Server.Conflict.Detail"),
SafeText = Loc.L("Server.Conflict.Cancel"),
SafeToolTip = Loc.L("Tooltips.Server.Conflict.Cancel"),
ActionText = Loc.L("Server.Sync.Action." + action),
ActionToolTip = Loc.L("Tooltips.Server.Sync." + action),
IsDestructive = true,
IsDestructive = action != SyncAction.SaveBoth,
};
private async Task UploadAllAsync()
@@ -335,11 +373,34 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private void OnChanged() => Dispatch(() => _ = ReloadAsync());
private void OnCultureChanged(object? sender, EventArgs e) => Dispatch(() =>
{
foreach (var chip in _chips) chip.Relabel();
foreach (var row in Rows) row.Relabel();
OnAllPropertiesChanged();
});
private void OnJobChanged(Job job)
{
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
_progress.TryRemove(job.Id, out _);
OnChanged();
Dispatch(() =>
{
OpenWhenCached(job);
_ = ReloadAsync();
});
}
/// <summary>
/// "Open with proxies" opens the editor when the download it queued is done, if the Server screen is still the one
/// in front; a failed or cancelled download drops the request.
/// </summary>
private void OpenWhenCached(Job job)
{
if (job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
var remoteId = _openWhenCached.FirstOrDefault(p => p.Value == job.Id).Key;
if (!_openWhenCached.Remove(remoteId)) return;
if (job.State == JobState.Done && ReferenceEquals(_shell.Current, _shell.Server)) _shell.OpenSequence(remoteId);
}
/// <summary>Transfer progress ("46 % received") without reading the table again, at most a few times a second.</summary>
@@ -352,11 +413,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
{
await Task.Delay(250);
Interlocked.Exchange(ref _progressQueued, 0);
var rights = Rights;
foreach (var row in Rows)
{
if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p))
row.Update(row.Entry with { Transfer = job with { ProgressDone = p.Done, ProgressTotal = p.Total } }, rights);
if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p)) row.UpdateProgress(p.Done, p.Total);
}
});
}