Compare commits

..

1 Commits

Author SHA1 Message Date
cesnimda e9fa42eccf Allow users to pause automatic Ghosted updates
CI and Deploy / test (pull_request) Failing after 4m31s
CI and Deploy / deploy (pull_request) Has been skipped
2026-12-04 18:27:24 +01:00
21 changed files with 268 additions and 407 deletions
@@ -1,145 +0,0 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging.Abstractions;
using MySqlConnector;
using Xunit;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class AiOperationPollingTests
{
private const string Owner = "queue-owner";
[Fact]
public async Task Hosted_worker_recovers_from_a_native_claim_lock_timeout()
{
await using var database = await MariaDbDatabase.CreateAsync();
var lockTimeout = new ClaimLockTimeout();
var handler = new SyntheticHandler();
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Workers:AiOperationsEnabled"] = "true",
["AiQueue:IdleDelayMs"] = "100",
}).Build();
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configuration);
services.AddLogging();
services.AddHttpContextAccessor();
services.AddScoped<CurrentUserService>();
services.AddScoped<ICurrentUserService>(scope => scope.GetRequiredService<CurrentUserService>());
services.AddDbContext<JobTrackerContext>(options => options.UseMySql(database.ConnectionString, database.ServerVersion)
.AddInterceptors(lockTimeout));
services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
services.AddSingleton(TimeProvider.System);
services.AddScoped<UserOperationStore>();
services.AddSingleton<AiPrivacyPolicy>();
services.AddSingleton<AiOperationExecutionScope>();
await using var provider = services.BuildServiceProvider();
await using var seed = provider.CreateAsyncScope();
var users = seed.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roles = seed.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var user = new ApplicationUser { Id = Owner, UserName = "native-queue@example.test", AiEnabled = true };
Assert.True((await roles.CreateAsync(new IdentityRole("Premium"))).Succeeded);
Assert.True((await users.CreateAsync(user)).Succeeded);
Assert.True((await users.AddToRoleAsync(user, "Premium")).Succeeded);
var now = DateTime.UtcNow;
var operation = new UserOperation
{
OwnerUserId = Owner, TaskType = handler.TaskType, IdempotencyKey = "native-lock",
CreatedAtUtc = now, AvailableAtUtc = now, EntitlementDecision = "allowed", PrivacyPolicy = "local_only",
};
var db = seed.ServiceProvider.GetRequiredService<JobTrackerContext>();
db.UserOperations.Add(operation);
await db.SaveChangesAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
await using var lockContext = database.Context(Owner);
await using var held = await lockContext.Database.BeginTransactionAsync(timeout.Token);
Assert.Equal(1, await lockContext.UserOperations.Where(row => row.Id == operation.Id)
.ExecuteUpdateAsync(set => set.SetProperty(row => row.Priority, 1), timeout.Token));
var worker = new AiOperationWorker(provider.GetRequiredService<IServiceScopeFactory>(), [handler],
provider.GetRequiredService<AiPrivacyPolicy>(), provider.GetRequiredService<AiOperationExecutionScope>(), configuration);
using var hosted = new AiOperationHostedService(worker, configuration, NullLogger<AiOperationHostedService>.Instance);
try
{
await hosted.StartAsync(timeout.Token);
var finished = await Task.WhenAny(hosted.ExecuteTask!, lockTimeout.Failure.Task).WaitAsync(timeout.Token);
if (finished == hosted.ExecuteTask) await finished;
var failure = await lockTimeout.Failure.Task;
Assert.Equal(1205, failure.Number);
Assert.True(failure.IsTransient);
var queued = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync(timeout.Token);
Assert.Equal(OperationStatuses.Queued, queued.Status);
Assert.Null(queued.LeaseToken);
Assert.Equal(0, queued.AttemptCount);
await held.RollbackAsync(timeout.Token);
UserOperation completed;
do
{
await Task.Delay(50, timeout.Token);
if (hosted.ExecuteTask!.IsCompleted) await hosted.ExecuteTask;
completed = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync(timeout.Token);
} while (completed.Status != OperationStatuses.Succeeded);
Assert.Equal(1, completed.AttemptCount);
Assert.Null(completed.LeaseToken);
Assert.Equal(Owner, completed.OwnerUserId);
Assert.Equal(1, handler.Executions);
Assert.Equal(Owner, (await db.UserNotifications.IgnoreQueryFilters().SingleAsync(timeout.Token)).OwnerUserId);
Assert.False(hosted.ExecuteTask!.IsCompleted);
}
finally
{
await hosted.StopAsync(timeout.Token);
}
}
private sealed class ClaimLockTimeout : DbCommandInterceptor
{
public TaskCompletionSource<MySqlException> Failure { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command,
CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (command.CommandText.StartsWith("UPDATE", StringComparison.Ordinal) &&
command.CommandText.Contains("`UserOperations`", StringComparison.Ordinal))
{
await using var setup = command.Connection!.CreateCommand();
setup.Transaction = command.Transaction;
setup.CommandText = "SET SESSION innodb_lock_wait_timeout = 1";
await setup.ExecuteNonQueryAsync(cancellationToken);
}
return result;
}
public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData,
CancellationToken cancellationToken = default)
{
if (eventData.Exception is MySqlException failure)
Failure.TrySetResult(failure);
return Task.CompletedTask;
}
}
private sealed class SyntheticHandler : IAiOperationHandler
{
private int _executions;
public int Executions => Volatile.Read(ref _executions);
public string TaskType => "synthetic.ai.mariadb";
public Task<AiOperationExecutionResult> ExecuteAsync(AiOperationExecutionContext context,
IServiceProvider services, CancellationToken cancellationToken)
{
Assert.Equal(Owner, services.GetRequiredService<ICurrentUserService>().UserId);
Interlocked.Increment(ref _executions);
return Task.FromResult(new AiOperationExecutionResult("native-result", "ollama", "synthetic", "local_primary", 0, 0));
}
}
}
@@ -0,0 +1,47 @@
using JobTrackerApi.Controllers;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Xunit;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class RulesPauseMigrationTests
{
[Fact]
public async Task Existing_thresholds_survive_pause_migration_and_numeric_writes_preserve_pause()
{
const string owner = "existing-rules-owner";
const string previous = "20261028090000_AddUserOperationEvents";
await using var database = await MariaDbDatabase.CreateAsync();
await using var db = database.Context(owner);
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync(previous);
await db.Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO UserRuleSettings
(OwnerUserId, AppliedFollowUpDays, AppliedGhostDays, OfferFollowUpDays, OfferGhostDays, FeedbackFollowUpDays, FeedbackGhostDays)
VALUES ({owner}, 9, 31, 7, 14, 7, 14)
""");
await migrator.MigrateAsync();
var initial = await RulesEngine.GetSettings(db, default);
Assert.Equal(31, initial.AppliedGhostDays);
Assert.Equal(false, initial.AutomaticGhostingPaused);
var controller = new RulesController(db);
Assert.IsType<NoContentResult>(await controller.Update(
new RuleSettings { AppliedGhostDays = 31, AutomaticGhostingPaused = true }, default));
Assert.IsType<NoContentResult>(await controller.Update(new RuleSettings { AppliedGhostDays = 32 }, default));
var committed = await RulesEngine.GetSettings(db, default);
Assert.Equal(true, committed.AutomaticGhostingPaused);
Assert.Equal(32, committed.AppliedGhostDays);
await migrator.MigrateAsync(previous);
var threshold = await db.Database.SqlQuery<int>($"""
SELECT AppliedGhostDays AS Value FROM UserRuleSettings WHERE OwnerUserId = {owner}
""").ToListAsync();
Assert.Equal(32, Assert.Single(threshold));
}
}
@@ -79,7 +79,7 @@ public sealed class StartupAndLockTests(ITestOutputHelper output)
db.Add(job);
await db.SaveChangesAsync();
var migrations = (await db.Database.GetAppliedMigrationsAsync()).ToArray();
Assert.Equal("20261028090000_AddUserOperationEvents", migrations[^1]);
Assert.Equal(db.Database.GetMigrations(), migrations);
// Only this test's newly-created schema is downgraded; no existing database is selected.
const string beforeRd21 = "20261021090000_AddDashboardLayoutPreference";
await db.GetService<IMigrator>().MigrateAsync(beforeRd21);
+4 -208
View File
@@ -1,212 +1,17 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
namespace JobTrackerApi.Tests;
public sealed class AiOperationQueueTests
{
[Fact]
public async Task Hosted_worker_survives_transient_claim_failure_and_completes_once()
{
var interruption = new ClaimInterruption();
await using var fixture = await Fixture.CreateAsync(interruption: interruption);
await fixture.SeedUserAsync("pro-1", pro: true);
await fixture.EnqueueAsync("pro-1", "recover");
var configuration = fixture.Provider.GetRequiredService<IConfiguration>();
configuration["Workers:AiOperationsEnabled"] = "true";
configuration["AiQueue:IdleDelayMs"] = "100";
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AiOperationHostedService>.Instance);
interruption.Armed = true;
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
await hosted.StartAsync(timeout.Token);
var finished = await Task.WhenAny(hosted.ExecuteTask!, interruption.PolledAfterRecovery.Task).WaitAsync(timeout.Token);
if (finished == hosted.ExecuteTask) await finished;
Assert.Same(interruption.PolledAfterRecovery.Task, finished);
}
finally
{
await hosted.StopAsync(timeout.Token);
}
await using var scope = fixture.Provider.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<JobTrackerContext>();
var operation = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync();
Assert.Equal(OperationStatuses.Succeeded, operation.Status);
Assert.Equal(1, operation.AttemptCount);
Assert.Null(operation.LeaseToken);
Assert.Equal("pro-1", fixture.Handler.OwnerUserId);
Assert.Single(await db.UserNotifications.IgnoreQueryFilters().ToListAsync());
}
private sealed class ClaimInterruption : DbCommandInterceptor
{
private int _polls;
public bool Armed { get; set; }
public TaskCompletionSource PolledAfterRecovery { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
if (Armed && command.CommandText.Contains("UserOperations", StringComparison.Ordinal) &&
command.CommandText.Contains("ORDER BY", StringComparison.Ordinal))
{
var poll = Interlocked.Increment(ref _polls);
if (poll == 1) throw new SqliteException("Synthetic busy claim", 5);
if (poll == 3) PolledAfterRecovery.TrySetResult();
}
return new(result);
}
}
[Theory]
[InlineData("retry")]
[InlineData("cancel")]
[InlineData("committed")]
[InlineData("permanent")]
public async Task Hosted_worker_recovers_a_terminal_database_interruption(string scenario)
{
var cancel = scenario == "cancel";
var committed = scenario == "committed";
var permanent = scenario == "permanent";
var commitInterruption = new TerminalCommitInterruption();
var clock = new AdjustableClock();
await using var fixture = await Fixture.CreateAsync(
interruption: committed ? commitInterruption : new TerminalSaveInterruption(permanent ? 19 : 5), clock: clock);
if (committed) fixture.Handler.OnResult = commitInterruption.Arm;
await fixture.SeedUserAsync("pro-1", pro: true);
await fixture.EnqueueAsync("pro-1", "recover-terminal");
var configuration = fixture.Provider.GetRequiredService<IConfiguration>();
configuration["Workers:AiOperationsEnabled"] = "true";
configuration["AiQueue:IdleDelayMs"] = "100";
configuration["AiQueue:LeaseSeconds"] = "30";
var logger = new PollingLogger();
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration, logger);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(12));
try
{
await hosted.StartAsync(timeout.Token);
var finished = await Task.WhenAny(hosted.ExecuteTask!, logger.TransientFailure.Task).WaitAsync(timeout.Token);
if (permanent)
{
Assert.Same(hosted.ExecuteTask, finished);
var failure = await Assert.ThrowsAsync<DbUpdateException>(() => finished);
Assert.Equal(19, Assert.IsType<SqliteException>(failure.InnerException).SqliteErrorCode);
Assert.False(logger.TransientFailure.Task.IsCompleted);
return;
}
if (finished == hosted.ExecuteTask) await finished;
Assert.Same(logger.TransientFailure.Task, finished);
await using var scope = fixture.Provider.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<JobTrackerContext>();
var operation = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().SingleAsync(timeout.Token);
Assert.Equal(committed ? OperationStatuses.Succeeded : OperationStatuses.Running, operation.Status);
Assert.Equal(1, operation.AttemptCount);
if (committed) Assert.Null(operation.LeaseToken);
else Assert.NotNull(operation.LeaseToken);
Assert.Equal("pro-1", operation.OwnerUserId);
Assert.Equal(committed ? 1 : 0, await db.UserNotifications.IgnoreQueryFilters().CountAsync(timeout.Token));
if (cancel)
{
var currentUser = scope.ServiceProvider.GetRequiredService<CurrentUserService>();
var store = scope.ServiceProvider.GetRequiredService<UserOperationStore>();
using (currentUser.UseBackgroundUser("other-tenant"))
Assert.False(await store.RequestCancellationAsync(operation.Id, timeout.Token));
using (currentUser.UseBackgroundUser("pro-1"))
Assert.True(await store.RequestCancellationAsync(operation.Id, timeout.Token));
}
clock.Advance(TimeSpan.FromSeconds(31));
if (committed) await fixture.EnqueueAsync("pro-1", "after-ambiguous-commit");
var expected = cancel ? OperationStatuses.Cancelled : OperationStatuses.Succeeded;
var operationId = operation.Id;
bool subsequentWorkCompleted;
do
{
await Task.Delay(40, timeout.Token);
if (hosted.ExecuteTask!.IsCompleted) await hosted.ExecuteTask;
var rows = await db.UserOperations.IgnoreQueryFilters().AsNoTracking().ToListAsync(timeout.Token);
operation = rows.Single(row => row.Id == operationId);
subsequentWorkCompleted = !committed || rows.Single(row => row.Id != operationId).Status == OperationStatuses.Succeeded;
} while (operation.Status != expected || !subsequentWorkCompleted);
Assert.Equal(cancel || committed ? 1 : 2, operation.AttemptCount);
Assert.Equal(cancel ? 1 : 2, fixture.Handler.Executions);
Assert.Null(operation.LeaseToken);
Assert.Equal(cancel ? null : "synthetic-result", operation.ResultReference);
var notifications = await db.UserNotifications.IgnoreQueryFilters().ToListAsync(timeout.Token);
Assert.Equal(committed ? 2 : 1, notifications.Count);
Assert.All(notifications, notification => Assert.Equal("pro-1", notification.OwnerUserId));
Assert.False(hosted.ExecuteTask!.IsCompleted);
}
finally
{
await hosted.StopAsync(timeout.Token);
}
}
private sealed class TerminalSaveInterruption(int errorCode) : DbCommandInterceptor
{
private int _interrupted;
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
if (command.CommandText.Contains("INSERT INTO \"UserNotifications\"", StringComparison.Ordinal)
&& Interlocked.Exchange(ref _interrupted, 1) == 0)
throw new SqliteException("Synthetic terminal save failure", errorCode);
return new(result);
}
}
private sealed class TerminalCommitInterruption : DbTransactionInterceptor
{
private int _state;
public void Arm() => Interlocked.CompareExchange(ref _state, 1, 0);
public override Task TransactionCommittedAsync(DbTransaction transaction, TransactionEndEventData eventData,
CancellationToken cancellationToken = default)
{
if (Interlocked.CompareExchange(ref _state, 2, 1) == 1)
throw new SqliteException("Synthetic lost reply after terminal commit", 5);
return Task.CompletedTask;
}
}
private sealed class PollingLogger : ILogger<AiOperationHostedService>
{
public TaskCompletionSource TransientFailure { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel == LogLevel.Warning;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
if (IsEnabled(logLevel)) TransientFailure.TrySetResult();
}
}
private sealed class AdjustableClock : TimeProvider
{
private long _ticks = DateTimeOffset.UtcNow.UtcTicks;
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan duration) => Interlocked.Add(ref _ticks, duration.Ticks);
}
[Fact]
public async Task Admission_is_pro_only_idempotent_bounded_and_contains_no_raw_payload()
{
@@ -324,9 +129,6 @@ public sealed class AiOperationQueueTests
private sealed class SyntheticHandler : IAiOperationHandler
{
private int _executions;
public int Executions => Volatile.Read(ref _executions);
public Action? OnResult { get; set; }
public string TaskType => "synthetic.ai";
public string? OwnerUserId { get; private set; }
public string? PrivacyPolicy { get; private set; }
@@ -335,12 +137,10 @@ public sealed class AiOperationQueueTests
public Task<AiOperationExecutionResult> ExecuteAsync(AiOperationExecutionContext context, IServiceProvider services, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _executions);
if (Failure is not null) throw Failure;
if (GenerationFailure is not null) throw GenerationFailure;
OwnerUserId = services.GetRequiredService<ICurrentUserService>().UserId;
PrivacyPolicy = context.EffectivePrivacyPolicy;
OnResult?.Invoke();
return Task.FromResult(new AiOperationExecutionResult(
"synthetic-result", "ollama", "qwen-test", "local_primary", 120, 40));
}
@@ -359,9 +159,9 @@ public sealed class AiOperationQueueTests
Handler = handler;
}
public static async Task<Fixture> CreateAsync(int perUserCapacity = 10, IInterceptor? interruption = null, TimeProvider? clock = null)
public static async Task<Fixture> CreateAsync(int perUserCapacity = 10)
{
var connection = new SqliteConnection($"Data Source=ai-queue-{Guid.NewGuid():N};Mode=Memory;Cache=Shared");
var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
@@ -377,13 +177,9 @@ public sealed class AiOperationQueueTests
services.AddHttpContextAccessor();
services.AddScoped<CurrentUserService>();
services.AddScoped<ICurrentUserService>(provider => provider.GetRequiredService<CurrentUserService>());
services.AddDbContext<JobTrackerContext>((_, options) =>
{
options.UseSqlite(connection.ConnectionString);
if (interruption is not null) options.AddInterceptors(interruption);
});
services.AddDbContext<JobTrackerContext>((_, options) => options.UseSqlite(connection));
services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
services.AddSingleton(clock ?? TimeProvider.System);
services.AddSingleton(TimeProvider.System);
services.AddScoped<UserOperationStore>();
services.AddSingleton<AiPrivacyPolicy>();
services.AddSingleton<AiOperationExecutionScope>();
@@ -1,10 +1,12 @@
using System.Collections.Concurrent;
using System.Text.Json;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
@@ -79,6 +81,39 @@ public sealed class BackgroundWorkerTenantTests
Assert.Equal("Applied", jobs[1].Status);
}
[Fact]
public async Task Paused_owner_keeps_applied_jobs_while_other_owner_runs_and_resume_takes_effect_next_run()
{
await using var fixture = await Fixture.CreateAsync(new Dictionary<string, string?> { ["Workers:RulesEnabled"] = "true" });
await fixture.SeedJobsAsync();
var worker = new RulesHostedService(fixture.Runner, fixture.Configuration, NullLogger<RulesHostedService>.Instance,
Mock.Of<IStartupReadiness>(), new MutableTimeProvider(FixedNow));
await SaveOwnerRules("user-1", true);
await SaveOwnerRules("user-2", null);
await SaveOwnerRules("user-1", null);
Assert.Equal(new BackgroundWorkerRunResult(true, 2, 2, 0), await worker.RunOnceAsync(default));
await using var verification = fixture.Provider.CreateAsyncScope();
var db = verification.ServiceProvider.GetRequiredService<JobTrackerContext>();
Assert.Equal(new[] { "Applied", "Ghosted" }, await ReadStatuses());
await SaveOwnerRules("user-1", false);
Assert.Equal(new BackgroundWorkerRunResult(true, 2, 2, 0), await worker.RunOnceAsync(default));
Assert.Equal(new[] { "Ghosted", "Ghosted" }, await ReadStatuses());
async Task SaveOwnerRules(string owner, bool? paused)
{
await using var scope = fixture.Provider.CreateAsyncScope();
using var user = scope.ServiceProvider.GetRequiredService<CurrentUserService>().UseBackgroundUser(owner);
var controller = new RulesController(scope.ServiceProvider.GetRequiredService<JobTrackerContext>());
Assert.IsType<NoContentResult>(await controller.Update(
new RuleSettings { AppliedGhostDays = 5, AutomaticGhostingPaused = paused }, default));
}
Task<string[]> ReadStatuses() => db.JobApplications.IgnoreQueryFilters().AsNoTracking()
.OrderBy(job => job.OwnerUserId).Select(job => job.Status).ToArrayAsync();
}
[Fact]
public async Task Affected_workers_are_disabled_by_default()
{
@@ -34,8 +34,7 @@ public sealed class CvProcessingOperationTests
var configuration = fixture.Provider.GetRequiredService<IConfiguration>();
configuration["Workers:AiOperationsEnabled"] = "false";
configuration["Workers:CvDocumentImportsEnabled"] = "true";
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AiOperationHostedService>.Instance);
using var hosted = new AiOperationHostedService(fixture.Provider.GetRequiredService<AiOperationWorker>(), configuration);
await hosted.StartAsync(default);
try
{
@@ -15,6 +15,28 @@ public sealed class MigrationChainTests
{
private const string SnapshotMigration = "20260711181039_SyncModelSnapshot";
[Fact]
public async Task Automatic_ghosting_pause_upgrade_and_rollback_preserve_existing_thresholds()
{
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
await using var db = Context(connection);
var migrator = db.GetService<IMigrator>();
const string previous = "20261028090000_AddUserOperationEvents";
await migrator.MigrateAsync(previous);
await ExecuteAsync(connection, """
INSERT INTO UserRuleSettings
(OwnerUserId, AppliedFollowUpDays, AppliedGhostDays, OfferFollowUpDays, OfferGhostDays, FeedbackFollowUpDays, FeedbackGhostDays)
VALUES ('existing-owner', 9, 31, 7, 14, 7, 14);
""");
await migrator.MigrateAsync();
Assert.Equal(0L, await ScalarAsync<long>(connection, "SELECT AutomaticGhostingPaused FROM UserRuleSettings;"));
await ExecuteAsync(connection, "UPDATE UserRuleSettings SET AutomaticGhostingPaused=1;");
await migrator.MigrateAsync(previous);
Assert.Equal(31L, await ScalarAsync<long>(connection, "SELECT AppliedGhostDays FROM UserRuleSettings;"));
Assert.Equal(0L, await ScalarAsync<long>(connection, "SELECT COUNT(*) FROM pragma_table_info('UserRuleSettings') WHERE name='AutomaticGhostingPaused';"));
}
[Fact]
public async Task Letter_document_upgrade_adds_nullable_fields_without_rewriting_old_letters_or_frozen_bytes()
{
@@ -32,6 +32,7 @@ namespace JobTrackerApi.Controllers
return Ok(new RuleSettings
{
Id = 1,
AutomaticGhostingPaused = u.AutomaticGhostingPaused,
AppliedFollowUpDays = u.AppliedFollowUpDays,
AppliedGhostDays = u.AppliedGhostDays,
OfferFollowUpDays = u.OfferFollowUpDays,
@@ -60,6 +61,8 @@ namespace JobTrackerApi.Controllers
{
var s = await GetOrCreateUserSettingsAsync(_db.CurrentUserId, cancellationToken);
if (incoming.AutomaticGhostingPaused is bool paused)
s.AutomaticGhostingPaused = paused;
s.AppliedFollowUpDays = Clamp(incoming.AppliedFollowUpDays, 1, 365);
s.AppliedGhostDays = Clamp(incoming.AppliedGhostDays, 1, 365);
s.OfferFollowUpDays = Clamp(incoming.OfferFollowUpDays, 1, 365);
@@ -0,0 +1,25 @@
using JobTrackerApi.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
namespace JobTrackerApi.Migrations;
[DbContext(typeof(JobTrackerContext))]
[Migration("20261204180000_AddUserAutomaticGhostingPause")]
public sealed class AddUserAutomaticGhostingPause : Migration
{
protected override void Up(MigrationBuilder migrationBuilder) =>
migrationBuilder.AddColumn<bool>(
name: "AutomaticGhostingPaused",
table: "UserRuleSettings",
nullable: false,
defaultValue: false);
protected override void Down(MigrationBuilder migrationBuilder)
{
if (ActiveProvider?.Contains("Sqlite", StringComparison.OrdinalIgnoreCase) == true)
migrationBuilder.Sql("ALTER TABLE \"UserRuleSettings\" DROP COLUMN \"AutomaticGhostingPaused\";");
else
migrationBuilder.DropColumn("AutomaticGhostingPaused", "UserRuleSettings");
}
}
@@ -2458,6 +2458,9 @@ namespace JobTrackerApi.Migrations
b.Property<string>("OwnerUserId")
.HasColumnType("TEXT");
b.Property<bool>("AutomaticGhostingPaused")
.HasColumnType("INTEGER");
b.Property<int>("AppliedFollowUpDays")
.HasColumnType("INTEGER");
+8
View File
@@ -1,3 +1,6 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
namespace JobTrackerApi.Models
{
// Single-row table to store workflow automation thresholds.
@@ -5,6 +8,11 @@ namespace JobTrackerApi.Models
{
public int Id { get; set; } = 1;
// The API accepts this only as a per-user override. Older clients can omit it.
[NotMapped]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public bool? AutomaticGhostingPaused { get; set; }
// Applied / no response yet
public int AppliedFollowUpDays { get; set; } = 14;
public int AppliedGhostDays { get; set; } = 30;
+1
View File
@@ -3,6 +3,7 @@ namespace JobTrackerApi.Models;
public sealed class UserRuleSettings
{
public string OwnerUserId { get; set; } = "";
public bool AutomaticGhostingPaused { get; set; }
// Applied / no response yet
public int AppliedFollowUpDays { get; set; } = 14;
+3 -25
View File
@@ -1,9 +1,7 @@
using System.Data.Common;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MySqlConnector;
namespace JobTrackerApi.Services;
@@ -253,8 +251,7 @@ public sealed class AiOperationWorker(
private static TimeSpan RetryDelay(int attempt) => TimeSpan.FromSeconds(Math.Min(60, (1 << Math.Min(attempt, 5)) + Random.Shared.Next(0, 4)));
}
public sealed class AiOperationHostedService(
AiOperationWorker worker, IConfiguration configuration, ILogger<AiOperationHostedService> logger) : BackgroundService
public sealed class AiOperationHostedService(AiOperationWorker worker, IConfiguration configuration) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
@@ -269,27 +266,8 @@ public sealed class AiOperationHostedService(
var idleDelayMs = Math.Clamp(configuration.GetValue("AiQueue:IdleDelayMs", 1000), 100, 10_000);
while (!stoppingToken.IsCancellationRequested)
{
try
{
if (await worker.RunOnceAsync(stoppingToken, documentImportsOnly)) continue;
}
catch (Exception failure) when (IsTransientDatabaseFailure(failure))
{
// The store owns recovery of any persisted lease when polling resumes.
logger.LogWarning("AI operation polling paused after a transient database error.");
}
await Task.Delay(idleDelayMs, stoppingToken);
if (!await worker.RunOnceAsync(stoppingToken, documentImportsOnly))
await Task.Delay(idleDelayMs, stoppingToken);
}
}
private static bool IsTransientDatabaseFailure(Exception failure)
{
// Pomelo's non-retrying execution strategy wraps transient provider errors.
if (failure is InvalidOperationException { InnerException: { } inner } &&
inner is MySqlException or DbUpdateException { InnerException: MySqlException })
failure = inner;
var providerError = failure is DbUpdateException update ? update.InnerException : failure;
return providerError is DbException { IsTransient: true }
or Microsoft.Data.Sqlite.SqliteException { SqliteErrorCode: 5 or 6 };
}
}
+1
View File
@@ -21,6 +21,7 @@ namespace JobTrackerApi.Services
return new RuleSettings
{
Id = 1,
AutomaticGhostingPaused = u.AutomaticGhostingPaused,
AppliedFollowUpDays = u.AppliedFollowUpDays,
AppliedGhostDays = u.AppliedGhostDays,
OfferFollowUpDays = u.OfferFollowUpDays,
@@ -40,6 +40,9 @@ public sealed class RulesHostedService(
{
var db = services.GetRequiredService<JobTrackerContext>();
var settings = await RulesEngine.GetSettings(db, cancellationToken);
if (settings.AutomaticGhostingPaused == true)
return;
var now = timeProvider.GetLocalNow().DateTime;
var lastMessages = await db.Correspondences
.GroupBy(message => message.JobApplicationId)
-15
View File
@@ -1,15 +0,0 @@
# Gitea continuation
The live Project 1 read on 2 December 2026 returned 101 open items. There were 32 Ready, 50 Blocked, 17 Backlog and two Testing. PR #130 was open and unmerged at `c05d6f89`. The backlog tool was run from the existing isolated migration checkout.
Issue #120 has a verified candidate on `codex/issue-120-ai-queue`, based on `ac64d2ee`. The original claim regression established SQLite polling recovery. The follow-up reproduced a polling exit on an EF-wrapped SQLite busy error during the terminal save and on Pomelo's wrapper around native MariaDB lock timeout 1205.
After the follow-up fix, 42 affected .NET Release tests passed. The SQLite fixtures prove that a rolled-back terminal save keeps the active lease until expiry, then allows one bounded retry or finalizes owner cancellation. Another tenant cannot cancel the operation. A lost reply after a successful commit preserves the original result and its single notification, and the worker polls a subsequent operation. The permanent SQLite error still faults the hosted task. MariaDB 12.2.2 passed the native claim-lock fixture. After rollback released the blocking transaction, the worker completed in one attempt with the correct owner, a cleared lease and one notification.
The injected terminal faults occur after the synthetic handler returns. Provider interruption during its execution and native MariaDB terminal-commit ambiguity were outside these fixtures. Publish the candidate and update the open issue with this evidence. Integration and production acceptance remain separate.
The live board move to Code Review and issue evidence note await authentication. The scoped credential file did not exist, the session had no `GITEA_TOKEN`, and the Playwright CLI reported no signed-in browser. The repository project REST endpoint returned 404. The public read through the existing board parser succeeded.
To resume board writes, sign in to the isolated Playwright session from the backlog tooling checkout using `playwright-cli.cmd -s=jobjakt-board open https://git.cesnimda.uk/cesnimda/jobtrackingapp/projects/1 --headed --browser=chrome`. Run `scripts/gitea-board.ps1 -Number 120 -Column 'Code Review'` without `-Apply` for a readback first. Apply only the current evidence-backed stage, then reload and verify. For issue notes use the scoped credential setup in the tooling README. Keep the token out of chat and files tracked by Git. Preserve the issue as open until its full criteria are met.
Next independent item is #121. Existing source still formats Companies dates in the viewer timezone and seeds editor inputs from the stored date prefix. The previous picker work covers user-selected dates. Reuse that evidence, define the legacy read/display contract and test display/edit/save in Los Angeles, Oslo and Kiritimati.
@@ -54,6 +54,54 @@ async function reflow(page: Page, info: TestInfo, name: string) {
expect(outside).toEqual([]);
}
for (const [language, width, mode] of [["en", 1440, "light"], ["nb", 390, "dark"]] as const) {
test(`automatic Ghosted pause keeps its draft and persists after retry in ${language}`, async ({ page, headers }, info) => {
const t = translations[language];
const rulesUrl = `${apiUrl}/rules`;
await page.setViewportSize({ width, height: 900 });
await page.addInitScript(({ mode, language }) => {
localStorage.setItem("jobtracker.themeMode", mode);
localStorage.setItem("uiLanguage", language);
}, { mode, language });
expect((await page.request.put(`${apiUrl}/auth/preferences/language`, {
headers, data: { language: language === "nb" ? "nb-NO" : "en" },
})).status()).toBe(204);
const openRules = async () => {
if (width === 390) {
await page.getByRole("combobox", { name: t.settingsNavigation }).press("Enter");
await page.getByRole("option", { name: t.settingsTabFollowUps, exact: true }).press("Enter");
} else {
await page.getByRole("tab", { name: t.settingsTabFollowUps, exact: true }).click();
}
};
const readPause = async () => (await (await page.request.get(rulesUrl, { headers })).json()).automaticGhostingPaused;
await page.goto("/settings");
await openRules();
const pause = page.getByRole("switch", { name: t.rulesPauseAutomaticGhosting, exact: true });
await expect(pause).not.toBeChecked();
await expect(pause).toHaveAccessibleDescription(t.rulesPauseAutomaticGhostingHelp);
await pause.press("Space");
await expect(pause).toBeChecked();
await expect(pause).toBeFocused();
await page.route(rulesUrl, route => route.fulfill({ status: 503, json: {} }), { times: 1 });
const save = page.getByRole("button", { name: t.rulesSave, exact: true });
await save.click();
await expect(page.getByRole("tabpanel", { name: t.settingsTabFollowUps }).getByRole("alert")).toHaveText(t.rulesSaveFailed);
expect(await readPause()).toBe(false);
await expect(pause).toBeChecked();
const saved = page.waitForResponse(response => response.url() === rulesUrl && response.request().method() === "PUT");
await save.click();
expect((await saved).status()).toBe(204);
expect(await readPause()).toBe(true);
await page.reload();
await openRules();
await expect(pause).toBeChecked();
await scan(page, info, `ghosted-pause-${language}`);
await reflow(page, info, `ghosted-pause-${language}`);
await capture(page, info, `ghosted-pause-${language}`);
});
}
for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb"] as const) {
test(`[PRES-E07 E08 E09 S03 S04 S05 J05 J10 M06 W11] ${mode}/${language} Settings headings, reflow and retained actions`, async ({ page, headers }, info) => {
test.setTimeout(180_000);
@@ -91,7 +139,7 @@ for (const mode of ["light", "dark"] as const) for (const language of ["en", "nb
await capture(page, info, `long-heading-${suffix}`);
const chooseSection = async (name: string) => {
if (page.viewportSize()!.width < 768) {
if (page.viewportSize()!.width < 1024) {
const selector = main.getByRole("combobox", { name: t.settingsNavigation, exact: true });
await selector.focus();
await selector.press("Enter");
@@ -1,6 +1,6 @@
import React from "react";
import { Alert, Box, Button, TextField, Typography } from "@mui/material";
import { Alert, Box, Button, FormControlLabel, FormHelperText, Switch, TextField, Typography } from "@mui/material";
import { PageSection } from "../layout/PageLayout";
import { useI18n } from "../i18n/I18nProvider";
@@ -13,11 +13,12 @@ export type RuleSettings = {
offerGhostDays: number;
feedbackFollowUpDays: number;
feedbackGhostDays: number;
automaticGhostingPaused?: boolean;
};
export const RULE_FIELDS = ["appliedFollowUpDays", "appliedGhostDays", "offerFollowUpDays", "offerGhostDays", "feedbackFollowUpDays", "feedbackGhostDays"] as const;
export type RuleField = typeof RULE_FIELDS[number];
export type RuleDraft = Record<RuleField, string>;
export type RuleDraft = Record<RuleField, string> & Pick<RuleSettings, "automaticGhostingPaused">;
type Props = {
draft: RuleDraft | null;
@@ -27,13 +28,15 @@ type Props = {
saving: boolean;
dirty: boolean;
onChange: (field: RuleField, value: string) => void;
onPauseChange: (paused: boolean) => void;
onSave: () => void;
onDiscard: () => void;
onRetry: () => void;
};
export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onSave, onDiscard, onRetry }: Props) {
export default function RulesSettingsCard({ draft, loadError, saveError, invalid, saving, dirty, onChange, onPauseChange, onSave, onDiscard, onRetry }: Props) {
const { t } = useI18n();
const pauseDescription = React.useId();
if (!draft) {
return (
<PageSection title={t("rulesTitle")}>
@@ -64,6 +67,14 @@ export default function RulesSettingsCard({ draft, loadError, saveError, invalid
<TextField label={t("rulesFeedbackFollowUpDays")} {...num("feedbackFollowUpDays")} />
<TextField label={t("rulesFeedbackGhostDays")} {...num("feedbackGhostDays")} />
</Box>
{typeof draft.automaticGhostingPaused === "boolean" && (
<Box sx={{ mt: 2 }}>
<FormControlLabel label={t("rulesPauseAutomaticGhosting")}
control={<Switch checked={draft.automaticGhostingPaused} onChange={(_, paused) => onPauseChange(paused)}
slotProps={{ input: { role: "switch", "aria-describedby": pauseDescription } }} />} />
<FormHelperText id={pauseDescription}>{t("rulesPauseAutomaticGhostingHelp")}</FormHelperText>
</Box>
)}
<Box sx={{ display: "flex", justifyContent: "flex-end", flexWrap: "wrap", gap: 1, mt: 2 }}>
<Button onClick={onDiscard} disabled={!dirty || saving}>{t("assetsDiscardChanges")}</Button>
+18 -7
View File
@@ -54,7 +54,10 @@ type NotificationPrefs = {
};
function ruleDraft(settings: RuleSettings): RuleDraft {
return Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])) as RuleDraft;
return {
...Object.fromEntries(RULE_FIELDS.map(field => [field, String(settings[field])])),
automaticGhostingPaused: settings.automaticGhostingPaused,
} as RuleDraft;
}
export default function SettingsView({
@@ -88,7 +91,10 @@ export default function SettingsView({
const aiControls = useRef<HTMLDivElement>(null);
const notificationRetryFocus = useRef<HTMLElement | null>(null);
const currentTranslation = useRef(t);
const rulesDirty = Boolean(rulesDraft && savedRules && RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field])));
const rulesDirty = Boolean(rulesDraft && savedRules && (
rulesDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused ||
RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field]))
));
const notificationsDirty = Boolean(notificationPrefs && savedNotificationPrefs && notificationPrefs.emailFollowUpRemindersEnabled !== savedNotificationPrefs.emailFollowUpRemindersEnabled);
useEffect(() => { currentTranslation.current = t; }, [t]);
@@ -139,11 +145,15 @@ export default function SettingsView({
setSavingRules(true);
setRulesSaveError(false);
try {
await api.put("/rules", submitted);
const pauseChanged = submittedDraft.automaticGhostingPaused !== savedRules.automaticGhostingPaused;
await api.put("/rules", pauseChanged ? { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused } : submitted);
if (!session.mounted) return;
setSavedRules(submitted);
const accepted = { ...submitted, automaticGhostingPaused: submittedDraft.automaticGhostingPaused };
setSavedRules(accepted);
// A completed save acknowledges its snapshot, not edits made while it was pending.
setRulesDraft(current => current && RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(submitted) : current);
setRulesDraft(current => current &&
current.automaticGhostingPaused === submittedDraft.automaticGhostingPaused &&
RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(accepted) : current);
toast(currentTranslation.current("rulesSaved"), "success");
} catch {
if (session.mounted) setRulesSaveError(true);
@@ -260,7 +270,7 @@ export default function SettingsView({
return (
<Box sx={{ minWidth: 0 }}>
<FormControl fullWidth sx={{ display: { xs: "flex", sm: "none" }, mb: 1 }}>
<FormControl fullWidth sx={{ display: { xs: "flex", md: "none" }, mb: 1 }}>
<InputLabel id="settings-section-label">{t("settingsNavigation")}</InputLabel>
<Select
labelId="settings-section-label"
@@ -276,7 +286,7 @@ export default function SettingsView({
</Select>
</FormControl>
<Tabs aria-label={t("settings")} value={tab} onChange={(_, v) => selectSection(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", sm: "flex" }, mb: 1 }}>
<Tabs aria-label={t("settings")} value={tab} onChange={(_, v) => selectSection(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", md: "flex" }, mb: 1 }}>
<Tab value={0} id="settings-tab-0" aria-controls="settings-panel-0" label={t("settingsTabGeneral")} />
<Tab value={4} id="settings-tab-4" aria-controls="settings-panel-4" label={t("settingsTabAutomation")} />
<Tab value={1} id="settings-tab-1" aria-controls="settings-panel-1" label={t("settingsTabFollowUps")} />
@@ -379,6 +389,7 @@ export default function SettingsView({
<TabPanel value={tab} index={1} label={t("settingsTabFollowUps")}>
<RulesSettingsCard draft={rulesDraft} loadError={rulesLoadError ? getApiErrorMessage(rulesLoadError.cause, t("rulesLoadFailed")) : null} saveError={rulesSaveError} invalid={invalidRules}
saving={savingRules} dirty={rulesDirty} onSave={() => void saveRules()} onRetry={() => void loadRules()} onDiscard={discardRules}
onPauseChange={paused => setRulesDraft(current => current ? { ...current, automaticGhostingPaused: paused } : current)}
onChange={(field, value) => {
setRulesDraft(current => current ? { ...current, [field]: value } : current);
setInvalidRules(current => current.filter(key => key !== field));
+4
View File
@@ -3105,6 +3105,8 @@ export const translations = {
jobDetailsNothingHighlighted: "Nothing highlighted yet.",
rulesTitle: "Follow-up rules by scenario",
rulesBody: "Set how long to wait before a follow-up is due and when a thread should be treated as ghosted.",
rulesPauseAutomaticGhosting: "Pause automatic Ghosted updates",
rulesPauseAutomaticGhostingHelp: "Applies from the next rules run. Follow-up reminders and manual status changes stay available.",
rulesLoading: "Loading your follow-up settings…",
rulesLoadFailed: "Could not load your follow-up settings.",
rulesAppliedFollowUpDays: "Applied: follow-up days",
@@ -6353,6 +6355,8 @@ export const translations = {
jobDetailsNothingHighlighted: "Ingenting fremhevet ennå.",
rulesTitle: "Oppfølgingsregler per scenario",
rulesBody: "Velg hvor lenge du vil vente før oppfølging forfaller, og når en tråd skal regnes som ghostet.",
rulesPauseAutomaticGhosting: "Sett automatiske Ghostet-oppdateringer på pause",
rulesPauseAutomaticGhostingHelp: "Gjelder fra neste regelkjøring. Oppfølgingspåminnelser og manuelle statusendringer er fortsatt tilgjengelige.",
rulesLoading: "Laster inn oppfølgingsinnstillingene dine…",
rulesLoadFailed: "Kunne ikke laste oppfølgingsinnstillingene dine.",
rulesAppliedFollowUpDays: "Søkt: oppfølgingsdager",
+26
View File
@@ -4,6 +4,7 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librar
import { MemoryRouter } from 'react-router-dom';
import SettingsView from './components/SettingsView';
import type { RuleSettings } from './components/RulesSettingsCard';
import { I18nProvider } from './i18n/I18nProvider';
import { ToastProvider } from './toast';
import { api } from './api';
@@ -245,6 +246,31 @@ test('[PRES-S03] failed Rules save remains actionable after tab return and expli
expect(screen.queryByText('Failed to save rules.')).not.toBeInTheDocument();
});
test('the supported Ghosted pause retains its draft after failure and persists only after an explicit retry', async () => {
const ordinaryGet = mockedApi.get.getMockImplementation()!;
mockedApi.get.mockImplementation(async (url, options) => {
const response = await ordinaryGet(url, options);
if (url !== '/rules') return response;
const { data } = response as { data: RuleSettings };
return { data: { ...data, automaticGhostingPaused: false } };
});
renderView();
await openRules();
const pause = () => screen.getByRole('switch', { name: translations.en.rulesPauseAutomaticGhosting });
expect(pause()).not.toBeChecked();
fireEvent.click(pause());
mockedApi.put.mockRejectedValueOnce(new Error('offline'));
const save = () => screen.getByRole('button', { name: /save rules/i });
fireEvent.click(save());
expect(await screen.findByRole('alert')).toHaveTextContent(translations.en.rulesSaveFailed);
rulesRoundTrip();
expect(pause()).toBeChecked();
fireEvent.click(save());
await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
expect(mockedApi.put).toHaveBeenLastCalledWith('/rules', expect.objectContaining({ automaticGhostingPaused: true }));
expect(pause()).toBeChecked();
});
test('[PRES-S03] invalid and empty Rules input and associated validation survive internal navigation', async () => {
renderView();
fireEvent.change(await openRules(), { target: { value: '' } });