Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceTestBed.cs
T
Alby96 b9d1c396a1 feat(app): Edit opens workspace projects, with versions, sync and the project menu
Owner review 2, phase 5a (R8), desktop package: editing moves out of the library. A sequence of this PC's archive
now opens in Edit as a project of the workspace (%LOCALAPPDATA%\Chronos\workspace, .\data\workspace when portable),
with this PC's archive as its home; the editor writes the workspace's working state, never the library.

- WorkspaceHost composes WorkspaceStore and WorkspaceSync over Settings > Workspace's folder: checkout and the
  WorkspaceCopy job, status, Save version with the sync after it (Sync automatically, on by default), sync (pull,
  then push), conflicts, restore, history, new / rename / delete project, and Remove local copy, which refuses
  while work is unsent unless the user sends it first or discards it, reads back the home's head and base and
  checks their hashes, and keeps discarded work in <workspace>/.trash; versions past Kept versions are pruned only
  once the home returns them with the same content.
- WorkspaceSequenceSource: frames and pixels of the media (proxies), the working state saved atomically under the
  project's lease and merged against the basis, the home's deep report while its frames are the media's, renders
  at the home with the portable settings recording the project and the version.
- Edit: the project opened last for the sequence, else "Open in workspace" (Main made from the sequence's settings,
  another project or a new one; proxies) checks out, copies and opens once the copy is done. The picker lists the
  workspace's projects with their state above the library. The title's project menu: Save version (Ctrl+S, note),
  Sync, History (compare, restore as one undo step), New project, Rename, Delete project, Remove local copy; a
  conflict dialog only on real conflicts (keep mine, take the library's, save both, later); Update media when the
  library's frames moved. .chronos files: format 2 opens its project, format 1 gives its settings to Main.
- Settings > Workspace: folder (shown, Open), Sync automatically, Kept versions. Strings in English and Italian.
- A capture (sample data without an engine) keeps editing the library.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit da47a580ba9db3ce2a1db2f11c30cf7344c8b394)
2026-10-27 22:53:05 +01:00

224 lines
9.8 KiB
C#

using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Tests.Editor;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Windows.Shell;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// This PC's archive with one sequence of synthetic photos as the projects' home, its job engine (the workspace copy
/// registered), and workspaces of the desktop that edit it (owner review 2, R8). No window: the view models run on the
/// test's thread.
/// </summary>
internal sealed class WorkspaceTestBed : IAsyncDisposable
{
private readonly TestContext _context;
private WorkspaceTestBed(TestContext context, string directory, ChronosDatabase db, ArchiveService archives, JobEngine engine, Guid sequenceId,
AppEnvironment environment)
{
_context = context;
Directory = directory;
Db = db;
Archives = archives;
Engine = engine;
SequenceId = sequenceId;
Environment = environment;
}
static WorkspaceTestBed() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
public string Directory { get; }
public ChronosDatabase Db { get; }
public ArchiveService Archives { get; }
public JobEngine Engine { get; }
public Guid SequenceId { get; }
/// <summary>An installed copy's environment (not a capture): its data folder under the test's own local app data.</summary>
public AppEnvironment Environment { get; }
public CancellationToken Ct => _context.Cancellation;
public static async Task<WorkspaceTestBed> CreateAsync(TestContext context, int frames = 8)
{
var directory = context.CreateTempDirectory("workspace-app");
var root = Path.Combine(directory, "archive");
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(root, "Test");
var sequence = EditorFixture.Sequence(frames);
var folder = Path.Combine(root, "Synthetic");
System.IO.Directory.CreateDirectory(folder);
for (var i = 0; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
var sequenceId = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. WorkspaceJobs.CreateHandlers(db, archives)],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var app = System.IO.Directory.CreateDirectory(Path.Combine(directory, "app")).FullName;
var local = System.IO.Directory.CreateDirectory(Path.Combine(directory, "local")).FullName;
var environment = AppEnvironment.From(AppPaths.Resolve(app, local, []));
return new WorkspaceTestBed(context, directory, db, archives, engine, sequenceId, environment);
}
/// <summary>A workspace of this PC (in its own folder when <paramref name="name"/> is given: another PC's, for conflicts).</summary>
public WorkspaceHost Host(AppSettings? settings = null, string? name = null)
{
settings ??= new AppSettings();
if (name is not null) settings.WorkspaceFolder = Path.Combine(Directory, name);
return new WorkspaceHost(Environment, settings, () => { }, () => Db, () => Archives, () => Engine) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
}
/// <summary>The sequence's row in the index now.</summary>
public async Task<Sequence> RowAsync() => (await Db.Sequences.GetAsync(SequenceId))!;
/// <summary>A photo taken before the others added to the sequence at its home (as an import of earlier photos does): every frame moves one place.</summary>
public async Task InsertEarlierFrameAsync()
{
var row = await RowAsync();
var archive = (await Db.Archives.GetAsync(row.ArchiveId))!;
var synthetic = EditorFixture.Sequence(1);
using var image = synthetic.Render(0);
var metadata = synthetic.Metadata[0] with { CapturedAt = row.FirstCapture!.Value.AddSeconds(-30) };
var bytes = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80, App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]] });
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
System.IO.Directory.CreateDirectory(staging);
var path = Path.Combine(staging, Guid.NewGuid().ToString("N") + ".part");
await File.WriteAllBytesAsync(path, bytes, Ct);
await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, SequenceId, null, null, path, "IMG_0000.JPG", bytes.Length,
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)), null, null), Ct);
}
/// <summary>A project of the sequence checked out into <paramref name="host"/>'s workspace and its media copied (Main by default).</summary>
public async Task<Guid> CheckoutAsync(WorkspaceHost host, Guid? projectId = null, string? newName = null)
{
var checkout = await host.CheckoutAsync(SequenceId, projectId, newName, cancellationToken: Ct);
await WaitForJobAsync(checkout.Copy.Id);
return checkout.Project.Id;
}
/// <summary>The project open in an editor session over the workspace (saves 20 ms after each edit).</summary>
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
{
var source = new WorkspaceSequenceSource(host.Sync, projectId, Db, DecoderFactory.CreateClient(null), Engine);
var content = await source.LoadAsync(Ct);
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
}
/// <summary>Waits until the job ends; it must end as <paramref name="expected"/>.</summary>
public async Task<Job> WaitForJobAsync(Guid jobId, JobState expected = JobState.Done)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, Ct);
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled })
{
Assert.Equal(expected, job.State, job.Error ?? job.LogTail);
return job;
}
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State} after its time budget");
await Task.Delay(50, Ct);
}
}
/// <summary>Polls <paramref name="condition"/> until it holds, within the time budget.</summary>
public static async Task UntilAsync(Func<bool> condition, string what, double seconds = 60)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(seconds));
while (!condition())
{
if (DateTime.UtcNow > deadline) Assert.Fail($"Not reached in time: {what}");
await Task.Delay(50);
}
}
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Db.DisposeAsync();
}
}
/// <summary>The window a project menu lives in, as the tests see it: dialogs opened, toasts said, projects opened and closed.</summary>
internal sealed class RecordingUi : IWorkspaceUi
{
public List<ArchiveDialogViewModel> Dialogs { get; } = [];
public ArchiveDialogViewModel? Open { get; private set; }
public List<(string Title, string? Message, bool IsError, Action? Action)> Toasts { get; } = [];
public List<ConfirmRequest> Confirmations { get; } = [];
/// <summary>What every confirmation answers.</summary>
public bool ConfirmAnswer { get; set; } = true;
public List<(Guid SequenceId, Guid ProjectId)> Opened { get; } = [];
public int Closed { get; private set; }
public List<Guid> SequencesChanged { get; } = [];
public void ShowDialog(ArchiveDialogViewModel dialog)
{
Open?.Dispose();
Dialogs.Add(dialog);
Open = dialog;
}
public void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(Open, dialog)) return;
dialog.Dispose();
Open = null;
}
public bool Confirm(ConfirmRequest request)
{
Confirmations.Add(request);
return ConfirmAnswer;
}
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) =>
Toasts.Add((title, message, isError, action));
public Task OpenProjectAsync(Guid sequenceId, Guid projectId)
{
Opened.Add((sequenceId, projectId));
return Task.CompletedTask;
}
public Task<bool> CloseProjectAsync()
{
Closed++;
return Task.FromResult(true);
}
public Task SequenceChangedAsync(Guid sequenceId)
{
SequencesChanged.Add(sequenceId);
return Task.CompletedTask;
}
}