diff --git a/src/Chronos.App/Editor/EditorPanels.xaml b/src/Chronos.App/Editor/EditorPanels.xaml
index 00f4b059..5ed7dd15 100644
--- a/src/Chronos.App/Editor/EditorPanels.xaml
+++ b/src/Chronos.App/Editor/EditorPanels.xaml
@@ -327,6 +327,9 @@
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
+
diff --git a/src/Chronos.App/Editor/EditorViewModel.cs b/src/Chronos.App/Editor/EditorViewModel.cs
index c36674aa..1f46a73f 100644
--- a/src/Chronos.App/Editor/EditorViewModel.cs
+++ b/src/Chronos.App/Editor/EditorViewModel.cs
@@ -634,7 +634,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var export = batch ? RenderExport : RenderExport with { Batch = [] };
var requests = Session.RenderRequests(export);
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
- if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
+ if (Session.Source is IProjectRenders { RendersLocally: true })
+ Shell.Notify(Loc.L("Editor.Render.QueuedLocal"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
+ else if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -957,7 +959,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void RefreshSteps()
{
if (_disposed) return;
- var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render),
+ var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render) ?? _jobs.Active(JobKind.WorkspaceRender),
_planned ? RenderBlockedReason : null, _rendered.Matches(Session.Project));
foreach (var tab in Tabs) tab.SetStep(EditPath.Of(tab.Key, facts));
Analysis.OnStepChanged();
@@ -1174,7 +1176,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (_disposed)
{
// Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read.
- if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
+ if (job is { State: JobState.Done } && IsRender(job.Kind) && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
AnnounceRender(job, read: false);
return;
}
@@ -1186,13 +1188,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!wasActive) return;
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited();
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
- if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
+ if (job.State == JobState.Done) _ = ReloadAsync(IsRender(job.Kind) && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
+ // A local render's send home (phase 5c): said once, here or on the Jobs screen.
+ if (job is { Kind: JobKind.WorkspaceSend, State: JobState.Done } && Shell.Jobs.ClaimRenderToast(job.Id)) Shell.Notify(Loc.L("Editor.Render.SentHome"), Title);
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so.
if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
- else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
+ else if (IsRemote && job.Kind is not (JobKind.WorkspaceRender or JobKind.WorkspaceSend) && job.State is JobState.Failed or JobState.Cancelled)
+ ReportServerJobEnded(job);
});
}
+ /// A render of the sequence: at its home, or on this PC from a workspace project's originals (phase 5c).
+ private static bool IsRender(JobKind kind) => kind is JobKind.Render or JobKind.WorkspaceRender;
+
///
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
diff --git a/src/Chronos.App/Editor/ExportTab.cs b/src/Chronos.App/Editor/ExportTab.cs
index 5fa4c15a..1cc5b943 100644
--- a/src/Chronos.App/Editor/ExportTab.cs
+++ b/src/Chronos.App/Editor/ExportTab.cs
@@ -403,6 +403,14 @@ public sealed class ExportTab : EditorTab
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory");
+ /// A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".
+ public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
+
+ /// Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace.
+ public string? UnsentToolTip => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 } source
+ ? Loc.L(source.IsServerHome ? "Tooltips.Editor.Render.NotSent.Server" : "Tooltips.Editor.Render.NotSent")
+ : null;
+
public IReadOnlyList Batch => Export.Batch;
/// Completes when the card estimates in flight are done.
diff --git a/src/Chronos.App/Editor/SequenceJobs.cs b/src/Chronos.App/Editor/SequenceJobs.cs
index 7093547a..3f44250b 100644
--- a/src/Chronos.App/Editor/SequenceJobs.cs
+++ b/src/Chronos.App/Editor/SequenceJobs.cs
@@ -11,8 +11,8 @@ public sealed class SequenceJobs(Guid sequenceId)
{
private readonly Dictionary _active = [];
- /// An analysis or render runs: settings wait.
- public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
+ /// An analysis or render runs: settings wait (a local render's send home does not hold them).
+ public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running && j.Kind != JobKind.WorkspaceSend);
/// A deep analysis waits, runs or is paused.
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
@@ -23,13 +23,17 @@ public sealed class SequenceJobs(Guid sequenceId)
/// The job of to show, chosen as is (the Edit path's steps).
public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind));
- /// An analysis or render of this sequence.
+ /// An analysis or render of this sequence, a workspace project's render on this PC or its send home (phase 5c).
public bool Concerns(Job job)
{
ArgumentNullException.ThrowIfNull(job);
- return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
+ return job.TargetIds.Contains(sequenceId) && IsSequenceKind(job.Kind);
}
+ /// The kinds the editor follows.
+ public static bool IsSequenceKind(JobKind kind) =>
+ kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend;
+
/// The job is one of those that wait, run or are paused.
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
diff --git a/src/Chronos.App/Editor/ServerJobs.cs b/src/Chronos.App/Editor/ServerJobs.cs
index f1cd4570..31160330 100644
--- a/src/Chronos.App/Editor/ServerJobs.cs
+++ b/src/Chronos.App/Editor/ServerJobs.cs
@@ -208,7 +208,7 @@ internal sealed class ServerJobs : IAsyncDisposable
_changed(job);
}
- private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
+ private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && SequenceJobs.IsSequenceKind(job.Kind);
/// A sequence deleted on the server reads as gone, like a local one removed from the index.
internal static async Task Call(Func> call)
diff --git a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs
index 549aed0d..0f1a4b3b 100644
--- a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs
+++ b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs
@@ -29,6 +29,9 @@ public interface IProjectRenders
{
/// The jobs that render of (the editor's settings, positions on the source's frames).
IReadOnlyList RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
+
+ /// The renders run on this PC (a workspace project holding its originals, phase 5c), whatever the home.
+ bool RendersLocally { get; }
}
///
@@ -95,6 +98,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace;
private bool _readOnly;
+ private bool _holdsOriginals;
+ private int _unsent;
private int _disposed;
/// The server the project's home is (phase 5b); null for a project of this PC's archive.
@@ -136,6 +141,15 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// Settings of a newer Chronos: shown, never saved.
public bool IsReadOnly => Volatile.Read(ref _readOnly);
+ ///
+ /// The media read last hold the originals (phase 5c): the project renders on this PC's engine from them, into its
+ /// exports/, and the renders are sent home after (), also for a server home.
+ ///
+ public bool RendersLocally => Volatile.Read(ref _holdsOriginals);
+
+ /// The local renders of the project's ledger not at the home yet, as read last.
+ public int UnsentRenders => Volatile.Read(ref _unsent);
+
public bool IsOutdated => false;
/// The library's values and the editor's are asked about where both changed a setting, as a sync asks.
@@ -179,6 +193,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
IReadOnlyList renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
return await Task.Run(() =>
{
+ renders = [.. renders, .. UnsentOf(session.Project, home.SequenceId)];
var frames = media.Frames;
Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly);
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
@@ -278,6 +293,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
Created = r.Created,
ProducedBy = r.ProducedBy,
}).ToList() ?? [];
+ renders = [.. renders.Concat(UnsentOf(session.Project, home.SequenceId)).OrderByDescending(r => r.Created)];
var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count);
var context = SequenceContext.FromFrames(frames);
return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
@@ -495,7 +511,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so.
public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
- if (_server is not null) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken);
+ ArgumentNullException.ThrowIfNull(request);
+ // A render from the workspace's originals and its send run on this PC's engine, whatever the home (phase 5c).
+ if (_server is not null && !RunsHere(request.Kind)) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken);
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
return job.Id;
@@ -504,26 +522,40 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).
public async Task> ListJobsAsync(CancellationToken cancellationToken)
{
- if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
- if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return [];
+ var local = (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
+ if (_server is null) return local;
+ // This PC's renders from the originals and their sends beside the server's jobs (phase 5c).
+ IReadOnlyList here = [.. local.Where(j => RunsHere(j.Kind))];
+ if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return here;
try
{
- return await jobs.ListAsync(cancellationToken);
+ return [.. (await jobs.ListAsync(cancellationToken)).Concat(here)];
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException)
{
Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}");
- return [];
+ return here;
}
}
- public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
- ? ServerJobsOrThrow().CancelAsync(jobId, cancellationToken)
- : (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
+ public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
+ {
+ if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().CancelAsync(jobId, cancellationToken);
+ else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
+ }
- public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
- ? ServerJobsOrThrow().RetryAsync(jobId, cancellationToken)
- : (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
+ public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
+ {
+ if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().RetryAsync(jobId, cancellationToken);
+ else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
+ }
+
+ /// The kinds a workspace project runs on this PC's engine whatever its home: a render from its originals and its send home.
+ private static bool RunsHere(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
+
+ /// A job of this PC's engine that runs here whatever the home ().
+ private async Task IsLocalJobAsync(Guid jobId, CancellationToken cancellationToken) =>
+ await _db.Jobs.GetAsync(jobId, cancellationToken) is { } job && RunsHere(job.Kind);
///
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
@@ -542,6 +574,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
+ if (RendersLocally && Workspace is { } workspace) return LocalRenderRequests(sequence, workspace.Home, portable, hash, export, sourceWidth, sourceHeight);
if (_server is not null)
{
if (InStepWithHome(project) is { } basis)
@@ -566,6 +599,75 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
+ ///
+ /// The render on this PC from the originals the workspace holds (phase 5c): one per
+ /// preset with the project's portable settings, naming the head version of versions/ when the settings are the
+ /// ones it holds (the render records it; an unsaved working state renders without a version), sent home after.
+ ///
+ private IReadOnlyList LocalRenderRequests(Sequence sequence, BundleHome home, string portable, string hash, ExportSettings export,
+ int sourceWidth, int sourceHeight)
+ {
+ var head = HeadVersion(hash);
+ var version = new ProjectVersion { Id = head ?? Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
+ var root = _sync.Store.Root;
+ var server = home.IsArchive ? null : home.Server;
+ return
+ [
+ .. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => WorkspaceJobs.Render(home.SequenceId,
+ r.Label ?? sequence.DisplayTitle, root, ProjectId, head, (head is null ? WithoutVersion(r.ParametersJson) : r.ParametersJson)!, server)),
+ ];
+ }
+
+ /// The id of the newest version the workspace holds when it holds ; null otherwise.
+ private Guid? HeadVersion(string hash)
+ {
+ try
+ {
+ return Project.Versions() is [.., var last] && string.Equals(last.ContentHash, hash, StringComparison.OrdinalIgnoreCase) ? last.Id : null;
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
+ return null;
+ }
+ }
+
+ /// The local renders of the project's ledger not at the home yet, as renders of (newest first).
+ private IReadOnlyList UnsentOf(WorkspaceProject project, Guid sequenceId)
+ {
+ try
+ {
+ var unsent = project.ReadRenders().Unsent;
+ Volatile.Write(ref _unsent, unsent.Count);
+ return
+ [
+ .. unsent.OrderByDescending(e => e.Rendered).Select(e => new Render
+ {
+ Id = e.RenderId,
+ SequenceId = sequenceId,
+ PresetName = e.PresetName,
+ OutputPath = project.ExportFile(e.File),
+ Codec = e.Codec,
+ Width = e.Width,
+ Height = e.Height,
+ Fps = e.Fps,
+ DurationSeconds = e.DurationSeconds,
+ Bytes = e.Size,
+ Created = e.Rendered,
+ ProducedBy = Environment.MachineName,
+ ProjectId = e.ProjectId,
+ ProjectVersionId = e.ProjectVersionId,
+ }),
+ ];
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("editor", $"The render ledger of workspace project {ProjectId} cannot be read", ex);
+ Volatile.Write(ref _unsent, 0);
+ return [];
+ }
+ }
+
///
/// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project
/// () holds what the base holds; null otherwise.
@@ -643,6 +745,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace;
+ _holdsOriginals = index.HoldsOriginals;
changed = _readOnly != readOnly;
_readOnly = readOnly;
}
diff --git a/src/Chronos.App/Sections/JobsViewModel.cs b/src/Chronos.App/Sections/JobsViewModel.cs
index 79da0724..33cc5b4e 100644
--- a/src/Chronos.App/Sections/JobsViewModel.cs
+++ b/src/Chronos.App/Sections/JobsViewModel.cs
@@ -303,7 +303,7 @@ public sealed class JobsViewModel : SectionViewModel
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
- if (notice == JobNotice.Done && job.Kind == JobKind.Render
+ if (notice == JobNotice.Done && job.Kind is JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job);
}
diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
index 318a7498..ab34e285 100644
--- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
+++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs
@@ -252,12 +252,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
///
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
- /// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive
- /// renders as it is: true.
+ /// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive,
+ /// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version
+ /// on render, a changed project is saved as a version first ().
///
public async Task ReadyToRenderAsync()
{
- if (!IsServerHome) return true;
+ if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false;
+ // Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is.
+ if (!IsServerHome || _source.RendersLocally) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
@@ -296,6 +299,45 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
+ ///
+ /// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version
+ /// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach,
+ /// it waits here). False when it could not be saved, or the sync met a conflict to settle first.
+ ///
+ private async Task SaveForRenderAsync()
+ {
+ await StoreEditAsync();
+ var status = await _host.StatusAsync(ProjectId);
+ if (_disposed) return false;
+ Apply(status);
+ if (!status.Modified || !CanSaveVersion) return true;
+ WorkspaceSaveResult result;
+ try
+ {
+ result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote"));
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex);
+ _ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
+ return false;
+ }
+ if (_disposed) return false;
+ Apply(result.Status);
+ if (result.Synced is { } taken) await TakeAsync(taken);
+ if (result.Version is { } version)
+ {
+ // The home numbers what it stores: the last one sent is this version.
+ var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number;
+ _ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name);
+ }
+ if (result.SyncError is { } error)
+ _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
+ if (result.Status.Conflict is not { } conflict) return true;
+ AskConflict(conflict);
+ return false;
+ }
+
///
/// Saves the working state as a version with , sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
diff --git a/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs
index f37c4e52..9dfe11cd 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs
@@ -1,24 +1,286 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Chronos.Core.Analysis.Deep;
+using Chronos.Core.Archiving;
+using Chronos.Core.Export;
+using Chronos.Core.Localization;
using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Core.Render;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
+using Chronos.Data.Processing;
+using Chronos.Data.Processing.Jobs;
+using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
namespace Chronos.Data.Workspaces;
///
/// (phase 5c, ): a workspace project rendered on this
/// PC from the originals its media hold, as renders an archive's sequence,
-/// into the project's exports/ (each output written as .part, then renamed), each output hashed and recorded in
-/// the project's ledger (, its id RenderJobHandler.RenderId(jobId, index)), then a
-/// queued with the new ids. Media without an original for every placed frame are refused.
+/// into the project's exports/ (each output written by the encoder under a hidden temporary name, then renamed), each
+/// output hashed and recorded in the project's ledger (, its id
+/// RenderJobHandler.RenderId(jobId, index)), then a queued with the new ids.
+/// Media without an original for every placed frame are refused. The project's lease is held while the inputs are read
+/// and while each ledger entry is written, not for the whole render: the editor keeps saving its working state meanwhile.
+/// The settings rendered are the ones the job embeds (the editor's portable settings), else the version it names from
+/// versions/; the version is recorded only when versions/ holds it with the content hash of what rendered.
+/// Checkpoint: the entries recorded and the output being written; a resumed job removes that output's leftovers (never one
+/// the ledger names) and renders only what is not recorded yet.
///
internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveService archives, WorkspaceJobOptions options) : IJobHandler
{
+ private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
+
public JobKind Kind => JobKind.WorkspaceRender;
- public Task RunAsync(JobContext context)
+ public async Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
- _ = (db, archives, options);
- throw new NotImplementedException("Local renders of a workspace project come with phase 5c (P2).");
+ // The index and the archive engine are not read: everything a local render needs is in the workspace project.
+ _ = (db, archives);
+ var cancellation = context.Cancellation;
+ var parameters = WorkspaceJobs.RenderParameters(context.Job) ?? throw new InvalidDataException(Loc.L("Errors.Workspace.JobParameters"));
+ var (render, export) = ProcessingJobs.ReadRender(parameters.RenderJson);
+ var store = new WorkspaceStore(parameters.WorkspaceRoot);
+ var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
+ var inputs = await ReadInputsAsync(project, parameters, render, cancellation).ConfigureAwait(false);
+ var (sequence, frames, settings, versionId) = (inputs.Sequence, inputs.Frames, inputs.Settings, inputs.VersionId);
+ // A local render's outputs stay in the project's exports, from where they are sent home.
+ var projectSettings = ProjectStore.Parse(settings) with { Export = export with { Folder = null } };
+ var settingsJson = projectSettings.ToJson();
+ var settingsHash = ProjectContent.Hash(inputs.Portable);
+
+ var exports = project.ExportsDirectory;
+ Directory.CreateDirectory(exports);
+ using var names = new OutputNames();
+ var all = RenderJobHandler.Targets(projectSettings.Export, render.PresetName);
+ var resume = RenderCheckpoint.Parse(context.Checkpoint);
+ var done = resume.Done.ToList();
+ var ledger = project.ReadRenders();
+ for (var i = 0; i < all.Count; i++)
+ {
+ if (!done.Contains(i) && ledger.Find(RenderJobHandler.RenderId(context.Job.Id, i)) is not null) done.Add(i);
+ }
+ if (resume is { Pending: { } pending, PendingOutput: { } chosen } && !done.Contains(pending) && Inside(exports, chosen) && names.TryReserve(chosen))
+ {
+ Discard(chosen, keepOutput: ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), chosen)));
+ names.Release(chosen);
+ }
+ var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
+ var recorded = new List();
+ if (targets.Count > 0)
+ {
+ string? writing = null;
+ IReadOnlyList outcomes;
+ try
+ {
+ await using var renderer = new SequenceRender(frames, projectSettings, inputs.Analysis, options.Processing, originals: true, companions: null);
+ outcomes = await renderer.RenderAllAsync(
+ targets,
+ (target, setup) => names.Reserve(taken => ExportNaming.OutputPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup),
+ name => taken(name) || ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), name)))),
+ (index, path) =>
+ {
+ writing = path;
+ return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total);
+ },
+ async (index, target, result) =>
+ {
+ // The output is complete: recorded even if the job is being cancelled, so it is never orphaned.
+ var id = RenderJobHandler.RenderId(context.Job.Id, index);
+ var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false);
+ using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
+ {
+ ledger = project.ReadRenders().With(entry);
+ project.WriteRenders(ledger);
+ }
+ done.Add(index);
+ recorded.Add(id);
+ writing = null;
+ await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
+ context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
+ foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
+ },
+ context.ReportAsync,
+ cancellation).ConfigureAwait(false);
+ if (renderer.StandIns.Count > 0)
+ context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", renderer.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
+ }
+ catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
+ {
+ // What the encoder was writing goes; every output recorded stays, and a resumed job renders the rest.
+ if (writing is { } partial) Discard(partial, keepOutput: true);
+ await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
+ throw;
+ }
+ var failed = outcomes.Where(o => o.Error is not null).ToList();
+ foreach (var outcome in failed) context.Log(Loc.L("Export.Log.Failed", outcome.Target.PresetName, outcome.Error));
+ await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
+ if (failed.Count > 0)
+ throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
+ }
+ }
+
+ /// What the render reads, taken under the project's lease so the media, the versions and the project file agree.
+ private sealed record Inputs(Sequence Sequence, SequenceFrames Frames, string Settings, string Portable, Guid? VersionId, DeepAnalysisReport? Analysis);
+
+ ///
+ /// The sequence over the workspace's originals, the settings to render (placed on its frames) and the version they are,
+ /// read under the project's lease.
+ ///
+ ///
+ /// The project is gone (Errors.Workspace.RenderProject), holds no originals (Errors.Workspace.OriginalsMissing),
+ /// lacks the original of a frame the render places (Errors.Workspace.RenderNoOriginals, with their number), or the
+ /// version the job names is not in versions/ (Errors.Workspace.RenderVersion).
+ ///
+ private static async Task ReadInputsAsync(WorkspaceProject project, WorkspaceRenderParameters parameters, Protocol.RenderJobParameters render,
+ CancellationToken cancellationToken)
+ {
+ using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
+ {
+ if (!File.Exists(project.BundlePath)) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
+ var bundle = project.ReadBundle();
+ var workspace = bundle.Workspace!;
+ var media = project.ReadMedia();
+ if (media is not { HoldsOriginals: true })
+ throw new InvalidOperationException(Loc.L(workspace.Home.IsArchive ? "Errors.Workspace.OriginalsMissing" : "Errors.Workspace.OriginalsMissing.Server"));
+ var versions = project.Versions();
+ var named = parameters.ProjectVersionId ?? render.ProjectVersionId;
+ var version = named is { } id ? versions.FirstOrDefault(v => v.Id == id) : null;
+ string portable;
+ if (render.SettingsJson is { Length: > 0 } embedded) portable = embedded;
+ else if (named is not null) portable = version?.SettingsJson ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderVersion"));
+ else portable = versions.Count > 0 ? versions[^1].SettingsJson : ProjectContent.ToPortable(bundle.Project, media.Photos);
+ // Recorded only for the settings it holds (a version is never named for settings it did not render).
+ Guid? versionId = version is not null && ProjectContent.Verifies(portable, version.ContentHash) ? version.Id : null;
+ var settings = portable.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase) ? Place(portable, media.Photos) : portable;
+ var placed = ProjectStore.Parse(settings);
+ var excluded = placed.ExcludedFrames.ToHashSet();
+ var lacking = media.Frames.Count(f => f.Original is null && !excluded.Contains(f.Index) && (f.Flags & SequenceFrames.NotRendered) == 0);
+ if (lacking > 0) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderNoOriginals", lacking));
+ var frames = media.ToOriginalFrames();
+ var files = media.Frames.Select(f => f.Original is { } original ? project.MediaFile(original) : null).ToList();
+ var sequence = SequenceOf(bundle, media, frames);
+ return new Inputs(sequence, new SequenceFrames(sequence, frames, files), settings, portable, versionId, Analysis(project, frames.Count));
+ }
+ }
+
+ /// The home's sequence as the project file and the media name it (the workspace keeps no index row of it).
+ private static Sequence SequenceOf(ProjectBundle bundle, WorkspaceMedia media, IReadOnlyList frames)
+ {
+ var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
+ var home = bundle.Workspace!.Home;
+ return new Sequence
+ {
+ Id = home.SequenceId,
+ ArchiveId = bundle.Archive.Id,
+ Title = bundle.Sequence.Title,
+ Folder = bundle.Sequence.Folder,
+ FrameCount = frames.Count,
+ FirstCapture = times.Count > 0 ? times[0] : null,
+ LastCapture = times.Count > 0 ? times[^1] : null,
+ FramesVersion = media.FramesVersion,
+ Origin = home.IsArchive ? SequenceOrigin.Local : SequenceOrigin.Server,
+ };
+ }
+
+ /// The deep report the copy brought from the home, when it describes these frames; null otherwise.
+ private static DeepAnalysisReport? Analysis(WorkspaceProject project, int frameCount)
+ {
+ if (!File.Exists(project.AnalysisPath)) return null;
+ try
+ {
+ var report = DeepAnalysisReport.Load(project.AnalysisPath);
+ return report.FrameCount == frameCount ? report : null;
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException or UnauthorizedAccessException)
+ {
+ Core.Diagnostics.Log.Warning("workspace", $"{project.AnalysisPath} cannot be read", ex);
+ return null;
+ }
+ }
+
+ /// Portable settings placed on the media's frames; others as they are.
+ private static string Place(string portable, FramePhotos photos)
+ {
+ try
+ {
+ return ProjectContent.Place(portable, photos);
+ }
+ catch (JsonException)
+ {
+ // Not a project: reading it says so.
+ return portable;
+ }
+ }
+
+ /// The ledger entry of a finished output: hashed as it is on the disk now.
+ private static async Task EntryAsync(WorkspaceProject project, Guid jobId, Guid renderId, ExportTarget target, RenderResult result,
+ Guid? versionId, string settingsHash)
+ {
+ var sha = await HashAsync(result.OutputPath).ConfigureAwait(false);
+ var file = Path.GetRelativePath(project.ExportsDirectory, result.OutputPath).Replace('\\', '/');
+ return new WorkspaceRenderEntry(renderId, jobId, file, sha, result.Bytes, target.PresetName, result.Codec.ToString(), result.Width, result.Height,
+ result.FrameRate.Value, result.DurationSeconds, project.ProjectId, versionId, settingsHash, DateTimeOffset.UtcNow);
+ }
+
+ ///
+ /// The SHA-256 of an output: of the file, or, for an image sequence's folder, of its files' relative paths and SHA-256 in
+ /// order (a send checks the folder the same way).
+ ///
+ internal static async Task HashAsync(string output)
+ {
+ if (File.Exists(output)) return await ContentHash.Sha256Async(output, cancellationToken: CancellationToken.None).ConfigureAwait(false);
+ var listing = new StringBuilder();
+ foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
+ {
+ var sha = await ContentHash.Sha256Async(file, cancellationToken: CancellationToken.None).ConfigureAwait(false);
+ listing.Append(Path.GetRelativePath(output, file).Replace('\\', '/')).Append(' ').Append(sha).Append('\n');
+ }
+ return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(listing.ToString())));
+ }
+
+ /// Queues the send home of the renders this run recorded, whatever stops the job now (they are done).
+ private static async Task QueueSendAsync(JobContext context, WorkspaceRenderParameters parameters, Sequence sequence, List recorded)
+ {
+ if (recorded.Count == 0) return;
+ var send = WorkspaceJobs.Send(sequence.Id, sequence.DisplayTitle, parameters.WorkspaceRoot, parameters.ProjectId, [.. recorded],
+ parameters.Server, context.Job.Priority);
+ await context.EnqueueFollowUpAsync(send.Kind, send.Targets, send.Label, send.ParametersJson, send.Priority, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ private static bool Inside(string folder, string path)
+ {
+ var relative = Path.GetRelativePath(folder, path);
+ return !relative.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(relative);
+ }
+
+ private static bool SamePath(string a, string b) =>
+ string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
+
+ ///
+ /// Removes what an interrupted attempt left of : the encoder's hidden temporary file or folder,
+ /// and an output completed but never recorded (it renders again under the same name) unless .
+ ///
+ private static void Discard(string output, bool keepOutput)
+ {
+ var parent = Path.GetDirectoryName(output);
+ if (parent is null || !Directory.Exists(parent)) return;
+ var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").ToList();
+ if (!keepOutput) leftovers.Add(output);
+ foreach (var leftover in leftovers)
+ {
+ try
+ {
+ if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
+ else if (File.Exists(leftover)) File.Delete(leftover);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Core.Diagnostics.Log.Warning("workspace", $"{leftover} could not be removed", ex);
+ }
+ }
}
}
diff --git a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
index 82011cda..a9755843 100644
--- a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
@@ -137,7 +137,7 @@ public sealed class ServerHomeTests(TestContext context)
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
- var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
+ var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
new file mode 100644
index 00000000..8acb9bb9
--- /dev/null
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
@@ -0,0 +1,128 @@
+using System.Globalization;
+using System.IO;
+using Chronos.App.Editor;
+using Chronos.App.Infrastructure;
+using Chronos.App.Workspace;
+using Chronos.Core.Export;
+using Chronos.Core.Imaging.Decoders;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Data.Processing;
+using Chronos.Data.Workspaces;
+using Chronos.Protocol.Client;
+using Chronos.Testing;
+
+namespace Chronos.App.Tests.Workspace;
+
+///
+/// Phase 5c in Edit: a workspace project that holds its originals renders on this PC (),
+/// also when its home is a server, and Settings › Workspace › Version on render saves a changed project as a version first.
+///
+[Category("workspace")]
+public sealed class WorkspaceLocalRenderTests(TestContext context)
+{
+ private const string Server = "https://nas.test:8443";
+
+ private static readonly ExportSettings Mjpeg = new()
+ {
+ Preset = new Auto().WithManual("mjpeg-avi"),
+ Overrides = new ExportOverrides { Width = 96, Height = 64 },
+ NameTemplate = "clip-{codec}",
+ };
+
+ static WorkspaceLocalRenderTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
+
+ [Test]
+ public async Task TheOriginalsRenderOnThisPcEvenForAServerHome()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
+ var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
+ await bed.WaitForJobAsync(checkout.Copy.Id);
+ var projectId = checkout.Project.Id;
+ // Named the server's, as a copy downloaded from the server leaves it.
+ var folder = host.Store.Find(projectId)!;
+ var bundle = folder.ReadBundle();
+ var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
+ folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
+
+ // Not signed in to the server: a render from the originals runs here all the same.
+ var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
+ new WorkspaceServerHome((IRemoteSequenceApi?)null));
+ var content = await source.LoadAsync(bed.Ct);
+ var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
+ await using (session)
+ {
+ Assert.True(source is { IsServerHome: true, RendersLocally: true, UnsentRenders: 0 });
+ var requests = session.RenderRequests(Mjpeg);
+ var request = requests.Single();
+ Assert.Equal(JobKind.WorkspaceRender, request.Kind);
+ Assert.SequenceEqual([bed.SequenceId], request.Targets);
+ var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
+ Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
+ var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
+ Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
+
+ // Queued on this PC's engine and listed beside the server's jobs (the render itself is the Data tests': this bed decodes nothing).
+ var jobId = await source.SubmitAsync(request, bed.Ct);
+ var queued = Assert.NotNull(await bed.Db.Jobs.GetAsync(jobId, bed.Ct));
+ Assert.Equal(JobKind.WorkspaceRender, queued.Kind);
+ Assert.Contains(await source.ListJobsAsync(bed.Ct), j => j.Id == jobId);
+ await WorkspaceTestBed.UntilAsync(() => bed.Db.Jobs.GetAsync(jobId).GetAwaiter().GetResult()?.State is JobState.Done or JobState.Failed, "the render ends");
+
+ // A render the ledger holds and the home has not taken: listed with the others, not sent.
+ var output = Path.Combine(folder.ExportsDirectory, "clip-MJPEG.avi");
+ Directory.CreateDirectory(folder.ExportsDirectory);
+ await File.WriteAllBytesAsync(output, [1, 2, 3], bed.Ct);
+ var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), jobId, "clip-MJPEG.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
+ projectId, null, null, DateTimeOffset.UtcNow);
+ using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry));
+ var reread = await source.LoadAsync(bed.Ct);
+ Assert.Equal(1, source.UnsentRenders);
+ Assert.Equal((entry.RenderId, output), (reread.Renders[0].Id, reread.Renders[0].OutputPath));
+ }
+ }
+
+ [Test]
+ public async Task VersionOnRenderSavesAChangedProjectFirst()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var settings = new AppSettings();
+ Assert.True(settings is { WorkspaceVersionOnRender: true, WorkspaceAutoSync: true }, "on by default");
+ var host = bed.Host(settings);
+ var projectId = await bed.CheckoutAsync(host);
+ var (source, session) = await bed.OpenAsync(host, projectId);
+ var ui = new RecordingUi();
+ await using (session)
+ using (var menu = new ProjectMenuViewModel(host, source, session, ui))
+ {
+ await menu.RefreshAsync();
+ var folder = host.Store.Find(projectId)!;
+ var before = folder.Versions().Count;
+
+ // Nothing changed: nothing saved.
+ Assert.True(await menu.ReadyToRenderAsync());
+ Assert.Equal(before, folder.Versions().Count);
+
+ // Changed: saved as a version noted Render and sent (Sync automatically); the render names it.
+ Assert.True(session.SetHero(2));
+ Assert.True(await session.FlushAsync());
+ Assert.True(await menu.ReadyToRenderAsync());
+ var saved = folder.Versions()[^1];
+ Assert.Equal((before + 1, Loc.L("Editor.Workspace.RenderNote")), (folder.Versions().Count, saved.Note));
+ Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
+ Assert.Equal(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(folder.ReadBundle().Workspace!.Base!.Number)), ui.Toasts[^1].Title);
+ var (render, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
+ Assert.Equal(folder.ReadBundle().Workspace!.Base!.VersionId, render.ProjectVersionId);
+
+ // Off: the project renders as it is, no version saved.
+ settings.WorkspaceVersionOnRender = false;
+ Assert.True(session.SetHero(3));
+ Assert.True(await session.FlushAsync());
+ Assert.True(await menu.ReadyToRenderAsync());
+ Assert.Equal(before + 1, folder.Versions().Count);
+ Assert.Empty(ui.Confirmations);
+ }
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceRenderTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceRenderTests.cs
new file mode 100644
index 00000000..4f87ded3
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceRenderTests.cs
@@ -0,0 +1,189 @@
+using Chronos.Core.Diagnostics.Synthetic;
+using Chronos.Core.Export;
+using Chronos.Core.Imaging;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Data.Archiving;
+using Chronos.Data.Archiving.Jobs;
+using Chronos.Data.Jobs;
+using Chronos.Data.Processing;
+using Chronos.Data.Processing.Jobs;
+using Chronos.Data.Projects;
+using Chronos.Data.Tests.Processing;
+using Chronos.Data.Workspaces;
+using Chronos.Testing;
+
+namespace Chronos.Data.Tests.Workspaces;
+
+///
+/// A workspace project rendered on this PC from the originals its media hold (phase 5c, ):
+/// into its exports, recorded in its ledger and sent home after; refused without the originals; a cancel leaves nothing half written.
+///
+[Category("workspace")]
+public sealed class WorkspaceRenderTests(TestContext context)
+{
+ private const int Frames = 24;
+
+ private static readonly ExportSettings Mjpeg = new()
+ {
+ Preset = new Auto().WithManual("mjpeg-avi"),
+ Overrides = new ExportOverrides { Width = 96, Height = 64 },
+ NameTemplate = "clip-{codec}",
+ };
+
+ private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
+
+ private sealed record Bed(ProcessingFixture Fx, Sequence Sequence, WorkspaceStore Store, WorkspaceProject Project, JobEngine Engine) : IAsyncDisposable
+ {
+ public async ValueTask DisposeAsync()
+ {
+ await Engine.DisposeAsync();
+ await Fx.DisposeAsync();
+ }
+ }
+
+ /// A sequence of the archive, Main checked out into a workspace with copied, and an engine running every handler.
+ private async Task BedAsync(string media = BundleMedia.Originals, Action? beforeCopy = null)
+ {
+ var fx = await ProcessingFixture.CreateAsync(context);
+ var sequence = await fx.AddAsync(Scene());
+ var engine = new JobEngine(fx.Db,
+ [
+ .. fx.Archive.Service.CreateJobHandlers(), .. fx.Processing.CreateJobHandlers(),
+ .. WorkspaceJobs.CreateHandlers(fx.Db, fx.Archive.Service, null, new WorkspaceJobOptions(fx.Processing.Options, () => false)),
+ ],
+ new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
+ await engine.StartAsync(fx.Ct);
+ var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("render-ws"), "workspace"));
+ var sync = new WorkspaceSync(store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
+ var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, sequence.Id);
+ var main = await fx.Archive.Service.Projects.MainAsync(sequence.Id, fx.Ct);
+ var project = await sync.CheckoutAsync(home, main.Id, media, fx.Ct);
+ beforeCopy?.Invoke(fx, sequence);
+ var copy = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, store.Root, main.Id, media), cancellationToken: fx.Ct);
+ await fx.WaitForAsync(copy.Id, JobState.Done);
+ return new Bed(fx, sequence, store, project, engine);
+ }
+
+ private static ArchiveJobRequest RenderRequest(Bed bed, Guid? versionId = null)
+ {
+ var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson!;
+ return WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, versionId, json);
+ }
+
+ [Test]
+ public async Task ARenderFromTheOriginalsIsWrittenToExportsRecordedAndSentAfter()
+ {
+ await using var bed = await BedAsync();
+ var fx = bed.Fx;
+ var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
+ await fx.WaitForAsync(job.Id, JobState.Done);
+
+ var output = Path.Combine(bed.Project.ExportsDirectory, "clip-MJPEG.avi");
+ Assert.FileExists(output);
+ Assert.Empty(Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory, ".*"));
+ var entry = bed.Project.ReadRenders().Entries.Single();
+ Assert.Equal(RenderJobHandler.RenderId(job.Id, 0), entry.RenderId);
+ Assert.Equal((job.Id, "clip-MJPEG.avi", new FileInfo(output).Length, WorkspaceRenderEntry.Pending, bed.Project.ProjectId),
+ (entry.JobId, entry.File, entry.Size, entry.State, entry.ProjectId));
+ 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.
+ 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));
+
+ // 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();
+ 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.
+ var again = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
+ await fx.WaitForAsync(again.Id, JobState.Done);
+ var entries = bed.Project.ReadRenders().Entries;
+ Assert.Equal(2, entries.Count);
+ Assert.True(entries[1].File != entries[0].File, entries[1].File);
+ Assert.Equal(entry, entries[0]);
+ }
+
+ [Test]
+ public async Task AVersionHeldInTheWorkspaceIsRecordedWithTheRender()
+ {
+ await using var bed = await BedAsync();
+ var fx = bed.Fx;
+ var (_, sync) = (bed.Store, new WorkspaceSync(bed.Store, "test"));
+ var session = await sync.OpenAsync(bed.Project.ProjectId, fx.Ct);
+ await sync.SaveAsync(bed.Project.ProjectId, session.Working with { ExcludedFrames = [2] }, fx.Ct);
+ var version = Assert.NotNull(await sync.CommitAsync(bed.Project.ProjectId, "Render", cancellationToken: fx.Ct));
+ var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!;
+ // The job names the version alone: the settings come from versions/.
+ var stripped = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
+ stripped.Remove("settingsJson");
+ var job = await bed.Engine.EnqueueAsync(
+ WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, version.Id, stripped.ToJsonString()), cancellationToken: fx.Ct);
+ await fx.WaitForAsync(job.Id, JobState.Done);
+ var entry = bed.Project.ReadRenders().Entries.Single();
+ Assert.Equal(version.Id, entry.ProjectVersionId);
+ Assert.Equal(version.ContentHash, entry.SettingsHash);
+
+ // A version the workspace does not hold: refused, saying so.
+ var unknown = await bed.Engine.EnqueueAsync(
+ WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, Guid.CreateVersion7(), stripped.ToJsonString()),
+ cancellationToken: fx.Ct);
+ Assert.Equal(Loc.L("Errors.Workspace.RenderVersion"), (await fx.WaitForAsync(unknown.Id, JobState.Failed)).Error);
+ }
+
+ [Test]
+ public async Task WithoutTheOriginalsTheRenderIsRefusedSayingHowManyLack()
+ {
+ await using var bed = await BedAsync(beforeCopy: (fx, sequence) =>
+ {
+ File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(3)));
+ File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(7)));
+ });
+ var fx = bed.Fx;
+ Assert.Equal(Frames - 2, bed.Project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
+ var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
+ Assert.Equal(Loc.L("Errors.Workspace.RenderNoOriginals", 2), (await fx.WaitForAsync(job.Id, JobState.Failed)).Error);
+ Assert.Empty(bed.Project.ReadRenders().Entries);
+ Assert.False(Directory.Exists(bed.Project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory).Any());
+ }
+
+ [Test]
+ public async Task ProxiesAloneAreRefused()
+ {
+ await using var bed = await BedAsync(BundleMedia.Proxies);
+ var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: bed.Fx.Ct);
+ Assert.Equal(Loc.L("Errors.Workspace.OriginalsMissing"), (await bed.Fx.WaitForAsync(job.Id, JobState.Failed)).Error);
+ }
+
+ [Test]
+ public async Task ACancelledRenderLeavesNoPartialOutput()
+ {
+ await using var bed = await BedAsync();
+ var fx = bed.Fx;
+ fx.Decoder.HoldPurpose = DecodePurpose.Render;
+ fx.Decoder.Hold = Path.GetFileName(bed.Project.ReadMedia()!.Frames[12].Original);
+ var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
+ await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
+ await bed.Engine.CancelAsync(job.Id, fx.Ct);
+ await fx.WaitForAsync(job.Id, JobState.Cancelled);
+ var until = DateTime.UtcNow.AddSeconds(30);
+ while (bed.Engine.RunningJobIds.Contains(job.Id))
+ {
+ Assert.True(DateTime.UtcNow < until, "the render did not stop");
+ await Task.Delay(20, fx.Ct);
+ }
+ var left = Directory.Exists(bed.Project.ExportsDirectory) ? Directory.GetFileSystemEntries(bed.Project.ExportsDirectory) : [];
+ Assert.Empty(left);
+ Assert.Empty(bed.Project.ReadRenders().Entries);
+ Assert.False((await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Any(j => j.Kind == JobKind.WorkspaceSend), "nothing to send");
+ }
+}