diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs
index 3a89c0f..7339236 100644
--- a/src/Febe.App/FebeApp.cs
+++ b/src/Febe.App/FebeApp.cs
@@ -749,6 +749,9 @@ public sealed class FebeApp : IAsyncDisposable
/// (), so that the log never says «collegato» while the monitor
/// says «Serve «Ho finito»».
///
+ /// Tests only: the composition started the automatic export (a normal start; never with problems).
+ internal bool AutoExportStarted => _autoExport is not null;
+
internal static string StartedMessage(BrowserConnectionService connection)
{
ArgumentNullException.ThrowIfNull(connection);
diff --git a/src/Febe.Core/Export/AutoExportSignal.cs b/src/Febe.Core/Export/AutoExportSignal.cs
index a226756..a0c33cb 100644
--- a/src/Febe.Core/Export/AutoExportSignal.cs
+++ b/src/Febe.Core/Export/AutoExportSignal.cs
@@ -2,8 +2,9 @@ namespace Febe.Core.Export;
///
/// Wakes the automatic export (tappa E5, decision D4): a line of _febe.jsonl was written, a rebuild ended, a
-/// destination was turned on, a job ended. The signal only makes the next pass sooner: what to copy always comes from
-/// the database. An instance, not a static, so parallel tests give their worker one of their own and cannot wake each
+/// destination was turned on or took more, «Riprendi ora». Not the end of a job: the worker watches its own job, and a
+/// signal at every job end would start a job after every job (docs/decisioni.md). The signal only makes the next pass
+/// sooner: what to copy always comes from the database. An instance, not a static, so parallel tests give their worker one of their own and cannot wake each
/// other; production code uses .
///
public sealed class AutoExportSignal
diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs
index d0d4549..cf4ad3f 100644
--- a/src/Febe.Core/Export/ExportText.cs
+++ b/src/Febe.Core/Export/ExportText.cs
@@ -262,10 +262,19 @@ public static class ExportText
///
/// The answer to «Interrompi» of an automatic copy (answer 53): what was copied stays, and the automatic copies wait
- /// until («Riprendi ora» before).
+ /// until («Riprendi ora» before), said as elsewhere: «alle 16:10», «all'1:20», «domani
+ /// alle 0:30».
///
- public static string AutomaticInterrupted(DateTimeOffset until, TimeZoneInfo zone) =>
- $"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle {ItalianText.Clock(until, zone)}.";
+ public static string AutomaticInterrupted(DateTimeOffset until, DateTimeOffset now, TimeZoneInfo zone) =>
+ $"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola {ItalianText.AtDay(until, now, zone)}.";
+
+ /// The answer to «Annulla» of a job of Alberto's.
+ public const string Discarded = "Annullata. I file già copiati restano dove sono.";
+
+ ///
+ /// The answer to «Annulla» of an automatic job (design D12): its files go back into the queue of the automatic copies.
+ ///
+ public const string DiscardedAutomatic = "Annullata. I file già copiati restano; quelli che mancano si copiano di nuovo da soli al prossimo passaggio. Per fermarli spegni «Automatica» della cartella.";
///
/// A paused destination still without room for the next file of its paused job (tappa E5, D11): the pause stays.
diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs
index 7ba4b2d..953f369 100644
--- a/src/Febe.Web/Api/ExportApi.cs
+++ b/src/Febe.Web/Api/ExportApi.cs
@@ -1,4 +1,3 @@
-using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
@@ -41,7 +40,8 @@ public static class ExportApi
/// How long the count of the files waiting for an automatic destination in pause is kept ().
private static readonly TimeSpan WaitingKept = TimeSpan.FromMinutes(1);
- private static readonly ConditionalWeakTable> WaitingCache = new();
+ // Per database: when the count was asked and the count itself, shared by the readings that miss it together.
+ private static readonly ConditionalWeakTable Files)>> WaitingCache = new();
///
/// One change of the export settings at a time: each saves all its keys from what it loaded, and the queue of the
@@ -282,8 +282,8 @@ public static class ExportApi
}
else
{
+ // No worker (the demonstration, a start with problems): nothing to wake, the API sends no signal.
service.ReleaseAutomaticHold();
- AutoExportSignal.Default.Signal(urgent: true);
}
return ApiHttp.Message("Copie automatiche di nuovo attive.");
@@ -395,7 +395,8 @@ public static class ExportApi
service.IsBusy,
error,
kind is { } k ? RunKind(k) : null,
- origin is { } o ? RunOrigin(o) : null),
+ origin is { } o ? RunOrigin(o) : null,
+ service.IsBusy && !service.AutomaticRunning),
FebeJsonContext.Default.ExportProgressDto);
});
@@ -424,7 +425,7 @@ public static class ExportApi
// An automatic copy stops the automatic copies until the next recovery round, at least an hour (answer 53).
var heldUntil = await service.InterruptAsync(ct).ConfigureAwait(false);
return ApiHttp.Message(heldUntil is { } until
- ? ExportText.AutomaticInterrupted(until, clock.LocalZone)
+ ? ExportText.AutomaticInterrupted(until, clock.Now, clock.LocalZone)
: "Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi.");
});
@@ -447,16 +448,17 @@ public static class ExportApi
});
});
- endpoints.MapPost("/api/export/runs/{id:long}/discard", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) =>
+ endpoints.MapPost("/api/export/runs/{id:long}/discard", async (long id, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var automatic = await storage.Exports.GetRunAsync(id, ct).ConfigureAwait(false) is { Origin: ExportRunOrigin.Automatic };
await GuardAsync(async () =>
{
await service.DiscardAsync(id, ct).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "export"));
- return ApiHttp.Message("Annullata. I file già copiati restano dove sono.");
+ return ApiHttp.Message(automatic ? ExportText.DiscardedAutomatic : ExportText.Discarded);
});
endpoints.MapGet("/api/export/runs/{id:long}/report", async (long id, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
@@ -598,8 +600,11 @@ public static class ExportApi
waiting);
}
- /// A destination with its counts (and, in pause, the files that wait for it), read from the database.
- public static async Task DestinationAsync(IFebeStorage storage, ExportDestination destination, ExportRootOptions root, IClock clock, CancellationToken ct)
+ ///
+ /// A destination with its counts (and, in pause, the files that wait for it, unless is
+ /// false: the account card of an account without its own folder never shows them), read from the database.
+ ///
+ public static async Task DestinationAsync(IFebeStorage storage, ExportDestination destination, ExportRootOptions root, IClock clock, CancellationToken ct, bool withWaiting = true)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(destination);
@@ -611,8 +616,13 @@ public static class ExportApi
names[accountId] = account.Username;
}
- var unfinished = destination.PausedAt is null ? [] : await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
- var waiting = await WaitingAsync(storage, destination, unfinished, clock, ct).ConfigureAwait(false);
+ int? waiting = null;
+ if (withWaiting)
+ {
+ var unfinished = destination.PausedAt is null ? [] : await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
+ waiting = await WaitingAsync(storage, destination, unfinished, clock, ct).ConfigureAwait(false);
+ }
+
return Destination(destination, names, counts, root, clock, waiting: waiting);
}
@@ -620,7 +630,8 @@ public static class ExportApi
/// The files that wait for a destination in pause (tappa E5, D14): for an automatic one, what it would copy by itself
/// (at least what its unfinished jobs still have to copy); for one without «Automatica», what its unfinished jobs
/// still have to copy. Null when it is not paused. The count of an automatic destination is kept a minute per
- /// database: a disk that stays unplugged must not make every reading of the Dashboard count the library again.
+ /// database: a disk that stays unplugged must not make every reading of the Dashboard count the library again; the
+ /// readings that find it stale together wait for one count.
///
public static async Task WaitingAsync(IFebeStorage storage, ExportDestination destination, IReadOnlyList unfinished, IClock clock, CancellationToken ct)
{
@@ -645,15 +656,20 @@ public static class ExportApi
}
var query = new ExportBacklogQuery(destination.Scope, destination.AccountId, destination.ContentTypes, destination.Id, destination.AutomaticSince);
- var cache = WaitingCache.GetValue(storage, _ => new ConcurrentDictionary());
+ var cache = WaitingCache.GetValue(storage, _ => []);
var now = clock.Now;
- if (!cache.TryGetValue(query, out var kept) || now - kept.At > WaitingKept || now < kept.At)
+ (DateTimeOffset At, Task Files) kept;
+ lock (cache)
{
- kept = (now, (await storage.Exports.CountAutomaticBacklogAsync(query, ct).ConfigureAwait(false)).Files);
- cache[query] = kept;
+ if (!cache.TryGetValue(query, out kept) || now - kept.At > WaitingKept || now < kept.At || kept.Files.IsFaulted || kept.Files.IsCanceled)
+ {
+ // Not tied to this request: another reading may wait for the same count.
+ kept = (now, Task.Run(async () => (await storage.Exports.CountAutomaticBacklogAsync(query, CancellationToken.None).ConfigureAwait(false)).Files, CancellationToken.None));
+ cache[query] = kept;
+ }
}
- return Math.Max(pending, kept.Files);
+ return Math.Max(pending, await kept.Files.WaitAsync(ct).ConfigureAwait(false));
}
/// «Copie esterne» of the account card (decisions D1-D3 of tappa E2).
@@ -669,7 +685,8 @@ public static class ExportApi
return new ExportAccountDto(
enabled,
own is not null,
- destination is null ? null : await DestinationAsync(storage, destination, root, clock, ct).ConfigureAwait(false),
+ // The card shows the files that wait only for the account's own folder: the general folder is not counted.
+ destination is null ? null : await DestinationAsync(storage, destination, root, clock, ct, withWaiting: own is not null).ConfigureAwait(false),
counts.Due,
counts.NotCopied,
counts.RemovedOrSuperseded,
diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs
index 0e1ad95..84adc4b 100644
--- a/src/Febe.Web/Api/ExportDtos.cs
+++ b/src/Febe.Web/Api/ExportDtos.cs
@@ -266,7 +266,8 @@ public sealed record CopyAgainRequest(long CopyId);
/// GET /api/export/progress, polled by the Dashboard tab. : preparing, checking,
/// waitingForSession, copying, finished. : files of the job per state. Tappa E5, from the job
/// being worked on: copy or recognize (null for «Controlla le copie»),
-/// manual or automatic.
+/// manual or automatic. : a job of Alberto's runs
+/// or starts (an automatic one is not: «Riprendi» makes it give way, answer 49).
///
public sealed record ExportProgressDto(
long? RunId,
@@ -282,7 +283,8 @@ public sealed record ExportProgressDto(
bool Running,
string? Error,
string? Kind = null,
- string? Origin = null);
+ string? Origin = null,
+ bool ManualRunning = false);
/// An export job. : copy or recognize; : manual or automatic.
public sealed record ExportRunDto(
diff --git a/src/Febe.Web/Demo/DemoExport.cs b/src/Febe.Web/Demo/DemoExport.cs
index e1da2e4..ff75881 100644
--- a/src/Febe.Web/Demo/DemoExport.cs
+++ b/src/Febe.Web/Demo/DemoExport.cs
@@ -212,6 +212,10 @@ public static class DemoExport
at = newest + TimeSpan.FromSeconds(1) < now ? newest + TimeSpan.FromSeconds(1) : now - TimeSpan.FromMinutes(2);
}
+ // Never in the last two minutes: the job left «interrotto» below starts at least a minute after this one,
+ // whatever minute the demonstration starts at.
+ at = at > now - TimeSpan.FromMinutes(2) ? now - TimeSpan.FromMinutes(2) : at;
+
await using var past = newService(new ShiftedClock(clock, at - now));
var held = byEntry.Select(g => g.Key).Where(id => !copiedIds.Contains(id)).ToList();
var start = await past.TryStartAutomaticAsync(new ExportSelection.Automatic([scope], held, Round: true), ct).ConfigureAwait(false);
@@ -236,7 +240,7 @@ public static class DemoExport
var lastRun = (await exports.ListRunsAsync(ct).ConfigureAwait(false)).Where(r => r.DestinationId == own.Id).Select(r => r.StartedAt).DefaultIfEmpty(now - TimeSpan.FromHours(2)).Max();
var started = left.Max(f => f.SavedAt) + TimeSpan.FromMinutes(2);
started = started < lastRun + TimeSpan.FromMinutes(10) ? lastRun + TimeSpan.FromMinutes(10) : started;
- started = started > now - TimeSpan.FromMinutes(1) ? now - TimeSpan.FromMinutes(1) : started;
+ started = started > now - TimeSpan.FromMinutes(1) ? now - TimeSpan.FromMinutes(1) : started; // still after lastRun (≤ now − 2 min)
var run = await exports.CreateRunAsync(
new ExportRun { DestinationId = own.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = started, CompletedAt = null },
ct).ConfigureAwait(false);
diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css
index 0e76c66..cf7e401 100644
--- a/src/Febe.Web/wwwroot/css/febe.css
+++ b/src/Febe.Web/wwwroot/css/febe.css
@@ -1171,6 +1171,7 @@ p.aiuto.descrizione-copie{margin-top:8px}
.stato-copie.avviso{margin-top:10px}
.cartelle-copie .tab td{vertical-align:top}
.cartelle-copie .tab td .dati{display:block;overflow-wrap:anywhere}
+.cartelle-copie .tab td a{overflow-wrap:anywhere}
.dialogo.destinazione{width:900px}
.dialogo.copia-in{width:600px}
.dialogo.resoconto-copia{width:700px}
@@ -1211,6 +1212,8 @@ p.aiuto.descrizione-copie{margin-top:8px}
.azioni-cartella.compatte{display:flex;flex-direction:column;align-items:flex-start;gap:4px}
.azioni-cartella.compatte .azioni-copie{gap:0;margin-left:-11px}
.azioni-cartella.compatte p{margin:0}
+/* On a phone the buttons of a table cell wrap their label instead of running past the panel (tappa E5). */
+.azioni-cartella.compatte .btn{white-space:normal;height:auto;min-height:30px;text-align:left}
.riga-pausa{display:flex;align-items:center;gap:6px}
.riga-etichetta{display:flex;align-items:center;gap:8px}
.riga-etichetta .etichetta{margin:0}
diff --git a/src/Febe.Web/wwwroot/js/core/text.js b/src/Febe.Web/wwwroot/js/core/text.js
index 400780f..38f907f 100644
--- a/src/Febe.Web/wwwroot/js/core/text.js
+++ b/src/Febe.Web/wwwroot/js/core/text.js
@@ -108,6 +108,13 @@ export function shortDay(day, today) {
return today && parseDay(today).y !== p.y ? `${base} ${p.y}` : base;
}
+/** «dal 3 dicembre», «dall'8 dicembre», «dall'11 dicembre», «dal 1º dicembre»: «dal» with the day, elided as spoken. */
+export function fromDay(day, today) {
+ const p = parseDay(day);
+ if (p.d === 1) return `dal 1º ${shortDay(day, today).slice(2)}`;
+ return `${p.d === 8 || p.d === 11 ? "dall'" : 'dal '}${shortDay(day, today)}`;
+}
+
/** Days between two calendar days (b − a). */
export function daysBetween(a, b) {
return Math.round(parseDay(b).number - parseDay(a).number);
diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js
index 73ce4a1..d22456a 100644
--- a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js
+++ b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js
@@ -183,11 +183,14 @@ export async function mountExport(page) {
}
async function resumeAutomatic(e) {
- e.currentTarget.disabled = true;
+ const button = e.currentTarget;
+ button.disabled = true;
try {
const result = await api('/api/export/automatic/resume', { method: 'POST' });
toast(result.message);
} catch (error) {
+ // The status does not change, so the line is not drawn again: the button is given back here.
+ button.disabled = false;
showError(error);
}
again();
@@ -215,7 +218,8 @@ export async function mountExport(page) {
pending.replaceChildren();
return;
}
- const busy = Boolean(progress && progress.running);
+ // Only a job of Alberto's keeps «Riprendi» off: an automatic copy gives way to it (answer 49).
+ const busy = Boolean(progress && progress.manualRunning);
fill(pending,
h('div.testa-blocco', h('h2', t('esportazione.dashboard.daRiprendere')),
waiting.length > 1 ? h('div.destra', h('button.btn.piccolo', { type: 'button', disabled: busy, onclick: resumeAll }, icon('play', 's'), t('esportazione.dashboard.riprendiTutte'))) : null),
@@ -283,7 +287,8 @@ export async function mountExport(page) {
async function discard(run) {
const ok = await confirmDialog({
title: t('esportazione.dashboard.annullaTitolo', { cartella: run.destination }),
- text: t('esportazione.dashboard.annullaTesto'),
+ // An automatic job's files go back into the queue at the next pass (D12): its text says so.
+ text: t(run.origin === 'automatic' ? 'esportazione.dashboard.annullaTestoAutomatica' : 'esportazione.dashboard.annullaTesto'),
buttons: [
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
{ label: t('esportazione.dashboard.annullaSi'), value: true, kind: 'pericolo' },
diff --git a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js
index b99a752..bb361d3 100644
--- a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js
+++ b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js
@@ -12,7 +12,7 @@
import { api } from '../core/api.js';
import { h, icon, fill, later } from '../core/dom.js';
-import { t, bytes, shortDay } from '../core/text.js';
+import { t, bytes, fromDay } from '../core/text.js';
import { checkbox, dialog, label, menu, radio, segmented, showError, toast, toggle } from '../core/ui.js';
import { formatLabel } from './frames.js';
@@ -134,7 +134,7 @@ export function describe(destination) {
/** «Automatica dal 4 dicembre», or «Automatica» when it copies every due file. */
export function automaticText(destination) {
return destination.automaticSince
- ? t('esportazione.automatica.descrizione', { data: shortDay(destination.automaticSince.day) })
+ ? t('esportazione.automatica.descrizione', { dal: fromDay(destination.automaticSince.day) })
: t('esportazione.automatica.etichetta');
}
@@ -150,7 +150,7 @@ function pausedText(d) {
if (!since) return t('esportazione.pausa', { problema: problem });
if (since.dayDelta === 0) return t('esportazione.pausaDa', { giorno: t('tempo.oggi'), problema: problem });
if (since.dayDelta === -1) return t('esportazione.pausaDa', { giorno: t('tempo.ieri'), problema: problem });
- return t('esportazione.pausaDal', { giorno: shortDay(since.day), problema: problem });
+ return t('esportazione.pausaDal', { dal: fromDay(since.day), problema: problem });
}
/**
@@ -265,6 +265,10 @@ export async function destinationDialog({ scope, accountId = null, username = ''
choice: 'new',
preview: null,
previewKey: '',
+ // The request of the count the question needs now, and the last count that failed (it is asked again at the next
+ // drawing, and its error stays shown meanwhile).
+ askedKey: '',
+ autoError: null,
widen: null,
autoWork: false,
};
@@ -466,6 +470,9 @@ export async function destinationDialog({ scope, accountId = null, username = ''
// ------------------------------------------------------------------------------- save
function ready() {
if (state.saving || !state.path || state.types.size === 0 || state.errors.length) return false;
+ // Turned on: «Salva» waits for the count of the folder and types as they are now, so «Copia anche gli N» is
+ // never saved from an older N (a count that failed lets it save «Solo i nuovi»).
+ if (asks() && !currentPreview() && !(state.autoError && state.autoError.key === state.askedKey)) return false;
// The folder of a destination being changed is not checked again when it stays the same: an unplugged disk
// must not stop a change of types or names.
if (destination && samePath(state.path, original)) return true;
@@ -481,7 +488,8 @@ export async function destinationDialog({ scope, accountId = null, username = ''
state.saving = true;
drawSave();
const asked = asks();
- const all = asked && state.choice === 'all' && state.preview && state.preview.files > 0;
+ const preview = currentPreview();
+ const all = asked && state.choice === 'all' && preview && preview.files > 0;
const body = {
scope,
accountId: general ? null : accountId,
@@ -501,7 +509,7 @@ export async function destinationDialog({ scope, accountId = null, username = ''
try {
const saved = await api(destination ? `/api/export/destinations/${destination.id}` : '/api/export/destinations', { method: destination ? 'PUT' : 'POST', body });
if (asked) {
- toast(all ? t('esportazione.automatica.accesaTutti', { n: state.preview.files }) : t('esportazione.automatica.accesaNuovi'));
+ toast(all ? t('esportazione.automatica.accesaTutti', { n: preview.files }) : t('esportazione.automatica.accesaNuovi'));
if (state.check && state.check.accepted === false) toast(t('esportazione.automatica.nonRisponde'));
} else {
toast(t('esportazione.salvata'));
@@ -537,6 +545,8 @@ export async function destinationDialog({ scope, accountId = null, username = ''
});
const autoBox = h('div.automatica-scelta', { 'aria-live': 'polite' });
const autoNotes = [];
+ // No folder Febe may write to (Docker without /esporta): the switch is off, and the note says why.
+ if (!root.active) autoNotes.push(h('p.avviso-testo.radice-spenta', icon('triangle-alert', 'xs'), ' ', root.problem || t('esportazione.automatica.radiceSpenta')));
if (!general && !accountEnabled) autoNotes.push(h('p.avviso-testo', icon('info', 'xs'), ' ', t('esportazione.automatica.accountSpento', { nome: username })));
if (!general && !destination && info.general && info.general.automatic) autoNotes.push(h('p.aiuto', icon('info', 'xs'), ' ', t('esportazione.automatica.generaleAccesa', { nome: username })));
const autoPart = orphan ? null : h('section.parte-dialogo.parte-automatica',
@@ -560,6 +570,11 @@ export async function destinationDialog({ scope, accountId = null, username = ''
return TYPES.map((x) => x.key).filter((k) => state.types.has(k));
}
+ /** The count of the question for the folder and types as they are now, or null while it is not there. */
+ function currentPreview() {
+ return state.preview && state.askedKey && state.preview.key === state.askedKey ? state.preview : null;
+ }
+
// The count is asked again only when what it depends on changes (types, the folder), never at each key.
let autoToken = 0;
const fetchAuto = later(async (mine, key, request) => {
@@ -568,10 +583,16 @@ export async function destinationDialog({ scope, accountId = null, username = ''
if (mine !== autoToken) return;
if (request.mode === 'widen') state.widen = { key, ...result };
else state.preview = { key, ...result };
+ if (state.autoError && state.autoError.key === key) state.autoError = null;
drawAuto();
} catch (error) {
if (mine !== autoToken) return;
- fill(autoBox, h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', error.message));
+ // Asked again at the next drawing (a key, the folder's answer, the switch), not from here: a server that keeps
+ // failing must not be asked in a loop. The error stays shown meanwhile.
+ if (state.previewKey === key) state.previewKey = '';
+ state.autoError = { key, message: error.message };
+ if (state.askedKey === key) showAuto(`errore|${key}|${error.message}`, h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', error.message));
+ drawSave();
}
}, 300);
@@ -597,14 +618,35 @@ export async function destinationDialog({ scope, accountId = null, username = ''
}
}
+ // What autoBox shows now: drawn again only when it changes, so a choice keeps the keyboard's focus and the live
+ // region is not read again at each key or at the folder's answer.
+ let drawnAuto = null;
+ function showAuto(signature, ...nodes) {
+ if (signature === drawnAuto) return;
+ drawnAuto = signature;
+ const focused = autoBox.contains(document.activeElement) ? document.activeElement : null;
+ const value = focused && focused.value;
+ fill(autoBox, ...nodes);
+ if (focused) {
+ const again = [...autoBox.querySelectorAll('input')].find((x) => x.value === value);
+ if (again) again.focus();
+ }
+ }
+
function drawAuto() {
+ drawAutoBox();
+ drawSave();
+ }
+
+ function drawAutoBox() {
if (!autoPart) return;
if (state.types.size === 0) {
- autoBox.replaceChildren();
+ state.askedKey = '';
+ showAuto('vuoto');
return;
}
if (asks()) {
- const preview = want({
+ const request = {
mode: 'switchOn',
destinationId: destination ? destination.id : null,
scope,
@@ -612,19 +654,24 @@ export async function destinationDialog({ scope, accountId = null, username = ''
// The copies of the folder count only while it stays the same; another folder has none, whatever its name.
path: destination && !folderChanged() ? original : '',
types: typeList(),
- });
+ };
+ const key = JSON.stringify(request);
+ state.askedKey = key;
+ const preview = want(request);
if (!preview) {
- fill(autoBox, h('p.aiuto', t('esportazione.automatica.conto')));
+ const failed = state.autoError && state.autoError.key === key ? state.autoError.message : null;
+ if (failed) showAuto(`errore|${key}|${failed}`, h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', failed));
+ else showAuto(`conto|${key}`, h('p.aiuto', t('esportazione.automatica.conto')));
return;
}
if (!preview.files) {
state.choice = 'new';
- fill(autoBox, h('p.aiuto', icon('info', 'xs'), ' ', t('esportazione.automatica.nessuno')));
+ showAuto(`nessuno|${key}`, h('p.aiuto', icon('info', 'xs'), ' ', t('esportazione.automatica.nessuno')));
return;
}
const free = preview.freeBytes != null ? preview.freeBytes : (state.check && state.check.accepted ? state.check.freeBytes : null);
const choose = (value) => { state.choice = value; };
- fill(autoBox,
+ showAuto(`scelta|${key}|${preview.files}|${preview.bytes}|${free}`,
h('p.domanda-automatica', h('b', t('esportazione.automatica.domanda'))),
h('div.scelte', { role: 'radiogroup', 'aria-label': t('esportazione.automatica.domanda') },
radio({ name: 'automatica-esistenti', value: 'new', checked: state.choice !== 'all', onchange: choose, labelNode: h('span', h('b', t('esportazione.automatica.soloNuovi')), h('small', t('esportazione.automatica.soloNuoviAiuto'))) }),
@@ -639,17 +686,20 @@ export async function destinationDialog({ scope, accountId = null, username = ''
})));
return;
}
+ state.askedKey = '';
if (state.automatic) {
// On already, with the same folder: what it copies, and the files in more when it takes more types (answer 55).
const since = destination.automaticSince;
const added = typeList().some((k) => !destination.types.includes(k));
const widen = added ? want({ mode: 'widen', destinationId: destination.id, types: typeList() }) : null;
- fill(autoBox,
- h('p.aiuto', icon('refresh-cw', 'xs'), ' ', since ? t('esportazione.automatica.dal', { data: shortDay(since.day) }) : t('esportazione.automatica.tutto')),
- widen && widen.files ? h('p.avviso-testo.in-piu', icon('info', 'xs'), ' ', t('esportazione.automatica.inPiu', { n: widen.files })) : null);
+ const more = widen && widen.files ? widen.files : 0;
+ showAuto(`accesa|${since ? since.day : ''}|${more}`,
+ h('p.aiuto', icon('refresh-cw', 'xs'), ' ', since ? t('esportazione.automatica.dal', { dal: fromDay(since.day) }) : t('esportazione.automatica.tutto')),
+ more ? h('p.avviso-testo.in-piu', icon('info', 'xs'), ' ', t('esportazione.automatica.inPiu', { n: more })) : null);
return;
}
- fill(autoBox, wasAutomatic && state.autoWork
+ const stops = wasAutomatic && state.autoWork;
+ showAuto(`spenta|${stops}`, stops
? h('p.avviso-testo.spegnere', icon('triangle-alert', 'xs'), ' ', t('esportazione.automatica.spegnere'))
: null);
}
diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json
index 3231bcb..1be827f 100644
--- a/src/Febe.Web/wwwroot/testi/it.json
+++ b/src/Febe.Web/wwwroot/testi/it.json
@@ -1103,7 +1103,7 @@
"controllaAiuto": "Guarda se i file copiati sono ancora nella cartella. Nessun file viene toccato.",
"riconosci": "Riconosci le copie già presenti",
"riconosciAiuto": "Cerca nella cartella i file che sono proprio le copie di quelli in libreria e li segna come «Copiato». Nessun file viene toccato.",
- "pausaDal": "In pausa dal {giorno}: {problema}",
+ "pausaDal": "In pausa {dal}: {problema}",
"pausaDa": "In pausa da {giorno}: {problema}",
"aspettano": "1 file aspetta questa cartella.|{n} file aspettano questa cartella.",
"pausaGiro": "Febe riprova da sola all'avvio e a ogni giro di recupero, ogni ora.",
@@ -1119,15 +1119,16 @@
"spazio": "Circa {spazio}. La copia parte da sola fuori dalle sessioni del motore e lascia il passo ai tuoi lavori.",
"pocoSpazio": "Nella cartella ci sono {liberi} liberi: quando lo spazio finisce la copia va in pausa.",
"nessuno": "Nessun file già in libreria da copiare qui: da adesso si copiano da soli i file nuovi.",
- "dal": "Automatica dal {data}: copia i file salvati in libreria da allora.",
+ "dal": "Automatica {dal}: copia i file salvati in libreria da allora.",
"tutto": "Automatica: copia tutti i file dovuti.",
"spegnere": "Spegnendo, la copia automatica di questa cartella si ferma e i file che restavano non si copiano da soli; quelli già copiati restano.",
"inPiu": "1 file in più si copierà da solo.|{n} file in più si copieranno da soli.",
- "accountSpento": "Per @{nome} «Esporta questo account» è spento: non si copia nulla, nemmeno da sola.",
+ "accountSpento": "Per @{nome} «Esporta questo account» è spento: non si copia nulla, nemmeno in automatico.",
+ "radiceSpenta": "Nessuna cartella in cui Febe possa scrivere le copie: «Automatica» non si può accendere.",
"generaleAccesa": "Con una cartella sua, i file nuovi di @{nome} non vanno più da soli nella cartella generale: qui «Automatica» è spenta finché non la accendi.",
"togliPropria": "1 file di @{nome} andrà da solo nella cartella generale.|{n} file di @{nome} andranno da soli nella cartella generale.",
"etichetta": "Automatica",
- "descrizione": "Automatica dal {data}",
+ "descrizione": "Automatica {dal}",
"accesaNuovi": "Automatica accesa: da adesso si copiano da soli i file nuovi.",
"accesaTutti": "Automatica accesa: 1 file da copiare; la copia parte fra poco, mai durante una sessione del motore.|Automatica accesa: {n} file da copiare; la copia parte fra poco, mai durante una sessione del motore.",
"nonRisponde": "La cartella ora non risponde: le copie partono quando torna.",
@@ -1449,6 +1450,7 @@
"annulla": "Annulla",
"annullaTitolo": "Annullare la copia in {cartella}?",
"annullaTesto": "I file già copiati restano dove sono; quelli che mancano non si copiano.",
+ "annullaTestoAutomatica": "I file già copiati restano; quelli che mancano si copiano di nuovo da soli al prossimo passaggio. Per fermarli spegni «Automatica» della cartella.",
"annullaSi": "Annulla la copia",
"ultimi": "Ultimi lavori",
"vuoto": "Nessuna copia ancora. Le copie partono da «Copia in…» nella Libreria, nel visualizzatore o nella scheda di un account; nelle cartelle con «Automatica» accesa le copie partono anche da sole.",
diff --git a/tests/Febe.Tests/Desktop/AutoExportCompositionTests.cs b/tests/Febe.Tests/Desktop/AutoExportCompositionTests.cs
index 604a766..c3ef903 100644
--- a/tests/Febe.Tests/Desktop/AutoExportCompositionTests.cs
+++ b/tests/Febe.Tests/Desktop/AutoExportCompositionTests.cs
@@ -2,6 +2,7 @@ using System.Diagnostics;
using Febe.Core.Export;
using Febe.Tests.Desktop.Support;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
namespace Febe.Tests.Desktop;
@@ -20,10 +21,14 @@ public sealed class AutoExportCompositionTests
{
var ct = TestContext.CancellationToken;
AutoExportWorker worker;
+ bool? runningWhenTheInterfaceStops = null;
await using (var bed = await DesktopTestBed.StartAsync())
{
Assert.IsEmpty(bed.App.Problems);
+ Assert.IsTrue(bed.App.AutoExportStarted);
worker = bed.App.Web.Services.GetRequiredService();
+ var seen = worker;
+ bed.App.Web.Services.GetRequiredService().ApplicationStopping.Register(() => runningWhenTheInterfaceStops = seen.Running);
var watch = Stopwatch.StartNew();
while ((await worker.StatusAsync(ct)).LastRound is null)
{
@@ -38,6 +43,7 @@ public sealed class AutoExportCompositionTests
}
Assert.IsFalse(worker.Running, "the stop ends the worker");
+ Assert.IsFalse(runningWhenTheInterfaceStops ?? true, "the worker is stopped first, before the interface and the engine");
}
[TestMethod]
@@ -46,8 +52,8 @@ public sealed class AutoExportCompositionTests
{
await using var bed = await DesktopTestBed.StartAsync(shell: new FakeDesktopShell { RuntimeVersion = null });
Assert.IsNotEmpty(bed.App.Problems);
+ Assert.IsFalse(bed.App.AutoExportStarted, "the composition does not start it");
var worker = bed.App.Web.Services.GetRequiredService();
- await Task.Delay(200, TestContext.CancellationToken);
Assert.IsFalse(worker.Running);
Assert.IsNull((await worker.StatusAsync(TestContext.CancellationToken)).LastRound);
}
diff --git a/tests/Febe.Tests/Export/AutoExportWorkerTests.cs b/tests/Febe.Tests/Export/AutoExportWorkerTests.cs
index 2582a48..bede3b0 100644
--- a/tests/Febe.Tests/Export/AutoExportWorkerTests.cs
+++ b/tests/Febe.Tests/Export/AutoExportWorkerTests.cs
@@ -375,6 +375,43 @@ public sealed class AutoExportWorkerTests
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
}
+ ///
+ /// A folder whose path leaves no room for the names of the scheme (it passes the folder check, which asks room for
+ /// one short name only): each file is «Non riuscito» with «Percorso troppo lungo per la cartella» and the run goes on
+ /// to the end; a signal pass leaves them, every round tries them again (answer 50).
+ ///
+ [TestMethod]
+ public async Task APathTooLongFailsEachFileAndTheRoundTriesItAgain()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Luca, "t01", 1, 2);
+ var room = WindowsFileNames.MaxPathLength - 4 - bed.Temp.Path.Length - 1;
+ var longRoot = bed.Temp.Combine("l" + new string('x', room - 1));
+ Directory.CreateDirectory(longRoot);
+ var usb = await TurnOnAsync(bed, await bed.GeneralAsync(folder: longRoot, ct: ct), onlyNew: false, ct);
+ var worker = Worker(bed);
+
+ Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
+ await bed.Service.WaitAsync(ct);
+ var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single();
+ Assert.AreEqual(ExportRunState.Completed, run.State, "the run goes to the end");
+ var items = await bed.ItemsAsync(run.Id, ct);
+ Assert.HasCount(2, items);
+ Assert.IsTrue(items.All(i => i is { State: ExportItemState.Failed, Note: ExportText.Notes.PathTooLong }), string.Join(", ", items.Select(i => $"{i.State} {i.Note}")));
+ var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
+ Assert.HasCount(2, copies);
+ Assert.IsTrue(copies.All(c => c.State == ExportCopyState.Failed && c.LastError is not null), "«Non riuscito», with the reason");
+ Assert.AreEqual("Percorso troppo lungo per la cartella", ExportText.Note(ExportText.Notes.PathTooLong));
+ Assert.IsFalse(Directory.EnumerateFileSystemEntries(longRoot).Any(), "nothing written");
+
+ Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct), "a signal pass leaves a «Non riuscito»");
+ Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct), "every round tries it again");
+ await bed.Service.WaitAsync(ct);
+ Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
+ Assert.IsTrue(post.Media.All(m => !File.Exists(Path.Combine(longRoot, "luca.demo", LibraryLayout.ToPlatform(m.RelativePath!)))));
+ }
+
///
/// One unfinished automatic run per destination: one stopped by an error is resumed only by the round, and meanwhile
/// the destination gets no other automatic run.
@@ -636,14 +673,20 @@ public sealed class AutoExportWorkerTests
await IdleAsync(bed, worker, clock!, ct);
var asked = clock!.Asked;
+ var first = clock.Now;
var post = await bed.PostAsync(bed.Luca, "g01", 1);
- var due = await clock.WaitForDelayAsync(asked, ct);
- Assert.AreEqual(clock.Now + TimeSpan.FromMinutes(2), due, "the settle");
+ Assert.AreEqual(first + TimeSpan.FromMinutes(2), await clock.WaitForDelayAsync(asked, ct), "the settle");
+
+ // A second file 90 s later: the settle starts again from it.
+ clock.Advance(TimeSpan.FromSeconds(90));
+ asked = clock.Asked;
var second = await bed.PostAsync(bed.Luca, "g02", 2);
- await clock.WaitForDelayAsync(asked + 1, ct);
- clock.Advance(TimeSpan.FromMinutes(1));
- await Task.Delay(50, ct);
- Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])), "two minutes after the last file, not the first");
+ Assert.AreEqual(clock.Now + TimeSpan.FromMinutes(2), await clock.WaitForDelayAsync(asked, ct), "two minutes after the last file, not the first");
+ var passes = worker.Passes;
+ clock.Advance(TimeSpan.FromSeconds(30)); // two minutes after the first file
+ Assert.AreEqual(first + TimeSpan.FromSeconds(90) + TimeSpan.FromMinutes(2), clock.Pending.Single(), "still settling");
+ Assert.AreEqual(passes, worker.Passes);
+ Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
bed.Signal.Signal(urgent: true);
@@ -653,6 +696,44 @@ public sealed class AutoExportWorkerTests
await loop;
}
+ ///
+ /// Files that keep arriving push the settle on, at most a quarter of an hour after the first one (§4.10): with a file
+ /// every 90 s the pass starts 15 minutes after the first file, not never.
+ ///
+ [TestMethod]
+ public async Task FilesThatKeepArrivingPostponeThePassAtMostAQuarterOfAnHour()
+ {
+ var ct = TestContext.CancellationToken;
+ GatedClock? clock = null;
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
+ await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
+ var worker = Worker(bed, clock);
+ var loop = worker.RunAsync(ct);
+ await IdleAsync(bed, worker, clock!, ct);
+
+ var asked = clock!.Asked;
+ var first = clock.Now;
+ var limit = first + TimeSpan.FromMinutes(15);
+ var post = await bed.PostAsync(bed.Luca, "q00", 1);
+ Assert.AreEqual(first + TimeSpan.FromMinutes(2), await clock.WaitForDelayAsync(asked, ct));
+ for (var i = 1; i <= 9; i++)
+ {
+ clock.Advance(TimeSpan.FromSeconds(90));
+ asked = clock.Asked;
+ await bed.PostAsync(bed.Luca, $"q{i:00}", i + 1);
+ var due = await clock.WaitForDelayAsync(asked, ct);
+ var expected = clock.Now + TimeSpan.FromMinutes(2) < limit ? clock.Now + TimeSpan.FromMinutes(2) : limit;
+ Assert.AreEqual(expected, due, $"file {i}");
+ Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
+ }
+
+ Assert.AreEqual(limit, clock.Pending.Single(), "the last settle ends at the quarter of an hour");
+ clock.Advance(limit - clock.Now);
+ await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))), ct);
+ await worker.StopAsync();
+ await loop;
+ }
+
/// A file saved while a pass's job is at work is copied by a pass after it: the signal is not lost.
[TestMethod]
public async Task ASignalDuringAPassIsNotLost()
diff --git a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs
index 70754a3..9889da7 100644
--- a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs
+++ b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs
@@ -617,8 +617,8 @@ public sealed class ExportServiceAutomaticTests
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryResumeAutomaticAsync([start.Runs[0].Id], ct)).Outcome);
Assert.AreEqual(
- $"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle {Core.Engine.ItalianText.Clock(until!.Value, bed.Clock.LocalZone)}.",
- ExportText.AutomaticInterrupted(until.Value, bed.Clock.LocalZone));
+ $"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola {Core.Engine.ItalianText.AtDay(until!.Value, bed.Clock.Now, bed.Clock.LocalZone)}.",
+ ExportText.AutomaticInterrupted(until.Value, bed.Clock.Now, bed.Clock.LocalZone));
// A longer hold wins; the hour passes; «Riprendi ora».
Assert.AreEqual(until.Value.AddHours(1), bed.Service.HoldAutomatic(until.Value.AddHours(1)));
@@ -665,6 +665,36 @@ public sealed class ExportServiceAutomaticTests
Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(auto.Id, ct: ct));
}
+ ///
+ /// With «Una copia sola» the backlog is each folder's own figure: the same content of two accounts, due in two
+ /// automatic folders, counts once in each; the job writes it once (the other is «Già copiato»), and then both
+ /// figures are 0 (pinned behaviour, IExportStore.CountAutomaticBacklogAsync).
+ ///
+ [TestMethod]
+ public async Task WithOneCopyOnlyEachFolderCountsItsOwnBacklog()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
+ await bed.PostAsync(bed.Marta, "c01", 31);
+ await bed.PostAsync(bed.Luca, "c02", 31);
+ var general = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), ct);
+ var own = await TurnOnAsync(bed, await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct), ct);
+ var generalQuery = new ExportBacklogQuery(ExportScope.General, null, ContentTypes.All, general.Id, null);
+ var ownQuery = new ExportBacklogQuery(ExportScope.Account, bed.Luca.Id, ContentTypes.All, own.Id, null);
+ Assert.AreEqual(1, (await bed.Db.Exports.CountAutomaticBacklogAsync(generalQuery, ct)).Files);
+ Assert.AreEqual(1, (await bed.Db.Exports.CountAutomaticBacklogAsync(ownQuery, ct)).Files);
+
+ var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(general), Scope(own)], [], Round: true), ct);
+ Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
+ await bed.Service.WaitAsync(ct);
+
+ var copies = (await bed.Db.Exports.ListCopiesAsync(general.Id, ct: ct)).Concat(await bed.Db.Exports.ListCopiesAsync(own.Id, ct: ct)).ToList();
+ Assert.HasCount(1, copies, "written once");
+ Assert.AreEqual(0, (await bed.Db.Exports.CountAutomaticBacklogAsync(generalQuery, ct)).Files);
+ Assert.AreEqual(0, (await bed.Db.Exports.CountAutomaticBacklogAsync(ownQuery, ct)).Files);
+ }
+
///
/// «Annulla» of an automatic run keeps automatic starts away until the run is «annullato»: the worker's resume of the
/// same run in that moment is refused (Busy), so the run stays «annullato» and nothing is copied.
@@ -704,6 +734,28 @@ public sealed class ExportServiceAutomaticTests
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome, "after «Annulla» the gate is open again");
}
+ ///
+ /// The answer to «Interrompi» says the time as the rest of the interface: «all'1:20», and «domani alle 0:30» when the
+ /// hold goes past midnight (decisioni.md, 4 December 2026).
+ ///
+ [TestMethod]
+ public void TheInterruptAnswerSaysTheTimeAsElsewhere()
+ {
+ var zone = TestZones.Rome;
+ var night = new DateTimeOffset(2026, 12, 4, 0, 20, 0, TimeSpan.FromHours(1));
+ Assert.AreEqual(
+ "Copia automatica interrotta: quello che è stato copiato resta; riprende da sola all'1:20.",
+ ExportText.AutomaticInterrupted(night.AddHours(1), night, zone));
+ var evening = new DateTimeOffset(2026, 12, 4, 23, 30, 0, TimeSpan.FromHours(1));
+ Assert.AreEqual(
+ "Copia automatica interrotta: quello che è stato copiato resta; riprende da sola domani alle 0:30.",
+ ExportText.AutomaticInterrupted(evening.AddHours(1), evening, zone));
+ var afternoon = new DateTimeOffset(2026, 12, 4, 15, 10, 0, TimeSpan.FromHours(1));
+ Assert.AreEqual(
+ "Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle 16:10.",
+ ExportText.AutomaticInterrupted(afternoon.AddHours(1), afternoon, zone));
+ }
+
///
/// The automatic export resumes only automatic runs: a manual «In pausa» stays Alberto's even when its folder
/// answers again (answer 48); «Riprova» resumes it.
diff --git a/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs b/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs
index b8fce46..6d7c101 100644
--- a/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs
+++ b/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs
@@ -220,10 +220,15 @@ public sealed partial class ExportApiTests
Assert.AreEqual(5, paused.Int("waiting"), paused.ToString());
Assert.AreEqual("La cartella non risponde.", paused.Str("problem"));
- // The account card shows the same folder, automatic, with what waits.
+ // The account card shows the same folder, automatic; the files that wait for the general folder are not
+ // counted for it (the card never shows them).
var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").GetProperty("destination");
Assert.IsTrue(card.Bool("automatic"));
- Assert.AreEqual(5, card.Int("waiting"));
+ Assert.AreEqual(JsonValueKind.Null, card.GetProperty("waiting").ValueKind);
+
+ // Readings that find the count stale together get the same count.
+ var together = await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => server.GetJsonAsync("/api/export")));
+ Assert.IsTrue(together.All(o => o.GetProperty("general").Int("waiting") == 5));
// A folder without «Automatica», in pause: what its unfinished jobs still have to copy.
var (ownStatus, ownSaved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas, scope: "account", accountId: luca.Account.Id));
@@ -240,6 +245,8 @@ public sealed partial class ExportApiTests
Assert.AreEqual(2, ownDto.Int("waiting"), ownDto.ToString());
Assert.AreEqual(JsonValueKind.Null, ownDto.GetProperty("automaticSince").ValueKind);
Assert.AreEqual(3, overview.GetProperty("general").Int("waiting"), "luca's files now go to his own folder");
+ var lucaCard = (await server.GetJsonAsync($"/api/accounts/{luca.Account.Id}")).GetProperty("export").GetProperty("destination");
+ Assert.AreEqual(2, lucaCard.Int("waiting"), "the own folder of the card is counted");
}
[TestMethod]
@@ -271,7 +278,7 @@ public sealed partial class ExportApiTests
var session = new FakeSessionState();
var clock = new GatedClock(new ManualClock(Make.T0));
await using var server = await StartAsync(session: session, clock: clock);
- await AddPhotosAsync(server, "marta.demo", 2);
+ var marta = await AddPhotosAsync(server, "marta.demo", 2);
var usb = server.Temp.Combine("usb");
Directory.CreateDirectory(usb);
var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true, onlyNew: false));
@@ -294,13 +301,14 @@ public sealed partial class ExportApiTests
})).GetValueOrDefault();
Assert.AreEqual("automatic", progress.Str("origin"));
Assert.AreEqual("copy", progress.Str("kind"));
+ Assert.IsFalse(progress.Bool("manualRunning"), "an automatic copy keeps no «Riprendi» off (answer 49)");
// «Interrompi» (answer 53): the automatic copies stop until the next round, at least an hour, and the answer says when.
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/interrupt");
Assert.AreEqual(HttpStatusCode.OK, status, answer.ToString());
var until = clock.Now + service.AutomaticHoldTime;
Assert.AreEqual(until, service.AutomaticHeldUntil);
- Assert.AreEqual(ExportText.AutomaticInterrupted(until, clock.LocalZone), answer.Str("message"));
+ Assert.AreEqual(ExportText.AutomaticInterrupted(until, clock.Now, clock.LocalZone), answer.Str("message"));
StringAssert.Contains(answer.Str("message"), "riprende da sola alle");
Assert.AreEqual(ExportRunState.Interrupted, (await server.Db.Exports.GetRunAsync(start.Runs[0].Id))!.State);
@@ -310,10 +318,25 @@ public sealed partial class ExportApiTests
Assert.AreEqual("Copie automatiche di nuovo attive.", resumeAnswer.Str("message"));
Assert.IsNull(service.AutomaticHeldUntil);
- // A manual job keeps the message of before.
- session.InSession = false;
+ // A job of Alberto's, waiting for the session: it is the one that keeps «Riprendi» off; «Interrompi» keeps the
+ // message of before.
+ service.AutomaticRunRecorded = null;
+ var (manualStatus, manualJob) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id, copyAgain = true });
+ Assert.AreEqual(HttpStatusCode.OK, manualStatus, manualJob.ToString());
+ var manualProgress = (await WaitForAsync(async () =>
+ {
+ var p = await server.GetJsonAsync("/api/export/progress");
+ return p.Bool("running") && p.Str("phase") == "waitingForSession" && p.Str("origin") == "manual" ? (JsonElement?)p : null;
+ })).GetValueOrDefault();
+ Assert.IsTrue(manualProgress.Bool("manualRunning"));
Assert.AreEqual("Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi.", (await server.SendJsonAsync(HttpMethod.Post, "/api/export/interrupt")).Body.Str("message"));
Assert.IsNull(service.AutomaticHeldUntil);
+ session.InSession = false;
+
+ // «Annulla» of the automatic job says that its files go back into the queue (D12).
+ var (discarded, discardAnswer) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/runs/{start.Runs[0].Id}/discard");
+ Assert.AreEqual(HttpStatusCode.OK, discarded, discardAnswer.ToString());
+ Assert.AreEqual(ExportText.DiscardedAutomatic, discardAnswer.Str("message"));
}
[TestMethod]
diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.Automatic.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.Automatic.cs
index 3a94a5c..b153522 100644
--- a/tests/Febe.Tests/Web/ExportInterfaceTests.Automatic.cs
+++ b/tests/Febe.Tests/Web/ExportInterfaceTests.Automatic.cs
@@ -76,12 +76,12 @@ public sealed partial class ExportInterfaceTests
await SaveFolderDialogAsync(ui);
await ui.WaitAsync(Shown("Automatica accesa: da adesso si copiano da soli i file nuovi."), "l'avviso dell'accensione");
await ui.WaitAsync($"{GeneralFolder}.then((g) => g.automatic === true && g.automaticSince !== null)", "automatica sul server, con l'istante");
- await ui.WaitAsync($"({GeneralDescription}).includes('· Automatica dal ')", "«Automatica dal …» sotto la cartella");
+ await ui.WaitAsync($"({GeneralDescription}).includes('· Automatica dal')", "«Automatica dal …» sotto la cartella");
// Opened again: on, the same folder: it says since when and asks nothing.
await OpenGeneralDialogAsync(ui);
Assert.IsTrue((await ui.EvalAsync($"{AutoSwitch}.checked")).GetBoolean());
- await ui.WaitAsync($"{AutoBox}.textContent.includes('Automatica dal ') && {AutoBox}.textContent.includes('copia i file salvati in libreria da allora')", "«Automatica dal …» nel dialogo");
+ await ui.WaitAsync($"{AutoBox}.textContent.includes('Automatica dal') && {AutoBox}.textContent.includes('copia i file salvati in libreria da allora')", "«Automatica dal …» nel dialogo");
Assert.AreEqual(0, (await ui.EvalAsync($"{AutoChoices}.length")).GetInt32(), "no question while it stays on");
// Off: no automatic job of this folder is unfinished, so no note; saved, it forgets the answer.
@@ -125,14 +125,14 @@ public sealed partial class ExportInterfaceTests
await ui.OpenAsync(new Uri(demo.Address, $"/account/{studio.Id}/impostazioni?veste=docker"));
const string Block = "document.querySelector('.copie-esterne')";
await ui.WaitAsync($"{Block}?.querySelector('.riga-etichetta .et.accento') != null", "l'etichetta «Automatica» " + ui.Report());
- StringAssert.StartsWith((await ui.EvalAsync($"{Block}.querySelector('.riga-etichetta .et.accento').textContent")).GetString(), "Automatica dal ");
+ StringAssert.StartsWith((await ui.EvalAsync($"{Block}.querySelector('.riga-etichetta .et.accento').textContent")).GetString(), "Automatica dal");
StringAssert.Contains((await ui.EvalAsync($"{Block}.querySelector('.riga-etichetta').textContent")).GetString(), "Nella sua cartella");
var buttons = await ui.EvalAsync($"[...{Block}.querySelectorAll('.stato-copie button')].map((b) => b.textContent.trim())");
CollectionAssert.AreEqual(new[] { "Controlla le copie", "Riconosci le copie già presenti" }, buttons);
// The dialog: on since a day; turned off, the automatic job left unfinished stops, and it says so before saving.
Assert.IsTrue((await ui.EvalAsync(ClickText(".copie-esterne .cartella", "button", "Modifica"))).GetBoolean());
- await ui.WaitAsync($"{AutoSwitch} != null && {AutoBox}.textContent.includes('Automatica dal ')", "il dialogo con «Automatica dal …»");
+ await ui.WaitAsync($"{AutoSwitch} != null && {AutoBox}.textContent.includes('Automatica dal')", "il dialogo con «Automatica dal …»");
Assert.IsTrue((await ui.EvalAsync($"{AutoSwitch}.checked")).GetBoolean());
await ui.EvalAsync($"{AutoSwitch}.click()");
await ui.WaitAsync($"{FolderDialog}.querySelector('.spegnere') != null", "la nota «Spegnendo…» " + ui.Report());
@@ -143,7 +143,7 @@ public sealed partial class ExportInterfaceTests
// On again with the same folder: nothing to ask. Another folder is a new destination: the question comes back,
// and counts the files the new folder would have (none copied there yet).
await ui.EvalAsync($"{AutoSwitch}.click()");
- await ui.WaitAsync($"{AutoBox}.textContent.includes('Automatica dal ') && {FolderDialog}.querySelector('.spegnere') === null", "di nuovo accesa");
+ await ui.WaitAsync($"{AutoBox}.textContent.includes('Automatica dal') && {FolderDialog}.querySelector('.spegnere') === null", "di nuovo accesa");
Assert.AreEqual(0, (await ui.EvalAsync($"{AutoChoices}.length")).GetInt32());
await ui.WaitAsync($"{FolderDialog}.querySelector('.sfoglia-voce') != null", "le cartelle");
await ui.EvalAsync($"[...{FolderDialog}.querySelectorAll('.sfoglia-voce')].find((b) => b.textContent.trim() === 'Chiavetta').click()");