fix(workspace): join the phase 5c packages at their seams

The local render, the send home, the clean-up, the settings page and the
folder move were built apart; together they left gaps:

- A local render to an image sequence writes a folder, which the send
  took for a missing file. The archive home now files the folder whole
  (checked by its listing hash, as the render recorded it) and the
  clean-up removes a sent folder; a server, which takes one file per
  render, refuses it with Errors.Workspace.SendSequence.
- Rename, delete and Remove local copy are refused while the folder is
  being moved, so no project folder changes under the move.
- Settings > Workspace shows the folder, usage, Move... and Change...
  again when a move ends (WorkspaceHost.MoveEnded).
- Empty... uses the Settings typed confirmation; the separate trash
  dialog, never shown, is removed. The move plan counts unsent renders
  with the clean-up's helper.
- Tests: the follow-up send now runs in the render tests; an end-to-end
  archive-home test (originals, version on render, local render, send
  with project and version, clean-up) and an image-sequence send test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 16:23:54 +01:00
1 parent 6daf5fa056
commit 09fcff4eb2
13 files changed
+210 -226

No files matched your search

+1
View File
@@ -114,4 +114,5 @@
<data name="Errors.Workspace.MoveChanged" xml:space="preserve"><value>The workspace changed after its plan was shown; nothing was moved: plan the move again.</value></data>
<data name="Errors.Workspace.MoveVerify" xml:space="preserve"><value>{0} did not match its source after it was copied; the workspace stays where it was.</value></data>
<data name="Errors.Workspace.MoveNoRoom" xml:space="preserve"><value>The target drive needs {0} GB more for the workspace.</value></data>
<data name="Errors.Workspace.SendSequence" xml:space="preserve"><value>{0} is an image sequence: a server takes one file per render, so it stays in the workspace.</value></data>
</root>
+1
View File
@@ -114,4 +114,5 @@
<data name="Errors.Workspace.MoveChanged" xml:space="preserve"><value>Lo spazio di lavoro è cambiato dopo che il piano è stato mostrato; non è stato spostato nulla: pianifica di nuovo.</value></data>
<data name="Errors.Workspace.MoveVerify" xml:space="preserve"><value>{0} non corrispondeva alla sua origine dopo la copia; lo spazio di lavoro resta dov'era.</value></data>
<data name="Errors.Workspace.MoveNoRoom" xml:space="preserve"><value>Al disco di destinazione servono altri {0} GB per lo spazio di lavoro.</value></data>
<data name="Errors.Workspace.SendSequence" xml:space="preserve"><value>{0} è una sequenza di immagini: un server accetta un file per render, quindi resta nello spazio di lavoro.</value></data>
</root>
@@ -765,6 +765,14 @@ public sealed class SettingsViewModel : SectionViewModel
WorkspaceRows.Refresh();
}
/// <summary>A move of the workspace folder ended (any thread): the page shows the folder in use, what it takes, and Move… and Change… again.</summary>
private void OnWorkspaceMoveEnded() => System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{
WorkspaceRows.Refresh();
CommandManager.InvalidateRequerySuggested();
if (_page == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
});
// ---------------- Server ----------------
public EditableField DefaultServer { get; }
@@ -875,6 +883,7 @@ public sealed class SettingsViewModel : SectionViewModel
}
LoadCertificates();
Shell.Services.Server.PropertyChanged += OnServerChanged;
Shell.Services.Workspace.MoveEnded += OnWorkspaceMoveEnded;
if (System.Windows.Application.Current is { } app) _interfacePriority = new InterfacePriority(app, () => _s.BackgroundPriority);
_ = LoadArchiveAsync();
switch (Shell.Services.StagedRestore)
@@ -908,6 +917,7 @@ public sealed class SettingsViewModel : SectionViewModel
{
Loc.CultureChanged -= OnCultureChanged;
Shell.Services.Server.PropertyChanged -= OnServerChanged;
Shell.Services.Workspace.MoveEnded -= OnWorkspaceMoveEnded;
_selfTest?.Cancel();
_interfacePriority?.Dispose();
base.Dispose();
+10 -15
View File
@@ -74,6 +74,12 @@ public sealed partial class WorkspaceHost
}
}
/// <summary>
/// A move of the workspace folder followed here ended, however it ended (any thread): the folder in use may have changed,
/// and the workspace is no longer held for it (Settings › Workspace shows the folder and what it takes again).
/// </summary>
public event Action? MoveEnded;
/// <summary>
/// A move stopped before it ended: the folder in use holds its journal and no move job waits, runs or is paused. Null
/// when there is none (a move under way is no move to take up). A move job waiting at start is followed from now on,
@@ -230,8 +236,10 @@ public sealed partial class WorkspaceHost
if (job.Kind != JobKind.WorkspaceMove || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
lock (_gate)
{
if (_moveJob == job.Id) _moveJob = Guid.Empty;
if (_moveJob != job.Id) return;
_moveJob = Guid.Empty;
}
MoveEnded?.Invoke();
}
/// <summary>A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).</summary>
@@ -244,7 +252,7 @@ public sealed partial class WorkspaceHost
try
{
var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
var renders = UnsentRenders(project);
var renders = WorkspaceCleaner.UnsentRenders(project);
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
status.Modified && !status.ReadOnly);
}
@@ -253,18 +261,5 @@ public sealed partial class WorkspaceHost
Log.Info("workspace", $"Where project {folder.ProjectId} stands could not be read for the move's plan: {ex.Message}");
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, true, false);
}
static int UnsentRenders(WorkspaceProject project)
{
try
{
return project.ReadRenders().Unsent.Count;
}
catch (InvalidDataException)
{
// A ledger this Chronos cannot read: what it lists is not known to be at the home.
return 1;
}
}
}
}
@@ -707,6 +707,7 @@ public sealed partial class WorkspaceHost
/// <exception cref="HomeUnavailableException">The home cannot be reached now: the name stays.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var project = Existing(projectId);
var renamed = await HomeOfProject(projectId).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
@@ -732,6 +733,7 @@ public sealed partial class WorkspaceHost
{
var (sequenceId, removed) = await Task.Run(async () =>
{
EnsureNotMoving();
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
@@ -816,6 +818,8 @@ public sealed partial class WorkspaceHost
{
var sequenceId = await Task.Run(async () =>
{
// A move takes every project folder as it stands: none goes to the trash meanwhile.
EnsureNotMoving();
var project = Existing(projectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
if (entry.Newer) throw Unreadable(entry);
@@ -1,109 +0,0 @@
using System.Globalization;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>One entry of the workspace's trash as Empty… lists it: "name · 1.2 GB · 04/11/2026".</summary>
public sealed class WorkspaceTrashRowViewModel(WorkspaceTrashItem item)
{
public WorkspaceTrashItem Item { get; } = item;
public string Text => Loc.L("Settings.Workspace.TrashPlan.Item", Item.Name, Formatting.Bytes(Item.Bytes),
Formatting.Date(Item.Trashed) + " " + Formatting.TimeOfDay(Item.Trashed));
}
/// <summary>
/// Settings › Workspace › Trash › Empty… (phase 5c): the plan (every entry of the workspace's trash, their number and size,
/// <see cref="WorkspaceTrashPlan"/>), then Erase for good, which enables only once the user typed the number of entries; the
/// emptying erases exactly the entries listed, and is refused when the trash changed since (the plan is shown again then).
/// Keep closes it, erasing nothing.
/// </summary>
public sealed class WorkspaceTrashDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<WorkspaceTrashPlan, Task<WorkspaceTrashResult>> _empty;
private readonly Action<WorkspaceTrashResult>? _emptied;
private string _typed = string.Empty;
/// <param name="empty">Erases the plan's entries (<see cref="WorkspaceHost.EmptyTrashAsync"/>).</param>
/// <param name="emptied">Told what was erased, once the dialog closes on it (the page measures the workspace again).</param>
public WorkspaceTrashDialogViewModel(WorkspaceTrashPlan plan, Func<WorkspaceTrashPlan, Task<WorkspaceTrashResult>> empty, Action<WorkspaceTrashResult>? emptied,
Action<ArchiveDialogViewModel> close)
: base(close)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(empty);
Plan = plan;
_empty = empty;
_emptied = emptied;
Rows = [.. plan.Items.Select(i => new WorkspaceTrashRowViewModel(i))];
EraseCommand = new AsyncRelayCommand(EraseAsync, () => CanErase);
}
public WorkspaceTrashPlan Plan { get; }
public IReadOnlyList<WorkspaceTrashRowViewModel> Rows { get; }
public string Heading => Loc.L("Settings.Workspace.TrashPlan.Title");
public string Message => Loc.L("Settings.Workspace.TrashPlan.Message");
/// <summary>"Entries: 3".</summary>
public string ItemsText => Loc.L("Settings.Workspace.TrashPlan.Items", Formatting.Count(Plan.Items.Count));
/// <summary>"Size: 1.2 GB".</summary>
public string SizeText => Loc.L("Settings.Workspace.TrashPlan.Size", Formatting.Bytes(Plan.Bytes));
/// <summary>What the user types to confirm: the number of entries, in plain digits.</summary>
public string Confirmation => Plan.Items.Count.ToString(CultureInfo.InvariantCulture);
/// <summary>"Type the number of entries, 3, to confirm".</summary>
public string TypedPrompt => Loc.L("Settings.Workspace.TrashPlan.Type", Confirmation);
/// <summary>What the user typed; Erase for good enables once it is <see cref="Confirmation"/>.</summary>
public string Typed
{
get => _typed;
set
{
if (!Set(ref _typed, value ?? string.Empty)) return;
OnPropertyChanged(nameof(CanErase));
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>The trash holds something, the number typed matches, and nothing runs.</summary>
public bool CanErase => !IsBusy && !Plan.IsEmpty && string.Equals(_typed.Trim(), Confirmation, StringComparison.Ordinal);
public ICommand EraseCommand { get; }
public string EraseToolTip => Plan.IsEmpty ? Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled") : Loc.L("Tooltips.Settings.Workspace.TrashPlan.Action");
public string KeepToolTip => Loc.L("Tooltips.Settings.Workspace.TrashPlan.Keep");
private async Task EraseAsync()
{
if (!CanErase) return;
ClearError();
IsBusy = true;
OnPropertyChanged(nameof(CanErase));
try
{
var result = await _empty(Plan);
IsBusy = false;
Close();
_emptied?.Invoke(result);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "The workspace's trash was not emptied", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
OnPropertyChanged(nameof(CanErase));
}
}
}
@@ -1,58 +0,0 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:ws="clr-namespace:Chronos.App.Workspace">
<!-- Settings › Workspace › Trash › Empty… (phase 5c), in-window, with the dialog kit of the Archive screen. -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- The plan of emptying the workspace's trash: every entry, their number and size, then the number typed before Erase for good enables. -->
<DataTemplate DataType="{x:Type ws:WorkspaceTrashDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560" MaxHeight="560">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Grid.Row="1" Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,12,0,8">
<TextBlock Text="{Binding ItemsText}" Typography.NumeralAlignment="Tabular" ToolTip="{Binding ItemsText}" />
<TextBlock Text="{Binding SizeText}" Margin="16,0,0,0" Typography.NumeralAlignment="Tabular" ToolTip="{Binding SizeText}" />
</StackPanel>
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" MinHeight="96" AutomationProperties.Name="{l:Loc Settings.Workspace.Trash}" KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Text}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ws:WorkspaceTrashRowViewModel}">
<TextBlock Text="{Binding Text}" Height="32" Padding="0,8,0,0" TextTrimming="CharacterEllipsis" ToolTip="{Binding Text}" FlowDirection="LeftToRight"
Typography.NumeralAlignment="Tabular" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Row="4" Margin="0,16,0,0">
<TextBlock Text="{Binding TypedPrompt}" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" />
<TextBox Margin="0,6,0,0" Text="{Binding Typed, UpdateSourceTrigger=PropertyChanged}" ui:Field.Placeholder="{Binding Confirmation}" ToolTip="{Binding TypedPrompt}"
AutomationProperties.Name="{Binding TypedPrompt}" />
</StackPanel>
<DockPanel Grid.Row="5" Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Editor.Project.Keep}" Command="{Binding CloseCommand}" ToolTip="{Binding KeepToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<!-- Erasing for good: enabled once the number of entries is typed, never the default button. -->
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Destructive}" Content="{l:Loc Settings.Workspace.TrashPlan.Action}" Command="{Binding EraseCommand}"
ToolTip="{Binding EraseToolTip}" ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,0" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</Grid>
</Border>
</DataTemplate>
</ResourceDictionary>
+15 -5
View File
@@ -545,10 +545,20 @@ internal sealed class SyncTransfers(SyncService sync)
if (!SequenceFolders.Holds(folder, row.Id)) return null;
Directory.CreateDirectory(folder.Exports);
var target = Unique(folder.Exports, name);
File.Move(part, target);
// An image sequence's folder (a workspace's local render) is filed whole, sized by its files, as the archive's own.
long bytes;
if (Directory.Exists(part))
{
Directory.Move(part, target);
bytes = new DirectoryInfo(target).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length);
}
else
{
File.Move(part, target);
bytes = new FileInfo(target).Length;
}
var relative = paths.ToRelative(target);
await db.Renders.InsertAsync(render with { SequenceId = row.Id, OutputPath = relative, Bytes = new FileInfo(target).Length }, CancellationToken.None)
.ConfigureAwait(false);
await db.Renders.InsertAsync(render with { SequenceId = row.Id, OutputPath = relative, Bytes = bytes }, CancellationToken.None).ConfigureAwait(false);
return (string?)relative;
}, cancellationToken);
@@ -578,13 +588,13 @@ internal sealed class SyncTransfers(SyncService sync)
return string.IsNullOrEmpty(file) || file.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || file is "." or ".." ? null : file;
}
/// <summary>"name.mp4", else "name (2).mp4", … — an existing export is never replaced.</summary>
/// <summary>"name.mp4", else "name (2).mp4", … — an existing export (a file, or an image sequence's folder) is never replaced.</summary>
internal static string Unique(string folder, string fileName)
{
var candidate = Path.Combine(folder, fileName);
var stem = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
for (var n = 2; File.Exists(candidate); n++) candidate = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{stem} ({n}){extension}"));
for (var n = 2; File.Exists(candidate) || Directory.Exists(candidate); n++) candidate = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{stem} ({n}){extension}"));
return candidate;
}
@@ -359,7 +359,8 @@ public sealed class WorkspaceCleaner
var path = project.ExportFile(entry.File);
try
{
if (File.Exists(path)) File.Delete(path);
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
else if (File.Exists(path)) File.Delete(path);
ledger = ledger.Without(entry.RenderId);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
@@ -385,8 +386,11 @@ public sealed class WorkspaceCleaner
/// <summary>What a clean-up may remove of the project: its proxies, its originals and the renders its home took.</summary>
private static long Cleanable(WorkspaceProject project, WorkspaceRenders renders) =>
Measure(project.ProxiesDirectory).Bytes + Measure(project.OriginalsDirectory).Bytes
+ renders.Entries.Where(e => e.IsSent).Select(e => new FileInfo(project.ExportFile(e.File))).Where(f => f.Exists).Sum(f => f.Length);
Measure(project.ProxiesDirectory).Bytes + Measure(project.OriginalsDirectory).Bytes + SentBytes(project, renders);
/// <summary>The bytes of the renders of <paramref name="renders"/> the home took that are still in <c>exports/</c> (an image sequence's folder counts its files).</summary>
private static long SentBytes(WorkspaceProject project, WorkspaceRenders renders) =>
renders.Entries.Where(e => e.IsSent).Select(e => project.ExportFile(e.File)).Sum(path => File.Exists(path) ? new FileInfo(path).Length : Measure(path).Bytes);
/// <summary>The project's ledger; null (logged) when it cannot be read.</summary>
private static WorkspaceRenders? ReadLedger(WorkspaceProject project)
@@ -457,7 +461,7 @@ public sealed class WorkspaceCleaner
var sent = 0L;
try
{
sent = project.ReadRenders().Entries.Where(e => e.IsSent).Select(e => new FileInfo(project.ExportFile(e.File))).Where(f => f.Exists).Sum(f => f.Length);
sent = SentBytes(project, project.ReadRenders());
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
@@ -109,7 +109,7 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
if (held) await WhileHeldAsync(context).ConfigureAwait(false);
var entry = entries[i];
var file = project.ExportFile(entry.File);
var refusal = await CheckAsync(project, entry, file, ct).ConfigureAwait(false);
var refusal = await CheckAsync(project, entry, file, folders: !held, ct).ConfigureAwait(false);
if (refusal is null)
{
if (entry.ProjectVersionId is { } versionId && !versions.Contains(versionId))
@@ -141,13 +141,27 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
if (refused > 0) throw new InvalidOperationException(Loc.L("Errors.Workspace.SendFailed", refused, entries.Count));
}
/// <summary>Why the render cannot be sent as it is (gone from the exports, or another file than the one rendered); null when it can.</summary>
private static async Task<string?> CheckAsync(WorkspaceProject project, WorkspaceRenderEntry entry, string file, CancellationToken ct)
/// <summary>
/// Why the render cannot be sent as it is (gone from the exports, another file than the one rendered, or an image
/// sequence's folder for a home that takes one file per render); null when it can. A folder (an image sequence, only
/// when <paramref name="folders"/>: this PC's archive files folders as its own renders do) is checked by its total size
/// and the hash of its listing, as the render recorded it (<see cref="WorkspaceRenderJobHandler.HashAsync"/>).
/// </summary>
private static async Task<string?> CheckAsync(WorkspaceProject project, WorkspaceRenderEntry entry, string file, bool folders, CancellationToken ct)
{
var name = Path.GetFileName(entry.File);
var exports = Path.TrimEndingDirectorySeparator(Path.GetFullPath(project.ExportsDirectory)) + Path.DirectorySeparatorChar;
// A ledger names files inside the exports only; one pointing elsewhere is never read.
if (!Path.GetFullPath(file).StartsWith(exports, StringComparison.OrdinalIgnoreCase) || !File.Exists(file)) return Loc.L("Errors.Workspace.SendMissing", name);
if (!Path.GetFullPath(file).StartsWith(exports, StringComparison.OrdinalIgnoreCase)) return Loc.L("Errors.Workspace.SendMissing", name);
if (Directory.Exists(file))
{
if (!folders) return Loc.L("Errors.Workspace.SendSequence", name);
return WorkspaceCleaner.Measure(file).Bytes != entry.Size
|| !string.Equals(await WorkspaceRenderJobHandler.HashAsync(file).ConfigureAwait(false), entry.Sha256, StringComparison.OrdinalIgnoreCase)
? Loc.L("Errors.Workspace.SendHashMismatch", name)
: null;
}
if (!File.Exists(file)) return Loc.L("Errors.Workspace.SendMissing", name);
if (new FileInfo(file).Length != entry.Size
|| !string.Equals(await ChronosClient.HashFileAsync(file, ct).ConfigureAwait(false), entry.Sha256, StringComparison.OrdinalIgnoreCase))
return Loc.L("Errors.Workspace.SendHashMismatch", name);
@@ -192,16 +206,27 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
SyncTransfers.EnsureSpace(paths.Root, entry.Size);
Directory.CreateDirectory(paths.StagingDirectory);
var staged = Path.Combine(paths.StagingDirectory, "workspace-render-" + entry.RenderId.ToString("N") + ".part");
var folder = Directory.Exists(file);
try
{
await using (var source = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.Asynchronous | FileOptions.SequentialScan))
await using (var target = new FileStream(staged, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 20, FileOptions.Asynchronous))
TryDelete(staged);
if (folder)
{
await source.CopyToAsync(target, ct).ConfigureAwait(false);
target.Flush(flushToDisk: true);
// An image sequence: every file of its folder, the folder filed whole as the archive's own renders are.
foreach (var source in Directory.EnumerateFiles(file, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(staged, Path.GetRelativePath(file, source));
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await CopyAsync(source, target, ct).ConfigureAwait(false);
}
Directory.CreateDirectory(staged);
}
else await CopyAsync(file, staged, ct).ConfigureAwait(false);
// Read back from the archive's volume: what is filed is the render as it was written.
if (!string.Equals(await ChronosClient.HashFileAsync(staged, ct).ConfigureAwait(false), entry.Sha256, StringComparison.OrdinalIgnoreCase))
var readBack = folder
? await WorkspaceRenderJobHandler.HashAsync(staged).ConfigureAwait(false)
: await ChronosClient.HashFileAsync(staged, ct).ConfigureAwait(false);
if (!string.Equals(readBack, entry.Sha256, StringComparison.OrdinalIgnoreCase))
throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", staged));
var name = SyncTransfers.SafeFileName(Path.GetFileName(entry.File)) ?? entry.RenderId.ToString("N");
var filed = await SyncTransfers.FileRenderAsync(archives, db, sequence, paths, staged, name, new Render
@@ -228,6 +253,15 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
}
}
/// <summary>Copies <paramref name="source"/> to <paramref name="target"/>, flushed to the disk.</summary>
private static async Task CopyAsync(string source, string target, CancellationToken ct)
{
await using var from = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.Asynchronous | FileOptions.SequentialScan);
await using var to = new FileStream(target, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 20, FileOptions.Asynchronous);
await from.CopyToAsync(to, ct).ConfigureAwait(false);
to.Flush(flushToDisk: true);
}
/// <summary>The project the entry names is one of the sequence's, and its version (when it names one) one of that project's.</summary>
private async Task<bool> ProjectOfAsync(Guid sequenceId, WorkspaceRenderEntry entry, CancellationToken ct)
{
@@ -290,7 +324,8 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
{
try
{
if (File.Exists(path)) File.Delete(path);
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
else if (File.Exists(path)) File.Delete(path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -3,6 +3,7 @@ using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Settings;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
@@ -112,36 +113,25 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
var plan = await host.PlanTrashAsync();
Assert.Equal((2, 2L * "kept aside a".Length), (plan.Items.Count, plan.Bytes));
var closed = 0;
WorkspaceTrashResult? emptied = null;
var dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++);
Assert.Equal(2, dialog.Rows.Count);
Assert.Equal("2", dialog.Confirmation);
Assert.False(dialog.EraseCommand.CanExecute(null), "nothing typed");
dialog.Typed = "3";
Assert.False(dialog.CanErase, "the wrong number");
dialog.Typed = " 2 ";
Assert.True(dialog.CanErase && dialog.EraseCommand.CanExecute(null), "the number of entries");
// The Empty… confirmation lists both entries and asks for their number typed.
var request = Assert.NotNull(WorkspaceSettingsRows.TrashRequest(plan));
Assert.Equal("2", request.TypedConfirmation);
Assert.True(request.IsDestructive, "erasing for good is destructive");
// An entry added since the plan: refused, nothing erased, the dialog stays open with why.
// An entry added since the plan: refused, nothing erased.
var late = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
File.WriteAllText(Path.Combine(late, "late.txt"), "late");
dialog.EraseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => dialog.ErrorText is { Length: > 0 }, "the emptying is refused");
Assert.Equal(0, closed);
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.EmptyTrashAsync(plan));
Assert.Equal(Loc.L("Errors.Workspace.TrashChanged"), refused.Message);
Assert.Equal(3, (await host.PlanTrashAsync()).Items.Count);
// As planned again: erased for good, the dialog closed.
// As planned again: erased for good.
plan = await host.PlanTrashAsync();
dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++) { Typed = "3" };
dialog.EraseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => closed == 1, "the dialog closes");
Assert.True(emptied is { Items: 3 }, "three entries erased");
var emptied = await host.EmptyTrashAsync(plan);
Assert.Equal(3, emptied.Items);
Assert.True((await host.PlanTrashAsync()).IsEmpty, "the trash is empty");
// An empty trash offers nothing to erase.
var none = new WorkspaceTrashDialogViewModel(await host.PlanTrashAsync(), p => host.EmptyTrashAsync(p), null, _ => { }) { Typed = "0" };
Assert.False(none.CanErase);
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled"), none.EraseToolTip);
Assert.Null(WorkspaceSettingsRows.TrashRequest(await host.PlanTrashAsync()));
}
}
@@ -90,18 +90,22 @@ public sealed class WorkspaceRenderTests(TestContext context)
Assert.Equal(await Chronos.Core.Archiving.ContentHash.Sha256Async(output), entry.Sha256);
Assert.Equal(("Mjpeg", 96, 64), (entry.Codec, entry.Width, entry.Height));
Assert.Null(entry.ProjectVersionId, "the working state the job embeds is no version this workspace holds");
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct));
// The send home follows with the new render.
// The send home follows with the new render, and files it in the archive with its project.
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
var sent = Assert.NotNull(WorkspaceJobs.SendParameters(send));
Assert.SequenceEqual([entry.RenderId], sent.RenderIds);
Assert.Equal((bed.Project.ProjectId, bed.Store.Root), (sent.ProjectId, sent.WorkspaceRoot));
await fx.WaitForAsync(send.Id, JobState.Done);
var filed = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
Assert.Equal((bed.Sequence.Id, (Guid?)bed.Project.ProjectId, (Guid?)null), (filed.SequenceId, filed.ProjectId, filed.ProjectVersionId));
entry = Assert.NotNull(bed.Project.ReadRenders().Find(entry.RenderId));
Assert.True(entry.IsSent, "the ledger says it went home");
// The same render of the archive's own sequence: the same pictures, at the same size and length.
var archive = await bed.Engine.EnqueueAsync(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64), cancellationToken: fx.Ct);
await fx.WaitForAsync(archive.Id, JobState.Done);
var row = (await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct)).Single();
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(RenderJobHandler.RenderId(archive.Id, 0), fx.Ct));
Assert.Equal((row.Width, row.Height, row.Fps, row.DurationSeconds), (entry.Width, entry.Height, entry.Fps, entry.DurationSeconds));
// Again: another name, the first output and its entry kept.
@@ -140,6 +144,67 @@ public sealed class WorkspaceRenderTests(TestContext context)
Assert.Equal(Loc.L("Errors.Workspace.RenderVersion"), (await fx.WaitForAsync(unknown.Id, JobState.Failed)).Error);
}
/// <summary>
/// The whole way of a local render to an archive home: originals copied, a version saved for the render, the render on this
/// PC, the send that pushes the version first and files the render with its project and version, then the clean-up that
/// removes the media and the sent file of the project, now in step with its home.
/// </summary>
[Test]
public async Task ALocalRenderGoesHomeWithItsVersionAndTheCleanUpThenFreesTheProject()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var id = bed.Project.ProjectId;
var sync = new WorkspaceSync(bed.Store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, bed.Sequence.Id);
Assert.True(bed.Project.ReadMedia() is { HoldsOriginals: true }, "the copy brought the originals");
// The archive's photos hashed (a Verify), so the home can say it holds each original as it is here.
var verify = await bed.Engine.EnqueueAsync(ArchiveJobs.Verify(fx.Archive.Archive, [bed.Sequence.Id]), cancellationToken: fx.Ct);
await fx.WaitForAsync(verify.Id, JobState.Done);
// Version on render: the working state saved as a version here, not sent yet.
var session = await sync.OpenAsync(id, fx.Ct);
await sync.SaveAsync(id, session.Working with { ExcludedFrames = [4] }, fx.Ct);
var version = Assert.NotNull(await sync.CommitAsync(id, "Render", cancellationToken: fx.Ct));
Assert.Null(await home.GetVersionAsync(id, version.Id, fx.Ct), "the home does not have the version yet");
var json = System.Text.Json.Nodes.JsonNode.Parse(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!)!.AsObject();
json.Remove("settingsJson");
var render = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, id, version.Id, json.ToJsonString()), cancellationToken: fx.Ct);
await fx.WaitForAsync(render.Id, JobState.Done);
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal((version.Id, WorkspaceRenderEntry.Pending), (entry.ProjectVersionId, entry.State));
// The send pushes the version, then files the render with its project and version.
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
send = await fx.WaitForAsync(send.Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionPushed", bed.Project.ReadBundle().Workspace!.Name, version.Number), send.LogTail);
Assert.NotNull(await home.GetVersionAsync(id, version.Id, fx.Ct));
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
Assert.Equal((bed.Sequence.Id, (Guid?)id, (Guid?)version.Id, entry.Size), (row.SequenceId, row.ProjectId, row.ProjectVersionId, row.Bytes));
Assert.Equal(entry.Sha256, await Chronos.Core.Archiving.ContentHash.Sha256Async(Path.Combine(fx.Archive.Paths.Root, row.OutputPath)));
Assert.True(bed.Project.ReadRenders().Find(entry.RenderId)!.IsSent, "the ledger says it went home");
Assert.Equal(WorkspaceState.InSync, (await sync.StatusAsync(id, home, fx.Ct)).State);
// The clean-up (here the size limit) frees the project: its proxies, originals and the sent render go; the originals
// are the home's own, so none is set aside in the trash.
var exported = bed.Project.ExportFile(entry.File);
var report = await new WorkspaceCleaner(sync, fx.Db, _ => home) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) }
.CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = 1 }, fx.Ct);
var cleaned = Assert.NotNull(report.Cleaned.SingleOrDefault());
Assert.Equal((id, 0), (cleaned.ProjectId, cleaned.Trashed));
Assert.Empty(report.Kept);
Assert.FileMissing(exported);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False(Directory.Exists(bed.Project.OriginalsDirectory), "the originals went");
Assert.False(Directory.Exists(bed.Project.ProxiesDirectory), "the proxies went");
Assert.True(bed.Project.ReadMedia() is { IsCleaned: true }, "the media index says it was cleaned");
Assert.Equal(WorkspaceState.MediaRemoved, (await sync.StatusAsync(id, home, fx.Ct)).State);
// The home keeps the render and the version.
Assert.FileExists(Path.Combine(fx.Archive.Paths.Root, row.OutputPath));
}
[Test]
public async Task WithoutTheOriginalsTheRenderIsRefusedSayingHowManyLack()
{
@@ -117,6 +117,42 @@ public abstract class WorkspaceSendTests(TestContext context) : DatabaseTest(con
Assert.Contains(Loc.L("Archive.Log.WorkspaceSent", project.ReadBundle().Workspace!.Name, 0, 0), nothing.LogTail);
}
[Test]
public async Task AnImageSequenceIsFiledWholeAndCheckedByItsListing()
{
var fx = await FixtureAsync();
var engine = await EngineAsync(fx);
var (store, _, project) = await CheckoutAsync(fx);
var folder = Path.Combine(project.ExportsDirectory, "Main frames");
Directory.CreateDirectory(folder);
for (var i = 0; i < 3; i++) File.WriteAllText(Path.Combine(folder, $"frame-{i:D4}.png"), "frame " + i);
var size = Directory.GetFiles(folder).Sum(f => new FileInfo(f).Length);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "Main frames", await WorkspaceRenderJobHandler.HashAsync(folder), size,
"PNG frames", "png", 96, 64, 24, 0.125, project.ProjectId, null, null, Rendered);
project.WriteRenders(project.ReadRenders().With(entry));
await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
Assert.Equal((size, (Guid?)project.ProjectId), (row.Bytes, row.ProjectId));
var filed = Path.Combine(fx.Archive.Archive.RootPath, row.OutputPath);
Assert.True(Directory.Exists(filed), filed);
Assert.Equal(entry.Sha256, await WorkspaceRenderJobHandler.HashAsync(filed));
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsSent);
Assert.Empty(Directory.GetFileSystemEntries(fx.Archive.Paths.StagingDirectory, "workspace-render-*"));
// A frame changed after the render: refused, the folder left where it is.
var changed = entry with { RenderId = Guid.CreateVersion7(), File = "Changed frames" };
Directory.CreateDirectory(project.ExportFile(changed.File));
foreach (var file in Directory.GetFiles(folder)) File.Copy(file, Path.Combine(project.ExportFile(changed.File), Path.GetFileName(file)));
File.WriteAllText(Path.Combine(project.ExportFile(changed.File), "frame-0001.png"), "frame X");
project.WriteRenders(project.ReadRenders().With(changed with { State = WorkspaceRenderEntry.Pending, Sent = null }));
var failed = await SendAsync(fx, engine, store, project.ProjectId, JobState.Failed);
Assert.Contains(Loc.L("Errors.Workspace.SendHashMismatch", "Changed frames"), failed.LogTail);
Assert.Null(await fx.Db.Renders.GetAsync(changed.RenderId, fx.Ct));
Assert.True(Directory.Exists(project.ExportFile(changed.File)), "the folder stays in the workspace");
}
[Test]
public async Task AVersionTheHomeLacksIsSentFirst()
{