diff --git a/.github/workflows/nitro-cli-e2e.yml b/.github/workflows/nitro-cli-e2e.yml index 5d26a48f89d..97fdd002b9c 100644 --- a/.github/workflows/nitro-cli-e2e.yml +++ b/.github/workflows/nitro-cli-e2e.yml @@ -87,6 +87,67 @@ jobs: "$nitro_bin" agent tasks show "$task_id" + # Widen the smoke past task CRUD: mail, memory and the agent + # registry each fall back to reflection Dapper when a call isn't + # AOT-interceptable, so exercise every store here too. + if ! "$nitro_bin" agent register --actor "$actor" --role planner; then + echo "::error::agent register --actor \"$actor\" --role planner failed." >&2 + exit 1 + fi + + if ! list_output="$("$nitro_bin" agent list --output json)"; then + echo "::error::agent list --output json failed." >&2 + exit 1 + fi + echo "$list_output" + if ! printf '%s' "$list_output" | tr -d '\n' | grep -Eq \ + "\"name\"[[:space:]]*:[[:space:]]*\"$actor\"[^}]*\"online\"[[:space:]]*:[[:space:]]*(true|false)"; then + echo "::error::agent list --output json did not report actor \"$actor\" with an online flag." >&2 + exit 1 + fi + + if ! "$nitro_bin" agent mail send --to "$actor" --actor "$actor" \ + --subject "AOT smoke" --body "hello"; then + echo "::error::agent mail send --to \"$actor\" --actor \"$actor\" --subject \"AOT smoke\" --body \"hello\" failed." >&2 + exit 1 + fi + + if ! inbox_output="$("$nitro_bin" agent mail inbox --actor "$actor" --output json)"; then + echo "::error::agent mail inbox --actor \"$actor\" --output json failed." >&2 + exit 1 + fi + echo "$inbox_output" + message_count="$(printf '%s' "$inbox_output" | grep -c '"id"' || true)" + if [ "$message_count" -ne 1 ]; then + echo "::error::agent mail inbox --actor \"$actor\" --output json did not report exactly one message." >&2 + exit 1 + fi + + if ! "$nitro_bin" agent memory save "AOT smoke memory" --type fact --actor "$actor"; then + echo "::error::agent memory save \"AOT smoke memory\" --type fact --actor \"$actor\" failed." >&2 + exit 1 + fi + + if ! "$nitro_bin" agent memory context; then + echo "::error::agent memory context failed." >&2 + exit 1 + fi + + if ! search_output="$("$nitro_bin" agent memory search "smoke" --output json)"; then + echo "::error::agent memory search \"smoke\" --output json failed." >&2 + exit 1 + fi + echo "$search_output" + if ! printf '%s' "$search_output" | grep -q '"id"'; then + echo "::error::agent memory search \"smoke\" --output json did not report any memories." >&2 + exit 1 + fi + + if ! "$nitro_bin" agent tasks close "$task_id" --actor "$actor" --reason "smoke"; then + echo "::error::agent tasks close \"$task_id\" --actor \"$actor\" --reason \"smoke\" failed." >&2 + exit 1 + fi + record-and-verify: runs-on: ubuntu-latest steps: diff --git a/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs b/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs index 83efa01e0d8..64663e42116 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs @@ -11,15 +11,20 @@ public class DeferTests public async Task VariableBatch_Defer_Should_Deliver_Payloads_Per_Item_When_Executed() { // arrange - // the timeout turns a lost-coordinator hang into a test failure instead of a block. - var executor = await DeferAndStreamTestSchema.CreateAsync(); + // a per-item gate makes the deferred split deterministic instead of racing wall-clock delays + var nameGates = new Dictionary + { + ["1"] = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), + ["2"] = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) + }; + var executor = await CreateGatedDeferExecutorAsync(nameGates); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); var request = OperationRequestBuilder .New() .SetDocument( """ - query ($id: ID!) { + query ($id: Int!) { person(id: $id) { id ... @defer { @@ -31,38 +36,61 @@ ... @defer { .SetVariableValues( new List> { - new Dictionary { ["id"] = "UGVyc29uOjE=" }, - new Dictionary { ["id"] = "UGVyc29uOjI=" } + new Dictionary { ["id"] = 1 }, + new Dictionary { ["id"] = 2 } }) .Build(); // act await using var result = await executor.ExecuteAsync(request, cts.Token); - - var summaries = new List(); - foreach (var item in result.ExpectOperationResultBatch().Results) - { - summaries.Add(await SummarizeStreamAsync(item.ExpectResponseStream(), cts.Token)); - } + var summaries = await SummarizeAllItemsConcurrentlyAsync(result, nameGates, cts.Token); // assert summaries.MatchInlineSnapshots( [ - "person.id=UGVyc29uOjE=; name=Pascal; hasNext=True,False", - "person.id=UGVyc29uOjI=; name=Rafi; hasNext=True,False" + "person.id=1; name=Pascal; hasNext=True,False", + "person.id=2; name=Rafi; hasNext=True,False" ]); } + private static ValueTask CreateGatedDeferExecutorAsync( + IReadOnlyDictionary nameGates) + => new ServiceCollection() + .AddSingleton(nameGates) + .AddGraphQL() + .AddQueryType() + .ModifyOptions( + o => + { + o.EnableDefer = true; + o.EnableStream = true; + }) + .BuildRequestExecutorAsync(); + + // Item 0's stream only settles once every item's deferred branch has completed, so the items + // are summarized concurrently: summarizing one to completion before starting the next would + // leave its gate unset and deadlock the batch. + private static Task SummarizeAllItemsConcurrentlyAsync( + IExecutionResult result, + IReadOnlyDictionary nameGates, + CancellationToken cancellationToken) + => Task.WhenAll( + result.ExpectOperationResultBatch().Results + .Select(item => SummarizeGatedStreamAsync(item.ExpectResponseStream(), nameGates, cancellationToken))); + // Reads a single item's response stream to completion and projects it to a delivery-shape - // summary that pins the initial data, the deferred data, and the per-payload hasNext sequence - // without depending on the non-deterministic branch identifiers in the incremental envelope. - private static async Task SummarizeStreamAsync( + // summary that pins the initial data, the deferred data, and the per-payload hasNext sequence. + // The corresponding name gate is released only once the initial payload has been observed, so + // the deferred resolver cannot complete before the split it is meant to produce. + private static async Task SummarizeGatedStreamAsync( ResponseStream stream, + IReadOnlyDictionary nameGates, CancellationToken cancellationToken) { string? personId = null; string? name = null; var hasNext = new List(); + var initialPayloadObserved = false; await foreach (var payload in stream.ReadResultsAsync().WithCancellation(cancellationToken)) { @@ -72,12 +100,19 @@ private static async Task SummarizeStreamAsync( hasNext.Add(root.TryGetProperty("hasNext", out var hasNextValue) && hasNextValue.GetBoolean()); - if (root.TryGetProperty("data", out var data) + if (!initialPayloadObserved + && root.TryGetProperty("data", out var data) && data.ValueKind is JsonValueKind.Object && data.TryGetProperty("person", out var person) && person.TryGetProperty("id", out var id)) { - personId = id.GetString(); + personId = id.GetRawText(); + initialPayloadObserved = true; + + if (nameGates.TryGetValue(personId, out var gate)) + { + gate.TrySetResult(); + } } // The deferred name must arrive inside an incremental entry's data (the deferred @@ -516,3 +551,28 @@ public override ValueTask OnCreateAsync( } } } + +// A defer schema whose deferred field blocks on a per-item gate instead of a wall-clock delay, so +// tests can pin exactly when a deferred branch is allowed to complete. +internal static class GatedDeferTestSchema +{ + public class Query + { + private static readonly Dictionary s_names = new() { [1] = "Pascal", [2] = "Rafi" }; + + public Person GetPerson(int id) => new(id, s_names[id]); + } + + public class Person(int id, string name) + { + public int Id { get; } = id; + + public async Task GetNameAsync( + [Service] IReadOnlyDictionary nameGates, + CancellationToken cancellationToken) + { + await nameGates[Id.ToString()].Task.WaitAsync(cancellationToken); + return name; + } + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentCommand.cs index 555a1a9709d..1d0242d6e9d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentCommand.cs @@ -57,9 +57,7 @@ private static async Task ExecuteAsync( { var mailStore = services.GetRequiredService(); var memoryStore = services.GetRequiredService(); - var agentRegistry = services.GetRequiredService(); - var agentSessionRegistry = services.GetRequiredService(); - var activityReader = services.GetRequiredService(); + var agentStore = services.GetRequiredService(); var timeProvider = services.GetRequiredService(); var mailWakeDaemonCoordinator = services.GetRequiredService(); @@ -68,9 +66,7 @@ private static async Task ExecuteAsync( taskStore, mailStore, memoryStore, - agentRegistry, - agentSessionRegistry, - activityReader, + agentStore, timeProvider, workspaceDirectory, mailWakeDaemonCoordinator, diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentTuiLauncher.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentTuiLauncher.cs index 6141dc62639..f7a30b0d08f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentTuiLauncher.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/AgentTuiLauncher.cs @@ -21,8 +21,6 @@ namespace ChilliCream.Nitro.CommandLine.Commands.Agent; /// internal static class AgentTuiLauncher { - private static readonly TimeSpan s_pendingSendShutdownTimeout = TimeSpan.FromSeconds(2); - /// /// Runs the TUI and owns its mail wake daemon. The board is an /// observer: it takes no actor and refuses every write. @@ -32,15 +30,13 @@ public static Task RunAsync( ITaskStore taskStore, IMailStore mailStore, IMemoryStore memoryStore, - IAgentRegistry agentRegistry, - IAgentSessionRegistry agentSessionRegistry, - IClaudeSessionActivityReader activityReader, + IAgentStore agentStore, TimeProvider timeProvider, string workspaceDirectory, IMailWakeDaemonCoordinator mailWakeDaemonCoordinator, CancellationToken cancellationToken) => RunShellAsync( - console, taskStore, mailStore, memoryStore, agentRegistry, agentSessionRegistry, activityReader, + console, taskStore, mailStore, memoryStore, agentStore, timeProvider, workspaceDirectory, mailWakeDaemonCoordinator, cancellationToken); private static async Task RunShellAsync( @@ -48,9 +44,7 @@ private static async Task RunShellAsync( ITaskStore taskStore, IMailStore mailStore, IMemoryStore memoryStore, - IAgentRegistry agentRegistry, - IAgentSessionRegistry agentSessionRegistry, - IClaudeSessionActivityReader activityReader, + IAgentStore agentStore, TimeProvider timeProvider, string workspaceDirectory, IMailWakeDaemonCoordinator mailWakeDaemonCoordinator, @@ -59,53 +53,31 @@ private static async Task RunShellAsync( var searchMode = new SearchMode(taskStore); var treeView = new DependencyTreeView(taskStore, rootId: ""); - // Pass the host shutdown token to the event loop and Mail tab. using var quitCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var tabs = BuildTabs( - taskStore, - mailStore, - memoryStore, - agentRegistry, - agentSessionRegistry, - activityReader, - timeProvider, - quitCts.Token); - - // An unavailable Mail tab has no send effects to drain on exit. - var mailMode = tabs.Select(t => t.RootMode).OfType().FirstOrDefault(); + var tabs = BuildTabs(taskStore, mailStore, memoryStore, agentStore, timeProvider); var shell = new TuiShell( tabs, console.Profile.Width, console.Profile.Height, + agentStore: agentStore, tasksTabIndex: 0, - searchMode, - treeView, - taskStore, + searchMode: searchMode, + treeView: treeView, + store: taskStore, actor: null, - mailWakeDaemonState: () => mailWakeDaemonCoordinator.Status.State, - quitGates: mailMode is null ? null : [mailMode.CreateQuitGate()]); + mailWakeDaemonState: () => mailWakeDaemonCoordinator.Status.State); var application = new TuiApplication(console); var dbWatcher = new SqliteDbWatcher(AgentWorkspace.GetDatabasePath(workspaceDirectory)); shell.QuitConfirmed += quitCts.Cancel; - if (mailMode is not null) - { - shell.QuitCancelled += mailMode.ResumeSendAcceptance; - } - // Start only after the shell is ready to report daemon status. await mailWakeDaemonCoordinator.StartAsync(cancellationToken); var eventSources = new List { dbWatcher.RunAsync }; - if (mailMode is not null) - { - eventSources.Add(mailMode.RunSendEffectEventsAsync); - } - try { await application.RunAsync(shell.Handle, shell.Render, quitCts.Token, eventSources); @@ -114,13 +86,6 @@ private static async Task RunShellAsync( { // Stop background delivery even when the event loop fails. await mailWakeDaemonCoordinator.StopAsync(CancellationToken.None); - - // Ctrl+C bypasses the quit gate. Give a started store write a - // brief chance to commit before the process exits. - if (mailMode is not null) - { - await mailMode.ShieldPendingSendsAsync(s_pendingSendShutdownTimeout, CancellationToken.None); - } } return ExitCodes.Success; @@ -134,21 +99,16 @@ internal static TuiTab[] BuildTabs( ITaskStore taskStore, IMailStore mailStore, IMemoryStore memoryStore, - IAgentRegistry agentRegistry, - IAgentSessionRegistry agentSessionRegistry, - IClaudeSessionActivityReader activityReader, - TimeProvider timeProvider, - CancellationToken effectCancellationToken = default) + IAgentStore agentStore, + TimeProvider timeProvider) { var loader = new BoardDataLoader(taskStore, timeProvider); var boardMode = new BoardMode(loader); var tasksTab = new TuiTab("Tasks", mnemonic: 'T', boardMode, new KeyDispatcher(KeyMap.CreateDefaultGlobal())); - var mailTab = BuildMailTab( - mailStore, agentRegistry, timeProvider, - effectCancellationToken); + var mailTab = BuildMailTab(mailStore, agentStore, timeProvider); - var agentsMode = new AgentsMode(taskStore, mailStore, agentSessionRegistry, activityReader, timeProvider); + var agentsMode = new AgentsMode(agentStore, mailStore, taskStore, memoryStore, timeProvider); var agentsTab = new TuiTab("Agents", mnemonic: 'A', agentsMode, new KeyDispatcher(KeyMap.CreateDefaultGlobal())); var memoryMode = new MemoryMode(memoryStore, timeProvider); @@ -158,24 +118,18 @@ internal static TuiTab[] BuildTabs( } /// - /// Builds the Mail tab without an acting identity, showing the workspace-wide - /// mailbox and refusing writes. + /// Builds the Mail tab: a read-only table of every workspace thread. The board has no + /// acting agent, so the tab title never carries an unread count. /// internal static TuiTab BuildMailTab( IMailStore mailStore, - IAgentRegistry agentRegistry, - TimeProvider timeProvider, - CancellationToken effectCancellationToken = default) + IAgentStore agentStore, + TimeProvider timeProvider) { - var mailMode = new MailMode( - mailStore, - actor: null, - agentRegistry, - timeProvider, - effectCancellationToken); + var mailMode = new MailMode(mailStore, agentStore, timeProvider); return new TuiTab( - () => mailMode.UnreadCount > 0 ? $"Mail ({mailMode.UnreadCount})" : "Mail", + "Mail", mnemonic: 'M', mailMode, new KeyDispatcher(MailKeyMap.CreateDefault())); diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/ClaudeHookCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/ClaudeHookCommand.cs index 9ea0813d845..96ead63835a 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/ClaudeHookCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/ClaudeHookCommand.cs @@ -9,6 +9,7 @@ public ClaudeHookCommand() : base("claude") Subcommands.Add(new SessionStartHookCommand()); Subcommands.Add(new UserPromptSubmitHookCommand()); Subcommands.Add(new StopHookCommand()); + Subcommands.Add(new NotificationHookCommand()); Subcommands.Add(new SessionEndHookCommand()); } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/NotificationHookCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/NotificationHookCommand.cs new file mode 100644 index 00000000000..b41f38692a7 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/NotificationHookCommand.cs @@ -0,0 +1,18 @@ +namespace ChilliCream.Nitro.CommandLine.Commands.Agent.Hook.Claude; + +/// +/// Adapts Claude Code's Notification hook: touches the session's last-seen +/// time on an idle-prompt notification. Payload JSON on stdin, {} on stdout, +/// always. +/// +internal sealed class NotificationHookCommand : Command +{ + public NotificationHookCommand() : base("notification") + { + Description = "Adapt Claude Code's Notification hook: touch last-seen on an idle-prompt notification."; + + this.SetHookAction( + "Notification", + (handler, payload, ct) => handler.HandleNotificationAsync(payload, skipSessionFileLookup: false, ct)); + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/SessionEndHookCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/SessionEndHookCommand.cs index 4d2c468596f..a56088ef938 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/SessionEndHookCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Claude/SessionEndHookCommand.cs @@ -1,15 +1,14 @@ namespace ChilliCream.Nitro.CommandLine.Commands.Agent.Hook.Claude; /// -/// Adapts Claude Code's SessionEnd hook: conditionally deletes this -/// session's presence row. Payload JSON on stdin, {} on stdout, -/// always. +/// Adapts Claude Code's SessionEnd hook: marks this session's agent +/// row as ended. Payload JSON on stdin, {} on stdout, always. /// internal sealed class SessionEndHookCommand : Command { public SessionEndHookCommand() : base("session-end") { - Description = "Adapt Claude Code's SessionEnd hook: delete this session's presence row."; + Description = "Adapt Claude Code's SessionEnd hook: mark this session's agent row as ended."; this.SetHookAction( "SessionEnd", diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Codex/SessionEndHookCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Codex/SessionEndHookCommand.cs index 115cffa47d1..444f0d2387d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Codex/SessionEndHookCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hook/Codex/SessionEndHookCommand.cs @@ -1,15 +1,15 @@ namespace ChilliCream.Nitro.CommandLine.Commands.Agent.Hook.Codex; /// -/// Adapts Codex CLI's SessionEnd hooks.json event: conditionally -/// deletes this session's presence row. Payload JSON on stdin, {} on +/// Adapts Codex CLI's SessionEnd hooks.json event: marks this +/// session's agent row as ended. Payload JSON on stdin, {} on /// stdout, always. /// internal sealed class SessionEndHookCommand : Command { public SessionEndHookCommand() : base("session-end") { - Description = "Adapt Codex CLI's SessionEnd hook: delete this session's presence row."; + Description = "Adapt Codex CLI's SessionEnd hook: mark this session's agent row as ended."; this.SetCodexHookAction( "SessionEnd", diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hooks/Opencode/StatusOpencodeHooksCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hooks/Opencode/StatusOpencodeHooksCommand.cs index 42b32a7293d..0396e70bfeb 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hooks/Opencode/StatusOpencodeHooksCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Hooks/Opencode/StatusOpencodeHooksCommand.cs @@ -65,9 +65,9 @@ private static async Task ExecuteAsync( } /// - /// Returns Opencode participants from this Nitro instance with their registered - /// endpoint and last recorded ping diagnostics. Returns an empty list when no - /// workspace exists. + /// Returns opencode agents in this workspace with their registered endpoint and last + /// recorded ping diagnostics. Ended and offline agents are omitted. Returns an empty + /// list when no workspace exists. /// private static async Task> ResolveOpencodeSessionsAsync( ICommandServices services, CancellationToken cancellationToken) @@ -79,12 +79,15 @@ private static async Task> ResolveOpencodeS return []; } - var sessionRegistry = services.GetRequiredService(); - var participants = await sessionRegistry.ListParticipantsAsync(cancellationToken); + var agentStore = services.GetRequiredService(); + var timeProvider = services.GetRequiredService(); + var now = timeProvider.GetUtcNow(); + var rows = await agentStore.ListAsync(cancellationToken); - return participants - .Where(participant => participant.Session.Harness == AgentSessionHarness.Opencode - && participant.State != AgentSessionState.Remote) + return rows + .Where(row => row.Harness == AgentSessionHarness.Opencode) + .Where(row => AgentStateResolver.Resolve(row, now) != AgentState.Offline) + .OrderBy(row => row.SessionId, StringComparer.Ordinal) .Select(OpencodeSessionStatus.From) .ToArray(); } @@ -106,35 +109,29 @@ public sealed record OpencodeHooksStatusResult( /// public sealed record OpencodeSessionStatus( string SessionId, - string? Actor, + string Actor, string EndpointKind, string EndpointAddress, string Reachability, string? LastPingResult, string? LastPingDetail) { - public static OpencodeSessionStatus From(AgentSessionParticipant participant) - { - var session = participant.Session; - - return new OpencodeSessionStatus( - session.SessionId, - session.AgentName, - session.EndpointKind, - session.EndpointAddr, - ComputeReachability(session), - session.LastPingResult, - session.LastPingDetail); - } + public static OpencodeSessionStatus From(AgentRow row) => new( + row.SessionId!, + row.Name, + row.EndpointKind, + row.EndpointAddr, + ComputeReachability(row), + row.LastPingResult, + row.LastPingDetail); public string FormatLine() { - var actor = Actor is { Length: > 0 } name ? name : "unbound"; var endpoint = EndpointKind == AgentSessionEndpointKind.None ? "no endpoint registered" : $"{EndpointKind} {EndpointAddress}".EscapeMarkup(); - return $" session {SessionId.EscapeMarkup()} (actor {actor.EscapeMarkup()}): " + return $" session {SessionId.EscapeMarkup()} (actor {Actor.EscapeMarkup()}): " + $"{endpoint}; {Reachability}; {DescribeLastPing()}"; } @@ -166,14 +163,14 @@ private string DescribeLastPing() /// is registered, otherwise classifies the last recorded ping result. /// Performs no live network probe. /// - private static string ComputeReachability(AgentSessionRecord session) + private static string ComputeReachability(AgentRow row) { - if (session.EndpointKind == AgentSessionEndpointKind.None) + if (row.EndpointKind == AgentSessionEndpointKind.None) { return OpencodeSessionReachability.NoEndpoint; } - return session.LastPingResult switch + return row.LastPingResult switch { AgentPingResult.Ok => OpencodeSessionReachability.ReachableAtLastPing, AgentPingResult.EndpointGone => OpencodeSessionReachability.EndpointGoneAtLastPing, diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/InitAgentCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/InitAgentCommand.cs index 467b818917b..012bf3ce68f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/InitAgentCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/InitAgentCommand.cs @@ -408,7 +408,7 @@ private static async Task UpdateSessionWorkspacePathsAsync( await connection.OpenAsync(cancellationToken); await connection.ExecuteAsync( - "UPDATE agent_sessions SET workspace_path = @workspacePath " + "UPDATE agents SET workspace_path = @workspacePath " + "WHERE workspace_path = @previousWorkspacePath;", new { diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/ListAgentCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/ListAgentCommand.cs index aca5dff75d0..c438905e438 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/ListAgentCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/ListAgentCommand.cs @@ -1,7 +1,7 @@ +using System.Globalization; using ChilliCream.Nitro.CommandLine.Commands.Agent.Options; using ChilliCream.Nitro.CommandLine.Helpers; using ChilliCream.Nitro.CommandLine.Results; -using ChilliCream.Nitro.CommandLine.Services.Tasks; using ChilliCream.Nitro.CommandLine.Services.Workspace; namespace ChilliCream.Nitro.CommandLine.Commands.Agent; @@ -10,7 +10,7 @@ internal sealed class ListAgentCommand : Command { public ListAgentCommand() : base("list") { - Description = "List the actors this workspace knows, with their session when they have one."; + Description = "Lists the agents in the workspace."; Options.Add(Opt.Instance); Options.Add(Opt.Instance); @@ -26,19 +26,14 @@ private static async Task ExecuteAsync( CancellationToken cancellationToken) { var console = services.GetRequiredService(); - var sessionRegistry = services.GetRequiredService(); + var agents = services.GetRequiredService(); + var timeProvider = services.GetRequiredService(); var resultHolder = services.GetRequiredService(); var role = parseResult.GetValue(Opt.Instance); + var now = timeProvider.GetUtcNow(); - // Actors are the unit: an actor allocated by `agent login` has no - // session until a hook binds one, and must still be listed. - var agents = services.GetRequiredService(); - var identities = await sessionRegistry.ListIdentitiesAsync(cancellationToken); - var byActor = identities.ToDictionary(view => view.Identity.Actor, StringComparer.Ordinal); - var rows = (await agents.ListAsync(role: null, staleBefore: null, cancellationToken)) - .Select(agent => new AgentListRow(agent, byActor.GetValueOrDefault(agent.Name))) - .ToArray(); + var rows = await agents.ListAsync(cancellationToken); if (role is not null) { @@ -46,86 +41,121 @@ private static async Task ExecuteAsync( rows = rows.Where(row => row.Role == normalizedRole).ToArray(); } + var ordered = Order(rows, now); + if (!console.IsHumanReadable) { - resultHolder.SetResult(new ListResult(rows.Select(ToRow).ToArray())); + resultHolder.SetResult( + new ListResult(ordered.Select(row => ToRow(row, now)).ToArray())); + return ExitCodes.Success; } - if (rows.Length == 0) + if (ordered.Count == 0) { console.WriteLine("No actors."); return ExitCodes.Success; } - foreach (var row in rows) + var lines = ordered.Select(row => AgentListLine.From(row, now)).ToArray(); + var widths = ColumnWidths.Compute(lines); + + foreach (var line in lines) { - console.WriteLine(FormatLine(row)); + console.WriteLine(line.Format(widths)); } return ExitCodes.Success; } /// - /// Renders one durable session identity: actor, online/offline state, - /// harness, optional role, and last-seen time. Connection diagnostics - /// remain available in machine output when the session is online. + /// Orders rows the way the board does: online agents first, then idle, then unreachable, + /// then offline, with ties broken by the most recently seen window and then by name. /// - private static string FormatLine(AgentListRow row) - { - var session = row.View?.Participant?.Session; - var versionSuffix = session?.HarnessVersion.Length > 0 ? $" {session.HarnessVersion}" : ""; - var roleSuffix = row.Role.Length > 0 ? $" role {row.Role}" : ""; - var harness = row.View?.Identity.Harness ?? "no session"; + private static IReadOnlyList Order(IReadOnlyList rows, DateTimeOffset now) + => rows + .OrderBy(row => (int)AgentStateResolver.Resolve(row, now)) + .ThenByDescending(row => AgentStateResolver.LastSeenWindowStart(row.LastSeenAt)) + .ThenBy(row => row.Name, StringComparer.Ordinal) + .ToArray(); - return $"{row.Actor} {row.State} {harness}{versionSuffix}{roleSuffix}" - + $" last heard {TaskDates.Format(row.LastSeenAt)}"; - } + private static AgentListRowResult ToRow(AgentRow row, DateTimeOffset now) => new( + row.Name, + row.Role, + row.Harness, + row.StartedAt, + row.LastSeenAt, + AgentStateResolver.Resolve(row, now) == AgentState.Online); /// - /// One actor, with the durable session identity bound to it when a hook - /// has bound one. + /// Formats the elapsed time between and + /// as a short relative age: "now" under a minute, then minutes, hours, or days, falling + /// back to an ISO date once the value is a week or older. A non-positive elapsed time + /// (a clock-skewed future timestamp) also formats as "now". /// - private sealed record AgentListRow(AgentRecord Agent, AgentSessionIdentityView? View) + private static string FormatAge(DateTimeOffset value, DateTimeOffset now) { - public string Actor => Agent.Name; + var elapsed = now - value; + + if (elapsed < TimeSpan.FromMinutes(1)) + { + return "now"; + } + + if (elapsed < TimeSpan.FromHours(1)) + { + return $"{(int)elapsed.TotalMinutes}m"; + } - public string Role => View?.Identity.Role is { Length: > 0 } role ? role : Agent.Role; + if (elapsed < TimeSpan.FromHours(24)) + { + return $"{(int)elapsed.TotalHours}h"; + } - public string State => View?.State ?? "offline"; + if (elapsed < TimeSpan.FromDays(7)) + { + return $"{(int)elapsed.TotalDays}d"; + } - public DateTimeOffset LastSeenAt => View?.LastSeenAt ?? Agent.LastSeenAt; + return value.ToUniversalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } - private static AgentListRowResult ToRow(AgentListRow row) => new( - row.Actor, - row.Role, - row.View?.Identity.Harness ?? "", - row.View?.Identity.SessionId ?? "", - row.View?.Online ?? false, - row.State, - row.View?.Participant?.Session.HarnessVersion ?? "", - row.View?.Participant?.Session.StartedAt, - row.LastSeenAt, - row.View?.Participant?.Session.Cwd, - row.View?.Participant?.Session.WorkspacePath, - row.View?.Participant?.Session.Host, - row.View?.Participant?.Session.EndpointKind, - row.View?.Participant?.Session.EndpointAddr); + /// + /// One agent's human-readable columns, ready to be padded against the other rows + /// printed alongside it. + /// + private readonly record struct AgentListLine( + string Name, string Role, string Harness, string Started, string LastSeen, bool Online) + { + public static AgentListLine From(AgentRow row, DateTimeOffset now) => new( + row.Name, + row.Role.Length > 0 ? row.Role : "-", + AgentHarnessDisplay.Name(row.Harness), + FormatAge(row.StartedAt, now), + FormatAge(row.LastSeenAt, now), + AgentStateResolver.Resolve(row, now) == AgentState.Online); + + public string Format(ColumnWidths widths) + => $"{Name.PadRight(widths.Name)} {Role.PadRight(widths.Role)} " + + $"{Harness.PadRight(widths.Harness)} {Started.PadRight(widths.Started)} " + + $"{LastSeen.PadRight(widths.LastSeen)} {(Online ? "yes" : "no")}"; + } + + private readonly record struct ColumnWidths(int Name, int Role, int Harness, int Started, int LastSeen) + { + public static ColumnWidths Compute(IReadOnlyList lines) => new( + lines.Max(line => line.Name.Length), + lines.Max(line => line.Role.Length), + lines.Max(line => line.Harness.Length), + lines.Max(line => line.Started.Length), + lines.Max(line => line.LastSeen.Length)); + } public sealed record AgentListRowResult( - string Actor, + string Name, string Role, - string Harness, - string SessionId, - bool Online, - string State, - string HarnessVersion, - DateTimeOffset? StartedAt, - DateTimeOffset LastHeardAt, - string? Cwd, - string? WorkspacePath, - string? Host, - string? EndpointKind, - string? EndpointAddr); + string? Harness, + DateTimeOffset StartedAt, + DateTimeOffset LastSeenAt, + bool Online); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/LoginAgentCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/LoginAgentCommand.cs index a6ad923d268..aae85d664d3 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/LoginAgentCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/LoginAgentCommand.cs @@ -28,10 +28,10 @@ private static async Task ExecuteAsync( CancellationToken cancellationToken) { var console = services.GetRequiredService(); - var registry = services.GetRequiredService(); + var agents = services.GetRequiredService(); var resultHolder = services.GetRequiredService(); - var agent = await registry.AllocateAsync(cancellationToken); + var agent = await agents.LoginAsync(cancellationToken); if (!console.IsHumanReadable) { diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/BroadcastMailCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/BroadcastMailCommand.cs index f13437b6176..20c04302ad8 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/BroadcastMailCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/BroadcastMailCommand.cs @@ -39,8 +39,7 @@ private static async Task ExecuteAsync( { var console = services.GetRequiredService(); var store = services.GetRequiredService(); - var registry = services.GetRequiredService(); - var sessions = services.GetRequiredService(); + var agents = services.GetRequiredService(); var nudge = services.GetRequiredService(); var timeProvider = services.GetRequiredService(); var fileSystem = services.GetRequiredService(); @@ -53,15 +52,15 @@ private static async Task ExecuteAsync( parseResult.GetValue(Opt.Instance), actorResolver, cancellationToken); var to = role is null - ? await ResolveEveryRegisteredAgentAsync(registry, actor, cancellationToken) - : await MailRoleRecipients.ResolveAsync(sessions, role, actor, cancellationToken); + ? await ResolveEveryRegisteredAgentAsync(agents, actor, cancellationToken) + : await MailRoleRecipients.ResolveAsync(agents, role, actor, cancellationToken); if (to.Count is 0) { throw new ExitException( role is null ? "No other registered agent to broadcast to." - : $"No live agent with role '{role}' to broadcast to (older sessions must re-register)."); + : $"No agent with role '{role}' to broadcast to."); } var body = await MailBody.ResolveAsync(parseResult, fileSystem, cancellationToken); @@ -96,18 +95,18 @@ await nudge.NudgeAsync( } /// - /// Returns the normalized names of every non-implicit registered agent - /// except . + /// Returns the normalized names, ordered by name, of every non-deleted + /// registered agent except . /// private static async Task> ResolveEveryRegisteredAgentAsync( - IAgentRegistry registry, string excludingActor, CancellationToken cancellationToken) + IAgentStore agents, string excludingActor, CancellationToken cancellationToken) { - var agents = await registry.ListAsync(role: null, staleBefore: null, cancellationToken); + var rows = await agents.ListAsync(cancellationToken); - return agents - .Where(agent => !agent.Implicit) + return rows .Select(agent => agent.Name) .Where(name => name != excludingActor) + .OrderBy(name => name, StringComparer.Ordinal) .ToArray(); } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailMessageResult.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailMessageResult.cs index f2724b25ebe..393d804e904 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailMessageResult.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailMessageResult.cs @@ -24,6 +24,11 @@ internal sealed record MailMessageResult /// public required bool MessageStored { get; init; } + /// + /// Names dropped from a reply-all because the agent is unknown or was deleted. + /// + public IReadOnlyList Skipped { get; init; } = []; + public static MailMessageResult Create(MailMessage message) => new() { Id = message.Id, @@ -42,6 +47,7 @@ internal sealed record MailMessageResult .ToArray(), Subject = message.Subject, CreatedAt = message.CreatedAt, - MessageStored = true + MessageStored = true, + Skipped = message.Skipped }; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailSendResult.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailSendResult.cs index c5a74cfffaf..4e3e75b482f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailSendResult.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/MailSendResult.cs @@ -4,8 +4,7 @@ namespace ChilliCream.Nitro.CommandLine.Commands.Agent.Mail; /// /// A sent message's core fields, as returned by the structured (JSON) output -/// of the send command. Unlike , this -/// carries the recipients that have never registered. +/// of the send command. /// internal sealed record MailSendResult { @@ -18,12 +17,6 @@ internal sealed record MailSendResult public required string Subject { get; init; } public required DateTimeOffset CreatedAt { get; init; } - /// - /// The normalized names, in recipient order, of every recipient that has - /// never registered. Empty when every recipient is registered. - /// - public required IReadOnlyList Unregistered { get; init; } - /// /// Always true: this result exists only after the message durably committed. /// @@ -47,7 +40,6 @@ internal sealed record MailSendResult .ToArray(), Subject = message.Subject, CreatedAt = message.CreatedAt, - Unregistered = message.Unregistered, MessageStored = true }; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReadMailCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReadMailCommand.cs index e51cf6f7f4d..e1809988620 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReadMailCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReadMailCommand.cs @@ -32,7 +32,7 @@ private static async Task ExecuteAsync( { var console = services.GetRequiredService(); var store = services.GetRequiredService(); - var registry = services.GetRequiredService(); + var agentStore = services.GetRequiredService(); var ledger = services.GetRequiredService(); var actorResolver = services.GetRequiredService(); var resultHolder = services.GetRequiredService(); @@ -74,7 +74,7 @@ private static async Task ExecuteAsync( console.WriteLine(); } - var sender = await registry.GetAsync(messages[i].Sender, cancellationToken); + var sender = await agentStore.FindAsync(messages[i].Sender, cancellationToken); WriteMessage(console, messages[i], sender?.Role ?? "", takeovers[i]); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReplyMailCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReplyMailCommand.cs index cf4f8444a94..d57642a6272 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReplyMailCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/ReplyMailCommand.cs @@ -66,6 +66,12 @@ await nudge.NudgeAsync( $"Sent '{message.Id.EscapeMarkup()}' to " + $"{string.Join(", ", message.Recipients.Select(recipient => recipient.Name)).EscapeMarkup()}."); + if (message.Skipped.Count > 0) + { + console.MarkupLine( + $"Skipped deleted or unknown agents: {string.Join(", ", message.Skipped).EscapeMarkup()}."); + } + return ExitCodes.Success; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/SendMailCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/SendMailCommand.cs index f6dd4bac2f5..c27f4765ac4 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/SendMailCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/Mail/SendMailCommand.cs @@ -80,11 +80,6 @@ await nudge.NudgeAsync( $"Sent '{message.Id.EscapeMarkup()}' to " + $"{string.Join(", ", message.Recipients.Select(recipient => recipient.Name)).EscapeMarkup()}."); - foreach (var name in message.Unregistered) - { - console.WriteLine($"note: '{name}' has never registered."); - } - return ExitCodes.Success; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/RegisterAgentCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/RegisterAgentCommand.cs index 2c46bcc0c0e..b1cafb3f10f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/RegisterAgentCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/RegisterAgentCommand.cs @@ -28,34 +28,60 @@ private static async Task ExecuteAsync( { var console = services.GetRequiredService(); var resultHolder = services.GetRequiredService(); - var agents = services.GetRequiredService(); + var agents = services.GetRequiredService(); var actor = MailAgentName.Normalize( parseResult.GetValue(Opt.Instance) ?? string.Empty); + var roleGiven = parseResult.GetResult(Opt.Instance) is { Implicit: false }; var role = parseResult.GetValue(Opt.Instance) ?? string.Empty; // Actor names are allocated, never invented: only `agent login` and // the session-start hooks mint one. - if (await agents.GetAsync(actor, cancellationToken) is null) + var existing = await agents.FindAsync(actor, cancellationToken); + + if (existing is null) { throw new ExitException( $"Unknown actor '{actor}'. Run `nitro agent login` to allocate one, " + "or `nitro agent list` to see the actors this workspace knows."); } - var registered = await agents.RegisterAsync(actor, role, client: string.Empty, cancellationToken); + if (existing.IsDeleted) + { + throw new ExitException($"Agent '{existing.Name}' was deleted."); + } + + string registeredName; + string registeredRole; + + if (roleGiven) + { + var registered = await agents.SetRoleAsync(actor, role, cancellationToken) + ?? throw new ExitException($"Agent '{actor}' was deleted."); + + registeredName = registered.Name; + registeredRole = registered.Role; + } + else + { + // Nothing else on the row changes: touch the beat and report the role as is. + await agents.TouchAsync(actor, cancellationToken); + + registeredName = existing.Name; + registeredRole = existing.Role; + } if (!console.IsHumanReadable) { - resultHolder.SetResult(new ObjectResult(new AgentRegisterResult(registered.Name, registered.Role))); + resultHolder.SetResult(new ObjectResult(new AgentRegisterResult(registeredName, registeredRole))); return ExitCodes.Success; } console.OkLine( - registered.Role.Length > 0 - ? $"Actor '{registered.Name.EscapeMarkup()}', role '{registered.Role.EscapeMarkup()}'." - : $"Actor '{registered.Name.EscapeMarkup()}'."); + registeredRole.Length > 0 + ? $"Actor '{registeredName.EscapeMarkup()}', role '{registeredRole.EscapeMarkup()}'." + : $"Actor '{registeredName.EscapeMarkup()}'."); return ExitCodes.Success; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/TakeoverAgentCommand.cs b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/TakeoverAgentCommand.cs index c7c6d786a83..27fd5ecdd9b 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/TakeoverAgentCommand.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Commands/Agent/TakeoverAgentCommand.cs @@ -35,8 +35,8 @@ private static async Task ExecuteAsync( { var console = services.GetRequiredService(); var resultHolder = services.GetRequiredService(); - var agents = services.GetRequiredService(); - var sessions = services.GetRequiredService(); + var agents = services.GetRequiredService(); + var timeProvider = services.GetRequiredService(); var mail = services.GetRequiredService(); var tasks = services.GetRequiredService(); var ledger = services.GetRequiredService(); @@ -48,27 +48,35 @@ private static async Task ExecuteAsync( var force = parseResult.GetValue(Opt.Instance); var reason = parseResult.GetValue(Opt.Instance); - var source = await agents.GetAsync(from, cancellationToken) + if (from == to) + { + throw new ExitException("The source and target actors must be different."); + } + + var source = await agents.FindAsync(from, cancellationToken) ?? throw UnknownActor(from); - var target = await agents.GetAsync(to, cancellationToken) + var target = await agents.FindAsync(to, cancellationToken) ?? throw UnknownActor(to); - if (from == to) + if (target.IsDeleted) { - throw new ExitException("The source and target actors must be different."); + throw DeletedActor(target.Name); } - if (!force - && (await sessions.FindLiveClaimedByAgentNameAsync(from, cancellationToken)).Count > 0) + var now = timeProvider.GetUtcNow(); + var sourceState = AgentStateResolver.Resolve(source, now); + + if (!force && sourceState == AgentState.Online) { throw new ExitException( - $"Actor '{from}' still has a live session; pass --force to take over anyway."); + $"Actor '{from}' is {sourceState}; pass --force to take over anyway."); } var role = target.Role; if (role.Length == 0 && source.Role.Length > 0) { - target = await agents.RegisterAsync(to, source.Role, target.Client, cancellationToken); + target = await agents.SetRoleAsync(to, source.Role, cancellationToken) + ?? throw DeletedActor(to); role = target.Role; } @@ -102,7 +110,6 @@ private static async Task ExecuteAsync( to, role, mailTransfer.RecipientsMoved, - mailTransfer.SendersMoved, taskIds))); return ExitCodes.Success; @@ -114,7 +121,7 @@ private static async Task ExecuteAsync( console.OkLine( $"'{to.EscapeMarkup()}' took over from '{from.EscapeMarkup()}': " + $"role '{role.EscapeMarkup()}', " - + $"{mailTransfer.RecipientsMoved + mailTransfer.SendersMoved} messages, {taskSummary}."); + + $"{mailTransfer.RecipientsMoved} messages, {taskSummary}."); return ExitCodes.Success; } @@ -122,16 +129,16 @@ private static async Task ExecuteAsync( private static ExitException UnknownActor(string actor) => new($"Unknown actor '{actor}'. Run `nitro agent list` to see the actors this workspace knows."); + private static ExitException DeletedActor(string actor) + => new($"Agent '{actor}' was deleted."); + private static IReadOnlyList CreateItems( MailTransferResult mailTransfer, IReadOnlyList taskIds) { var items = new List( - mailTransfer.SenderMessageIds.Count - + mailTransfer.RecipientMessageIds.Count + mailTransfer.RecipientMessageIds.Count + taskIds.Count); - items.AddRange(mailTransfer.SenderMessageIds.Select( - id => new TakeoverItem { Kind = TakeoverItemKinds.MessageSender, ItemId = id })); items.AddRange(mailTransfer.RecipientMessageIds.Select( id => new TakeoverItem { Kind = TakeoverItemKinds.MessageRecipient, ItemId = id })); items.AddRange(taskIds.Select( @@ -146,6 +153,5 @@ public sealed record AgentTakeoverResult( string To, string Role, int RecipientsMoved, - int SendersMoved, IReadOnlyList Tasks); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Extensions/ServiceCollectionExtensions.cs b/src/Nitro/CommandLine/src/CommandLine/Extensions/ServiceCollectionExtensions.cs index 05f284dbe8d..52bd0575e5a 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Extensions/ServiceCollectionExtensions.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Extensions/ServiceCollectionExtensions.cs @@ -37,21 +37,19 @@ public static IServiceCollection AddNitroServices(this IServiceCollection servic services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(); - services.TryAddSingleton(); + services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); + services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); + services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); @@ -65,7 +63,6 @@ public static IServiceCollection AddNitroServices(this IServiceCollection servic services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/AgentEffectiveRole.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/AgentEffectiveRole.cs deleted file mode 100644 index ea04390be86..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/AgentEffectiveRole.cs +++ /dev/null @@ -1,35 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Services.Hook; - -internal static class AgentEffectiveRole -{ - public static async Task ResolveAsync( - string sessionRole, - string actor, - IAgentRegistry agentRegistry, - CancellationToken cancellationToken) - { - if (sessionRole.Length > 0) - { - return sessionRole; - } - - try - { - return (await agentRegistry.GetAsync(actor, cancellationToken))?.Role ?? string.Empty; - } - catch (OperationCanceledException) - { - throw; - } - catch (AgentWorkspaceSchemaMismatchException) - { - throw; - } - catch - { - return string.Empty; - } - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookHandler.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookHandler.cs index 7d0edef7ce6..c246655d8ab 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookHandler.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookHandler.cs @@ -7,13 +7,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Hook; internal sealed class ClaudeHookHandler( IFileSystem fileSystem, TimeProvider timeProvider, - IAgentSessionRegistry sessionRegistry, - IAgentRegistry agentRegistry, - ISessionDeliveryLedger ledger, + IAgentStore agentStore, + IAgentDeliveryLedger ledger, IMailStore mailStore, - IClaudeSessionFileReader sessionFileReader, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider) : IClaudeHookHandler + IClaudeSessionFileReader sessionFileReader) : IClaudeHookHandler { /// /// The maximum number of Stop blocks per turn, reset on UserPromptSubmit. @@ -30,112 +27,71 @@ private static string BlockReason(string actor) public async Task HandleSessionStartAsync( ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) { - var resolved = await ResolveAsync(payload, skipSessionFileLookup, cancellationToken); + if (IsSubagentSession(payload)) + { + return ClaudeHookOutcome.Neutral; + } + + var resolved = Resolve(payload, skipSessionFileLookup); if (resolved is null) { return ClaudeHookOutcome.Neutral; } - var (endpointKind, endpointAddr) = resolved.EndpointName is { Length: > 0 } name - && EndpointAddress.IsValid(name) - ? (AgentSessionEndpointKind.ClaudePeer, name) - : (AgentSessionEndpointKind.None, string.Empty); + var result = await agentStore.StartSessionAsync(BuildStartRequest(payload, resolved), cancellationToken); - var session = await sessionRegistry.StartAsync( - resolved.Generation, - payload.Cwd!, - resolved.WorkspaceDirectory, - endpointKind, - endpointAddr, - envActor: null, - cancellationToken); - - if (resolved.HarnessVersion.Length > 0) + if (result.Kind == AgentSessionStartKind.Ignored) { - await sessionRegistry.RecordHarnessVersionAsync( - resolved.Generation, resolved.HarnessVersion, cancellationToken); + return ClaudeHookOutcome.Neutral; } - var role = await AgentEffectiveRole.ResolveAsync( - session.Role, session.AgentName!, agentRegistry, cancellationToken); + var row = result.Row!; - return new ClaudeHookOutcome - { - AdditionalContext = AgentActorContext.Format(session.AgentName!, role) - }; + return new ClaudeHookOutcome { AdditionalContext = AgentActorContext.Format(row.Name, row.Role) }; } public async Task HandleUserPromptSubmitAsync( ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) { - var resolved = await ResolveAsync(payload, skipSessionFileLookup, cancellationToken); - - if (resolved is null) + if (IsSubagentSession(payload)) { return ClaudeHookOutcome.Neutral; } - var row = await sessionRegistry.FindByGenerationAsync(resolved.Generation, cancellationToken); - - if (row is null) - { - var (endpointKind, endpointAddr) = resolved.EndpointName is { Length: > 0 } name - && EndpointAddress.IsValid(name) - ? (AgentSessionEndpointKind.ClaudePeer, name) - : (AgentSessionEndpointKind.None, string.Empty); - row = await sessionRegistry.StartAsync( - resolved.Generation, - payload.Cwd!, - resolved.WorkspaceDirectory, - endpointKind, - endpointAddr, - envActor: null, - cancellationToken); - } - else - { - await sessionRegistry.TouchAsync(resolved.Generation, cancellationToken); - } + var resolved = await ResolveOrStartRowAsync(payload, skipSessionFileLookup, cancellationToken); - if (row.BindingKind == AgentSessionBindingKind.None || row.AgentName is null) + if (resolved is null) { return ClaudeHookOutcome.Neutral; } - await sessionRegistry.ResetBlockBudgetAsync(resolved.Generation, cancellationToken); + var row = resolved.Row; + + await agentStore.ResetBlockBudgetAsync(row.Name, cancellationToken); - var digest = await BuildDigestAsync( - resolved.Generation, row.AgentName, AgentSessionChannel.Digest, cancellationToken); + var digest = await BuildDigestAsync(row.Name, AgentSessionChannel.Digest, cancellationToken); + var context = ComposeContext(resolved.Minted ? Announce(row) : null, digest?.Text); - return digest is null - ? ClaudeHookOutcome.Neutral - : new ClaudeHookOutcome { AdditionalContext = digest.Text }; + return context is null ? ClaudeHookOutcome.Neutral : new ClaudeHookOutcome { AdditionalContext = context }; } public async Task HandleStopAsync( ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) { - if (payload.StopHookActive) + if (IsSubagentSession(payload) || payload.StopHookActive) { return ClaudeHookOutcome.Neutral; } - var resolved = await ResolveAsync(payload, skipSessionFileLookup, cancellationToken); + var resolved = await ResolveOrStartRowAsync(payload, skipSessionFileLookup, cancellationToken); if (resolved is null) { return ClaudeHookOutcome.Neutral; } - await sessionRegistry.TouchAsync(resolved.Generation, cancellationToken); - - var row = await sessionRegistry.FindByGenerationAsync(resolved.Generation, cancellationToken); - - if (row is null || row.BindingKind == AgentSessionBindingKind.None || row.AgentName is null) - { - return ClaudeHookOutcome.Neutral; - } + var row = resolved.Row; if (row.BlockBudgetUsed >= MaxBlocksPerTurn) { @@ -143,19 +99,19 @@ public async Task HandleStopAsync( return ClaudeHookOutcome.Neutral; } - var digest = await BuildDigestAsync( - resolved.Generation, row.AgentName, AgentSessionChannel.Gate, cancellationToken); + var digest = await BuildDigestAsync(row.Name, AgentSessionChannel.Gate, cancellationToken); if (digest is null) { return ClaudeHookOutcome.Neutral; } - var incremented = await sessionRegistry.IncrementBlockBudgetAsync(resolved.Generation, cancellationToken); + var incremented = await agentStore.IncrementBlockBudgetAsync(row.Name, cancellationToken); - if (incremented is null) + if (incremented == 0) { - // The session ended before the budget could be incremented. + // The agent no longer matches (deleted, or otherwise gone) before the budget + // could be incremented. return ClaudeHookOutcome.Neutral; } @@ -164,29 +120,108 @@ public async Task HandleStopAsync( Block = true, BlockReason = digest.HasMessages ? $"{BlockDigestPreamble}\n{digest.Text}" - : BlockReason(row.AgentName) + : BlockReason(row.Name) }; } + public async Task HandleNotificationAsync( + ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) + { + if (IsSubagentSession(payload) || payload.NotificationType != "idle_prompt") + { + return ClaudeHookOutcome.Neutral; + } + + var resolved = await ResolveOrStartRowAsync(payload, skipSessionFileLookup, cancellationToken); + + return resolved is { Minted: true } + ? new ClaudeHookOutcome { AdditionalContext = Announce(resolved.Row) } + : ClaudeHookOutcome.Neutral; + } + public async Task HandleSessionEndAsync( ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) { - var resolved = await ResolveAsync(payload, skipSessionFileLookup, cancellationToken); + if (IsSubagentSession(payload)) + { + return ClaudeHookOutcome.Neutral; + } + + var resolved = Resolve(payload, skipSessionFileLookup); if (resolved is not null) { - await sessionRegistry.EndAsync(resolved.Generation, cancellationToken); + await agentStore.EndSessionAsync(AgentSessionHarness.ClaudeCode, payload.SessionId!, cancellationToken); } return ClaudeHookOutcome.Neutral; } + /// + /// Resolves the current harness session's row, minting one exactly like + /// without announcing it here when none is bound + /// yet; callers decide whether the mint is announced. Returns null when the payload + /// does not resolve, the session belongs to a deleted agent, or the mint itself is + /// ignored for the same reason. + /// + private async Task ResolveOrStartRowAsync( + ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) + { + var resolved = Resolve(payload, skipSessionFileLookup); + + if (resolved is null) + { + return null; + } + + var row = await agentStore.FindBySessionAsync( + AgentSessionHarness.ClaudeCode, payload.SessionId!, cancellationToken); + + if (row is not null) + { + if (row.IsDeleted) + { + return null; + } + + await agentStore.TouchSessionAsync(AgentSessionHarness.ClaudeCode, payload.SessionId!, cancellationToken); + + return new ResolvedRow(row, Minted: false); + } + + var result = await agentStore.StartSessionAsync(BuildStartRequest(payload, resolved), cancellationToken); + + return result.Kind == AgentSessionStartKind.Ignored + ? null + : new ResolvedRow(result.Row!, result.Kind == AgentSessionStartKind.Minted); + } + + /// + /// A payload carries a subagent marker when agent_id is set, meaning the hook + /// fired inside a subagent session rather than the top-level one. + /// + private static bool IsSubagentSession(ClaudeHookPayload payload) + => !string.IsNullOrEmpty(payload.AgentId); + + private static string Announce(AgentRow row) => AgentActorContext.Format(row.Name, row.Role); + + /// + /// Joins the mint announcement and the mail digest with a blank line when both are + /// present, or returns whichever one is present, or null when neither is. + /// + private static string? ComposeContext(string? announcement, string? digest) => (announcement, digest) switch + { + (null, null) => null, + ({ } head, null) => head, + (null, { } tail) => tail, + ({ } head, { } tail) => $"{head}\n\n{tail}" + }; + /// /// Returns a digest or unread-count reminder for newly reserved messages in the /// current inbox batch, or null when that batch yields no reservations. /// private async Task BuildDigestAsync( - AgentSessionGeneration generation, string actor, string channel, CancellationToken cancellationToken) @@ -201,14 +236,9 @@ public async Task HandleSessionEndAsync( } var messageIds = unread.Select(message => message.Id).ToList(); - var delivered = await ledger.FindDeliveredAsync(generation, messageIds, cancellationToken); + var delivered = await ledger.FindDeliveredAsync(actor, messageIds, cancellationToken); var reserved = await ledger.ReserveAsync( - generation.Harness, - generation.SessionId, - messageIds, - channel, - timeProvider.GetUtcNow(), - cancellationToken); + actor, messageIds, channel, timeProvider.GetUtcNow(), cancellationToken); if (reserved.Count == 0) { @@ -228,12 +258,12 @@ public async Task HandleSessionEndAsync( } /// - /// Resolves the session identity and workspace, or null when the session id or cwd - /// is missing, no workspace is found, or the payload and process workspaces differ. - /// The session-file lookup is skipped when is true. + /// Resolves the session's workspace and, when available, its peer name and harness + /// version, or null when the session id or cwd is missing, no workspace is found, or + /// the payload and process workspaces differ. The session-file lookup is skipped when + /// is true. /// - private async Task ResolveAsync( - ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken) + private ResolvedSession? Resolve(ClaudeHookPayload payload, bool skipSessionFileLookup) { if (string.IsNullOrWhiteSpace(payload.Cwd) || string.IsNullOrWhiteSpace(payload.SessionId)) { @@ -252,21 +282,37 @@ public async Task HandleSessionEndAsync( // address and the harness version. var session = skipSessionFileLookup ? null : sessionFileReader.Find(payload.SessionId); - var host = await instanceIdProvider.GetIdAsync( - globalConfigDirectoryProvider.GetDirectory(), cancellationToken); + return new ResolvedSession(payloadWorkspace, session?.Name, session?.Version ?? string.Empty); + } - var generation = new AgentSessionGeneration( - AgentSessionHarness.ClaudeCode, payload.SessionId, host); + private static AgentSessionStartRequest BuildStartRequest(ClaudeHookPayload payload, ResolvedSession resolved) + { + var (endpointKind, endpointAddr) = resolved.EndpointName is { Length: > 0 } name + && EndpointAddress.IsValid(name) + ? (AgentSessionEndpointKind.ClaudePeer, name) + : (AgentSessionEndpointKind.None, string.Empty); - return new ResolvedGeneration( - generation, payloadWorkspace, session?.Name, session?.Version ?? string.Empty); + return new AgentSessionStartRequest + { + Harness = AgentSessionHarness.ClaudeCode, + SessionId = payload.SessionId!, + HarnessVersion = resolved.HarnessVersion, + Cwd = payload.Cwd!, + WorkspacePath = resolved.WorkspaceDirectory, + EndpointKind = endpointKind, + EndpointAddr = endpointAddr + }; } - private sealed record ResolvedGeneration( - AgentSessionGeneration Generation, + private sealed record ResolvedSession( string WorkspaceDirectory, string? EndpointName, string HarnessVersion); + /// + /// A resolved harness session's row, and whether resolving it just minted a new agent. + /// + private sealed record ResolvedRow(AgentRow Row, bool Minted); + private sealed record MailDigestResult(string Text, bool HasMessages); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookPayload.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookPayload.cs index 304591cb38d..471d6e4fe4c 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookPayload.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHookPayload.cs @@ -4,8 +4,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Hook; /// /// The fields this adapter reads from a Claude Code hook's stdin JSON: -/// session_id and cwd on every event, plus -/// stop_hook_active on Stop. Other fields are left unparsed. +/// session_id and cwd on every event, agent_id when the +/// event fires inside a subagent session, plus stop_hook_active on +/// Stop and notification_type on Notification. Other +/// fields are left unparsed. /// internal sealed record ClaudeHookPayload { @@ -15,6 +17,12 @@ internal sealed record ClaudeHookPayload [JsonPropertyName("cwd")] public string? Cwd { get; init; } + [JsonPropertyName("agent_id")] + public string? AgentId { get; init; } + [JsonPropertyName("stop_hook_active")] public bool StopHookActive { get; init; } + + [JsonPropertyName("notification_type")] + public string? NotificationType { get; init; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHooksTemplate.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHooksTemplate.cs index 1d596ef0800..3e8b024404a 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHooksTemplate.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ClaudeHooksTemplate.cs @@ -19,13 +19,15 @@ internal static class ClaudeHooksTemplate /// Claude Code hook event names this installer manages, in the order /// hooks install and hooks status report them. /// - public static readonly IReadOnlyList Events = ["SessionStart", "UserPromptSubmit", "Stop", "SessionEnd"]; + public static readonly IReadOnlyList Events = + ["SessionStart", "UserPromptSubmit", "Stop", "Notification", "SessionEnd"]; public static string EventCommand(string claudeEvent) => claudeEvent switch { "SessionStart" => "session-start", "UserPromptSubmit" => "user-prompt-submit", "Stop" => "stop", + "Notification" => "notification", "SessionEnd" => "session-end", _ => throw new ArgumentOutOfRangeException( nameof(claudeEvent), claudeEvent, "Not a hook event this installer manages.") diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/CodexHookHandler.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/CodexHookHandler.cs index 3b6e6938fc8..27def6d5096 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/CodexHookHandler.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/CodexHookHandler.cs @@ -7,135 +7,61 @@ namespace ChilliCream.Nitro.CommandLine.Services.Hook; internal sealed class CodexHookHandler( IFileSystem fileSystem, TimeProvider timeProvider, - IAgentSessionRegistry sessionRegistry, - IAgentRegistry agentRegistry, - ISessionDeliveryLedger ledger, + IAgentStore agentStore, + IAgentDeliveryLedger ledger, IMailStore mailStore, ICodexHarnessVersionResolver harnessVersionResolver, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider, ICodexQueueClient queueClient) : ICodexHookHandler { - public CodexHookHandler( - IFileSystem fileSystem, - TimeProvider timeProvider, - IAgentSessionRegistry sessionRegistry, - IAgentRegistry agentRegistry, - ISessionDeliveryLedger ledger, - IMailStore mailStore, - IEnvironmentVariableProvider environmentVariableProvider, - ICodexHarnessVersionResolver harnessVersionResolver, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider, - ICodexQueueClient queueClient) - : this( - fileSystem, - timeProvider, - sessionRegistry, - agentRegistry, - ledger, - mailStore, - harnessVersionResolver, - instanceIdProvider, - globalConfigDirectoryProvider, - queueClient) - { - ArgumentNullException.ThrowIfNull(environmentVariableProvider); - } - public async Task HandleSessionStartAsync( CodexHookPayload payload, CancellationToken cancellationToken) { - var resolved = await ResolveAsync(payload, cancellationToken); + var workspaceDirectory = Resolve(payload); - if (resolved is null) + if (workspaceDirectory is null) { return CodexHookOutcome.Neutral; } - // The Codex endpoint address is the thread id itself, which equals the - // session id. - var (endpointKind, endpointAddr) = EndpointAddress.IsValid(resolved.Generation.SessionId) - ? (AgentSessionEndpointKind.CodexThread, resolved.Generation.SessionId) - : (AgentSessionEndpointKind.None, string.Empty); + var result = await agentStore.StartSessionAsync( + BuildStartRequest(payload, workspaceDirectory), cancellationToken); - var session = await sessionRegistry.StartAsync( - resolved.Generation, - payload.Cwd!, - resolved.WorkspaceDirectory, - endpointKind, - endpointAddr, - envActor: null, - cancellationToken); - - var harnessVersion = harnessVersionResolver.Resolve(resolved.Generation.SessionId); - - if (harnessVersion.Length > 0) + if (result.Kind == AgentSessionStartKind.Ignored) { - await sessionRegistry.RecordHarnessVersionAsync(resolved.Generation, harnessVersion, cancellationToken); + return CodexHookOutcome.Neutral; } - var role = await AgentEffectiveRole.ResolveAsync( - session.Role, session.AgentName!, agentRegistry, cancellationToken); + var row = result.Row!; - return new CodexHookOutcome - { - AdditionalContext = AgentActorContext.Format(session.AgentName!, role) - }; + return new CodexHookOutcome { AdditionalContext = AgentActorContext.Format(row.Name, row.Role) }; } public async Task HandleUserPromptSubmitAsync( CodexHookPayload payload, CancellationToken cancellationToken) { - var resolved = await ResolveAsync(payload, cancellationToken); + var resolved = await ResolveOrStartRowAsync(payload, cancellationToken); if (resolved is null) { return CodexHookOutcome.Neutral; } - var row = await sessionRegistry.FindByGenerationAsync(resolved.Generation, cancellationToken); + var row = resolved.Row; - if (row is null) - { - var (endpointKind, endpointAddr) = EndpointAddress.IsValid(resolved.Generation.SessionId) - ? (AgentSessionEndpointKind.CodexThread, resolved.Generation.SessionId) - : (AgentSessionEndpointKind.None, string.Empty); - row = await sessionRegistry.StartAsync( - resolved.Generation, - payload.Cwd!, - resolved.WorkspaceDirectory, - endpointKind, - endpointAddr, - envActor: null, - cancellationToken); - } - else - { - await sessionRegistry.TouchAsync(resolved.Generation, cancellationToken); - } + var digest = await BuildDigestAsync(row.Name, AgentSessionChannel.Digest, cancellationToken); + var context = ComposeContext(resolved.Minted ? Announce(row) : null, digest?.Text); - if (row.BindingKind == AgentSessionBindingKind.None || row.AgentName is null) - { - return CodexHookOutcome.Neutral; - } - - var digest = await BuildDigestAsync( - resolved.Generation, row.AgentName, AgentSessionChannel.Digest, cancellationToken); - - return digest is null - ? CodexHookOutcome.Neutral - : new CodexHookOutcome { AdditionalContext = digest.Text }; + return context is null ? CodexHookOutcome.Neutral : new CodexHookOutcome { AdditionalContext = context }; } public async Task HandleSessionEndAsync( CodexHookPayload payload, CancellationToken cancellationToken) { - var resolved = await ResolveAsync(payload, cancellationToken); + var workspaceDirectory = Resolve(payload); - if (resolved is not null) + if (workspaceDirectory is not null) { - await sessionRegistry.EndAsync(resolved.Generation, cancellationToken); + await agentStore.EndSessionAsync(AgentSessionHarness.Codex, payload.SessionId!, cancellationToken); } return CodexHookOutcome.Neutral; @@ -154,7 +80,7 @@ public async Task HandleNotifyAsync( return CodexNotifyOutcome.Neutral; } - var resolved = await ResolveAsync( + var resolved = await ResolveOrStartRowAsync( new CodexHookPayload { SessionId = payload.ThreadId, Cwd = payload.Cwd }, cancellationToken); if (resolved is null) @@ -162,17 +88,9 @@ public async Task HandleNotifyAsync( return CodexNotifyOutcome.Neutral; } - await sessionRegistry.TouchAsync(resolved.Generation, cancellationToken); - - var row = await sessionRegistry.FindByGenerationAsync(resolved.Generation, cancellationToken); - - if (row is null || row.BindingKind == AgentSessionBindingKind.None || row.AgentName is null) - { - return CodexNotifyOutcome.Neutral; - } + var row = resolved.Row; - var digest = await BuildDigestAsync( - resolved.Generation, row.AgentName, AgentSessionChannel.Gate, cancellationToken); + var digest = await BuildDigestAsync(row.Name, AgentSessionChannel.Gate, cancellationToken); if (digest is null) { @@ -185,12 +103,64 @@ public async Task HandleNotifyAsync( return new CodexNotifyOutcome { Queued = queueResult == CodexQueueResult.Ok }; } + /// + /// Resolves the current thread's row, minting one exactly like + /// without announcing it here when none is bound + /// yet; callers decide whether the mint is announced. Returns null when the payload + /// does not resolve, the session belongs to a deleted agent, or the mint itself is + /// ignored for the same reason. + /// + private async Task ResolveOrStartRowAsync( + CodexHookPayload payload, CancellationToken cancellationToken) + { + var workspaceDirectory = Resolve(payload); + + if (workspaceDirectory is null) + { + return null; + } + + var row = await agentStore.FindBySessionAsync(AgentSessionHarness.Codex, payload.SessionId!, cancellationToken); + + if (row is not null) + { + if (row.IsDeleted) + { + return null; + } + + await agentStore.TouchSessionAsync(AgentSessionHarness.Codex, payload.SessionId!, cancellationToken); + + return new ResolvedRow(row, Minted: false); + } + + var result = await agentStore.StartSessionAsync( + BuildStartRequest(payload, workspaceDirectory), cancellationToken); + + return result.Kind == AgentSessionStartKind.Ignored + ? null + : new ResolvedRow(result.Row!, result.Kind == AgentSessionStartKind.Minted); + } + + private static string Announce(AgentRow row) => AgentActorContext.Format(row.Name, row.Role); + + /// + /// Joins the mint announcement and the mail digest with a blank line when both are + /// present, or returns whichever one is present, or null when neither is. + /// + private static string? ComposeContext(string? announcement, string? digest) => (announcement, digest) switch + { + (null, null) => null, + ({ } head, null) => head, + (null, { } tail) => tail, + ({ } head, { } tail) => $"{head}\n\n{tail}" + }; + /// /// Returns a digest or unread-count reminder for newly reserved messages in the /// current inbox batch, or null when that batch yields no reservations. /// private async Task BuildDigestAsync( - AgentSessionGeneration generation, string actor, string channel, CancellationToken cancellationToken) @@ -205,14 +175,9 @@ public async Task HandleNotifyAsync( } var messageIds = unread.Select(message => message.Id).ToList(); - var delivered = await ledger.FindDeliveredAsync(generation, messageIds, cancellationToken); + var delivered = await ledger.FindDeliveredAsync(actor, messageIds, cancellationToken); var reserved = await ledger.ReserveAsync( - generation.Harness, - generation.SessionId, - messageIds, - channel, - timeProvider.GetUtcNow(), - cancellationToken); + actor, messageIds, channel, timeProvider.GetUtcNow(), cancellationToken); if (reserved.Count == 0) { @@ -226,18 +191,16 @@ public async Task HandleNotifyAsync( .ToList(); var unreadTotal = await mailStore.CountUnreadAsync(actor, cancellationToken); - return new MailDigestResult( - MailDigest.Render(actor, messages, unreadTotal)); + return new MailDigestResult(MailDigest.Render(actor, messages, unreadTotal)); } /// - /// Resolves the session identity and workspace, or null when the session id or cwd - /// is missing, no workspace is found, or the payload and process workspaces differ. + /// Resolves the session's workspace directory, or null when the session id or cwd is + /// missing, no workspace is found, or the payload and process workspaces differ. /// - private async Task ResolveAsync( - CodexHookPayload payload, CancellationToken cancellationToken) + private string? Resolve(CodexHookPayload payload) { - if (string.IsNullOrWhiteSpace(payload.Cwd)) + if (string.IsNullOrWhiteSpace(payload.Cwd) || string.IsNullOrWhiteSpace(payload.SessionId)) { return null; } @@ -245,26 +208,32 @@ public async Task HandleNotifyAsync( var payloadWorkspace = AgentWorkspace.Find(fileSystem, payload.Cwd); var processWorkspace = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()); - if (payloadWorkspace is null || payloadWorkspace != processWorkspace) - { - return null; - } + return payloadWorkspace is null || payloadWorkspace != processWorkspace ? null : payloadWorkspace; + } - var host = await instanceIdProvider.GetIdAsync( - globalConfigDirectoryProvider.GetDirectory(), cancellationToken); + private AgentSessionStartRequest BuildStartRequest(CodexHookPayload payload, string workspaceDirectory) + { + // The Codex endpoint address is the thread id itself, which equals the session id. + var (endpointKind, endpointAddr) = EndpointAddress.IsValid(payload.SessionId!) + ? (AgentSessionEndpointKind.CodexThread, payload.SessionId!) + : (AgentSessionEndpointKind.None, string.Empty); - if (string.IsNullOrWhiteSpace(payload.SessionId)) + return new AgentSessionStartRequest { - return null; - } - - var generation = new AgentSessionGeneration( - AgentSessionHarness.Codex, payload.SessionId, host); - - return new ResolvedGeneration(generation, payloadWorkspace); + Harness = AgentSessionHarness.Codex, + SessionId = payload.SessionId!, + HarnessVersion = harnessVersionResolver.Resolve(payload.SessionId!), + Cwd = payload.Cwd!, + WorkspacePath = workspaceDirectory, + EndpointKind = endpointKind, + EndpointAddr = endpointAddr + }; } - private sealed record ResolvedGeneration(AgentSessionGeneration Generation, string WorkspaceDirectory); - private sealed record MailDigestResult(string Text); + + /// + /// A resolved thread's row, and whether resolving it just minted a new agent. + /// + private sealed record ResolvedRow(AgentRow Row, bool Minted); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/IClaudeHookHandler.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/IClaudeHookHandler.cs index de49933f2da..fe0fff95553 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/IClaudeHookHandler.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/IClaudeHookHandler.cs @@ -1,8 +1,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Hook; /// -/// Handles Claude session registration, unread-mail context, Stop decisions, and -/// session removal. Exceptions propagate to the hook executor. +/// Handles Claude session registration, unread-mail context, Stop decisions, and session +/// end, returning a neutral outcome without writing anything when the payload carries +/// , which marks a subagent session. Exceptions +/// propagate to the hook executor. /// internal interface IClaudeHookHandler { @@ -31,7 +33,15 @@ Task HandleStopAsync( ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken); /// - /// Conditionally deletes the session's presence row. + /// Touches the session's last-seen time, minting the row first when it is not yet known, + /// only when is idle_prompt; any + /// other type, or a payload that does not resolve, leaves the store untouched. + /// + Task HandleNotificationAsync( + ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken); + + /// + /// Stamps the session's agent row as ended, keeping it in place. /// Task HandleSessionEndAsync( ClaudeHookPayload payload, bool skipSessionFileLookup, CancellationToken cancellationToken); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ICodexHookHandler.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ICodexHookHandler.cs index fcadc7e5973..f51e5c1c86f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ICodexHookHandler.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/ICodexHookHandler.cs @@ -1,7 +1,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Hook; /// -/// Handles Codex session registration, unread-mail context, session removal, and +/// Handles Codex session registration, unread-mail context, session end, and /// notify delivery. Exceptions propagate to the hook executor. /// internal interface ICodexHookHandler @@ -21,7 +21,7 @@ Task HandleUserPromptSubmitAsync( CodexHookPayload payload, CancellationToken cancellationToken); /// - /// Conditionally deletes the session's presence row. + /// Stamps the session's agent row as ended, keeping it in place. /// Task HandleSessionEndAsync( CodexHookPayload payload, CancellationToken cancellationToken); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/OpencodeHookHandler.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/OpencodeHookHandler.cs index abeb0c859be..613cddbf085 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Hook/OpencodeHookHandler.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Hook/OpencodeHookHandler.cs @@ -10,12 +10,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Hook; internal sealed class OpencodeHookHandler( IFileSystem fileSystem, TimeProvider timeProvider, - IAgentSessionRegistry sessionRegistry, - ISessionDeliveryLedger ledger, + IAgentStore agentStore, + IAgentDeliveryLedger ledger, IMailStore mailStore, - IEnvironmentVariableProvider environmentVariableProvider, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider) : IOpencodeHookHandler + IEnvironmentVariableProvider environmentVariableProvider) : IOpencodeHookHandler { /// /// The maximum number of unread messages considered for delivery reservations in one call. @@ -28,40 +26,27 @@ public async Task HandleSessionCreatedAsync( // dryRun does not change opencode handler behavior. _ = dryRun; - var resolved = await ResolveAsync(payload, cancellationToken); + var resolved = Resolve(payload); if (resolved is null) { return OpencodeHookOutcome.Neutral; } - // Only a valid endpoint reported as bound is registered for push delivery. - var trusted = EndpointAddress.IsTrustedOpencodeServerUrl(payload.ServerUrl!, payload.ServerBound); - var (endpointKind, endpointAddr, endpointSecret) = trusted - ? (AgentSessionEndpointKind.OpencodeServer, payload.ServerUrl!, payload.ServerPassword) - : (AgentSessionEndpointKind.None, string.Empty, null); - - await sessionRegistry.StartAsync( - resolved.Generation, - resolved.Cwd, - resolved.WorkspaceDirectory, - endpointKind, - endpointAddr, - endpointSecret, - envActor: null, - cancellationToken); + var result = await agentStore.StartSessionAsync(BuildStartRequest(payload, resolved), cancellationToken); - if (!string.IsNullOrWhiteSpace(payload.HarnessVersion)) + if (result.Kind == AgentSessionStartKind.Ignored) { - await sessionRegistry.RecordHarnessVersionAsync( - resolved.Generation, payload.HarnessVersion, cancellationToken); + return OpencodeHookOutcome.Neutral; } - await sessionRegistry.ArmAnnouncementAsync(resolved.Generation, cancellationToken); + var row = result.Row!; - if (trusted) + await agentStore.ArmAnnouncementAsync(row.Name, cancellationToken); + + if (row.EndpointKind == AgentSessionEndpointKind.OpencodeServer) { - await sessionRegistry.RearmIdlePushAsync(resolved.Generation, cancellationToken); + await agentStore.RearmIdlePushAsync(row.Name, cancellationToken); } return OpencodeHookOutcome.Neutral; @@ -72,40 +57,39 @@ public async Task HandleChatMessageAsync( { _ = dryRun; // see HandleSessionCreatedAsync - var resolved = await ResolveAsync(payload, cancellationToken); + var resolved = Resolve(payload); if (resolved is null) { return OpencodeHookOutcome.Neutral; } - if (!await sessionRegistry.TouchAsync(resolved.Generation, cancellationToken)) + var row = await agentStore.FindBySessionAsync(AgentSessionHarness.Opencode, payload.SessionId!, cancellationToken); + + if (row is null || row.IsDeleted) { return OpencodeHookOutcome.Neutral; } - var row = await sessionRegistry.FindByGenerationAsync(resolved.Generation, cancellationToken); + await agentStore.TouchSessionAsync(AgentSessionHarness.Opencode, payload.SessionId!, cancellationToken); // An unconfirmed previous delivery rearms the announcement and releases digest // reservations for the current unread batch. if (payload.Delivered == false) { - await sessionRegistry.ArmAnnouncementAsync(resolved.Generation, cancellationToken); + await agentStore.ArmAnnouncementAsync(row.Name, cancellationToken); - if (row?.AgentName is { } releaseActor) + var stillUnread = await mailStore.QueryInboxAsync( + new MailInboxFilter { Actor = row.Name, UnreadOnly = true, Limit = MaxDigestMessages }, + cancellationToken); + + if (stillUnread.Count > 0) { - var stillUnread = await mailStore.QueryInboxAsync( - new MailInboxFilter { Actor = releaseActor, UnreadOnly = true, Limit = MaxDigestMessages }, + await ledger.ReleaseAsync( + row.Name, + stillUnread.Select(static message => message.Id).ToList(), + AgentSessionChannel.Digest, cancellationToken); - - if (stillUnread.Count > 0) - { - await ledger.ReleaseAsync( - resolved.Generation, - stillUnread.Select(static message => message.Id).ToList(), - AgentSessionChannel.Digest, - cancellationToken); - } } } @@ -115,31 +99,24 @@ await ledger.ReleaseAsync( return OpencodeHookOutcome.Neutral; } - if (row?.EndpointKind == AgentSessionEndpointKind.OpencodeServer) + if (row.EndpointKind == AgentSessionEndpointKind.OpencodeServer) { - await sessionRegistry.RearmIdlePushAsync(resolved.Generation, cancellationToken); + await agentStore.RearmIdlePushAsync(row.Name, cancellationToken); } - await sessionRegistry.ResetBlockBudgetAsync(resolved.Generation, cancellationToken); - - if (row is null || row.BindingKind == AgentSessionBindingKind.None || row.AgentName is null) - { - return OpencodeHookOutcome.Neutral; - } + await agentStore.ResetBlockBudgetAsync(row.Name, cancellationToken); - var digest = await BuildDigestAsync( - resolved.Generation, row.AgentName, AgentSessionChannel.Digest, cancellationToken); + var digest = await BuildDigestAsync(row.Name, AgentSessionChannel.Digest, cancellationToken); bool announce; try { - announce = await sessionRegistry.ClaimAnnouncementAsync(resolved.Generation, cancellationToken); + announce = await agentStore.ClaimAnnouncementAsync(row.Name, cancellationToken); } catch { // Compensation releases only the message ids reserved by this call. - await ReleaseCompensatingReservationAsync( - resolved.Generation, digest.ReservedIds, AgentSessionChannel.Digest); + await ReleaseCompensatingReservationAsync(row.Name, digest.ReservedIds, AgentSessionChannel.Digest); throw; } @@ -148,7 +125,7 @@ await ReleaseCompensatingReservationAsync( if (announce) { - parts.Add(AgentActorContext.Format(row.AgentName, row.Role)); + parts.Add(AgentActorContext.Format(row.Name, row.Role)); } if (digest.Text is not null) @@ -169,7 +146,7 @@ public async Task HandleSessionIdleAsync( return OpencodeHookOutcome.Neutral; } - var resolved = await ResolveAsync(payload, cancellationToken); + var resolved = Resolve(payload); if (resolved is null) { @@ -177,7 +154,7 @@ public async Task HandleSessionIdleAsync( } // Idle events refresh presence without claiming the push gate or reserving messages. - await sessionRegistry.TouchAsync(resolved.Generation, cancellationToken); + await agentStore.TouchSessionAsync(AgentSessionHarness.Opencode, payload.SessionId!, cancellationToken); return OpencodeHookOutcome.Neutral; } @@ -187,18 +164,21 @@ public async Task HandleSessionDeletedAsync( { _ = dryRun; // see HandleSessionCreatedAsync - var resolved = await ResolveAsync(payload, cancellationToken); + var resolved = Resolve(payload); if (resolved is not null) { - await sessionRegistry.EndAsync(resolved.Generation, cancellationToken); + await agentStore.EndSessionAsync(AgentSessionHarness.Opencode, payload.SessionId!, cancellationToken); } return OpencodeHookOutcome.Neutral; } + /// + /// Returns a digest or unread-count reminder for newly reserved messages in the + /// current inbox batch, or null when that batch yields no reservations. + /// private async Task BuildDigestAsync( - AgentSessionGeneration generation, string actor, string channel, CancellationToken cancellationToken) @@ -212,9 +192,9 @@ private async Task BuildDigestAsync( return DigestBuildResult.Empty; } - // A missing session or a session owned by another host yields no reservations. + // A deleted agent yields no reservations. var reserved = await ledger.ReserveAsync( - generation, + actor, unread.Select(static message => message.Id).ToList(), channel, timeProvider.GetUtcNow(), @@ -233,7 +213,7 @@ private async Task BuildDigestAsync( } catch { - await ReleaseCompensatingReservationAsync(generation, reserved, channel); + await ReleaseCompensatingReservationAsync(actor, reserved, channel); throw; } } @@ -243,11 +223,11 @@ private async Task BuildDigestAsync( /// Release failures are ignored. /// private async Task ReleaseCompensatingReservationAsync( - AgentSessionGeneration generation, IReadOnlyList messageIds, string channel) + string actor, IReadOnlyList messageIds, string channel) { try { - await ledger.ReleaseAsync(generation, messageIds, channel, CancellationToken.None); + await ledger.ReleaseAsync(actor, messageIds, channel, CancellationToken.None); } catch { @@ -259,9 +239,11 @@ private sealed record DigestBuildResult(string? Text, IReadOnlyList Rese public static readonly DigestBuildResult Empty = new(null, []); } - private async Task ResolveAsync( - OpencodeHookPayload payload, - CancellationToken cancellationToken) + /// + /// Resolves the session's workspace and cwd, or null when the session id or server URL + /// is missing or invalid, no workspace is found, or the payload and process workspaces differ. + /// + private ResolvedSession? Resolve(OpencodeHookPayload payload) { if (string.IsNullOrWhiteSpace(payload.SessionId) || string.IsNullOrWhiteSpace(payload.ServerUrl) @@ -281,15 +263,29 @@ private sealed record DigestBuildResult(string? Text, IReadOnlyList Rese return null; } - var host = await instanceIdProvider.GetIdAsync( - globalConfigDirectoryProvider.GetDirectory(), cancellationToken); - var generation = new AgentSessionGeneration(AgentSessionHarness.Opencode, payload.SessionId, host); + return new ResolvedSession(cwd, workspaceDirectory); + } - return new ResolvedGeneration(generation, cwd, workspaceDirectory); + private static AgentSessionStartRequest BuildStartRequest(OpencodeHookPayload payload, ResolvedSession resolved) + { + // Only a valid endpoint reported as bound is registered for push delivery. + var trusted = EndpointAddress.IsTrustedOpencodeServerUrl(payload.ServerUrl!, payload.ServerBound); + var (endpointKind, endpointAddr, endpointSecret) = trusted + ? (AgentSessionEndpointKind.OpencodeServer, payload.ServerUrl!, payload.ServerPassword) + : (AgentSessionEndpointKind.None, string.Empty, null); + + return new AgentSessionStartRequest + { + Harness = AgentSessionHarness.Opencode, + SessionId = payload.SessionId!, + HarnessVersion = payload.HarnessVersion ?? string.Empty, + Cwd = resolved.Cwd, + WorkspacePath = resolved.WorkspaceDirectory, + EndpointKind = endpointKind, + EndpointAddr = endpointAddr, + EndpointSecret = endpointSecret + }; } - private sealed record ResolvedGeneration( - AgentSessionGeneration Generation, - string Cwd, - string WorkspaceDirectory); + private sealed record ResolvedSession(string Cwd, string WorkspaceDirectory); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/IMailStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/IMailStore.cs index 98901e0dbc1..6d93c2f0828 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/IMailStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/IMailStore.cs @@ -21,11 +21,11 @@ Task InitializeWorkspaceAsync( /// /// Starts a thread with normalized addresses and recipients deduplicated in first - /// occurrence order (To wins over Cc), registering the sender and creating implicit identities for unknown recipients. + /// occurrence order (To wins over Cc). The sender must exist and not be deleted. /// Stores the message and recipients atomically with wake generations when /// requests them; invalid addresses, - /// a trimmed subject outside 1 to 500 characters, or no recipients cause an - /// . + /// a trimmed subject outside 1 to 500 characters, no recipients, or an unusable + /// sender or recipient cause an . /// Task SendMessageAsync( MailMessageCreation creation, @@ -34,8 +34,11 @@ Task SendMessageAsync( /// /// Replies in the original thread with its root subject, addressing the original /// sender and recipients as To recipients except the replying actor, and applying - /// . Throws if the message - /// is missing, the actor is not a participant, or no recipients remain. + /// . The actor must exist and not be deleted; among + /// several remaining recipients an unknown or deleted one is dropped and reported + /// in , but a lone remaining recipient must be + /// usable. Throws if the message is missing, the actor + /// is not a participant or is unusable, or no usable recipient remains. /// Task ReplyMessageAsync( string inReplyToId, @@ -55,7 +58,8 @@ Task ReplyMessageAsync( => ReplyMessageAsync(inReplyToId, sender, body, MailWakePolicy.Skip, cancellationToken); /// - /// Transfers mail participation from one agent to another. Recipient + /// Moves the source agent's unread, unarchived recipient rows to the target agent, + /// leaving read or archived rows and every message's sender untouched. Recipient /// conflicts preserve the target agent's recipient state. /// Task TransferParticipationAsync( @@ -171,6 +175,18 @@ Task> QueryWorkspaceThreadsAsync( string? agent, CancellationToken cancellationToken); + /// + /// Returns one row per thread where the agent sent a message or was a to or cc recipient + /// of one, ranked by the agent's own newest such message in the thread then thread id + /// descending, and capped by a non-null . Unread and archived + /// counts are scoped to the agent. + /// + Task> QueryParticipationThreadsAsync( + string agent, + int? limit, + CancellationToken cancellationToken) + => Task.FromException>(new NotSupportedException()); + /// /// Returns the actor's sent or received messages whose subject, body, or sender /// contains the text, matching ASCII case-insensitively. diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailMessage.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailMessage.cs index d6d4e6d5fb2..c5304eea272 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailMessage.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailMessage.cs @@ -27,15 +27,15 @@ internal sealed record MailMessage /// public IReadOnlyList Recipients { get; init; } = []; - /// - /// Names of implicit recipient identities in recipient order, populated by - /// . Other operations leave this empty. - /// - public IReadOnlyList Unregistered { get; init; } = []; - /// /// Wake generation tokens returned by sends or replies that use /// . Other operations leave this empty. /// public IReadOnlyList WakeReceipts { get; init; } = []; + + /// + /// Names dropped from a reply-all because the agent is unknown or was deleted. + /// Empty for a send, a direct reply, or a reply-all where every participant is usable. + /// + public IReadOnlyList Skipped { get; init; } = []; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailRoleRecipients.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailRoleRecipients.cs index 645ba7e5342..b01271338fd 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailRoleRecipients.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailRoleRecipients.cs @@ -3,27 +3,26 @@ namespace ChilliCream.Nitro.CommandLine.Services.Mail; /// -/// Resolves role-targeted recipients from registered session participants. +/// Resolves role-targeted recipients from the agents table. /// internal static class MailRoleRecipients { /// - /// Returns distinct non-implicit actor names whose session role matches the normalized - /// role, excluding . An empty session role falls - /// back to the actor's role; presence state is not filtered. + /// Returns distinct, non-deleted agent names whose role matches the normalized role, + /// excluding . /// public static async Task> ResolveAsync( - IAgentSessionRegistry sessions, + IAgentStore agents, string role, string excludingActor, CancellationToken cancellationToken) { var normalizedRole = AgentRole.Normalize(role); - var participants = await sessions.ListParticipantsAsync(cancellationToken); + var rows = await agents.ListAsync(cancellationToken); - return participants - .Where(participant => participant.Agent is { Implicit: false } && participant.MatchesRole(normalizedRole)) - .Select(participant => participant.Agent!.Name) + return rows + .Where(agent => agent.Role == normalizedRole) + .Select(agent => agent.Name) .Where(name => name != excludingActor) .Distinct(StringComparer.Ordinal) .ToArray(); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStore.cs index eada2e6af07..71de99f3187 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStore.cs @@ -12,9 +12,7 @@ internal sealed class MailStore( IFileSystem fileSystem, TimeProvider timeProvider, AgentDatabase database, - IAgentRegistry agentRegistry, - INitroInstanceIdProvider? instanceIdProvider = null, - IGlobalConfigDirectoryProvider? globalConfigDirectoryProvider = null) : IMailStore + IAgentStore agentStore) : IMailStore { private const string IdPrefix = "m-"; private const string IdAlphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; @@ -70,16 +68,17 @@ public async Task SendMessageAsync( var now = timeProvider.GetUtcNow(); var seed = $"{sender}|{subject}|{now:O}"; - // Registers the sender before the message transaction. - await agentRegistry.TouchAsync(sender, cancellationToken); + // Second line of defense behind the --actor resolver: a caller that reaches the + // store directly (a hook, the TUI) can still pass an unusable sender. + await EnsureAgentUsableAsync(sender, cancellationToken); - // Creates missing recipient identities before the message transaction. - var unregistered = await EnsureRecipientsAsync(recipients, cancellationToken); + // Refreshes the sender's presence before the message transaction. + await agentStore.TouchAsync(sender, cancellationToken); - // Resolves wake ownership before the message transaction. - var nitroInstanceId = creation.WakePolicy == MailWakePolicy.Enqueue - ? await ResolveNitroInstanceIdAsync(cancellationToken) - : null; + // Rejects the whole send when a recipient is unknown or deleted. + await EnsureRecipientsExistAsync(recipients, cancellationToken); + + var shouldEnqueueWake = creation.WakePolicy == MailWakePolicy.Enqueue; await using var connection = await ConnectAsync(cancellationToken); await using var transaction = await connection.BeginTransactionAsync(cancellationToken); @@ -122,9 +121,9 @@ INSERT INTO messages ( await InsertRecipientsAsync(connection, id, recipients, cancellationToken, transaction); - var wakeReceipts = nitroInstanceId is null - ? [] - : await EnqueueWakeAsync(connection, nitroInstanceId, recipients, now, cancellationToken, transaction); + var wakeReceipts = shouldEnqueueWake + ? await EnqueueWakeAsync(connection, recipients, now, cancellationToken, transaction) + : []; await transaction.CommitAsync(cancellationToken); @@ -138,7 +137,6 @@ INSERT INTO messages ( Body = creation.Body, CreatedAt = now, Recipients = recipients, - Unregistered = unregistered, WakeReceipts = wakeReceipts }; } @@ -160,16 +158,13 @@ public async Task ReplyMessageAsync( var actor = MailAgentName.Normalize(sender); var now = timeProvider.GetUtcNow(); - var (original, root, recipients) = + var (original, root, recipients, skipped) = await ResolveReplyAsync(inReplyToId, actor, cancellationToken); - // Registers the replying actor after participant validation. - await agentRegistry.TouchAsync(actor, cancellationToken); + // Refreshes the replying actor's presence after participant validation. + await agentStore.TouchAsync(actor, cancellationToken); - // Resolves wake ownership before the reply transaction. - var nitroInstanceId = wakePolicy == MailWakePolicy.Enqueue - ? await ResolveNitroInstanceIdAsync(cancellationToken) - : null; + var shouldEnqueueWake = wakePolicy == MailWakePolicy.Enqueue; await using var connection = await ConnectAsync(cancellationToken); await using var transaction = await connection.BeginTransactionAsync(cancellationToken); @@ -213,9 +208,9 @@ INSERT INTO messages ( await InsertRecipientsAsync(connection, id, recipients, cancellationToken, transaction); - var wakeReceipts = nitroInstanceId is null - ? [] - : await EnqueueWakeAsync(connection, nitroInstanceId, recipients, now, cancellationToken, transaction); + var wakeReceipts = shouldEnqueueWake + ? await EnqueueWakeAsync(connection, recipients, now, cancellationToken, transaction) + : []; await transaction.CommitAsync(cancellationToken); @@ -229,7 +224,8 @@ INSERT INTO messages ( Body = body, CreatedAt = now, Recipients = recipients, - WakeReceipts = wakeReceipts + WakeReceipts = wakeReceipts, + Skipped = skipped }; } @@ -259,15 +255,14 @@ public async Task TransferParticipationAsync( throw new ExitException($"Target agent '{target}' does not exist."); } - var senderMessageIds = (await connection.QueryAsync( - "SELECT id FROM messages WHERE sender = @source ORDER BY id", - new { source, cancellationToken }, - transaction)).ToArray(); - + // Only unread, unarchived recipient rows move; read or archived mail stays + // with the source, and a message's sender is never rewritten. var dropped = await connection.ExecuteAsync( """ DELETE FROM message_recipients AS source WHERE source.recipient = @source + AND source.read_at IS NULL + AND source.archived_at IS NULL AND EXISTS ( SELECT 1 FROM message_recipients AS target @@ -278,7 +273,11 @@ FROM message_recipients AS target transaction); var recipientMessageIds = (await connection.QueryAsync( - "SELECT message_id FROM message_recipients WHERE recipient = @source ORDER BY message_id", + """ + SELECT message_id FROM message_recipients + WHERE recipient = @source AND read_at IS NULL AND archived_at IS NULL + ORDER BY message_id + """, new { source, cancellationToken }, transaction)).ToArray(); @@ -287,55 +286,26 @@ FROM message_recipients AS target UPDATE message_recipients SET recipient = @target WHERE recipient = @source - """, - new { source, target, cancellationToken }, - transaction); - - var sendersMoved = await connection.ExecuteAsync( - """ - UPDATE messages - SET sender = @target - WHERE sender = @source + AND read_at IS NULL + AND archived_at IS NULL """, new { source, target, cancellationToken }, transaction); await transaction.CommitAsync(cancellationToken); - return new MailTransferResult(recipientsMoved, sendersMoved, dropped) + return new MailTransferResult(recipientsMoved, dropped) { - SenderMessageIds = senderMessageIds, RecipientMessageIds = recipientMessageIds }; } /// - /// Resolves this machine's Nitro instance id for a - /// send or reply. Throws - /// when this store was - /// constructed without the instance id and global config directory - /// providers requires. - /// - private async Task ResolveNitroInstanceIdAsync(CancellationToken cancellationToken) - { - if (instanceIdProvider is null || globalConfigDirectoryProvider is null) - { - throw new InvalidOperationException( - "MailWakePolicy.Enqueue requires this MailStore to be constructed with an " - + "INitroInstanceIdProvider and an IGlobalConfigDirectoryProvider."); - } - - return await instanceIdProvider.GetIdAsync(globalConfigDirectoryProvider.GetDirectory(), cancellationToken); - } - - /// - /// Advances each recipient's wake generation for the Nitro instance and returns - /// the resulting tokens in recipient order. Preserves the earlier due time - /// when wake work already exists. + /// Advances each recipient's wake generation and returns the resulting tokens + /// in recipient order. Preserves the earlier due time when wake work already exists. /// private static async Task> EnqueueWakeAsync( SqliteConnection connection, - string nitroInstanceId, IReadOnlyList recipients, DateTimeOffset now, CancellationToken cancellationToken, @@ -345,20 +315,22 @@ private static async Task> EnqueueWakeAsync( foreach (var recipient in recipients) { - var generation = await connection.QueryFirstOrDefaultAsync( + await using var command = connection.CreateCommand(); + command.Transaction = (SqliteTransaction)transaction; + command.CommandText = """ - INSERT INTO mail_wake_outbox ( - nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at - ) - VALUES (@nitroInstanceId, @actor, 1, 0, @now, @now) - ON CONFLICT (nitro_instance_id, actor) DO UPDATE SET + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES (@actor, 1, 0, @now, @now) + ON CONFLICT (actor) DO UPDATE SET requested_generation = requested_generation + 1, due_at = MIN(due_at, excluded.due_at), updated_at = excluded.updated_at RETURNING requested_generation - """, - new { nitroInstanceId, actor = recipient.Name, now, cancellationToken }, - transaction); + """; + command.Parameters.AddWithValue("@actor", recipient.Name); + command.Parameters.AddWithValue("@now", now); + + var generation = (long)(await command.ExecuteScalarAsync(cancellationToken))!; receipts.Add(new MailWakeReceipt { Actor = recipient.Name, Generation = generation }); } @@ -367,14 +339,16 @@ RETURNING requested_generation } /// - /// Returns the original message, thread root, and computed reply recipients. - /// Throws when the message is missing, the actor is not - /// a participant, or no recipients remain. + /// Returns the original message, thread root, computed reply recipients, and the + /// names dropped for being unknown or deleted. Throws + /// when the message is missing, the actor is not a participant or is unusable, a + /// lone remaining recipient is unusable, or every remaining recipient is unusable. /// - private async Task<(MailMessage Original, MailMessage Root, List Recipients)> ResolveReplyAsync( - string inReplyToId, - string actor, - CancellationToken cancellationToken) + private async Task<(MailMessage Original, MailMessage Root, List Recipients, IReadOnlyList Skipped)> + ResolveReplyAsync( + string inReplyToId, + string actor, + CancellationToken cancellationToken) { await using var connection = await ConnectAsync(cancellationToken); @@ -394,11 +368,15 @@ RETURNING requested_generation $"'{actor}' is not the sender or a recipient of '{inReplyToId}' and cannot reply to it."); } + // Second line of defense behind the --actor resolver: a caller that reaches the + // store directly (a hook, the TUI) can still pass an unusable actor. + await EnsureAgentUsableAsync(actor, cancellationToken); + var candidates = new List { original.Sender }; candidates.AddRange(original.Recipients.OrderBy(r => r.Ordinal).Select(r => r.Name)); var seen = new HashSet(StringComparer.Ordinal); - var recipients = new List(); + var candidateNames = new List(); foreach (var name in candidates) { @@ -407,24 +385,75 @@ RETURNING requested_generation continue; } - recipients.Add(new MailRecipient - { - Name = name, - Kind = MailRecipientKinds.To, - Ordinal = recipients.Count - }); + candidateNames.Add(name); } - if (recipients.Count == 0) + if (candidateNames.Count == 0) { throw new ExitException( $"Replying to '{inReplyToId}' as '{actor}' would leave no recipients."); } + var (recipients, skipped) = candidateNames.Count == 1 + ? await ResolveDirectReplyRecipientAsync(candidateNames[0], cancellationToken) + : await ResolveReplyAllRecipientsAsync(candidateNames, cancellationToken); + var root = await GetMessageAsync(connection, original.ThreadId, cancellationToken) ?? original; - return (original, root, recipients); + return (original, root, recipients, skipped); + } + + /// + /// Resolves a direct reply's single recipient, rejecting it outright with the same + /// message as an unusable send recipient rather than dropping it to no recipients. + /// + private async Task<(List Recipients, IReadOnlyList Skipped)> ResolveDirectReplyRecipientAsync( + string name, + CancellationToken cancellationToken) + { + await EnsureAgentUsableAsync(name, cancellationToken); + + return ([new MailRecipient { Name = name, Kind = MailRecipientKinds.To, Ordinal = 0 }], []); + } + + /// + /// Resolves a reply-all's recipients, dropping every unknown or deleted participant + /// and reporting the drops in Skipped. Throws when + /// every candidate is unusable. + /// + private async Task<(List Recipients, IReadOnlyList Skipped)> ResolveReplyAllRecipientsAsync( + IReadOnlyList candidateNames, + CancellationToken cancellationToken) + { + var recipients = new List(); + var skipped = new List<(string Name, bool WasDeleted)>(); + + foreach (var name in candidateNames) + { + var availability = await CheckParticipantAsync(name, cancellationToken); + + if (availability == MailParticipantAvailability.Usable) + { + recipients.Add(new MailRecipient + { + Name = name, + Kind = MailRecipientKinds.To, + Ordinal = recipients.Count + }); + } + else + { + skipped.Add((name, availability == MailParticipantAvailability.Deleted)); + } + } + + if (recipients.Count == 0) + { + throw ThrowHelper.NoReplyRecipientsRemaining(skipped); + } + + return (recipients, skipped.Select(s => s.Name).ToArray()); } public async Task GetMessageAsync( @@ -837,7 +866,15 @@ GROUP BY m.thread_id """, new { actor = normalizedActor, cancellationToken }); - return await BuildThreadSummariesAsync(connection, rollups, normalizedActor, cancellationToken); + return await BuildThreadSummariesAsync( + connection, + rollups, + normalizedActor, + preserveOrder: false, + lastMessagesByThreadId: null, + countsByThreadId: null, + recipientsByMessageId: null, + cancellationToken: cancellationToken); } public async Task> QueryInboxThreadsAsync( @@ -883,7 +920,15 @@ GROUP BY m.thread_id """, new { actor = normalizedActor, cancellationToken }); - return await BuildThreadSummariesAsync(connection, rollups, normalizedActor, cancellationToken); + return await BuildThreadSummariesAsync( + connection, + rollups, + normalizedActor, + preserveOrder: false, + lastMessagesByThreadId: null, + countsByThreadId: null, + recipientsByMessageId: null, + cancellationToken: cancellationToken); } public async Task> QuerySentThreadsAsync( @@ -908,7 +953,15 @@ GROUP BY m.thread_id """, new { actor = normalizedActor, cancellationToken }); - return await BuildThreadSummariesAsync(connection, rollups, normalizedActor, cancellationToken); + return await BuildThreadSummariesAsync( + connection, + rollups, + normalizedActor, + preserveOrder: false, + lastMessagesByThreadId: null, + countsByThreadId: null, + recipientsByMessageId: null, + cancellationToken: cancellationToken); } public async Task> QueryWorkspaceThreadsAsync( @@ -921,16 +974,14 @@ public async Task> QueryWorkspaceThreadsAsync( var rollups = normalizedAgent is null ? await connection.QueryAsync( - new CommandDefinition( - """ + """ SELECT thread_id AS ThreadId, COUNT(*) AS MessageCount, MAX(created_at) AS LastMessageAt FROM messages GROUP BY thread_id - """, - cancellationToken: cancellationToken)) + """) : await connection.QueryAsync( """ SELECT @@ -951,74 +1002,323 @@ GROUP BY m.thread_id new { agent = normalizedAgent, cancellationToken }); // Workspace summaries omit per-actor unread and archived counts. - return await BuildThreadSummariesAsync(connection, rollups, unreadActor: null, cancellationToken); + return await BuildThreadSummariesAsync( + connection, + rollups, + unreadActor: null, + preserveOrder: false, + lastMessagesByThreadId: null, + countsByThreadId: null, + recipientsByMessageId: null, + cancellationToken: cancellationToken); + } + + public async Task> QueryParticipationThreadsAsync( + string agent, + int? limit, + CancellationToken cancellationToken) + { + var normalizedAgent = MailAgentName.Normalize(agent); + + await using var connection = await ConnectAsync(cancellationToken); + + // Ranks threads by the agent's own newest sent-or-received message in the + // thread, not the thread's overall last message, so a later reply from + // someone else does not outrank the agent's own activity. + var rankSql = + """ + SELECT thread_id + FROM ( + SELECT thread_id, created_at FROM messages WHERE sender = @agent + UNION + SELECT m.thread_id, m.created_at + FROM messages m + JOIN message_recipients mr ON mr.message_id = m.id + WHERE mr.recipient = @agent + ) + GROUP BY thread_id + ORDER BY MAX(created_at) DESC, thread_id DESC + """; + + var rankParameters = new Dictionary { ["agent"] = normalizedAgent }; + + if (limit is { } value) + { + rankParameters["limit"] = value; + rankSql += " LIMIT @limit"; + } + + var rankedThreadIds = await ExecuteIdQueryAsync(connection, rankSql, rankParameters, cancellationToken); + + if (rankedThreadIds.Count == 0) + { + return []; + } + + // Thread ids are our own generated ids (never external input), so they are + // inlined directly into an IN-list rather than bound as a parameter: a dynamic + // thread count cannot be expanded by Dapper.AOT's compile-time query analysis. + var threadIdList = string.Join(", ", rankedThreadIds.Select(id => $"'{id.Replace("'", "''")}'")); + + // Reads the true message count and last-message time (any sender) for every + // ranked thread in a single IN-list query, unlike the ranking key above. + var rollupByThreadId = new Dictionary(); + + await using (var rollupCommand = connection.CreateCommand()) + { + rollupCommand.CommandText = + $""" + SELECT thread_id, COUNT(*), MAX(created_at) + FROM messages + WHERE thread_id IN ({threadIdList}) + GROUP BY thread_id + """; + + await using var reader = await rollupCommand.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + var row = new ThreadRollupRow + { + ThreadId = reader.GetString(0), + MessageCount = reader.GetInt32(1), + LastMessageAt = reader.GetString(2) + }; + + rollupByThreadId[row.ThreadId] = row; + } + } + + var rollups = rankedThreadIds.Select(id => rollupByThreadId[id]).ToList(); + + // Reads the last message for every ranked thread in a single windowed query + // instead of a LIMIT 1 query per thread. + var lastMessageByThreadId = new Dictionary(); + + await using (var lastMessageCommand = connection.CreateCommand()) + { + lastMessageCommand.CommandText = + $""" + SELECT id, thread_id, in_reply_to, sender, subject, body, created_at + FROM ( + SELECT *, ROW_NUMBER() OVER ( + PARTITION BY thread_id ORDER BY created_at DESC, id DESC + ) AS rn + FROM messages + WHERE thread_id IN ({threadIdList}) + ) + WHERE rn = 1 + """; + + await using var reader = await lastMessageCommand.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + var row = new MailMessageRow + { + Id = reader.GetString(0), + ThreadId = reader.GetString(1), + InReplyTo = reader.IsDBNull(2) ? null : reader.GetString(2), + Sender = reader.GetString(3), + Subject = reader.GetString(4), + Body = reader.GetString(5), + CreatedAt = reader.GetString(6) + }; + + lastMessageByThreadId[row.ThreadId] = row; + } + } + + // Reads per-agent unread and archived counts for every ranked thread in a single + // grouped query instead of two COUNT(*) queries per thread. + var countsByThreadId = new Dictionary(); + + await using (var countsCommand = connection.CreateCommand()) + { + countsCommand.CommandText = + $""" + SELECT + m.thread_id, + SUM(CASE WHEN mr.read_at IS NULL THEN 1 ELSE 0 END), + SUM(CASE WHEN mr.archived_at IS NOT NULL THEN 1 ELSE 0 END) + FROM message_recipients mr + JOIN messages m ON m.id = mr.message_id + WHERE mr.recipient = @agent AND m.thread_id IN ({threadIdList}) + GROUP BY m.thread_id + """; + + countsCommand.Parameters.AddWithValue("@agent", normalizedAgent); + + await using var reader = await countsCommand.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + countsByThreadId[reader.GetString(0)] = (reader.GetInt32(1), reader.GetInt32(2)); + } + } + + // Reads the recipients of every ranked thread's last message in a single query + // instead of one query per thread. + var recipientNamesByMessageId = new Dictionary>(); + + if (lastMessageByThreadId.Count > 0) + { + var lastMessageIdList = string.Join( + ", ", + lastMessageByThreadId.Values.Select(m => $"'{m.Id.Replace("'", "''")}'")); + + await using var recipientsCommand = connection.CreateCommand(); + + recipientsCommand.CommandText = + $""" + SELECT message_id AS MessageId, {MailRecipient.Columns} + FROM message_recipients + WHERE message_id IN ({lastMessageIdList}) + ORDER BY message_id, ordinal + """; + + await using var reader = await recipientsCommand.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + var messageId = reader.GetString(0); + var name = reader.GetString(1); + + if (!recipientNamesByMessageId.TryGetValue(messageId, out var names)) + { + names = []; + recipientNamesByMessageId[messageId] = names; + } + + names.Add(name); + } + } + + var recipientsByMessageId = recipientNamesByMessageId.ToDictionary( + entry => entry.Key, + entry => (IReadOnlyList)entry.Value); + + return await BuildThreadSummariesAsync( + connection, + rollups, + normalizedAgent, + preserveOrder: true, + lastMessagesByThreadId: lastMessageByThreadId, + countsByThreadId: countsByThreadId, + recipientsByMessageId: recipientsByMessageId, + cancellationToken: cancellationToken); } /// - /// Returns thread summaries ordered by last-message time and thread id, newest first. - /// Unread and archived counts are null when is null. + /// Builds thread summaries from , ordered by last-message time + /// and thread id newest first, or in rollup order when is + /// true. , , and + /// each supply their per-thread data when non-null; + /// unread and archived counts are null when is null. /// private static async Task> BuildThreadSummariesAsync( SqliteConnection connection, IEnumerable rollups, string? unreadActor, + bool preserveOrder, + IReadOnlyDictionary? lastMessagesByThreadId, + IReadOnlyDictionary? countsByThreadId, + IReadOnlyDictionary>? recipientsByMessageId, CancellationToken cancellationToken) { var summaries = new List(); foreach (var rollup in rollups) { - var root = await connection.QueryFirstOrDefaultAsync( - $"SELECT {MailMessage.Columns} FROM messages WHERE id = @id", - new { id = rollup.ThreadId, cancellationToken }); + string subject; + MailMessageRow? lastMessage; - var lastMessage = await connection.QueryFirstOrDefaultAsync( - $""" - SELECT {MailMessage.Columns} FROM messages - WHERE thread_id = @threadId - ORDER BY created_at DESC, id DESC - LIMIT 1 - """, - new { threadId = rollup.ThreadId, cancellationToken }); + if (lastMessagesByThreadId is not null) + { + lastMessagesByThreadId.TryGetValue(rollup.ThreadId, out lastMessage); + subject = lastMessage?.Subject ?? ""; + } + else + { + var root = await connection.QueryFirstOrDefaultAsync( + $"SELECT {MailMessage.Columns} FROM messages WHERE id = @id", + new { id = rollup.ThreadId, cancellationToken }); + + lastMessage = await connection.QueryFirstOrDefaultAsync( + $""" + SELECT {MailMessage.Columns} FROM messages + WHERE thread_id = @threadId + ORDER BY created_at DESC, id DESC + LIMIT 1 + """, + new { threadId = rollup.ThreadId, cancellationToken }); + + subject = root?.Subject ?? ""; + } - IReadOnlyList lastRecipients = lastMessage is null - ? [] - : (await GetRecipientsAsync(connection, lastMessage.Id, cancellationToken)) + IReadOnlyList lastRecipients; + + if (lastMessage is null) + { + lastRecipients = []; + } + else if (recipientsByMessageId is not null) + { + lastRecipients = recipientsByMessageId.TryGetValue(lastMessage.Id, out var names) + ? names + : []; + } + else + { + lastRecipients = (await GetRecipientsAsync(connection, lastMessage.Id, cancellationToken)) .Select(r => r.Name) .ToArray(); + } int? unreadCount = null; int? archivedCount = null; if (unreadActor is not null) { - unreadCount = await connection.ExecuteScalarAsync( - """ - SELECT COUNT(*) - FROM message_recipients mr - JOIN messages m ON m.id = mr.message_id - WHERE m.thread_id = @threadId - AND mr.recipient = @actor - AND mr.read_at IS NULL - """, - new { threadId = rollup.ThreadId, actor = unreadActor, cancellationToken }); - - archivedCount = await connection.ExecuteScalarAsync( - """ - SELECT COUNT(*) - FROM message_recipients mr - JOIN messages m ON m.id = mr.message_id - WHERE m.thread_id = @threadId - AND mr.recipient = @actor - AND mr.archived_at IS NOT NULL - """, - new { threadId = rollup.ThreadId, actor = unreadActor, cancellationToken }); + if (countsByThreadId is not null) + { + var (unread, archived) = countsByThreadId.TryGetValue(rollup.ThreadId, out var counts) + ? counts + : (0, 0); + + unreadCount = unread; + archivedCount = archived; + } + else + { + unreadCount = await connection.ExecuteScalarAsync( + """ + SELECT COUNT(*) + FROM message_recipients mr + JOIN messages m ON m.id = mr.message_id + WHERE m.thread_id = @threadId + AND mr.recipient = @actor + AND mr.read_at IS NULL + """, + new { threadId = rollup.ThreadId, actor = unreadActor, cancellationToken }); + + archivedCount = await connection.ExecuteScalarAsync( + """ + SELECT COUNT(*) + FROM message_recipients mr + JOIN messages m ON m.id = mr.message_id + WHERE m.thread_id = @threadId + AND mr.recipient = @actor + AND mr.archived_at IS NOT NULL + """, + new { threadId = rollup.ThreadId, actor = unreadActor, cancellationToken }); + } } summaries.Add(new MailThreadSummary { ThreadId = rollup.ThreadId, - Subject = root?.Subject ?? "", + Subject = subject, MessageCount = rollup.MessageCount, LastMessageAt = DateTimeOffset.Parse(rollup.LastMessageAt, CultureInfo.InvariantCulture), LastSender = lastMessage?.Sender ?? "", @@ -1029,6 +1329,11 @@ AND mr.archived_at IS NOT NULL }); } + if (preserveOrder) + { + return summaries; + } + return summaries .OrderByDescending(s => s.LastMessageAt) .ThenByDescending(s => s.ThreadId, StringComparer.Ordinal) @@ -1191,28 +1496,55 @@ private static List BuildRecipients( } /// - /// Ensures every recipient has an agent row, implicit-creating one for - /// any name that has never registered or acted, and returns the names, - /// in recipient order, whose row is implicit, whether it already was or - /// was just created here. + /// Fails the whole send when a to or cc recipient does not exist or was deleted. + /// Checks recipients in order and throws for the + /// first offending name. /// - private async Task> EnsureRecipientsAsync( + private async Task EnsureRecipientsExistAsync( IReadOnlyList recipients, CancellationToken cancellationToken) { - var unregistered = new List(); - foreach (var recipient in recipients) { - var agent = await agentRegistry.EnsureImplicitAsync(recipient.Name, cancellationToken); + await EnsureAgentUsableAsync(recipient.Name, cancellationToken); + } + } + + /// + /// Throws when the named agent does not exist or was + /// deleted, using the same messages as a rejected send recipient. + /// + private async Task EnsureAgentUsableAsync(string name, CancellationToken cancellationToken) + { + var agent = await agentStore.FindAsync(name, cancellationToken); + + if (agent is null) + { + throw ThrowHelper.UnknownMailRecipient(name); + } - if (agent.Implicit) - { - unregistered.Add(recipient.Name); - } + if (agent.IsDeleted) + { + throw ThrowHelper.DeletedMailRecipient(name); + } + } + + /// + /// Classifies the named agent as usable, unknown, or deleted, without throwing, + /// for callers that drop rather than reject an unusable participant. + /// + private async Task CheckParticipantAsync( + string name, + CancellationToken cancellationToken) + { + var agent = await agentStore.FindAsync(name, cancellationToken); + + if (agent is null) + { + return MailParticipantAvailability.Unknown; } - return unregistered; + return agent.IsDeleted ? MailParticipantAvailability.Deleted : MailParticipantAvailability.Usable; } private static async Task InsertRecipientsAsync( @@ -1299,6 +1631,16 @@ private static string CreateIdSuffix(string seed, long messageCount, int attempt private static string EscapeLikeText(string value) => value.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_"); + /// + /// Whether a reply-all participant is usable, unknown, or deleted. + /// + private enum MailParticipantAvailability + { + Usable, + Unknown, + Deleted + } + internal sealed class MailMessageRow { public required string Id { get; init; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStoreSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStoreSchema.cs index bbdaec72e4a..a3fc6c73b79 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStoreSchema.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailStoreSchema.cs @@ -11,7 +11,7 @@ CREATE TABLE IF NOT EXISTS messages ( id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, in_reply_to TEXT REFERENCES messages (id), - sender TEXT NOT NULL REFERENCES agents (name), + sender TEXT NOT NULL, subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 500), body TEXT NOT NULL, created_at TEXT NOT NULL @@ -23,7 +23,7 @@ created_at TEXT NOT NULL CREATE TABLE IF NOT EXISTS message_recipients ( message_id TEXT NOT NULL REFERENCES messages (id) ON DELETE CASCADE, - recipient TEXT NOT NULL REFERENCES agents (name), + recipient TEXT NOT NULL, kind TEXT NOT NULL DEFAULT 'to' CHECK (kind IN ('to', 'cc')), ordinal INTEGER NOT NULL CHECK (ordinal >= 0), read_at TEXT, diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailTransferResult.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailTransferResult.cs index 2306ed7117f..561a2912804 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailTransferResult.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Mail/MailTransferResult.cs @@ -2,10 +2,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Mail; internal sealed record MailTransferResult( int RecipientsMoved, - int SendersMoved, int Dropped) { - public IReadOnlyList SenderMessageIds { get; init; } = []; - public IReadOnlyList RecipientMessageIds { get; init; } = []; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/IMemoryStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/IMemoryStore.cs index 5bd6c8156f9..be770646c71 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/IMemoryStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/IMemoryStore.cs @@ -117,4 +117,13 @@ Task PromoteAsync( string type, IReadOnlyList tags, CancellationToken cancellationToken); + + /// + /// Returns the curated memories and journal entries the given agent created, + /// a promoted journal entry appearing once, as the curated memory. Ordered by + /// created_at descending, then id, up to the given limit (unlimited when + /// null). + /// + Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryParticipationEntry.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryParticipationEntry.cs new file mode 100644 index 00000000000..5bb7db47887 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryParticipationEntry.cs @@ -0,0 +1,23 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Memory; + +/// +/// Distinguishes a curated memory from a journal entry in a participation result. +/// +internal enum MemoryParticipationKind +{ + Curated, + Journal +} + +/// +/// A curated memory or journal entry an agent created. A journal entry that was +/// promoted to a curated memory is represented once, as the curated memory; a +/// journal entry has a null and empty . +/// +internal sealed record MemoryParticipationEntry( + MemoryParticipationKind Kind, + string Id, + string? Type, + IReadOnlyList Tags, + string Body, + DateTimeOffset CreatedAt); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStore.cs index 7b708c96051..5fe4c5ab241 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStore.cs @@ -171,36 +171,50 @@ WHERE memory_curated_fts MATCH @match sql += "\n AND c.type = @type"; } - if (since is { } minimum) + if (since is not null) { - _ = minimum; sql += "\n AND c.updated_at >= @since"; } - foreach (var (tag, index) in normalizedTags.Select((tag, index) => (tag, index))) + for (var index = 0; index < normalizedTags.Count; index++) { - _ = tag; sql += "\n AND EXISTS (SELECT 1 FROM memory_curated_tags t " + $"WHERE t.id = c.id AND t.tag = @tag{index})"; } sql += "\nORDER BY f.rank, c.updated_at DESC, c.id\nLIMIT @limit;"; - var parameters = new DynamicParameters(); - parameters.Add("match", match); - parameters.Add("type", normalizedType); - parameters.Add("since", since); - parameters.Add("limit", limit ?? -1); + await using var command = connection.CreateCommand(); + command.CommandText = sql; + command.Parameters.AddWithValue("@match", match); + command.Parameters.AddWithValue("@limit", limit ?? -1); + + if (normalizedType is not null) + { + command.Parameters.AddWithValue("@type", normalizedType); + } + + if (since is { } minimum) + { + command.Parameters.AddWithValue("@since", minimum); + } for (var index = 0; index < normalizedTags.Count; index++) { - parameters.Add($"tag{index}", normalizedTags[index]); + command.Parameters.AddWithValue($"@tag{index}", normalizedTags[index]); } - var ids = await connection.QueryAsync( - new CommandDefinition(sql, parameters, cancellationToken: cancellationToken)); + var ids = new List(); - return await LoadCuratedAsync(connection, ids.ToList()); + await using (var reader = await command.ExecuteReaderAsync(cancellationToken)) + { + while (await reader.ReadAsync(cancellationToken)) + { + ids.Add(reader.GetString(0)); + } + } + + return await LoadCuratedAsync(connection, ids); } public async Task LogAsync( @@ -306,12 +320,10 @@ public async Task PromoteAsync( await using var transaction = await connection.BeginTransactionAsync(cancellationToken); var entry = await connection.QueryFirstOrDefaultAsync( - new CommandDefinition( - "SELECT id AS Id, body AS Body, created_at AS CreatedAt, created_by AS CreatedBy " + "SELECT id AS Id, body AS Body, created_at AS CreatedAt, created_by AS CreatedBy " + "FROM memory_journal WHERE id = @journalId;", new { journalId }, - transaction, - cancellationToken: cancellationToken)) + transaction) ?? throw new ExitException($"Journal entry '{journalId}' does not exist."); var id = MemoryPromotedId.Derive(journalId); @@ -342,6 +354,46 @@ INSERT OR IGNORE INTO memory_curated ( return new MemoryPromotionOutcome(record, AlreadyPromoted: false); } + public async Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + { + await using var connection = await ConnectAsync(cancellationToken); + + var rows = await connection.QueryAsync( + """ + SELECT id AS Id, 'curated' AS Kind, created_at AS CreatedAt + FROM memory_curated + WHERE created_by = @agent + UNION ALL + SELECT j.id AS Id, 'journal' AS Kind, j.created_at AS CreatedAt + FROM memory_journal j + WHERE j.created_by = @agent + AND NOT EXISTS (SELECT 1 FROM memory_curated c WHERE c.promoted_from = j.id) + ORDER BY CreatedAt DESC, Id + LIMIT @limit; + """, + new { agent, limit = limit ?? -1 }); + + var ordered = rows.ToList(); + var curatedIds = ordered.Where(row => row.Kind == "curated").Select(row => row.Id).ToList(); + var journalIds = ordered.Where(row => row.Kind == "journal").Select(row => row.Id).ToList(); + + var curatedById = (await LoadCuratedAsync(connection, curatedIds)).ToDictionary(record => record.Id); + var journalById = (await LoadJournalAsync(connection, journalIds)).ToDictionary(entry => entry.Id); + + return ordered + .Select(row => row.Kind == "curated" + ? ToParticipationEntry(curatedById[row.Id]) + : ToParticipationEntry(journalById[row.Id])) + .ToList(); + } + + private static MemoryParticipationEntry ToParticipationEntry(MemoryRecord record) => new( + MemoryParticipationKind.Curated, record.Id, record.Type, record.Tags, record.Body, record.CreatedAt); + + private static MemoryParticipationEntry ToParticipationEntry(MemoryJournalEntry entry) => new( + MemoryParticipationKind.Journal, entry.Id, Type: null, Tags: [], entry.Body, entry.CreatedAt); + private static async Task InsertTagsAsync( SqliteConnection connection, DbTransaction transaction, @@ -389,34 +441,80 @@ private static async Task> LoadCuratedAsync( return ids.Where(byId.ContainsKey).Select(id => byId[id]).ToList(); } + /// + /// Returns journal entries for the supplied ids, omitting missing entries. + /// Empty input returns an empty result. + /// + private static async Task> LoadJournalAsync( + SqliteConnection connection, + IReadOnlyList ids) + { + if (ids.Count == 0) + { + return []; + } + + var idList = string.Join(", ", ids.Select(id => $"'{MemoryId.Require(id)}'")); + + var rows = await connection.QueryAsync( + "SELECT id AS Id, body AS Body, created_at AS CreatedAt, created_by AS CreatedBy " + + $"FROM memory_journal WHERE id IN ({idList});"); + + return rows.Select(row => row.ToEntry()).ToList(); + } + private static async Task FindCuratedAsync( SqliteConnection connection, DbTransaction? transaction, string id, CancellationToken cancellationToken) { - var row = await connection.QueryFirstOrDefaultAsync( - new CommandDefinition( - "SELECT id AS Id, type AS Type, body AS Body, created_at AS CreatedAt, " - + "updated_at AS UpdatedAt, created_by AS CreatedBy, promoted_from AS PromotedFrom " - + "FROM memory_curated WHERE id = @id;", - new { id }, - transaction, - cancellationToken: cancellationToken)); + await using var command = connection.CreateCommand(); + command.Transaction = (SqliteTransaction?)transaction; + command.CommandText = + "SELECT id, type, body, created_at, updated_at, created_by, promoted_from " + + "FROM memory_curated WHERE id = @id;"; + command.Parameters.AddWithValue("@id", id); + + CuratedRow? row; + + await using (var reader = await command.ExecuteReaderAsync(cancellationToken)) + { + row = await reader.ReadAsync(cancellationToken) + ? new CuratedRow + { + Id = reader.GetString(0), + Type = reader.GetString(1), + Body = reader.GetString(2), + CreatedAt = reader.GetString(3), + UpdatedAt = reader.GetString(4), + CreatedBy = reader.GetString(5), + PromotedFrom = reader.IsDBNull(6) ? null : reader.GetString(6) + } + : null; + } if (row is null) { return null; } - var tags = await connection.QueryAsync( - new CommandDefinition( - "SELECT tag FROM memory_curated_tags WHERE id = @id ORDER BY tag;", - new { id }, - transaction, - cancellationToken: cancellationToken)); + var tags = new List(); + + await using var tagsCommand = connection.CreateCommand(); + tagsCommand.Transaction = (SqliteTransaction?)transaction; + tagsCommand.CommandText = "SELECT tag FROM memory_curated_tags WHERE id = @id ORDER BY tag;"; + tagsCommand.Parameters.AddWithValue("@id", id); + + await using (var reader = await tagsCommand.ExecuteReaderAsync(cancellationToken)) + { + while (await reader.ReadAsync(cancellationToken)) + { + tags.Add(reader.GetString(0)); + } + } - return row.ToRecord(tags.ToArray()); + return row.ToRecord(tags); } private static async Task FindPromotedAsync( @@ -426,11 +524,9 @@ private static async Task FindPromotedAsync( CancellationToken cancellationToken) { var id = await connection.QueryFirstAsync( - new CommandDefinition( - "SELECT id FROM memory_curated WHERE promoted_from = @journalId;", + "SELECT id FROM memory_curated WHERE promoted_from = @journalId;", new { journalId }, - transaction, - cancellationToken: cancellationToken)); + transaction); return (await FindCuratedAsync(connection, transaction, id, cancellationToken))!; } @@ -515,7 +611,14 @@ private static string ValidateActor(string actor) return trimmed; } - private sealed class JournalRow + internal sealed class ParticipationRow + { + public required string Id { get; init; } + public required string Kind { get; init; } + public required string CreatedAt { get; init; } + } + + internal sealed class JournalRow { public required string Id { get; init; } public required string Body { get; init; } @@ -531,13 +634,13 @@ private sealed class JournalRow }; } - private sealed class CuratedTagRow + internal sealed class CuratedTagRow { public required string Id { get; init; } public required string Tag { get; init; } } - private sealed class CuratedRow + internal sealed class CuratedRow { public required string Id { get; init; } public required string Type { get; init; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStoreSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStoreSchema.cs index 0845bf55026..f51fa82eb8f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStoreSchema.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Memory/MemoryStoreSchema.cs @@ -16,6 +16,7 @@ created_by TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_memory_journal_created_at ON memory_journal (created_at); + CREATE INDEX IF NOT EXISTS idx_memory_journal_created_by ON memory_journal (created_by); CREATE TABLE IF NOT EXISTS memory_curated ( id TEXT PRIMARY KEY, @@ -32,6 +33,7 @@ promoted_from TEXT CREATE INDEX IF NOT EXISTS idx_memory_curated_updated_at ON memory_curated (updated_at); CREATE INDEX IF NOT EXISTS idx_memory_curated_type ON memory_curated (type); + CREATE INDEX IF NOT EXISTS idx_memory_curated_created_by ON memory_curated (created_by); CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_curated_promoted_from ON memory_curated (promoted_from) WHERE promoted_from IS NOT NULL; diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeDispatcher.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeDispatcher.cs index a93d1422bf4..1db35d044df 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeDispatcher.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeDispatcher.cs @@ -6,34 +6,28 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// -/// Dispatches one actor's outstanding wake work to at most one coding session. +/// Dispatches one actor's outstanding wake work to the actor's own agent row. /// Returns null when no batch can be claimed and leaves unresolved work pending for retry. /// internal sealed class ActorWakeDispatcher( IMailWakeBatchStore batchStore, - IAgentSessionRegistry sessionRegistry, + IAgentStore agentStore, ISessionGateCoordinator gateCoordinator, IPingSessionExecutor executor, IMailStore mailStore, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider, TimeProvider timeProvider) : IActorWakeDispatcher { public async Task DispatchAsync( - string actor, DateTimeOffset deadline, CancellationToken cancellationToken) + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) { var normalizedActor = MailAgentName.Normalize(actor); - var nitroInstanceId = await instanceIdProvider.GetIdAsync( - globalConfigDirectoryProvider.GetDirectory(), cancellationToken); - - var candidates = await ResolveCandidatesAsync(normalizedActor, cancellationToken); var now = timeProvider.GetUtcNow(); - var ownerId = $"dispatcher-{Guid.NewGuid():N}"; + var ownerId = leaderToken; var batchAttemptId = $"batch-{Guid.NewGuid():N}"; var claim = await batchStore.TryClaimAsync( - nitroInstanceId, normalizedActor, ownerId, batchAttemptId, candidates, now, + normalizedActor, ownerId, batchAttemptId, [normalizedActor], now, WakeDispatchPolicy.BatchLeaseDuration, cancellationToken); if (claim is null) @@ -41,12 +35,6 @@ internal sealed class ActorWakeDispatcher( return null; } - if (claim.Targets.Count == 0) - { - await batchStore.TryCompleteAsync(claim.BatchId, ownerId, batchAttemptId, now, cancellationToken); - return new ActorWakeReceipt(normalizedActor, MailWakeTargetStatus.Skipped, []); - } - var unread = await mailStore.CountUnreadAsync(normalizedActor, cancellationToken); if (unread == 0) @@ -59,19 +47,6 @@ internal sealed class ActorWakeDispatcher( normalizedActor, claim, ownerId, batchAttemptId, deadline, cancellationToken); } - private async Task> ResolveCandidatesAsync( - string actor, CancellationToken cancellationToken) - { - var sessions = await sessionRegistry.FindLiveClaimedByAgentNameAsync(actor, cancellationToken); - - return sessions - .Where(s => s.Harness != AgentSessionHarness.NitroBoard) - .OrderByDescending(s => s.LastBeatAt) - .Take(1) - .Select(s => new AgentSessionGeneration(s.Harness, s.SessionId, s.Host)) - .ToList(); - } - private async Task CompleteAlreadyReadAsync( string actor, MailWakeBatchClaim claim, @@ -120,7 +95,6 @@ private async Task DispatchTargetsAsync( claim.BatchId, ownerId, batchAttemptId, - actor, claim.Targets.Single(), claim.ClaimedGeneration, batchDeadline, @@ -210,8 +184,7 @@ private async Task DispatchTargetAsync( string batchId, string ownerId, string batchAttemptId, - string actor, - AgentSessionGeneration target, + string target, long claimedGeneration, DateTimeOffset batchDeadline, CancellationToken dispatchToken, @@ -219,32 +192,49 @@ private async Task DispatchTargetAsync( { try { - var session = await sessionRegistry.FindByGenerationAsync(target, dispatchToken); + var row = await agentStore.FindAsync(target, dispatchToken); + + if (row is null) + { + return await RecordSkippedAsync(batchId, target, ownerId, batchAttemptId, "offline"); + } + + if (row.EndedAt is not null) + { + return await RecordSkippedAsync(batchId, target, ownerId, batchAttemptId, "ended"); + } - if (session is null) + var state = AgentStateResolver.Resolve(row, timeProvider.GetUtcNow()); + + if (state == AgentState.Offline) { - return await RecordFailureAsync(batchId, target, ownerId, batchAttemptId, "session-gone"); + return await RecordSkippedAsync(batchId, target, ownerId, batchAttemptId, "offline"); } - if (session.EndpointKind == AgentSessionEndpointKind.None) + if (state == AgentState.Unreachable) { - return await RecordFailureAsync(batchId, target, ownerId, batchAttemptId, "no-endpoint"); + return await RecordSkippedAsync(batchId, target, ownerId, batchAttemptId, "unreachable"); } - if (session.EndpointKind is AgentSessionEndpointKind.DbWatch - or AgentSessionEndpointKind.CopilotExtension) + if (row.EndpointKind is AgentSessionEndpointKind.DbWatch or AgentSessionEndpointKind.CopilotExtension) { // Database-watching endpoints require no direct transport. return await RecordDeliveredAsync(batchId, target, ownerId, batchAttemptId, claimedGeneration); } - if (session.EndpointKind is not AgentSessionEndpointKind.ClaudePeer + if (row.EndpointKind is not AgentSessionEndpointKind.ClaudePeer and not AgentSessionEndpointKind.CodexThread and not AgentSessionEndpointKind.OpencodeServer) { return await RecordFailureAsync(batchId, target, ownerId, batchAttemptId, "unsupported"); } + if (row.EndpointKind is AgentSessionEndpointKind.ClaudePeer or AgentSessionEndpointKind.OpencodeServer + && row.SessionId is null) + { + return await RecordSkippedAsync(batchId, target, ownerId, batchAttemptId, "unreachable"); + } + var now = timeProvider.GetUtcNow(); var pingAttemptId = MemoryId.New(now); var reservation = await gateCoordinator.TryReserveAsync(target, pingAttemptId, now, dispatchToken); @@ -262,23 +252,23 @@ and not AgentSessionEndpointKind.CodexThread try { - if (session.EndpointKind == AgentSessionEndpointKind.OpencodeServer - && !await sessionRegistry.ClaimIdlePushAsync(target, dispatchToken)) + if (row.EndpointKind == AgentSessionEndpointKind.OpencodeServer + && !await agentStore.ClaimIdlePushAsync(target, dispatchToken)) { - // An unarmed session remains pending for a later attempt. + // An unarmed agent remains pending for a later attempt. return await RecordOfferedAsync( batchId, target, ownerId, batchAttemptId, claimedGeneration, "idle-not-armed"); } - if (session.EndpointKind == AgentSessionEndpointKind.OpencodeServer) + if (row.EndpointKind == AgentSessionEndpointKind.OpencodeServer) { - // This attempt holds the session's idle-push claim. + // This attempt holds the agent's idle-push claim. idlePushClaimed = true; } // Claims the ping attempt; no transport runs if the claim fails. - var stamped = await sessionRegistry.TryClaimPingCooldownAsync( - session, pingAttemptId, now, TimeSpan.Zero, dispatchToken); + var stamped = await agentStore.TryClaimPingCooldownAsync( + target, TimeSpan.Zero, pingAttemptId, dispatchToken); if (!stamped) { @@ -287,27 +277,25 @@ and not AgentSessionEndpointKind.CodexThread var attemptDeadline = ClampDeadline(now, batchDeadline); - var outcome = session.EndpointKind switch + var outcome = (row.EndpointKind, row.SessionId) switch { - AgentSessionEndpointKind.ClaudePeer => await executor.ExecuteClaudePeerAsync( - session.Harness, session.SessionId, actor, pingAttemptId, held.Slot, + (AgentSessionEndpointKind.ClaudePeer, { } sessionId) => await executor.ExecuteClaudePeerAsync( + target, sessionId, pingAttemptId, held.Slot, attemptDeadline, dispatchToken), + (AgentSessionEndpointKind.CodexThread, _) => await executor.ExecuteCodexThreadAsync( + target, row.EndpointAddr, pingAttemptId, held.Slot, attemptDeadline, dispatchToken), + (AgentSessionEndpointKind.OpencodeServer, { } sessionId) => await executor.ExecuteOpencodeServerAsync( + target, sessionId, row.EndpointAddr, row.EndpointSecret, pingAttemptId, held.Slot, attemptDeadline, dispatchToken), - AgentSessionEndpointKind.CodexThread => await executor.ExecuteCodexThreadAsync( - session.Harness, session.SessionId, actor, session.EndpointAddr, pingAttemptId, held.Slot, - attemptDeadline, dispatchToken), - AgentSessionEndpointKind.OpencodeServer => await executor.ExecuteOpencodeServerAsync( - session.Harness, session.SessionId, actor, session.EndpointAddr, session.EndpointSecret, - pingAttemptId, held.Slot, attemptDeadline, dispatchToken), _ => throw new UnreachableException( - $"Endpoint kind '{session.EndpointKind}' passed the earlier supported-kind guard.") + $"Endpoint kind '{row.EndpointKind}' passed the earlier supported-kind guard.") }; - if (session.EndpointKind == AgentSessionEndpointKind.OpencodeServer + if (row.EndpointKind == AgentSessionEndpointKind.OpencodeServer && (outcome.Reason != PingAttemptReason.Ok || outcome.Detail == PingSessionExecutor.HealthOnlyDetail)) { // An unsuccessful push or health-only check restores the idle-push claim. - await sessionRegistry.RearmIdlePushAsync(target, CancellationToken.None); + await agentStore.RearmIdlePushAsync(target, CancellationToken.None); } idlePushSettled = true; @@ -336,7 +324,7 @@ and not AgentSessionEndpointKind.CodexThread if (idlePushClaimed && !idlePushSettled) { // An interrupted attempt restores the idle-push claim. - await sessionRegistry.RearmIdlePushAsync(target, CancellationToken.None); + await agentStore.RearmIdlePushAsync(target, CancellationToken.None); } // Reservation cleanup continues after dispatch cancellation. @@ -351,7 +339,7 @@ and not AgentSessionEndpointKind.CodexThread } private async Task RecordDeliveredAsync( - string batchId, AgentSessionGeneration target, string ownerId, string attemptId, long claimedGeneration) + string batchId, string target, string ownerId, string attemptId, long claimedGeneration) { var recorded = await batchStore.TryRecordTargetOutcomeAsync( batchId, target, ownerId, attemptId, MailWakeTargetStatus.Delivered, @@ -364,7 +352,7 @@ private async Task RecordDeliveredAsync( } private async Task RecordFailureAsync( - string batchId, AgentSessionGeneration target, string ownerId, string attemptId, string reason) + string batchId, string target, string ownerId, string attemptId, string reason) { var recorded = await batchStore.TryRecordTargetOutcomeAsync( batchId, target, ownerId, attemptId, MailWakeTargetStatus.Failed, @@ -376,8 +364,21 @@ private async Task RecordFailureAsync( : new ActorWakeTargetReceipt(target, MailWakeTargetStatus.Pending, null, null, null); } + private async Task RecordSkippedAsync( + string batchId, string target, string ownerId, string attemptId, string reason) + { + var recorded = await batchStore.TryRecordTargetOutcomeAsync( + batchId, target, ownerId, attemptId, MailWakeTargetStatus.Skipped, + offeredGeneration: null, acceptedGeneration: null, lastError: reason, + timeProvider.GetUtcNow(), CancellationToken.None); + + return recorded + ? new ActorWakeTargetReceipt(target, MailWakeTargetStatus.Skipped, null, null, reason) + : new ActorWakeTargetReceipt(target, MailWakeTargetStatus.Pending, null, null, null); + } + private async Task RecordOfferedAsync( - string batchId, AgentSessionGeneration target, string ownerId, string attemptId, + string batchId, string target, string ownerId, string attemptId, long claimedGeneration, string reason) { var recorded = await batchStore.TryRecordTargetOutcomeAsync( diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeTargetReceipt.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeTargetReceipt.cs index e9828d15b94..916af6875b5 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeTargetReceipt.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ActorWakeTargetReceipt.cs @@ -1,5 +1,3 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// @@ -7,7 +5,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// An outcome that could not be recorded is reported as pending with null generations and diagnostic. /// internal sealed record ActorWakeTargetReceipt( - AgentSessionGeneration Target, + string Target, string Status, long? OfferedGeneration, long? AcceptedGeneration, diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IActorWakeDispatcher.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IActorWakeDispatcher.cs index a7a062a1a40..9342324c75a 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IActorWakeDispatcher.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IActorWakeDispatcher.cs @@ -8,9 +8,10 @@ internal interface IActorWakeDispatcher { /// /// Dispatches the actor's pending wake work within the supplied transport deadline, - /// returning null when no batch can be claimed. Transport outcomes are recorded - /// without propagating transport failures; caller cancellation and workspace or - /// storage failures propagate. + /// fencing every batch write on the caller's leader lease token, and returns null + /// when no batch can be claimed. Transport outcomes are recorded without propagating + /// transport failures; caller cancellation and workspace or storage failures propagate. /// - Task DispatchAsync(string actor, DateTimeOffset deadline, CancellationToken cancellationToken); + Task DispatchAsync( + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IPingSessionExecutor.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IPingSessionExecutor.cs index 427df8debf4..dab59c6dcd5 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IPingSessionExecutor.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/IPingSessionExecutor.cs @@ -12,8 +12,6 @@ internal interface IPingSessionExecutor /// failures return an outcome, with best-effort recording and lease release. /// Task ExecuteCodexThreadAsync( - string harness, - string sessionId, string actorName, string endpointAddr, string attemptId, @@ -26,9 +24,8 @@ Task ExecuteCodexThreadAsync( /// best-effort cleanup contract of . /// Task ExecuteClaudePeerAsync( - string harness, - string sessionId, string actorName, + string sessionId, string attemptId, int slot, DateTimeOffset deadline, @@ -40,9 +37,8 @@ Task ExecuteClaudePeerAsync( /// of . /// Task ExecuteOpencodeServerAsync( - string harness, - string sessionId, string actorName, + string sessionId, string endpointAddr, string? endpointSecret, string attemptId, diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ISessionGateCoordinator.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ISessionGateCoordinator.cs index d90c94b6ac9..ec1919cb146 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ISessionGateCoordinator.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/ISessionGateCoordinator.cs @@ -1,21 +1,19 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// -/// Reserves a session gate and one shared transport slot for a ping attempt. +/// Reserves an agent's ping gate and one shared transport slot for a ping attempt. /// Completion releases the slot and either starts a cooldown on success or releases the gate on failure. /// internal interface ISessionGateCoordinator { Task TryReserveAsync( - AgentSessionGeneration target, + string target, string attemptId, DateTimeOffset now, CancellationToken cancellationToken); /// - /// Releases the attempt's transport slot and either renews its unexpired session gate + /// Releases the attempt's transport slot and either renews its unexpired ping gate /// for a successful attempt's cooldown or releases it after failure. /// Reservations now owned by a different attempt are unchanged. /// diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailNudge.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailNudge.cs index 65d3459e68b..daf95ab0437 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailNudge.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailNudge.cs @@ -5,9 +5,9 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; internal sealed class MailNudge( - IAgentSessionRegistry sessions, + IAgentStore agentStore, IMailStore mail, - ISessionDeliveryLedger ledger, + IAgentDeliveryLedger ledger, IClaudePeerClient claudePeerClient, ICodexQueueClient codexQueueClient, TimeProvider timeProvider) : IMailNudge @@ -33,90 +33,97 @@ private async Task NudgeCoreAsync( return; } - var participants = await sessions.ListParticipantsAsync(cancellationToken); - foreach (var actor in actors.Distinct(StringComparer.Ordinal)) { - // Sessions are selected by actor binding without checking their presence state. - var targets = participants - .Where(participant => participant.Session.AgentName == actor) - .ToArray(); - - if (targets.Length == 0) + try { - continue; - } + var row = await agentStore.FindAsync(actor, cancellationToken); - foreach (var target in targets) - { - try + if (row is null + || AgentStateResolver.Resolve(row, timeProvider.GetUtcNow()) is not (AgentState.Online or AgentState.Idle)) { - var unread = await mail.QueryInboxAsync( - new MailInboxFilter - { - Actor = actor, - UnreadOnly = true, - Limit = MailDigestPolicy.MaxMessages - }, - cancellationToken); + // Nudging only reaches an actor the wake system could itself target. + continue; + } - if (unread.Count == 0) - { - continue; - } + if (!CanTransport(row)) + { + // Reserving a Ping delivery for an endpoint kind SendAsync + // cannot reach would strand the message as delivered + // without it ever reaching the agent. + continue; + } - var generation = new AgentSessionGeneration( - target.Session.Harness, - target.Session.SessionId, - target.Session.Host); - var messageIds = unread.Select(message => message.Id).ToList(); - var delivered = await ledger.FindDeliveredAsync( - generation, messageIds, cancellationToken); - var reserved = await ledger.ReserveAsync( - generation.Harness, - generation.SessionId, - messageIds, - AgentSessionChannel.Ping, - timeProvider.GetUtcNow(), - cancellationToken); - var reservedIds = reserved.ToHashSet(StringComparer.Ordinal); - var deliveredIds = delivered.ToHashSet(StringComparer.Ordinal); - var messages = unread - .Where(message => - reservedIds.Contains(message.Id) && !deliveredIds.Contains(message.Id)) - .ToList(); - var unreadTotal = await mail.CountUnreadAsync(actor, cancellationToken); - var text = MailDigest.Render(actor, messages, unreadTotal); + var unread = await mail.QueryInboxAsync( + new MailInboxFilter + { + Actor = actor, + UnreadOnly = true, + Limit = MailDigestPolicy.MaxMessages + }, + cancellationToken); - await SendAsync(target.Session, text, cancellationToken); - } - catch (Exception exception) when (exception is not OperationCanceledException) + if (unread.Count == 0) { - // Notification failure leaves the mail unread. + continue; } + + var messageIds = unread.Select(message => message.Id).ToList(); + var delivered = await ledger.FindDeliveredAsync(actor, messageIds, cancellationToken); + var reserved = await ledger.ReserveAsync( + actor, messageIds, AgentSessionChannel.Ping, timeProvider.GetUtcNow(), cancellationToken); + var reservedIds = reserved.ToHashSet(StringComparer.Ordinal); + var deliveredIds = delivered.ToHashSet(StringComparer.Ordinal); + var messages = unread + .Where(message => reservedIds.Contains(message.Id) && !deliveredIds.Contains(message.Id)) + .ToList(); + var unreadTotal = await mail.CountUnreadAsync(actor, cancellationToken); + var text = MailDigest.Render(actor, messages, unreadTotal); + + await SendAsync(row, text, cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + // Notification failure leaves the mail unread. } } } + /// + /// Reports whether can deliver to the given agent's endpoint: + /// a Claude peer with a session, or a Codex thread. + /// + private static bool CanTransport(AgentRow row) => row.EndpointKind switch + { + AgentSessionEndpointKind.ClaudePeer => row.SessionId is not null, + AgentSessionEndpointKind.CodexThread => true, + _ => false + }; + /// /// Sends through a Claude peer or Codex thread endpoint, skipping other endpoint kinds. /// Cancellation propagates; other transport failures are ignored. /// private async Task SendAsync( - AgentSessionRecord session, + AgentRow row, string text, CancellationToken cancellationToken) { try { - switch (session.EndpointKind) + switch (row.EndpointKind) { case AgentSessionEndpointKind.ClaudePeer: - await claudePeerClient.SendAsync(session.SessionId, text, cancellationToken); + if (row.SessionId is null) + { + break; + } + + await claudePeerClient.SendAsync(row.SessionId, text, cancellationToken); break; case AgentSessionEndpointKind.CodexThread: - await codexQueueClient.QueueAsync(session.EndpointAddr, text, cancellationToken); + await codexQueueClient.QueueAsync(row.EndpointAddr, text, cancellationToken); break; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonCoordinator.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonCoordinator.cs index 4b0852acd01..cbbdee81871 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonCoordinator.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonCoordinator.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Globalization; using ChilliCream.Nitro.CommandLine.Services.Workspace; using Dapper; @@ -6,7 +7,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// -/// Coordinates background mail wakes for one workspace and Nitro instance. +/// Coordinates background mail wakes for this workspace. /// Lease loss returns it to standby; a Claude access denial temporarily degrades it. /// internal sealed class MailWakeDaemonCoordinator( @@ -14,16 +15,46 @@ internal sealed class MailWakeDaemonCoordinator( IActorWakeDispatcher dispatcher, IFileSystem fileSystem, AgentDatabase database, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider, TimeProvider timeProvider, MailWakeDaemonPolicy policy) : IMailWakeDaemonCoordinator { private const int MaxTransientAttempts = 5; - private readonly string _ownerId = $"daemon-{Guid.NewGuid():N}"; + /// + /// Invoked after its poll delay is armed, at the end of every admission loop iteration. + /// + internal Func? AfterAdmissionTickAsync { get; init; } + + /// + /// Invoked after its poll delay is armed, at the end of every standby loop iteration. + /// + internal Func? AfterStandbyTickAsync { get; init; } + + /// + /// Invoked once leadership is ending, either because was called + /// or the coordinator degraded itself, before it bounds its wait for the heartbeat and + /// admission loops to drain. + /// + internal Func? AfterLeadershipEndedAsync { get; init; } + + /// + /// Invoked after a transient busy-retry delay is armed, before it is awaited. + /// + internal Func? AfterRetryDelayArmedAsync { get; init; } + + /// + /// Invoked after a bounded wait for shutdown is armed, before it is awaited. + /// + internal Func? AfterShutdownWaitArmedAsync { get; init; } + private readonly object _statusLock = new(); private readonly ConcurrentDictionaryBackoff _backoff = new(); + private readonly ConcurrentDictionary _inFlightActors = new(StringComparer.Ordinal); + + // Regenerated per leadership term (every successful TryAcquireWithRetryAsync), so a + // dispatch orphaned by an earlier term carries a stale token that the store's fencing + // rejects once a new term begins. + private string _ownerToken = NewOwnerToken(); private MailWakeDaemonStatus _status = MailWakeDaemonStatus.Initial; private CancellationTokenSource? _lifetime; @@ -57,6 +88,12 @@ public MailWakeDaemonStatus Status { lock (_statusLock) { + if (_status.State == MailWakeDaemonState.Ready + && timeProvider.GetUtcNow() >= _status.LeaseExpiresAt) + { + return _status with { State = MailWakeDaemonState.Standby, OwnerToken = null, LeaseExpiresAt = null }; + } + return _status; } } @@ -90,7 +127,14 @@ public async Task StopAsync(CancellationToken cancellationToken) try { await lifetime.CancelAsync(); - await runTask.WaitAsync(policy.ShutdownWait, cancellationToken); + var stopped = runTask.WaitAsync(policy.ShutdownWait, timeProvider, cancellationToken); + + if (AfterShutdownWaitArmedAsync is { } afterShutdownWaitArmedAsync) + { + await afterShutdownWaitArmedAsync(cancellationToken); + } + + await stopped; } catch (TimeoutException) { @@ -119,23 +163,18 @@ public async Task StopAsync(CancellationToken cancellationToken) private async Task RunAsync(CancellationToken stopToken) { - string? nitroInstanceId = null; - while (!stopToken.IsCancellationRequested) { try { - nitroInstanceId ??= await instanceIdProvider.GetIdAsync( - globalConfigDirectoryProvider.GetDirectory(), stopToken); - - var epoch = await StandbyUntilLeaderAsync(nitroInstanceId, stopToken); + var acquired = await StandbyUntilLeaderAsync(stopToken); - if (epoch is null) + if (!acquired) { return; } - await RunAsLeaderAsync(nitroInstanceId, epoch.Value, stopToken); + await RunAsLeaderAsync(stopToken); } catch (OperationCanceledException) { @@ -145,9 +184,16 @@ private async Task RunAsync(CancellationToken stopToken) { UpdateStatus(s => s with { State = MailWakeDaemonState.Standby, LastError = Bound(ex.Message) }); + var delay = Task.Delay(policy.StandbyPollInterval, timeProvider, stopToken); + + if (AfterRetryDelayArmedAsync is { } afterRetryDelayArmedAsync) + { + await afterRetryDelayArmedAsync(stopToken); + } + try { - await Task.Delay(policy.StandbyPollInterval, timeProvider, stopToken); + await delay; } catch (OperationCanceledException) { @@ -157,7 +203,7 @@ private async Task RunAsync(CancellationToken stopToken) } } - private async Task StandbyUntilLeaderAsync(string nitroInstanceId, CancellationToken stopToken) + private async Task StandbyUntilLeaderAsync(CancellationToken stopToken) { while (!stopToken.IsCancellationRequested) { @@ -169,37 +215,44 @@ private async Task RunAsync(CancellationToken stopToken) ? s : new MailWakeDaemonStatus( selfDenied ? MailWakeDaemonState.Degraded : MailWakeDaemonState.Standby, - null, null, null, s.LastError)); + null, null, s.LastError)); if (!selfDenied) { - var lease = await ReadLeaseWithRetryAsync(nitroInstanceId, stopToken); + var lease = await ReadLeaseWithRetryAsync(stopToken); if (lease is null || lease.ExpiresAt <= now) { - var epoch = await TryAcquireWithRetryAsync(nitroInstanceId, now, stopToken); + var acquired = await TryAcquireWithRetryAsync(now, stopToken); - if (epoch is not null) + if (acquired) { - return epoch; + return true; } } } + var delay = Task.Delay(policy.StandbyPollInterval, timeProvider, stopToken); + + if (AfterStandbyTickAsync is { } afterStandbyTickAsync) + { + await afterStandbyTickAsync(stopToken); + } + try { - await Task.Delay(policy.StandbyPollInterval, timeProvider, stopToken); + await delay; } catch (OperationCanceledException) { - return null; + return false; } } - return null; + return false; } - private async Task RunAsLeaderAsync(string nitroInstanceId, long epoch, CancellationToken stopToken) + private async Task RunAsLeaderAsync(CancellationToken stopToken) { var now = timeProvider.GetUtcNow(); @@ -207,21 +260,61 @@ private async Task RunAsLeaderAsync(string nitroInstanceId, long epoch, Cancella UpdateStatus(s => s.State == MailWakeDaemonState.Stopping ? s : new MailWakeDaemonStatus( - MailWakeDaemonState.Ready, _ownerId, epoch, now + policy.LeaderLeaseDuration, null)); + MailWakeDaemonState.Ready, _ownerToken, now + policy.LeaderLeaseDuration, null)); _backoff.Clear(); using var degradedSource = new CancellationTokenSource(); using var leaderSource = CancellationTokenSource.CreateLinkedTokenSource(stopToken, degradedSource.Token); - var heartbeatTask = HeartbeatLoopAsync(nitroInstanceId, epoch, degradedSource, leaderSource.Token); - var admissionTask = AdmissionLoopAsync(nitroInstanceId, epoch, degradedSource, leaderSource.Token); + var heartbeatTask = HeartbeatLoopAsync(degradedSource, leaderSource.Token); + var admissionTask = AdmissionLoopAsync(degradedSource, leaderSource.Token); + var loopsCompleted = Task.WhenAll(AwaitLoopAsync(heartbeatTask), AwaitLoopAsync(admissionTask)); - await Task.WhenAll(AwaitLoopAsync(heartbeatTask), AwaitLoopAsync(admissionTask)); + // Cheap and never blocked by an in-flight dispatch: leaderSource cancels the moment + // either StopAsync is called or the coordinator degrades itself. + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, leaderSource.Token); + } + catch (OperationCanceledException) + { + } - if (stopToken.IsCancellationRequested && Status.State != MailWakeDaemonState.Degraded) + if (stopToken.IsCancellationRequested || degradedSource.IsCancellationRequested) { - await leaderStore.TryReleaseAsync( - nitroInstanceId, _ownerId, epoch, timeProvider.GetUtcNow(), CancellationToken.None); + if (AfterLeadershipEndedAsync is { } afterLeadershipEndedAsync) + { + await afterLeadershipEndedAsync(CancellationToken.None); + } + + // Bounded, and strictly shorter than the outer StopAsync/ShutdownWait budget, so a + // dispatch that ignores its cancellation token cannot hold the lease forever and the + // release below still has time to land within that outer budget; the loops keep + // draining in the background either way. + var drained = loopsCompleted.WaitAsync(policy.DispatchStopWait, timeProvider, CancellationToken.None); + + if (AfterShutdownWaitArmedAsync is { } afterShutdownWaitArmedAsync) + { + await afterShutdownWaitArmedAsync(CancellationToken.None); + } + + try + { + await drained; + } + catch (TimeoutException) + { + var stuckActors = _inFlightActors.Keys.ToArray(); + var actorsText = stuckActors.Length > 0 ? string.Join(", ", stuckActors) : "unknown actor"; + UpdateStatus(s => s with + { + LastError = Bound( + $"Dispatch for actor(s) [{actorsText}] under owner token {_ownerToken} " + + "ignored cancellation past the shutdown wait; leadership was released anyway.") + }); + } + + await ReleaseWithRetryAsync(CancellationToken.None); } } @@ -236,8 +329,7 @@ private static async Task AwaitLoopAsync(Task loop) } } - private async Task HeartbeatLoopAsync( - string nitroInstanceId, long epoch, CancellationTokenSource degradedSource, CancellationToken loopToken) + private async Task HeartbeatLoopAsync(CancellationTokenSource degradedSource, CancellationToken loopToken) { while (true) { @@ -249,7 +341,7 @@ private async Task HeartbeatLoopAsync( try { renewed = await leaderStore.TryRenewAsync( - nitroInstanceId, _ownerId, epoch, now, policy.LeaderLeaseDuration, Status.LastError, loopToken); + _ownerToken, now, policy.LeaderLeaseDuration, loopToken); } catch (OperationCanceledException) { @@ -258,7 +350,7 @@ private async Task HeartbeatLoopAsync( catch (Exception ex) { UpdateStatus(_ => new MailWakeDaemonStatus( - MailWakeDaemonState.Standby, null, null, null, Bound(ex.Message))); + MailWakeDaemonState.Standby, null, null, Bound(ex.Message))); await degradedSource.CancelAsync(); return; } @@ -266,7 +358,7 @@ private async Task HeartbeatLoopAsync( if (!renewed) { UpdateStatus(s => new MailWakeDaemonStatus( - MailWakeDaemonState.Standby, null, null, null, s.LastError)); + MailWakeDaemonState.Standby, null, null, s.LastError)); await degradedSource.CancelAsync(); return; } @@ -277,12 +369,9 @@ private async Task HeartbeatLoopAsync( } } - private async Task AdmissionLoopAsync( - string nitroInstanceId, long epoch, CancellationTokenSource degradedSource, CancellationToken loopToken) + private async Task AdmissionLoopAsync(CancellationTokenSource degradedSource, CancellationToken loopToken) { using var executionGate = new SemaphoreSlim(policy.MaxConcurrentActorExecutions); - var inFlight = new HashSet(StringComparer.Ordinal); - var inFlightLock = new object(); var executionTasks = new List(); try @@ -292,23 +381,20 @@ private async Task AdmissionLoopAsync( try { var now = timeProvider.GetUtcNow(); - var due = await FindDueActorsWithRetryAsync(nitroInstanceId, now, loopToken) ?? []; - foreach (var actor in due) + if (Status.State == MailWakeDaemonState.Ready) { - lock (inFlightLock) + var due = await FindDueActorsWithRetryAsync(now, loopToken) ?? []; + + foreach (var actor in due) { - if (inFlight.Contains(actor) || !_backoff.IsEligible(actor, now)) + if (!_backoff.IsEligible(actor, now) || !_inFlightActors.TryAdd(actor, true)) { continue; } - inFlight.Add(actor); + executionTasks.Add(ExecuteActorAsync(actor, executionGate, degradedSource, loopToken)); } - - executionTasks.Add(ExecuteActorAsync( - nitroInstanceId, actor, epoch, executionGate, inFlight, inFlightLock, degradedSource, - loopToken)); } executionTasks.RemoveAll(t => t.IsCompleted); @@ -322,7 +408,14 @@ private async Task AdmissionLoopAsync( UpdateStatus(s => s with { LastError = Bound(ex.Message) }); } - await Task.Delay(policy.AdmissionPollInterval, timeProvider, loopToken); + var delay = Task.Delay(policy.AdmissionPollInterval, timeProvider, loopToken); + + if (AfterAdmissionTickAsync is { } afterAdmissionTickAsync) + { + await afterAdmissionTickAsync(loopToken); + } + + await delay; } } finally @@ -338,12 +431,8 @@ private async Task AdmissionLoopAsync( } private async Task ExecuteActorAsync( - string nitroInstanceId, string actor, - long epoch, SemaphoreSlim gate, - HashSet inFlight, - object inFlightLock, CancellationTokenSource degradedSource, CancellationToken loopToken) { @@ -354,7 +443,7 @@ private async Task ExecuteActorAsync( try { var deadline = timeProvider.GetUtcNow() + WakeDispatchPolicy.BatchDeadline; - var receipt = await dispatcher.DispatchAsync(actor, deadline, loopToken); + var receipt = await dispatcher.DispatchAsync(actor, _ownerToken, deadline, loopToken); if (receipt is null) { @@ -369,16 +458,8 @@ private async Task ExecuteActorAsync( SelfDeniedUntil = timeProvider.GetUtcNow() + MailWakeDaemonRetryPolicy.MaxDelay; UpdateStatus(s => s with { State = MailWakeDaemonState.Degraded, LastError = "access-denied" }); - // Signals sibling dispatches to cancel before releasing leadership. - try - { - await degradedSource.CancelAsync(); - } - finally - { - await ReleaseWithRetryAsync(nitroInstanceId, epoch, CancellationToken.None); - } - + // Leadership is released once both the heartbeat and admission loops have stopped. + await degradedSource.CancelAsync(); return; } @@ -408,10 +489,7 @@ private async Task ExecuteActorAsync( } finally { - lock (inFlightLock) - { - inFlight.Remove(actor); - } + _inFlightActors.TryRemove(actor, out _); } } @@ -435,26 +513,71 @@ private void UpdateStatus(Func updat private static bool IsBusy(SqliteException ex) => ex.SqliteErrorCode is 5 or 6; // SQLITE_BUSY / SQLITE_LOCKED - private async Task TryAcquireWithRetryAsync( - string nitroInstanceId, DateTimeOffset now, CancellationToken cancellationToken) - => await RunWithBusyRetryAsync( - ct => leaderStore.TryAcquireAsync(nitroInstanceId, _ownerId, now, policy.LeaderLeaseDuration, ct), + private async Task TryAcquireWithRetryAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + // A fresh candidate token per acquisition attempt, so every leadership term gets + // its own token; it only becomes _ownerToken once the acquire actually succeeds. + var candidateToken = NewOwnerToken(); + var acquired = await RunBoolWithBusyRetryAsync( + ct => leaderStore.TryAcquireAsync(candidateToken, now, policy.LeaderLeaseDuration, ct), cancellationToken); - private async Task ReadLeaseWithRetryAsync(string nitroInstanceId, CancellationToken cancellationToken) - => await RunWithBusyRetryAsync(ct => ReadLeaseAsync(nitroInstanceId, ct), cancellationToken); + if (acquired) + { + _ownerToken = candidateToken; + } + + return acquired; + } + + private static string NewOwnerToken() => $"daemon-{Guid.NewGuid():N}"; + + private async Task ReadLeaseWithRetryAsync(CancellationToken cancellationToken) + => await RunWithBusyRetryAsync(ReadLeaseAsync, cancellationToken); private async Task?> FindDueActorsWithRetryAsync( - string nitroInstanceId, DateTimeOffset now, CancellationToken cancellationToken) - => await RunWithBusyRetryAsync( - async ct => await FindDueActorsAsync(nitroInstanceId, now, ct), cancellationToken); - - private async Task ReleaseWithRetryAsync(string nitroInstanceId, long epoch, CancellationToken cancellationToken) - => await RunWithBusyRetryAsync( - async ct => await leaderStore.TryReleaseAsync( - nitroInstanceId, _ownerId, epoch, timeProvider.GetUtcNow(), ct), + DateTimeOffset now, CancellationToken cancellationToken) + => await RunWithBusyRetryAsync(async ct => await FindDueActorsAsync(now, ct), cancellationToken); + + private async Task ReleaseWithRetryAsync(CancellationToken cancellationToken) + => await RunBoolWithBusyRetryAsync( + ct => leaderStore.TryReleaseAsync(_ownerToken, timeProvider.GetUtcNow(), ct), cancellationToken); + /// + /// Retries under the same busy-retry policy as + /// , returning false once retries are exhausted. + /// + private async Task RunBoolWithBusyRetryAsync( + Func> operation, CancellationToken cancellationToken) + { + for (var attempt = 1; attempt <= MaxTransientAttempts; attempt++) + { + try + { + return await operation(cancellationToken); + } + catch (SqliteException ex) when (IsBusy(ex)) + { + if (attempt == MaxTransientAttempts) + { + return false; + } + + var delay = Task.Delay(MailWakeDaemonRetryPolicy.ComputeDelay(attempt), timeProvider, cancellationToken); + + if (AfterRetryDelayArmedAsync is { } afterRetryDelayArmedAsync) + { + await afterRetryDelayArmedAsync(cancellationToken); + } + + await delay; + } + } + + return false; + } + private async Task RunWithBusyRetryAsync( Func> operation, CancellationToken cancellationToken) { @@ -471,43 +594,46 @@ private async Task ReleaseWithRetryAsync(string nitroInstanceId, long epoch, Can return default; } - await Task.Delay(MailWakeDaemonRetryPolicy.ComputeDelay(attempt), timeProvider, cancellationToken); + var delay = Task.Delay(MailWakeDaemonRetryPolicy.ComputeDelay(attempt), timeProvider, cancellationToken); + + if (AfterRetryDelayArmedAsync is { } afterRetryDelayArmedAsync) + { + await afterRetryDelayArmedAsync(cancellationToken); + } + + await delay; } } return default; } - private async Task ReadLeaseAsync(string nitroInstanceId, CancellationToken cancellationToken) + private async Task ReadLeaseAsync(CancellationToken cancellationToken) { await using var connection = await ConnectAsync(cancellationToken); var row = await connection.QueryFirstOrDefaultAsync( """ - SELECT owner_id AS OwnerId, epoch AS Epoch, expires_at AS ExpiresAt - FROM mail_wake_daemons - WHERE nitro_instance_id = @nitroInstanceId - """, - new { nitroInstanceId, cancellationToken }); + SELECT owner_token AS OwnerToken, expires_at AS ExpiresAt + FROM mail_wake_daemons + WHERE id = 1 + """); return row is null ? null - : new LeaseSnapshot(row.OwnerId, row.Epoch, DateTimeOffset.Parse(row.ExpiresAt, CultureInfo.InvariantCulture)); + : new LeaseSnapshot(row.OwnerToken, DateTimeOffset.Parse(row.ExpiresAt, CultureInfo.InvariantCulture)); } - private async Task> FindDueActorsAsync( - string nitroInstanceId, DateTimeOffset now, CancellationToken cancellationToken) + private async Task> FindDueActorsAsync(DateTimeOffset now, CancellationToken cancellationToken) { await using var connection = await ConnectAsync(cancellationToken); var actors = await connection.QueryAsync( """ - SELECT actor FROM mail_wake_outbox - WHERE nitro_instance_id = @nitroInstanceId - AND settled_generation < requested_generation - AND due_at <= @now - """, - new { nitroInstanceId, now, cancellationToken }); + SELECT actor FROM mail_wake_outbox + WHERE settled_generation < requested_generation AND due_at <= @now + """, + new { now }); return actors.AsList(); } @@ -520,12 +646,11 @@ private async Task ConnectAsync(CancellationToken cancellation return await database.ConnectAsync(workspaceDirectory, cancellationToken); } - private sealed record LeaseSnapshot(string OwnerId, long Epoch, DateTimeOffset ExpiresAt); + private sealed record LeaseSnapshot(string OwnerToken, DateTimeOffset ExpiresAt); internal sealed class LeaseRow { - public required string OwnerId { get; init; } - public required long Epoch { get; init; } + public required string OwnerToken { get; init; } public required string ExpiresAt { get; init; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonPolicy.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonPolicy.cs index 79e2176f624..71e541f964c 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonPolicy.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonPolicy.cs @@ -25,4 +25,10 @@ internal sealed record MailWakeDaemonPolicy( StandbyPollInterval: TimeSpan.FromSeconds(1), MaxConcurrentActorExecutions: 4, ShutdownWait: TimeSpan.FromSeconds(5)); + + /// + /// The bound for draining in-flight dispatches when leadership ends. Always strictly + /// shorter than . + /// + public TimeSpan DispatchStopWait => ShutdownWait / 2; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonStatus.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonStatus.cs index b27be0549ef..c81768270b4 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonStatus.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/MailWakeDaemonStatus.cs @@ -1,16 +1,15 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// -/// The coordinator's latest leadership snapshot, with owner and epoch values that -/// may remain set during stopping or degradation until the next standby observation. +/// The coordinator's latest leadership snapshot, with an owner token that may +/// remain set during stopping or degradation until the next standby observation. /// internal sealed record MailWakeDaemonStatus( MailWakeDaemonState State, - string? OwnerId, - long? Epoch, + string? OwnerToken, DateTimeOffset? LeaseExpiresAt, string? LastError) { public static readonly MailWakeDaemonStatus Initial = - new(MailWakeDaemonState.Standby, null, null, null, null); + new(MailWakeDaemonState.Standby, null, null, null); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingAttemptOutcome.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingAttemptOutcome.cs index ea0ff22e123..c14f7d2e400 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingAttemptOutcome.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingAttemptOutcome.cs @@ -1,7 +1,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// -/// A ping outcome with its result, reason, retry hint, session, attempt, and completion time. +/// A ping outcome with its result, reason, retry hint, actor, attempt, and completion time. /// is diagnostic text from the transport or a caught exception, /// truncated to at most 200 characters; recording the outcome is best effort. /// @@ -10,7 +10,6 @@ internal sealed record PingAttemptOutcome( PingAttemptReason Reason, bool Retryable, string? Detail, - string Harness, - string SessionId, + string ActorName, string AttemptId, DateTimeOffset CompletedAt); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingSessionExecutor.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingSessionExecutor.cs index 2e0dda8afce..586bffaec0a 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingSessionExecutor.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/PingSessionExecutor.cs @@ -6,10 +6,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; internal sealed class PingSessionExecutor( IMailStore mailStore, - ISessionDeliveryLedger ledger, + IAgentDeliveryLedger ledger, ICodexQueueClient queueClient, IClaudePeerClient claudePeerClient, - IAgentSessionRegistry sessionRegistry, + IAgentStore agentStore, IPingLeaseStore leaseStore, TimeProvider timeProvider, IOpencodeServerClient opencodeServerClient) : IPingSessionExecutor @@ -20,8 +20,6 @@ internal sealed class PingSessionExecutor( internal const string HealthOnlyDetail = "health-only"; public Task ExecuteCodexThreadAsync( - string harness, - string sessionId, string actorName, string endpointAddr, string attemptId, @@ -29,8 +27,6 @@ public Task ExecuteCodexThreadAsync( DateTimeOffset deadline, CancellationToken cancellationToken) => ExecuteAsync( - harness, - sessionId, actorName, attemptId, slot, @@ -41,16 +37,13 @@ public Task ExecuteCodexThreadAsync( cancellationToken); public Task ExecuteClaudePeerAsync( - string harness, - string sessionId, string actorName, + string sessionId, string attemptId, int slot, DateTimeOffset deadline, CancellationToken cancellationToken) => ExecuteAsync( - harness, - sessionId, actorName, attemptId, slot, @@ -61,9 +54,8 @@ public Task ExecuteClaudePeerAsync( cancellationToken); public Task ExecuteOpencodeServerAsync( - string harness, - string sessionId, string actorName, + string sessionId, string endpointAddr, string? endpointSecret, string attemptId, @@ -71,8 +63,6 @@ public Task ExecuteOpencodeServerAsync( DateTimeOffset deadline, CancellationToken cancellationToken) => ExecuteAsync( - harness, - sessionId, actorName, attemptId, slot, @@ -99,12 +89,10 @@ await opencodeServerClient.PushMessageAsync( /// /// Builds a digest and invokes within the attempt budget, - /// passing null when no unread mail or matching claimed session remains. - /// Outcome recording and lease release are best effort. + /// passing null when no unread mail remains. Outcome recording and lease release + /// are best effort. /// private async Task ExecuteAsync( - string harness, - string sessionId, string actorName, string attemptId, int slot, @@ -119,8 +107,7 @@ private async Task ExecuteAsync( // An expired deadline produces a timeout without digest or transport work. try { - return await WriteResultAsync( - harness, sessionId, attemptId, PingAttemptReason.Timeout, null); + return await WriteResultAsync(actorName, attemptId, PingAttemptReason.Timeout, null); } finally { @@ -138,13 +125,11 @@ private async Task ExecuteAsync( try { - digest = await BuildDigestAsync( - harness, sessionId, actorName, linkedSource.Token); + digest = await BuildDigestAsync(actorName, linkedSource.Token); } catch (OperationCanceledException) when (timeoutSource.IsCancellationRequested) { - return await WriteResultAsync( - harness, sessionId, attemptId, PingAttemptReason.Timeout, null); + return await WriteResultAsync(actorName, attemptId, PingAttemptReason.Timeout, null); } TransportOutcome transportOutcome; @@ -155,18 +140,17 @@ private async Task ExecuteAsync( } catch (OperationCanceledException) when (timeoutSource.IsCancellationRequested) { - return await WriteResultAsync( - harness, sessionId, attemptId, PingAttemptReason.Timeout, null); + return await WriteResultAsync(actorName, attemptId, PingAttemptReason.Timeout, null); } return await WriteResultAsync( - harness, sessionId, attemptId, transportOutcome.Reason, Truncate(transportOutcome.Detail)); + actorName, attemptId, transportOutcome.Reason, Truncate(transportOutcome.Detail)); } catch (Exception exception) when (exception is not OperationCanceledException) { // Non-cancellation failures produce a transport-error outcome. return await WriteResultAsync( - harness, sessionId, attemptId, PingAttemptReason.TransportError, Truncate(exception.Message)); + actorName, attemptId, PingAttemptReason.TransportError, Truncate(exception.Message)); } finally { @@ -174,11 +158,7 @@ private async Task ExecuteAsync( } } - private async Task BuildDigestAsync( - string harness, - string sessionId, - string actorName, - CancellationToken cancellationToken) + private async Task BuildDigestAsync(string actorName, CancellationToken cancellationToken) { var unread = await mailStore.QueryInboxAsync( new MailInboxFilter { Actor = actorName, UnreadOnly = true, Limit = MailDigestPolicy.MaxMessages }, @@ -189,27 +169,10 @@ private async Task ExecuteAsync( return null; } - var session = (await sessionRegistry.FindLiveClaimedByAgentNameAsync(actorName, cancellationToken)) - .FirstOrDefault(candidate => - candidate.Harness == harness && candidate.SessionId == sessionId); - - if (session is null) - { - return null; - } - - var generation = new AgentSessionGeneration( - session.Harness, session.SessionId, session.Host); var messageIds = unread.Select(message => message.Id).ToList(); - var delivered = await ledger.FindDeliveredAsync( - generation, messageIds, cancellationToken); + var delivered = await ledger.FindDeliveredAsync(actorName, messageIds, cancellationToken); var reserved = await ledger.ReserveAsync( - generation.Harness, - generation.SessionId, - messageIds, - AgentSessionChannel.Ping, - timeProvider.GetUtcNow(), - cancellationToken); + actorName, messageIds, AgentSessionChannel.Ping, timeProvider.GetUtcNow(), cancellationToken); var reservedIds = reserved.ToHashSet(StringComparer.Ordinal); var deliveredIds = delivered.ToHashSet(StringComparer.Ordinal); var messages = unread @@ -225,14 +188,13 @@ private async Task ExecuteAsync( /// even if recording fails. /// private async Task WriteResultAsync( - string harness, string sessionId, string attemptId, PingAttemptReason reason, string? detail) + string actorName, string attemptId, PingAttemptReason reason, string? detail) { var result = ToResult(reason); try { - await sessionRegistry.WritePingResultAsync( - harness, sessionId, attemptId, result, detail, CancellationToken.None); + await agentStore.WritePingResultAsync(actorName, attemptId, result, detail, CancellationToken.None); } catch { @@ -244,8 +206,7 @@ await sessionRegistry.WritePingResultAsync( reason, IsRetryable(reason), detail, - harness, - sessionId, + actorName, attemptId, timeProvider.GetUtcNow()); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/SessionGateCoordinator.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/SessionGateCoordinator.cs index 41e7b0af132..0530f0f72c3 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/SessionGateCoordinator.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/SessionGateCoordinator.cs @@ -3,10 +3,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Notify; internal sealed class SessionGateCoordinator( - ISessionPingGateStore gateStore, IPingLeaseStore leaseStore) : ISessionGateCoordinator + IAgentPingGateStore gateStore, IPingLeaseStore leaseStore) : ISessionGateCoordinator { public async Task TryReserveAsync( - AgentSessionGeneration target, + string target, string attemptId, DateTimeOffset now, CancellationToken cancellationToken) @@ -24,7 +24,7 @@ public async Task TryReserveAsync( if (slot is null) { - // Releases the session gate when no transport slot is available. + // Releases the ping gate when no transport slot is available. await gateStore.ReleaseAsync(target, attemptId, cancellationToken); return WakeReservationResult.Rejected(WakeReservationFailure.CapacityDropped); } @@ -42,7 +42,7 @@ public async Task CompleteAsync( if (success) { - // A successful attempt starts the session's cooldown. + // A successful attempt starts the agent's cooldown. await gateStore.TryRenewAsync( reservation.Target, reservation.AttemptId, now, PingPolicy.Cooldown, cancellationToken); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/WakeGateReservation.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/WakeGateReservation.cs index e630fe3ce46..4cd90948409 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Notify/WakeGateReservation.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Notify/WakeGateReservation.cs @@ -1,10 +1,7 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - namespace ChilliCream.Nitro.CommandLine.Services.Notify; /// -/// One target's held reservation: the session gate and the shared lease -/// slot a dispatch attempt claimed together, and the attempt id that fences -/// both. +/// One agent's held reservation: the ping gate and the shared lease slot a +/// dispatch attempt claimed together, and the attempt id that fences both. /// -internal sealed record WakeGateReservation(AgentSessionGeneration Target, string AttemptId, int Slot); +internal sealed record WakeGateReservation(string Target, string AttemptId, int Slot); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/ITaskStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/ITaskStore.cs index bfd48927748..14cf78874da 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/ITaskStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/ITaskStore.cs @@ -19,6 +19,17 @@ Task> QueryTasksAsync( TaskFilter filter, CancellationToken cancellationToken); + /// + /// Returns the non-tombstone tasks an agent participated in, either through an event + /// whose actor is the agent or through a current assignment, ordered by the agent's + /// latest event on the task (falling back to updated_at when only assigned), newest + /// first then by id. A null limit returns every matching task. + /// + Task> QueryParticipationAsync( + string agent, + int? limit, + CancellationToken cancellationToken); + /// /// Returns the task, including a tombstone, or null when its id does not exist. /// @@ -281,6 +292,15 @@ Task DeleteTaskAsync( string actor, CancellationToken cancellationToken); + /// + /// Releases every in-progress task assigned to the given agent, moving each to open + /// with no assignee and recording the reason. Returns the number of tasks released. + /// + Task ReleaseAssigneeAsync( + string agent, + string reason, + CancellationToken cancellationToken); + /// /// Closes every epic whose non-tombstone children all closed, and records /// a closed event for each. After the close commits, enforces diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStore.cs index 63a7423d03a..844e319239d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStore.cs @@ -138,7 +138,7 @@ RETURNING last_child throw new ExitException("Could not allocate a unique task ID."); } - private async Task RecordEventAsync( + private static async Task RecordEventAsync( SqliteConnection connection, TaskEvent taskEvent, CancellationToken cancellationToken, @@ -341,6 +341,46 @@ public async Task> QueryTasksAsync( return tasks.ToList(); } + public async Task> QueryParticipationAsync( + string agent, + int? limit, + CancellationToken cancellationToken) + { + var parameters = new Dictionary + { + ["agent"] = agent, + ["tombstone"] = TaskStates.Tombstone + }; + + var sql = $""" + SELECT {TaskItem.Columns}, + COALESCE( + (SELECT MAX(e.created_at) FROM events e + WHERE e.task_id = tasks.id AND e.actor = @agent), + tasks.updated_at + ) AS RankAt + FROM tasks + WHERE status != @tombstone + AND ( + assignee = @agent + OR EXISTS ( + SELECT 1 FROM events e2 + WHERE e2.task_id = tasks.id AND e2.actor = @agent) + ) + ORDER BY RankAt DESC, id ASC + """; + + if (limit is { } sqlLimit) + { + parameters["limit"] = sqlLimit; + sql += " LIMIT @limit"; + } + + await using var connection = await ConnectAsync(cancellationToken); + + return await ExecuteTaskQueryAsync(connection, sql, parameters, cancellationToken); + } + private static async Task> ExecuteTaskQueryAsync( SqliteConnection connection, string sql, @@ -1661,6 +1701,100 @@ await RecordEventAsync( return task; } + public async Task ReleaseAssigneeAsync( + string agent, + string reason, + CancellationToken cancellationToken) + { + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = + (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); + + var count = await ReleaseAssigneeWithinTransactionAsync( + connection, transaction, agent, reason, now, cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return count; + } + + /// + /// Releases every in-progress task assigned to the given agent within the supplied + /// transaction, moving each to open with no assignee and recording the reason. + /// Returns the number of tasks released. + /// + public static async Task ReleaseAssigneeWithinTransactionAsync( + SqliteConnection connection, + SqliteTransaction transaction, + string agent, + string reason, + DateTimeOffset now, + CancellationToken cancellationToken) + { + var ids = (await connection.QueryAsync( + "SELECT id FROM tasks WHERE status = @status AND assignee = @agent", + new { status = TaskStates.InProgress, agent, cancellationToken }, + transaction)).ToList(); + + if (ids.Count == 0) + { + return 0; + } + + await connection.ExecuteAsync( + """ + UPDATE tasks + SET status = @newStatus, + assignee = NULL, + updated_at = @now + WHERE status = @oldStatus AND assignee = @agent + """, + new + { + newStatus = TaskStates.Open, + oldStatus = TaskStates.InProgress, + agent, + now, + cancellationToken + }, + transaction); + + foreach (var id in ids) + { + await RecordEventAsync( + connection, + new TaskEvent + { + TaskId = id, + Type = TaskEventTypes.AssigneeChanged, + OldValue = agent, + NewValue = "", + Comment = reason, + CreatedAt = now + }, + cancellationToken, + transaction); + + await RecordEventAsync( + connection, + new TaskEvent + { + TaskId = id, + Type = TaskEventTypes.StatusChanged, + OldValue = TaskStates.InProgress, + NewValue = TaskStates.Open, + Comment = reason, + CreatedAt = now + }, + cancellationToken, + transaction); + } + + return ids.Count; + } + public async Task> CloseEligibleEpicsAsync( string actor, CancellationToken cancellationToken) diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStoreSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStoreSchema.cs index ac31623b37e..83edad61c31 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStoreSchema.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Tasks/TaskStoreSchema.cs @@ -63,6 +63,7 @@ created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_comments_task ON comments (task_id); + CREATE INDEX IF NOT EXISTS idx_comments_author ON comments (author); CREATE TABLE IF NOT EXISTS events ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -76,6 +77,7 @@ created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_events_task ON events (task_id); + CREATE INDEX IF NOT EXISTS idx_events_actor_created ON events (actor, created_at); CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY, diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ActingActorResolver.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ActingActorResolver.cs index 6a03c2fbc41..c057e78fe86 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ActingActorResolver.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ActingActorResolver.cs @@ -2,7 +2,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; -internal sealed class ActingActorResolver(IAgentRegistry agents) : IActingActorResolver +internal sealed class ActingActorResolver(IAgentStore agents) : IActingActorResolver { public async Task ResolveAsync( string? optionValue, @@ -17,13 +17,23 @@ public async Task ResolveAsync( var actor = MailAgentName.Normalize(optionValue); - if (await agents.GetAsync(actor, cancellationToken) is null) + var existing = await agents.FindAsync(actor, cancellationToken); + + if (existing is null) { throw new ExitException( $"Unknown actor '{actor}'. Run `nitro agent login` to allocate one, " + "or `nitro agent list` to see the actors this workspace knows."); } + if (existing.IsDeleted) + { + throw new ExitException($"Agent '{existing.Name}' was deleted."); + } + + // Every command run with --actor is a presence beat. + await agents.TouchAsync(actor, cancellationToken); + return actor; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentActorAllocator.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentActorAllocator.cs index cafc01ed6d2..15e1a865249 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentActorAllocator.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentActorAllocator.cs @@ -7,31 +7,20 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; internal static class AgentActorAllocator { - private static readonly string[] s_baseActors = - [ - "alex", "jamie", "sam", "max", "leo", "maya", "nina", "theo", "eli", "luca", - "mia", "nora", "ben", "adam", "noah", "lena", "eva", "zoe", "ryan", "jack", - "anna", "emma", "sara", "dani", "chris", "robin", "taylor", "jordan", "casey", "morgan", - "riley", "jesse", "quinn", "avery", "logan", "dylan", "owen", "clara", "lucy", "sophie", - "hugo", "felix", "oscar", "henry", "louis", "ella", "grace", "kate", "tom", "will" - ]; - - internal static IReadOnlyList BaseActors => s_baseActors; + internal static IReadOnlyList BaseActors => AgentNamePool.Names; public static async Task AllocateAsync( SqliteConnection connection, DbTransaction transaction) { - // Names in either the agent registry or durable session identities are unavailable. + // A name is unavailable once it has ever been minted: agent rows, including + // tombstones whose deleted_at is set. var occupied = (await connection.QueryAsync( - """ - SELECT actor FROM agent_session_identities - UNION - SELECT name FROM agents - """, + "SELECT name FROM agents", transaction: transaction)) .ToHashSet(StringComparer.Ordinal); - var order = Enumerable.Range(0, s_baseActors.Length).ToArray(); + var names = AgentNamePool.Names; + var order = Enumerable.Range(0, names.Count).ToArray(); for (var i = order.Length - 1; i > 0; i--) { @@ -39,11 +28,21 @@ SELECT name FROM agents (order[i], order[swap]) = (order[swap], order[i]); } - for (var suffix = 0; ; suffix++) + foreach (var index in order) + { + if (!occupied.Contains(names[index])) + { + return names[index]; + } + } + + // The pool is exhausted: every name is already in use, so append a numeric suffix to a + // shuffled pick, starting at 2, until one is free. + for (var suffix = 2; ; suffix++) { foreach (var index in order) { - var actor = suffix == 0 ? s_baseActors[index] : $"{s_baseActors[index]}-{suffix}"; + var actor = $"{names[index]}-{suffix}"; if (!occupied.Contains(actor)) { diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDatabase.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDatabase.cs index f76a982b521..3d263eef17c 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDatabase.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDatabase.cs @@ -1,4 +1,3 @@ -using System.Data.Common; using Dapper; using Microsoft.Data.Sqlite; using ChilliCream.Nitro.CommandLine.Services.Memory; @@ -15,13 +14,21 @@ internal sealed class AgentDatabase /// /// The current unified schema version. /// - public const int CurrentVersion = 14; + public const int CurrentVersion = 18; + + /// + /// The schema version at which messages.sender and + /// message_recipients.recipient stopped referencing agents (name) + /// as a foreign key. A database below this version has its mail tables + /// rebuilt without that constraint before the rest of the upgrade runs. + /// + private const int MailForeignKeysRemovedVersion = 16; /// /// Schema versions upgrades in place /// instead of rejecting. /// - private static readonly int[] s_upgradableVersions = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; + private static readonly int[] s_upgradableVersions = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]; /// /// True for a schema version upgrades in @@ -62,19 +69,26 @@ public async Task InitializeAsync( throw; } - // The constraint rebuild runs in its own transaction. - await RebuildAgentSessionsCheckConstraintIfStaleAsync(connection, cancellationToken); + if (version > 0 && version < MailForeignKeysRemovedVersion) + { + await RemoveMailAgentForeignKeysAsync(connection, cancellationToken); + } + + if (version < CurrentVersion) + { + await ResetAgentDomainTablesAsync(connection, cancellationToken); + } await using var transaction = await connection.BeginTransactionAsync(cancellationToken); await connection.ExecuteAsync(TaskStoreSchema.Create, transaction: transaction); await connection.ExecuteAsync(AgentRegistrySchema.Create, transaction: transaction); await connection.ExecuteAsync(MailStoreSchema.Create, transaction: transaction); - await connection.ExecuteAsync(AgentSessionSchema.Create, transaction: transaction); - await connection.ExecuteAsync(AgentSessionIdentitySchema.Create, transaction: transaction); + await connection.ExecuteAsync(PingLeaseSchema.Create, transaction: transaction); await connection.ExecuteAsync(MailWakeSchema.Create, transaction: transaction); - await connection.ExecuteAsync(SessionPingGateSchema.Create, transaction: transaction); + await connection.ExecuteAsync(AgentDeliverySchema.Create, transaction: transaction); + await connection.ExecuteAsync(AgentPingGateSchema.Create, transaction: transaction); await connection.ExecuteAsync(MemoryStoreSchema.Create, transaction: transaction); @@ -84,183 +98,46 @@ public async Task InitializeAsync( await MemoryMarkdownImport.ImportAsync( connection, transaction, workspaceDirectory, cancellationToken); - await RebuildMailWakeTargetsHarnessCheckConstraintIfStaleAsync(connection, transaction); - await RebuildSessionPingGatesHarnessCheckConstraintIfStaleAsync(connection, transaction); - await RebuildAgentSessionIdentitiesHarnessCheckConstraintIfStaleAsync(connection, transaction); - - await UpgradeAgentsTableAsync(connection, transaction); - - await UpgradeAgentSessionsMetadataColumnsAsync(connection, transaction); - - if (version == 8) - { - await ResetLegacyAgentStateAsync(connection, transaction); - } - await connection.ExecuteAsync( $"""PRAGMA user_version = {CurrentVersion};""", transaction: transaction); await transaction.CommitAsync(cancellationToken); - // The constraint rebuild runs after the schema transaction commits. - await RebuildAgentSessionsHarnessCheckConstraintIfStaleAsync(connection, cancellationToken); - return connection; } - private static Task ResetLegacyAgentStateAsync( - SqliteConnection connection, - DbTransaction transaction) - => connection.ExecuteAsync( - """ - DELETE FROM mail_wake_targets; - DELETE FROM mail_wake_batches; - DELETE FROM mail_wake_outbox; - DELETE FROM mail_wake_daemons; - DELETE FROM session_ping_gates; - DELETE FROM session_deliveries; - DELETE FROM ping_leases; - DELETE FROM message_recipients; - DELETE FROM messages; - DELETE FROM agent_sessions; - DELETE FROM agent_session_identities; - DELETE FROM agents; - """, - transaction: transaction); - - /// - /// Adds any missing role, implicit, and client columns to the agents table. - /// - private static async Task UpgradeAgentsTableAsync( - SqliteConnection connection, - DbTransaction transaction) - { - var columns = (await connection.QueryAsync( - "SELECT name FROM pragma_table_info('agents');", transaction: transaction)) - .ToHashSet(StringComparer.Ordinal); - - if (!columns.Contains("role")) - { - await connection.ExecuteAsync( - "ALTER TABLE agents ADD COLUMN role TEXT NOT NULL DEFAULT '';", - transaction: transaction); - } - - if (!columns.Contains("implicit")) - { - await connection.ExecuteAsync( - "ALTER TABLE agents ADD COLUMN implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1));", - transaction: transaction); - } - - if (!columns.Contains("client")) - { - await connection.ExecuteAsync( - "ALTER TABLE agents ADD COLUMN client TEXT NOT NULL DEFAULT '';", - transaction: transaction); - } - } - - /// - /// Adds missing session metadata and delivery-state columns. - /// - private static async Task UpgradeAgentSessionsMetadataColumnsAsync( - SqliteConnection connection, - DbTransaction transaction) - { - var columns = (await connection.QueryAsync( - "SELECT name FROM pragma_table_info('agent_sessions');", transaction: transaction)) - .ToHashSet(StringComparer.Ordinal); - - if (!columns.Contains("role")) - { - await connection.ExecuteAsync( - "ALTER TABLE agent_sessions ADD COLUMN role TEXT NOT NULL DEFAULT '';", - transaction: transaction); - } - - if (!columns.Contains("harness_version")) - { - await connection.ExecuteAsync( - "ALTER TABLE agent_sessions ADD COLUMN harness_version TEXT NOT NULL DEFAULT '';", - transaction: transaction); - } - - if (!columns.Contains("endpoint_secret")) - { - await connection.ExecuteAsync( - "ALTER TABLE agent_sessions ADD COLUMN endpoint_secret TEXT NULL;", - transaction: transaction); - } - - if (!columns.Contains("announcement_pending")) - { - await connection.ExecuteAsync( - "ALTER TABLE agent_sessions ADD COLUMN announcement_pending INTEGER NOT NULL DEFAULT 0 " - + "CHECK (announcement_pending IN (0, 1));", - transaction: transaction); - } - - if (!columns.Contains("idle_push_armed")) - { - await connection.ExecuteAsync( - "ALTER TABLE agent_sessions ADD COLUMN idle_push_armed INTEGER NOT NULL DEFAULT 0 " - + "CHECK (idle_push_armed IN (0, 1));", - transaction: transaction); - } - } - /// - /// Rebuilds agent_sessions in place when its stamped CHECK - /// constraint on last_ping_result predates unsupported. A - /// no-op when the constraint already lists unsupported or when - /// the table does not exist yet. + /// Drops every agent-domain table (identity, session, wake, and ping + /// state) so the schema creation that follows lays them down fresh. Mail, + /// task, and memory tables are left untouched. A no-op for tables that do + /// not exist yet. /// - private static async Task RebuildAgentSessionsCheckConstraintIfStaleAsync( + private static async Task ResetAgentDomainTablesAsync( SqliteConnection connection, CancellationToken cancellationToken) { - var createTableSql = await connection.ExecuteScalarAsync( - "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'agent_sessions';"); - - if (createTableSql is null || createTableSql.Contains("'unsupported'", StringComparison.Ordinal)) - { - return; - } - await connection.ExecuteAsync("PRAGMA foreign_keys = OFF;"); try { await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - const string rebuildTableName = "agent_sessions_check_rebuild"; - - await connection.ExecuteAsync( - $"""DROP TABLE IF EXISTS "{rebuildTableName}";""", transaction: transaction); await connection.ExecuteAsync( - AgentSessionSchema.CreateAgentSessionsTable(rebuildTableName), transaction: transaction); - await connection.ExecuteAsync( - $""" - INSERT INTO "{rebuildTableName}" ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - block_budget_used, last_ping_at, last_ping_attempt, last_ping_result, last_ping_detail - ) - SELECT - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - block_budget_used, last_ping_at, last_ping_attempt, last_ping_result, last_ping_detail - FROM agent_sessions; + """ + DROP TABLE IF EXISTS agent_sessions; + DROP TABLE IF EXISTS agent_session_identities; + DROP TABLE IF EXISTS session_deliveries; + DROP TABLE IF EXISTS session_ping_gates; + DROP TABLE IF EXISTS ping_leases; + DROP TABLE IF EXISTS mail_wake_outbox; + DROP TABLE IF EXISTS mail_wake_batches; + DROP TABLE IF EXISTS mail_wake_targets; + DROP TABLE IF EXISTS mail_wake_daemons; + DROP TABLE IF EXISTS agent_deliveries; + DROP TABLE IF EXISTS agent_ping_gates; + DROP TABLE IF EXISTS agents; """, transaction: transaction); - await connection.ExecuteAsync("DROP TABLE agent_sessions;", transaction: transaction); - await connection.ExecuteAsync( - $"""ALTER TABLE "{rebuildTableName}" RENAME TO agent_sessions;""", transaction: transaction); - - await connection.ExecuteAsync( - "CREATE INDEX IF NOT EXISTS idx_agent_sessions_name ON agent_sessions (agent_name);", - transaction: transaction); await transaction.CommitAsync(cancellationToken); } @@ -271,25 +148,18 @@ await connection.ExecuteAsync( } /// - /// Rebuilds agent_sessions in place when its stamped CHECK - /// constraints on harness or endpoint_kind predate the - /// current accepted values, or when it still carries the retired - /// pid column. A no-op when the table is already current or does - /// not exist yet. + /// Rebuilds messages and message_recipients so neither + /// column carries a foreign key to agents, preserving every row. + /// A no-op when the mail tables do not exist yet. /// - private static async Task RebuildAgentSessionsHarnessCheckConstraintIfStaleAsync( + private static async Task RemoveMailAgentForeignKeysAsync( SqliteConnection connection, CancellationToken cancellationToken) { - var createTableSql = await connection.ExecuteScalarAsync( - "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'agent_sessions';"); - - if (createTableSql is null - || (createTableSql.Contains("'opencode'", StringComparison.Ordinal) - && createTableSql.Contains("'nitro-board'", StringComparison.Ordinal) - && createTableSql.Contains("'opencode-server'", StringComparison.Ordinal) - && createTableSql.Contains("endpoint_secret", StringComparison.Ordinal) - && !createTableSql.Contains("pid INTEGER", StringComparison.Ordinal))) + var mailTablesExist = await connection.ExecuteScalarAsync( + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'messages';") > 0; + + if (!mailTablesExist) { return; } @@ -300,35 +170,49 @@ private static async Task RebuildAgentSessionsHarnessCheckConstraintIfStaleAsync { await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - const string rebuildTableName = "agent_sessions_harness_rebuild"; - - await connection.ExecuteAsync( - $"""DROP TABLE IF EXISTS "{rebuildTableName}";""", transaction: transaction); await connection.ExecuteAsync( - AgentSessionSchema.CreateAgentSessionsTable(rebuildTableName), transaction: transaction); - await connection.ExecuteAsync( - $""" - INSERT INTO "{rebuildTableName}" ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, endpoint_secret, started_at, last_beat_at, - block_budget_used, last_ping_at, last_ping_attempt, last_ping_result, last_ping_detail, - role, harness_version - ) - SELECT - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, endpoint_secret, started_at, last_beat_at, - block_budget_used, last_ping_at, last_ping_attempt, last_ping_result, last_ping_detail, - role, harness_version - FROM agent_sessions; + """ + CREATE TABLE messages_new ( + id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + in_reply_to TEXT REFERENCES messages (id), + sender TEXT NOT NULL, + subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 500), + body TEXT NOT NULL, + created_at TEXT NOT NULL + ); + + INSERT INTO messages_new (id, thread_id, in_reply_to, sender, subject, body, created_at) + SELECT id, thread_id, in_reply_to, sender, subject, body, created_at FROM messages; + + CREATE TABLE message_recipients_new ( + message_id TEXT NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + recipient TEXT NOT NULL, + kind TEXT NOT NULL DEFAULT 'to' CHECK (kind IN ('to', 'cc')), + ordinal INTEGER NOT NULL CHECK (ordinal >= 0), + read_at TEXT, + archived_at TEXT, + PRIMARY KEY (message_id, recipient), + UNIQUE (message_id, ordinal) + ); + + INSERT INTO message_recipients_new (message_id, recipient, kind, ordinal, read_at, archived_at) + SELECT message_id, recipient, kind, ordinal, read_at, archived_at FROM message_recipients; + + DROP TABLE message_recipients; + DROP TABLE messages; + + ALTER TABLE messages_new RENAME TO messages; + ALTER TABLE message_recipients_new RENAME TO message_recipients; + + CREATE INDEX idx_messages_thread_id ON messages (thread_id); + CREATE INDEX idx_messages_created_at ON messages (created_at); + CREATE INDEX idx_messages_sender ON messages (sender); + + CREATE INDEX idx_message_recipients_recipient + ON message_recipients (recipient); """, transaction: transaction); - await connection.ExecuteAsync("DROP TABLE agent_sessions;", transaction: transaction); - await connection.ExecuteAsync( - $"""ALTER TABLE "{rebuildTableName}" RENAME TO agent_sessions;""", transaction: transaction); - - await connection.ExecuteAsync( - "CREATE INDEX IF NOT EXISTS idx_agent_sessions_name ON agent_sessions (agent_name);", - transaction: transaction); await transaction.CommitAsync(cancellationToken); } @@ -338,140 +222,6 @@ await connection.ExecuteAsync( } } - /// - /// Rebuilds agent_session_identities when its harness CHECK - /// constraint predates the opencode harness value. - /// - private static async Task RebuildAgentSessionIdentitiesHarnessCheckConstraintIfStaleAsync( - SqliteConnection connection, - DbTransaction transaction) - { - var createTableSql = await connection.ExecuteScalarAsync( - "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'agent_session_identities';", - transaction: transaction); - - if (createTableSql is null || createTableSql.Contains("'opencode'", StringComparison.Ordinal)) - { - return; - } - - const string rebuildTableName = "agent_session_identities_harness_rebuild"; - - await connection.ExecuteAsync( - $"""DROP TABLE IF EXISTS "{rebuildTableName}";""", transaction: transaction); - await connection.ExecuteAsync( - AgentSessionIdentitySchema.CreateAgentSessionIdentitiesTable(rebuildTableName), transaction: transaction); - await connection.ExecuteAsync( - $""" - INSERT INTO "{rebuildTableName}" ( - harness, session_id, actor, role, actor_revision, created_at, last_seen_at - ) - SELECT - harness, session_id, actor, role, actor_revision, created_at, last_seen_at - FROM agent_session_identities; - """, - transaction: transaction); - await connection.ExecuteAsync("DROP TABLE agent_session_identities;", transaction: transaction); - await connection.ExecuteAsync( - $"""ALTER TABLE "{rebuildTableName}" RENAME TO agent_session_identities;""", transaction: transaction); - await connection.ExecuteAsync( - "CREATE INDEX IF NOT EXISTS idx_agent_session_identities_actor " - + "ON agent_session_identities (actor);", - transaction: transaction); - } - - /// - /// Rebuilds mail_wake_targets in place when its stamped - /// harness CHECK constraint predates the current accepted values, - /// or when it still carries the retired pid column. A no-op when - /// the table is already current, or when it does not exist yet. - /// - private static async Task RebuildMailWakeTargetsHarnessCheckConstraintIfStaleAsync( - SqliteConnection connection, - DbTransaction transaction) - { - var createTableSql = await connection.ExecuteScalarAsync( - "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'mail_wake_targets';", - transaction: transaction); - - if (createTableSql is null - || (createTableSql.Contains("'opencode'", StringComparison.Ordinal) - && createTableSql.Contains("'nitro-board'", StringComparison.Ordinal) - && !createTableSql.Contains("pid INTEGER", StringComparison.Ordinal))) - { - return; - } - - const string rebuildTableName = "mail_wake_targets_harness_rebuild"; - - await connection.ExecuteAsync( - $"""DROP TABLE IF EXISTS "{rebuildTableName}";""", transaction: transaction); - await connection.ExecuteAsync( - MailWakeSchema.CreateMailWakeTargetsTable(rebuildTableName), transaction: transaction); - await connection.ExecuteAsync( - $""" - INSERT INTO "{rebuildTableName}" ( - batch_id, harness, session_id, host, - status, offered_generation, accepted_generation, last_error, updated_at - ) - SELECT - batch_id, harness, session_id, host, - status, offered_generation, accepted_generation, last_error, updated_at - FROM mail_wake_targets; - """, - transaction: transaction); - await connection.ExecuteAsync("DROP TABLE mail_wake_targets;", transaction: transaction); - await connection.ExecuteAsync( - $"""ALTER TABLE "{rebuildTableName}" RENAME TO mail_wake_targets;""", transaction: transaction); - } - - /// - /// Rebuilds session_ping_gates in place when its stamped - /// harness CHECK constraint predates the current accepted values, - /// or when it still carries the retired pid column. A no-op when - /// the table is already current, or when it does not exist yet. - /// - private static async Task RebuildSessionPingGatesHarnessCheckConstraintIfStaleAsync( - SqliteConnection connection, - DbTransaction transaction) - { - var createTableSql = await connection.ExecuteScalarAsync( - "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'session_ping_gates';", - transaction: transaction); - - if (createTableSql is null - || (createTableSql.Contains("'opencode'", StringComparison.Ordinal) - && createTableSql.Contains("'nitro-board'", StringComparison.Ordinal) - && !createTableSql.Contains("pid INTEGER", StringComparison.Ordinal))) - { - return; - } - - const string rebuildTableName = "session_ping_gates_harness_rebuild"; - - await connection.ExecuteAsync( - $"""DROP TABLE IF EXISTS "{rebuildTableName}";""", transaction: transaction); - await connection.ExecuteAsync( - SessionPingGateSchema.CreateSessionPingGatesTable(rebuildTableName), transaction: transaction); - await connection.ExecuteAsync( - $""" - INSERT INTO "{rebuildTableName}" ( - harness, session_id, host, attempt_id, acquired_at, expires_at - ) - SELECT - harness, session_id, host, attempt_id, acquired_at, expires_at - FROM session_ping_gates; - """, - transaction: transaction); - await connection.ExecuteAsync("DROP TABLE session_ping_gates;", transaction: transaction); - await connection.ExecuteAsync( - $"""ALTER TABLE "{rebuildTableName}" RENAME TO session_ping_gates;""", transaction: transaction); - - await connection.ExecuteAsync( - "CREATE INDEX IF NOT EXISTS idx_session_ping_gates_expires ON session_ping_gates (expires_at);", - transaction: transaction); - } - /// /// Opens a connection to the workspace database at the given directory /// for normal use. Throws when the @@ -563,11 +313,13 @@ private static async Task OpenAsync( return connection; } - private static Task ConfigureAcceptedConnectionAsync( + private static async Task ConfigureAcceptedConnectionAsync( SqliteConnection connection, CancellationToken cancellationToken) - => connection.ExecuteAsync( - new CommandDefinition( - "PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;", - cancellationToken: cancellationToken)); + { + await using var command = connection.CreateCommand(); + command.CommandText = "PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"; + + await command.ExecuteNonQueryAsync(cancellationToken); + } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDeliveryLedger.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDeliveryLedger.cs new file mode 100644 index 00000000000..a3e316ea8cf --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDeliveryLedger.cs @@ -0,0 +1,130 @@ +using Microsoft.Data.Sqlite; + +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +internal sealed class AgentDeliveryLedger(IFileSystem fileSystem, AgentDatabase database) : IAgentDeliveryLedger +{ + public async Task> FindDeliveredAsync( + string agent, + IReadOnlyList messageIds, + CancellationToken cancellationToken) + { + if (messageIds.Count == 0) + { + return []; + } + + await using var connection = await ConnectAsync(cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + SELECT DISTINCT message_id + FROM agent_deliveries + WHERE agent = @agent AND message_id IN ( + """ + + string.Join(", ", messageIds.Select((_, index) => $"@messageId{index}")) + + ");"; + command.Parameters.AddWithValue("@agent", agent); + + for (var i = 0; i < messageIds.Count; i++) + { + command.Parameters.AddWithValue($"@messageId{i}", messageIds[i]); + } + + var delivered = new HashSet(StringComparer.Ordinal); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + delivered.Add(reader.GetString(0)); + } + + return messageIds.Where(delivered.Contains).ToArray(); + } + + public async Task> ReserveAsync( + string agent, + IReadOnlyList messageIds, + string channel, + DateTimeOffset deliveredAt, + CancellationToken cancellationToken) + { + if (messageIds.Count == 0) + { + return []; + } + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + + var reserved = new List(messageIds.Count); + + foreach (var messageId in messageIds) + { + await using var command = connection.CreateCommand(); + command.Transaction = (SqliteTransaction)transaction; + command.CommandText = + """ + INSERT INTO agent_deliveries (agent, message_id, channel, delivered_at) + VALUES (@agent, @messageId, @channel, @deliveredAt) + ON CONFLICT DO NOTHING; + """; + command.Parameters.AddWithValue("@agent", agent); + command.Parameters.AddWithValue("@messageId", messageId); + command.Parameters.AddWithValue("@channel", channel); + command.Parameters.AddWithValue("@deliveredAt", deliveredAt); + + var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); + + if (rowsAffected > 0) + { + reserved.Add(messageId); + } + } + + await transaction.CommitAsync(cancellationToken); + + return reserved; + } + + public async Task ReleaseAsync( + string agent, + IReadOnlyList messageIds, + string channel, + CancellationToken cancellationToken) + { + if (messageIds.Count == 0) + { + return; + } + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + + foreach (var messageId in messageIds) + { + await using var command = connection.CreateCommand(); + command.Transaction = (SqliteTransaction)transaction; + command.CommandText = + """ + DELETE FROM agent_deliveries + WHERE agent = @agent AND message_id = @messageId AND channel = @channel; + """; + command.Parameters.AddWithValue("@agent", agent); + command.Parameters.AddWithValue("@messageId", messageId); + command.Parameters.AddWithValue("@channel", channel); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + await transaction.CommitAsync(cancellationToken); + } + + private async Task ConnectAsync(CancellationToken cancellationToken) + { + var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) + ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); + + return await database.ConnectAsync(workspaceDirectory, cancellationToken); + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDeliverySchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDeliverySchema.cs new file mode 100644 index 00000000000..0472e0cfb93 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentDeliverySchema.cs @@ -0,0 +1,18 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Defines per-channel delivery reservations keyed by agent name. +/// +internal static class AgentDeliverySchema +{ + public const string Create = + """ + CREATE TABLE IF NOT EXISTS agent_deliveries ( + agent TEXT NOT NULL REFERENCES agents (name), + message_id TEXT NOT NULL, + channel TEXT NOT NULL CHECK (channel IN ('digest', 'gate', 'ping')), + delivered_at TEXT NOT NULL, + PRIMARY KEY (agent, message_id, channel) + ); + """; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentHarnessDisplay.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentHarnessDisplay.cs new file mode 100644 index 00000000000..9b3e58e9b69 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentHarnessDisplay.cs @@ -0,0 +1,19 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Maps a canonical harness id to the display name shown by the CLI list and the board. +/// +internal static class AgentHarnessDisplay +{ + /// + /// Returns the display name for , or - for a login-only agent. + /// + public static string Name(string? harness) => harness switch + { + "claude-code" => "Claude Code", + "codex" => "Codex", + "copilot" => "Copilot", + "opencode" => "OpenCode", + _ => "-" + }; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentNamePool.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentNamePool.cs new file mode 100644 index 00000000000..959db38c09b --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentNamePool.cs @@ -0,0 +1,55 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// The pool of first names draws from when it mints a new +/// agent name. Every entry satisfies the MailAgentName rules and none collides with a +/// well-known agent role word. +/// +internal static class AgentNamePool +{ + private static readonly string[] s_names = + [ + "ackbar", "ahsoka", "aladdin", "albus", "alice", "anakin", "andy", "angel", "anna", "annabelle", + "annabeth", "aragorn", "argus", "ariel", "arwen", "ash", "atta", "atticus", "austin", "bail", + "balin", "bard", "barry", "bathilda", "baymax", "bella", "bellatrix", "belle", "benjamin", "betsy", + "biff", "bilbo", "billy", "blondie", "boba", "bobby", "boromir", "brian", "bruce", "bubba", + "bucky", "butch", "buzz", "cal", "cameron", "carl", "carlito", "carol", "carrie", "cassian", + "cedric", "charles", "chewbacca", "cho", "chucky", "cinna", "claire", "clara", "clarice", "clark", + "clayton", "clint", "commodus", "connie", "coraline", "coriolanus", "dallas", "dan", "danny", "denethor", + "diana", "django", "dobby", "dolores", "dominic", "donny", "dooku", "dorothy", "dory", "draco", + "drax", "dutch", "dwalin", "edward", "effie", "einstein", "elinor", "elle", "ellen", "ellie", + "elliot", "elrond", "elsa", "elvira", "emmett", "eowyn", "erik", "esmeralda", "ethan", "eve", + "faramir", "fergus", "ferris", "fili", "filius", "finn", "finnick", "fiona", "fleur", "flik", + "forrest", "fred", "fredo", "frenchy", "frodo", "frollo", "furiosa", "galadriel", "gale", "gamora", + "gandalf", "gaston", "george", "gertie", "gimli", "ginny", "gisele", "glinda", "gogo", "gollum", + "groot", "grover", "hagrid", "hamm", "hammond", "han", "hank", "hannibal", "harley", "harry", + "haymitch", "hector", "hedwig", "hela", "henry", "hercules", "hermione", "hicks", "hiro", "holdo", + "hope", "hux", "ilsa", "indiana", "iorek", "iris", "jabba", "jack", "jacob", "jafar", + "jane", "jango", "jasmine", "jason", "jasper", "jean", "jeffrey", "jem", "jennifer", "jenny", + "jessie", "jimmy", "johanna", "john", "josey", "joy", "jules", "jyn", "kamala", "kane", + "karen", "katarina", "katniss", "kenickie", "kida", "kili", "kingsley", "kitty", "korg", "kristoff", + "kubo", "kurt", "kuzco", "kyle", "kylo", "lando", "laura", "laurie", "legolas", "leia", + "letty", "lex", "lilo", "logan", "loki", "lorraine", "louis", "lucilla", "lucius", "luke", + "luna", "lyra", "malcolm", "manny", "mara", "marion", "marla", "marlin", "marsellus", "marty", + "maude", "maui", "max", "maximus", "megara", "megatron", "merida", "merry", "mia", "miguel", + "mike", "mikey", "milo", "minerva", "moana", "molly", "monica", "morpheus", "mufasa", "mulan", + "muldoon", "myrtle", "nakia", "nala", "nani", "narcissa", "natasha", "nedry", "nemo", "neo", + "neville", "newt", "nick", "nien", "norman", "nova", "nux", "nymphadora", "obi", "okoye", + "olaf", "optimus", "ororo", "oswald", "owen", "pacha", "padme", "palpatine", "pamela", "paulie", + "peeta", "pennywise", "pepper", "percy", "peter", "phil", "piotr", "pippin", "plo", "pocahontas", + "poe", "pomona", "primrose", "pumbaa", "quasimodo", "quill", "radagast", "rambo", "raven", "regan", + "remus", "remy", "renesmee", "rex", "rexy", "rey", "rhett", "rick", "riley", "ripley", + "riri", "rizzo", "robert", "roman", "ron", "rosalie", "rose", "rubeus", "russell", "sam", + "samara", "sandy", "sarah", "saruman", "scabior", "scarlett", "scott", "scout", "sebastian", "selina", + "severus", "shmi", "shrek", "shuri", "simba", "sirius", "sloane", "smaug", "snoke", "sonny", + "stephen", "steve", "sulley", "tarzan", "tej", "theoden", "theodore", "thor", "thorin", "thranduil", + "thrawn", "timon", "tom", "tommy", "tony", "toto", "travis", "treebeard", "trinity", "tuco", + "tyler", "ursula", "valkyrie", "victor", "viktor", "vincent", "vito", "wade", "walter", "wanda", + "warren", "watto", "william", "willie", "wong", "woody", "wybie", "yoda", "yondu" + ]; + + /// + /// The full name pool, in declaration order. + /// + internal static IReadOnlyList Names => s_names; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingGateSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingGateSchema.cs new file mode 100644 index 00000000000..95f55658b5c --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingGateSchema.cs @@ -0,0 +1,19 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Defines the transport lease keyed by agent name. +/// +internal static class AgentPingGateSchema +{ + public const string Create = + """ + CREATE TABLE IF NOT EXISTS agent_ping_gates ( + agent TEXT PRIMARY KEY REFERENCES agents (name), + attempt_id TEXT NOT NULL, + acquired_at TEXT NOT NULL, + expires_at TEXT NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_agent_ping_gates_expires ON agent_ping_gates (expires_at); + """; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingGateStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingGateStore.cs new file mode 100644 index 00000000000..2165b067ab1 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingGateStore.cs @@ -0,0 +1,72 @@ +using Dapper; +using Microsoft.Data.Sqlite; + +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +internal sealed class AgentPingGateStore(IFileSystem fileSystem, AgentDatabase database) : IAgentPingGateStore +{ + public async Task TryAcquireAsync( + string agent, + string attemptId, + DateTimeOffset now, + TimeSpan leaseDuration, + CancellationToken cancellationToken) + { + await using var connection = await ConnectAsync(cancellationToken); + + // An unexpired gate remains claimed by its current attempt. + var claimed = await connection.QueryFirstOrDefaultAsync( + """ + INSERT INTO agent_ping_gates (agent, attempt_id, acquired_at, expires_at) + VALUES (@agent, @attemptId, @now, @expiresAt) + ON CONFLICT (agent) DO UPDATE SET + attempt_id = excluded.attempt_id, + acquired_at = excluded.acquired_at, + expires_at = excluded.expires_at + WHERE agent_ping_gates.expires_at <= @now + RETURNING attempt_id + """, + new { agent, attemptId, now, expiresAt = now + leaseDuration }); + + return claimed is not null; + } + + public async Task TryRenewAsync( + string agent, + string attemptId, + DateTimeOffset now, + TimeSpan leaseDuration, + CancellationToken cancellationToken) + { + await using var connection = await ConnectAsync(cancellationToken); + + var renewed = await connection.QueryFirstOrDefaultAsync( + """ + UPDATE agent_ping_gates SET expires_at = @expiresAt + WHERE agent = @agent AND attempt_id = @attemptId AND expires_at > @now + RETURNING attempt_id + """, + new { agent, attemptId, now, expiresAt = now + leaseDuration }); + + return renewed is not null; + } + + public async Task ReleaseAsync(string agent, string attemptId, CancellationToken cancellationToken) + { + await using var connection = await ConnectAsync(cancellationToken); + + await connection.ExecuteAsync( + """ + DELETE FROM agent_ping_gates WHERE agent = @agent AND attempt_id = @attemptId + """, + new { agent, attemptId }); + } + + private async Task ConnectAsync(CancellationToken cancellationToken) + { + var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) + ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); + + return await database.ConnectAsync(workspaceDirectory, cancellationToken); + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingResult.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingResult.cs index c70fd1fc160..a9570d8370f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingResult.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPingResult.cs @@ -1,7 +1,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// The agent_sessions.last_ping_result values, matching the table's +/// The agents.last_ping_result values, matching the table's /// CHECK constraint. /// internal static class AgentPingResult diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPresence.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPresence.cs deleted file mode 100644 index c74d84f43ba..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPresence.cs +++ /dev/null @@ -1,67 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// The combined presence of an actor's surviving sessions. -/// -internal sealed record AgentPresence( - string State, - bool Conflicted, - int SessionCount, - string? EndpointKind, - string? EndpointAddr, - string? Activity) -{ - /// - /// The display order for distinct session states in a conflicted presence. - /// - private static readonly string[] s_statePriority = - [ - AgentSessionState.Online, - AgentSessionState.Unreachable, - AgentSessionState.Unobservable, - AgentSessionState.Remote - ]; - - /// - /// The presence of an agent with no live sessions at all. - /// - public static readonly AgentPresence Offline = new(AgentPresenceState.Offline, false, 0, null, null, null); - - /// - /// Combines one actor's sessions into a presence, joining distinct states in priority - /// order and marking conflicts when states differ. Endpoint details require exactly - /// one session; activity additionally requires that session to be online in Claude Code. - /// - public static AgentPresence Compute( - IReadOnlyList sessions, IClaudeSessionActivityReader activityReader) - { - if (sessions.Count == 0) - { - return Offline; - } - - var distinctStates = sessions.Select(v => v.State).Distinct().ToArray(); - var conflicted = distinctStates.Length > 1; - var state = conflicted - ? string.Join("+", s_statePriority.Where(distinctStates.Contains)) - : distinctStates[0]; - - string? endpointKind = null; - string? endpointAddr = null; - string? activity = null; - - if (sessions.Count == 1) - { - var only = sessions[0]; - endpointKind = only.Session.EndpointKind; - endpointAddr = only.Session.EndpointAddr; - - if (only.State == AgentSessionState.Online && only.Session.Harness == AgentSessionHarness.ClaudeCode) - { - activity = activityReader.GetStatus(only.Session.SessionId); - } - } - - return new AgentPresence(state, conflicted, sessions.Count, endpointKind, endpointAddr, activity); - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPresenceState.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPresenceState.cs deleted file mode 100644 index c6615f4e758..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentPresenceState.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Actor presence states, including offline when the actor has no surviving sessions. -/// -internal static class AgentPresenceState -{ - public const string Offline = "offline"; - public const string Online = AgentSessionState.Online; - public const string Unreachable = AgentSessionState.Unreachable; - public const string Unobservable = AgentSessionState.Unobservable; - public const string Remote = AgentSessionState.Remote; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRecord.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRecord.cs deleted file mode 100644 index 97f55530529..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRecord.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// An agent identity shared by workspace features. -/// -internal sealed record AgentRecord -{ - /// - /// The column list matching this type's properties, for use in SELECT - /// statements against the agents table. - /// - public const string Columns = - "name AS Name, role AS Role, client AS Client, implicit AS Implicit, " - + "registered_at AS RegisteredAt, last_seen_at AS LastSeenAt"; - - public required string Name { get; init; } - public required string Role { get; init; } - - /// - /// The normalized lowercase client program name, or empty when unknown. - /// - public required string Client { get; init; } - - /// - /// True for a placeholder identity that has not been registered or marked active. - /// - public required bool Implicit { get; init; } - - public required DateTimeOffset RegisteredAt { get; init; } - public required DateTimeOffset LastSeenAt { get; init; } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistry.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistry.cs deleted file mode 100644 index 0ab9e656b83..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistry.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System.Data.Common; -using System.Globalization; -using ChilliCream.Nitro.CommandLine.Services.Mail; -using Dapper; -using Microsoft.Data.Sqlite; - -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed class AgentRegistry( - IFileSystem fileSystem, - TimeProvider timeProvider, - AgentDatabase database) : IAgentRegistry -{ - public async Task RegisterAsync( - string name, - string role, - string client, - CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var agent = await UpsertWithinTransactionAsync( - connection, transaction, timeProvider, name, role, client, cancellationToken); - - await transaction.CommitAsync(cancellationToken); - - return agent; - } - - public async Task AllocateAsync(CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var actor = await AgentActorAllocator.AllocateAsync(connection, transaction); - var agent = await UpsertWithinTransactionAsync( - connection, transaction, timeProvider, actor, string.Empty, string.Empty, cancellationToken); - - await transaction.CommitAsync(cancellationToken); - - return agent; - } - - /// - /// Registers an agent within the supplied transaction using normalized name, role, - /// and client values. Refreshes last-seen time, clears the implicit flag, and - /// replaces the role and client values. - /// - public static async Task UpsertWithinTransactionAsync( - SqliteConnection connection, - DbTransaction transaction, - TimeProvider timeProvider, - string name, - string role, - string client, - CancellationToken cancellationToken) - { - var normalizedName = MailAgentName.Normalize(name); - var normalizedRole = AgentRole.Normalize(role); - var normalizedClient = NormalizeClient(client); - var now = timeProvider.GetUtcNow(); - - var row = await connection.QueryFirstAsync( - """ - INSERT INTO agents (name, registered_at, last_seen_at, role, client, implicit) - VALUES (@name, @now, @now, @role, @client, 0) - ON CONFLICT (name) DO UPDATE SET - last_seen_at = @now, - role = @role, - client = @client, - implicit = 0 - RETURNING - name AS Name, - role AS Role, - client AS Client, - implicit AS Implicit, - registered_at AS RegisteredAt, - last_seen_at AS LastSeenAt - """, - new { name = normalizedName, now, role = normalizedRole, client = normalizedClient, cancellationToken }, - transaction); - - return row.ToAgentRecord(); - } - - public async Task TouchAsync( - string name, - CancellationToken cancellationToken) - { - var normalizedName = MailAgentName.Normalize(name); - var now = timeProvider.GetUtcNow(); - - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var row = await connection.QueryFirstAsync( - """ - INSERT INTO agents (name, registered_at, last_seen_at, role, client, implicit) - VALUES (@name, @now, @now, '', '', 0) - ON CONFLICT (name) DO UPDATE SET - last_seen_at = @now, - implicit = 0 - RETURNING - name AS Name, - role AS Role, - client AS Client, - implicit AS Implicit, - registered_at AS RegisteredAt, - last_seen_at AS LastSeenAt - """, - new { name = normalizedName, now, cancellationToken }, - transaction); - - await transaction.CommitAsync(cancellationToken); - - return row.ToAgentRecord(); - } - - public async Task GetAsync( - string name, - CancellationToken cancellationToken) - { - var normalizedName = MailAgentName.Normalize(name); - - await using var connection = await ConnectAsync(cancellationToken); - - var row = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentRecord.Columns} FROM agents WHERE name = @name", - new { name = normalizedName, cancellationToken }); - - return row?.ToAgentRecord(); - } - - public async Task EnsureImplicitAsync( - string name, - CancellationToken cancellationToken) - { - var normalizedName = MailAgentName.Normalize(name); - var now = timeProvider.GetUtcNow(); - - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - // Existing agent values are preserved. - var row = await connection.QueryFirstAsync( - """ - INSERT INTO agents (name, registered_at, last_seen_at, role, client, implicit) - VALUES (@name, @now, @now, '', '', 1) - ON CONFLICT (name) DO UPDATE SET name = excluded.name - RETURNING - name AS Name, - role AS Role, - client AS Client, - implicit AS Implicit, - registered_at AS RegisteredAt, - last_seen_at AS LastSeenAt - """, - new { name = normalizedName, now, cancellationToken }, - transaction); - - await transaction.CommitAsync(cancellationToken); - - return row.ToAgentRecord(); - } - - public async Task> ListAsync( - string? role, - DateTimeOffset? staleBefore, - CancellationToken cancellationToken) - { - var normalizedRole = role is null ? null : AgentRole.Normalize(role); - - await using var connection = await ConnectAsync(cancellationToken); - - if (normalizedRole is null && staleBefore is null) - { - var rows = await connection.QueryAsync( - $"SELECT {AgentRecord.Columns} FROM agents ORDER BY name"); - - return rows.Select(r => r.ToAgentRecord()).ToList(); - } - - if (normalizedRole is not null && staleBefore is null) - { - var rows = await connection.QueryAsync( - $"SELECT {AgentRecord.Columns} FROM agents WHERE role = @role ORDER BY name", - new { role = normalizedRole, cancellationToken }); - - return rows.Select(r => r.ToAgentRecord()).ToList(); - } - - if (normalizedRole is null) - { - var rows = await connection.QueryAsync( - $""" - SELECT {AgentRecord.Columns} FROM agents - WHERE last_seen_at < @staleBefore - ORDER BY name - """, - new { staleBefore, cancellationToken }); - - return rows.Select(r => r.ToAgentRecord()).ToList(); - } - - var filteredRows = await connection.QueryAsync( - $""" - SELECT {AgentRecord.Columns} FROM agents - WHERE role = @role AND last_seen_at < @staleBefore - ORDER BY name - """, - new { role = normalizedRole, staleBefore, cancellationToken }); - - return filteredRows.Select(r => r.ToAgentRecord()).ToList(); - } - - /// - /// Trims and lowercases the client name; null or whitespace yields an empty string. - /// - private static string NormalizeClient(string? client) => (client ?? string.Empty).Trim().ToLowerInvariant(); - - private async Task ConnectAsync(CancellationToken cancellationToken) - { - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException( - "No agent workspace found. Run `nitro agent init` first."); - - return await database.ConnectAsync(workspaceDirectory, cancellationToken); - } - - internal sealed class AgentRegistryRow - { - public required string Name { get; init; } - public required string Role { get; init; } - public required string Client { get; init; } - public required bool Implicit { get; init; } - public required string RegisteredAt { get; init; } - public required string LastSeenAt { get; init; } - - public AgentRecord ToAgentRecord() => new() - { - Name = Name, - Role = Role, - Client = Client, - Implicit = Implicit, - RegisteredAt = DateTimeOffset.Parse(RegisteredAt, CultureInfo.InvariantCulture), - LastSeenAt = DateTimeOffset.Parse(LastSeenAt, CultureInfo.InvariantCulture) - }; - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistrySchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistrySchema.cs index a6ff6f0b620..db562dd03af 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistrySchema.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRegistrySchema.cs @@ -3,17 +3,35 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; internal static class AgentRegistrySchema { /// - /// Creates the agent registry table if it does not exist; existing tables are unchanged. + /// Creates the unified agents table if it does not exist; existing tables are unchanged. /// public const string Create = """ CREATE TABLE IF NOT EXISTS agents ( name TEXT PRIMARY KEY, + role TEXT NOT NULL DEFAULT '', + harness TEXT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode')), + harness_version TEXT NOT NULL DEFAULT '', + session_id TEXT NULL, + cwd TEXT NOT NULL DEFAULT '', + workspace_path TEXT NOT NULL DEFAULT '', registered_at TEXT NOT NULL, + started_at TEXT NOT NULL, last_seen_at TEXT NOT NULL, - role TEXT NOT NULL DEFAULT '', - implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)), - client TEXT NOT NULL DEFAULT '' + ended_at TEXT NULL, + deleted_at TEXT NULL, + endpoint_kind TEXT NOT NULL DEFAULT 'none' CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'opencode-server', 'db-watch', 'none')), + endpoint_addr TEXT NOT NULL DEFAULT '', + endpoint_secret TEXT NULL, + block_budget_used INTEGER NOT NULL DEFAULT 0, + last_ping_at TEXT NULL, + last_ping_attempt TEXT NULL, + last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), + last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), + announcement_pending INTEGER NOT NULL DEFAULT 0, + idle_push_armed INTEGER NOT NULL DEFAULT 0 ); + + CREATE UNIQUE INDEX IF NOT EXISTS idx_agents_session ON agents (harness, session_id) WHERE harness IS NOT NULL; """; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRow.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRow.cs new file mode 100644 index 00000000000..54f48146aae --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentRow.cs @@ -0,0 +1,146 @@ +using System.Globalization; +using Microsoft.Data.Sqlite; + +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// One row of the unified agents table: an agent's identity, its +/// harness session binding, presence, and wake state. +/// +internal sealed record AgentRow +{ + /// + /// The column list matching this type's properties, for use in SELECT + /// statements against the agents table. + /// + public const string Columns = + "name AS Name, role AS Role, harness AS Harness, harness_version AS HarnessVersion, " + + "session_id AS SessionId, cwd AS Cwd, workspace_path AS WorkspacePath, " + + "registered_at AS RegisteredAt, started_at AS StartedAt, last_seen_at AS LastSeenAt, " + + "ended_at AS EndedAt, deleted_at AS DeletedAt, endpoint_kind AS EndpointKind, " + + "endpoint_addr AS EndpointAddr, endpoint_secret AS EndpointSecret, " + + "block_budget_used AS BlockBudgetUsed, last_ping_at AS LastPingAt, " + + "last_ping_attempt AS LastPingAttempt, last_ping_result AS LastPingResult, " + + "last_ping_detail AS LastPingDetail, announcement_pending AS AnnouncementPending, " + + "idle_push_armed AS IdlePushArmed"; + + public required string Name { get; init; } + public required string Role { get; init; } + + /// + /// The canonical harness id, or null for a login-only agent. + /// + public string? Harness { get; init; } + + public required string HarnessVersion { get; init; } + + /// + /// The harness session id, or null for a login-only agent. + /// + public string? SessionId { get; init; } + + public required string Cwd { get; init; } + public required string WorkspacePath { get; init; } + public required DateTimeOffset RegisteredAt { get; init; } + public required DateTimeOffset StartedAt { get; init; } + public required DateTimeOffset LastSeenAt { get; init; } + + /// + /// When the agent's session ended, or null while it is still running. + /// + public DateTimeOffset? EndedAt { get; init; } + + /// + /// When the agent was soft-deleted, or null while it is active. + /// + public DateTimeOffset? DeletedAt { get; init; } + + public required string EndpointKind { get; init; } + + /// + /// Empty only when is none. + /// + public required string EndpointAddr { get; init; } + + /// + /// The credential for endpoints that require one, or null when the + /// endpoint has no credential. + /// + public string? EndpointSecret { get; init; } + + public required int BlockBudgetUsed { get; init; } + public DateTimeOffset? LastPingAt { get; init; } + + /// + /// The most recent ping attempt id, or null before an attempt is claimed. + /// + public string? LastPingAttempt { get; init; } + + /// + /// The most recent completed ping result from . + /// + public string? LastPingResult { get; init; } + + /// + /// The optional ping diagnostic, limited to 200 characters. + /// + public string? LastPingDetail { get; init; } + + public required bool AnnouncementPending { get; init; } + public required bool IdlePushArmed { get; init; } + + /// + /// True when the agent has been soft-deleted. + /// + public bool IsDeleted => DeletedAt is not null; + + /// + /// Reads the current row using the column names declared by . + /// + public static AgentRow ReadFrom(SqliteDataReader reader) => new() + { + Name = reader.GetString(reader.GetOrdinal("Name")), + Role = reader.GetString(reader.GetOrdinal("Role")), + Harness = reader.IsDBNull(reader.GetOrdinal("Harness")) + ? null + : reader.GetString(reader.GetOrdinal("Harness")), + HarnessVersion = reader.GetString(reader.GetOrdinal("HarnessVersion")), + SessionId = reader.IsDBNull(reader.GetOrdinal("SessionId")) + ? null + : reader.GetString(reader.GetOrdinal("SessionId")), + Cwd = reader.GetString(reader.GetOrdinal("Cwd")), + WorkspacePath = reader.GetString(reader.GetOrdinal("WorkspacePath")), + RegisteredAt = DateTimeOffset.Parse( + reader.GetString(reader.GetOrdinal("RegisteredAt")), CultureInfo.InvariantCulture), + StartedAt = DateTimeOffset.Parse( + reader.GetString(reader.GetOrdinal("StartedAt")), CultureInfo.InvariantCulture), + LastSeenAt = DateTimeOffset.Parse( + reader.GetString(reader.GetOrdinal("LastSeenAt")), CultureInfo.InvariantCulture), + EndedAt = reader.IsDBNull(reader.GetOrdinal("EndedAt")) + ? null + : DateTimeOffset.Parse(reader.GetString(reader.GetOrdinal("EndedAt")), CultureInfo.InvariantCulture), + DeletedAt = reader.IsDBNull(reader.GetOrdinal("DeletedAt")) + ? null + : DateTimeOffset.Parse(reader.GetString(reader.GetOrdinal("DeletedAt")), CultureInfo.InvariantCulture), + EndpointKind = reader.GetString(reader.GetOrdinal("EndpointKind")), + EndpointAddr = reader.GetString(reader.GetOrdinal("EndpointAddr")), + EndpointSecret = reader.IsDBNull(reader.GetOrdinal("EndpointSecret")) + ? null + : reader.GetString(reader.GetOrdinal("EndpointSecret")), + BlockBudgetUsed = reader.GetInt32(reader.GetOrdinal("BlockBudgetUsed")), + LastPingAt = reader.IsDBNull(reader.GetOrdinal("LastPingAt")) + ? null + : DateTimeOffset.Parse(reader.GetString(reader.GetOrdinal("LastPingAt")), CultureInfo.InvariantCulture), + LastPingAttempt = reader.IsDBNull(reader.GetOrdinal("LastPingAttempt")) + ? null + : reader.GetString(reader.GetOrdinal("LastPingAttempt")), + LastPingResult = reader.IsDBNull(reader.GetOrdinal("LastPingResult")) + ? null + : reader.GetString(reader.GetOrdinal("LastPingResult")), + LastPingDetail = reader.IsDBNull(reader.GetOrdinal("LastPingDetail")) + ? null + : reader.GetString(reader.GetOrdinal("LastPingDetail")), + AnnouncementPending = reader.GetInt32(reader.GetOrdinal("AnnouncementPending")) != 0, + IdlePushArmed = reader.GetInt32(reader.GetOrdinal("IdlePushArmed")) != 0 + }; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionBindingKind.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionBindingKind.cs deleted file mode 100644 index 5b5e9a9d80b..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionBindingKind.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// The agent_sessions.binding_kind values, matching the table's CHECK -/// constraint. -/// -internal static class AgentSessionBindingKind -{ - public const string None = "none"; - public const string Env = "env"; - public const string Explicit = "explicit"; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionClaimResult.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionClaimResult.cs deleted file mode 100644 index a04b8fab7cd..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionClaimResult.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// The session after a claim, whether its binding changed, and the prior binding -/// used by the claim transition. -/// -internal sealed record AgentSessionClaimResult( - AgentSessionRecord Session, bool Changed, string PreviousBindingKind, string? PreviousAgentName); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionEndpointKind.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionEndpointKind.cs index 9daaec34404..888fc9cb479 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionEndpointKind.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionEndpointKind.cs @@ -1,7 +1,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// The agent_sessions.endpoint_kind values, matching the table's +/// The agents.endpoint_kind values, matching the table's /// CHECK constraint. /// internal static class AgentSessionEndpointKind diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionGeneration.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionGeneration.cs deleted file mode 100644 index d5cd9b144ed..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionGeneration.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Identifies a harness session and its owning Nitro instance. -/// is the Nitro instance id. -/// -internal sealed record AgentSessionGeneration(string Harness, string SessionId, string Host); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionHarness.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionHarness.cs index d9eeb0a6d93..1bfded52758 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionHarness.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionHarness.cs @@ -1,7 +1,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// The agent_sessions.harness values, matching the table's CHECK +/// The agents.harness values, matching the table's CHECK /// constraint. /// internal static class AgentSessionHarness @@ -12,7 +12,9 @@ internal static class AgentSessionHarness public const string Opencode = "opencode"; /// - /// A Nitro agent board session. + /// Returns true when is one of the coding agent harnesses + /// (, , or ). /// - public const string NitroBoard = "nitro-board"; + public static bool IsAgentHarness(string harness) + => harness is ClaudeCode or Codex or Copilot or Opencode; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentityRecord.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentityRecord.cs deleted file mode 100644 index 28ae3943430..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentityRecord.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed record AgentSessionIdentityRecord -{ - public const string Columns = - "harness AS Harness, session_id AS SessionId, actor AS Actor, role AS Role, " - + "actor_revision AS ActorRevision, created_at AS CreatedAt, last_seen_at AS LastSeenAt"; - - public required string Harness { get; init; } - public required string SessionId { get; init; } - public required string Actor { get; init; } - public required string Role { get; init; } - public required long ActorRevision { get; init; } - public string CreatedAt { get; init; } = ""; - public string LastSeenAt { get; init; } = ""; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentitySchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentitySchema.cs deleted file mode 100644 index 890f24fe7aa..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentitySchema.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal static class AgentSessionIdentitySchema -{ - private const string AgentSessionIdentitiesColumns = - """ - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode')), - session_id TEXT NOT NULL, - actor TEXT NOT NULL UNIQUE REFERENCES agents (name), - role TEXT NOT NULL DEFAULT '', - actor_revision INTEGER NOT NULL DEFAULT 1 CHECK (actor_revision > 0), - created_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id) - """; - - public const string Create = - """ - CREATE TABLE IF NOT EXISTS agent_session_identities ( - """ - + AgentSessionIdentitiesColumns - + """ - ); - - CREATE INDEX IF NOT EXISTS idx_agent_session_identities_actor - ON agent_session_identities (actor); - """; - - public static string CreateAgentSessionIdentitiesTable(string tableName) => - $""" - CREATE TABLE "{tableName}" ( - {AgentSessionIdentitiesColumns} - ); - """; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentityView.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentityView.cs deleted file mode 100644 index 2c9c3fe2671..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionIdentityView.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed record AgentSessionIdentityView( - AgentSessionIdentityRecord Identity, - AgentSessionParticipant? Participant) -{ - public string State => Participant?.State ?? "offline"; - - public bool Online => Participant?.State == AgentSessionState.Online; - - public DateTimeOffset LastSeenAt - => Participant?.Session.LastBeatAt ?? DateTimeOffset.Parse(Identity.LastSeenAt); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionParticipant.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionParticipant.cs deleted file mode 100644 index 04aed1e8d8e..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionParticipant.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// A session, its associated agent identity when available, and its computed presence state. -/// -internal sealed record AgentSessionParticipant(AgentSessionRecord Session, AgentRecord? Agent, string State) -{ - /// - /// True when an associated agent exists and the session role matches - /// , or the session role is empty and the agent role matches. - /// - public bool MatchesRole(string normalizedRole) - => Agent is not null - && (Session.Role == normalizedRole || (Session.Role.Length is 0 && Agent.Role == normalizedRole)); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRecord.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRecord.cs deleted file mode 100644 index 7a2ba008e06..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRecord.cs +++ /dev/null @@ -1,82 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// A session presence record with its actor binding, endpoint, heartbeat, and ping state. -/// -internal sealed record AgentSessionRecord -{ - /// - /// The column list matching this type's properties, for use in SELECT - /// statements against the agent_sessions table. - /// - public const string Columns = - "harness AS Harness, session_id AS SessionId, agent_name AS AgentName, " - + "binding_kind AS BindingKind, host AS Host, cwd AS Cwd, workspace_path AS WorkspacePath, endpoint_kind AS EndpointKind, " - + "endpoint_addr AS EndpointAddr, endpoint_secret AS EndpointSecret, started_at AS StartedAt, last_beat_at AS LastBeatAt, " - + "block_budget_used AS BlockBudgetUsed, last_ping_at AS LastPingAt, " - + "last_ping_attempt AS LastPingAttempt, last_ping_result AS LastPingResult, " - + "last_ping_detail AS LastPingDetail, role AS Role, harness_version AS HarnessVersion"; - - public required string Harness { get; init; } - public required string SessionId { get; init; } - - /// - /// Null when the row is unclaimed ( is - /// "none"). - /// - public string? AgentName { get; init; } - - public required string BindingKind { get; init; } - - /// - /// This Nitro instance's id, not the OS hostname. - /// - public required string Host { get; init; } - - public required string Cwd { get; init; } - public required string WorkspacePath { get; init; } - public required string EndpointKind { get; init; } - - /// - /// Empty only when is "none". - /// - public required string EndpointAddr { get; init; } - - /// - /// The credential for endpoints that require one, or null when the - /// endpoint has no credential. - /// - public string? EndpointSecret { get; init; } - - public required DateTimeOffset StartedAt { get; init; } - public required DateTimeOffset LastBeatAt { get; init; } - public required int BlockBudgetUsed { get; init; } - public DateTimeOffset? LastPingAt { get; init; } - - /// - /// The most recent ping attempt id, or null before an attempt is claimed. - /// Only results carrying the current attempt id are recorded. - /// - public string? LastPingAttempt { get; init; } - - /// - /// The most recent completed ping result from . - /// Null before any attempt or while the latest attempt has no recorded result. - /// - public string? LastPingResult { get; init; } - - /// - /// The optional ping diagnostic, limited to 200 characters. - /// - public string? LastPingDetail { get; init; } - - /// - /// The normalized session role, or empty when no role is assigned. - /// - public required string Role { get; init; } - - /// - /// The most recently recorded harness version, or empty when no version is recorded. - /// - public required string HarnessVersion { get; init; } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRegisterResult.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRegisterResult.cs deleted file mode 100644 index 5ecac4db07c..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRegisterResult.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// The agent and session after registration, whether the binding or role changed, -/// and the prior binding reported by the registration operation. -/// -internal sealed record AgentSessionRegisterResult( - AgentRecord Agent, AgentSessionRecord Session, bool Changed, string PreviousBindingKind, string? PreviousAgentName); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRegistry.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRegistry.cs deleted file mode 100644 index 3ef303ba45d..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionRegistry.cs +++ /dev/null @@ -1,1401 +0,0 @@ -using System.Data.Common; -using System.Globalization; -using ChilliCream.Nitro.CommandLine.Services.Mail; -using Dapper; -using Microsoft.Data.Sqlite; - -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed class AgentSessionRegistry( - IFileSystem fileSystem, - TimeProvider timeProvider, - AgentDatabase database, - IAgentRegistry agentRegistry, - INitroInstanceIdProvider instanceIdProvider, - IGlobalConfigDirectoryProvider globalConfigDirectoryProvider) : IAgentSessionRegistry -{ - /// - /// The heartbeat age at which current-instance session presence becomes eligible for reaping. - /// - private static readonly TimeSpan s_staleAfter = TimeSpan.FromHours(24); - - /// - /// Invoked after a stale reap candidate is read and before its guarded delete. - /// - internal Func? OnStaleReapCandidateCapturedAsync { get; init; } - - public Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? envActor, - CancellationToken cancellationToken) - => StartAsync( - generation, - cwd, - workspacePath, - endpointKind, - endpointAddr, - endpointSecret: null, - envActor: envActor, - cancellationToken: cancellationToken); - - public async Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? endpointSecret, - string? envActor, - CancellationToken cancellationToken) - { - var now = timeProvider.GetUtcNow(); - var (normalizedEndpointKind, normalizedEndpointAddr, normalizedEndpointSecret) = - NormalizeEndpoint(generation.Harness, endpointKind, endpointAddr, endpointSecret); - - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = connection.BeginTransaction(deferred: false); - - string? boundAgentName; - string bindingKind; - string identityRole; - - if (generation.Harness is AgentSessionHarness.ClaudeCode - or AgentSessionHarness.Codex - or AgentSessionHarness.Copilot - or AgentSessionHarness.Opencode) - { - var identity = await EnsureCodingIdentityWithinTransactionAsync( - connection, transaction, generation, now, envActor, cancellationToken); - boundAgentName = identity.Actor; - bindingKind = envActor is not null - && identity.Actor == MailAgentName.Normalize(envActor) - ? AgentSessionBindingKind.Env - : AgentSessionBindingKind.Explicit; - identityRole = identity.Role; - } - else - { - boundAgentName = envActor is null ? null : MailAgentName.Normalize(envActor); - bindingKind = boundAgentName is null ? AgentSessionBindingKind.None : AgentSessionBindingKind.Env; - identityRole = string.Empty; - - if (boundAgentName is not null) - { - await EnsureImplicitActorWithinTransactionAsync( - connection, transaction, boundAgentName, now, cancellationToken); - } - } - - var existing = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - if (existing is null) - { - await connection.ExecuteAsync( - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, endpoint_secret, started_at, last_beat_at, - block_budget_used, role - ) VALUES ( - @harness, @sessionId, @agentName, @bindingKind, @host, - @cwd, @workspacePath, @endpointKind, @endpointAddr, @endpointSecret, @now, @now, 0, @role - ); - """, - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - agentName = boundAgentName, - bindingKind, - host = generation.Host, - cwd, - workspacePath, - endpointKind = normalizedEndpointKind, - endpointAddr = normalizedEndpointAddr, - endpointSecret = normalizedEndpointSecret, - now, - role = identityRole, - cancellationToken - }, - transaction); - } - else if (IsSameGeneration(existing, generation)) - { - // A matching host refreshes presence; an actor mismatch also reconciles the - // binding and role and clears delivery reservations. - if (existing.AgentName == boundAgentName) - { - await connection.ExecuteAsync( - "UPDATE agent_sessions SET last_beat_at = @now " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - now, - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - } - else - { - await connection.ExecuteAsync( - "UPDATE agent_sessions SET agent_name = @agentName, binding_kind = @bindingKind, " - + "role = @role, last_beat_at = @now " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - agentName = boundAgentName, - bindingKind, - role = identityRole, - now, - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - await connection.ExecuteAsync( - "DELETE FROM session_deliveries WHERE harness = @harness AND session_id = @sessionId", - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - cancellationToken - }, - transaction); - } - } - else - { - // A different host replaces session presence and clears delivery, block, and ping state. - var rowsAffected = await connection.ExecuteAsync( - """ - UPDATE agent_sessions SET - agent_name = @agentName, - binding_kind = @bindingKind, - host = @host, - cwd = @cwd, - workspace_path = @workspacePath, - endpoint_kind = @endpointKind, - endpoint_addr = @endpointAddr, - endpoint_secret = @endpointSecret, - started_at = @now, - last_beat_at = @now, - block_budget_used = 0, - last_ping_at = NULL, - last_ping_attempt = NULL, - last_ping_result = NULL, - last_ping_detail = NULL, - role = @role, - harness_version = '' - WHERE harness = @harness AND session_id = @sessionId - AND host = @oldHost; - """, - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - agentName = boundAgentName, - bindingKind, - host = generation.Host, - cwd, - workspacePath, - endpointKind = normalizedEndpointKind, - endpointAddr = normalizedEndpointAddr, - endpointSecret = normalizedEndpointSecret, - now, - role = identityRole, - oldHost = existing.Host, - cancellationToken - }, - transaction); - - if (rowsAffected > 0) - { - await connection.ExecuteAsync( - "DELETE FROM session_deliveries WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - } - } - - var row = await connection.QueryFirstAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - await transaction.CommitAsync(cancellationToken); - - return row.ToRecord(); - } - - private async Task EnsureCodingIdentityWithinTransactionAsync( - SqliteConnection connection, - DbTransaction transaction, - AgentSessionGeneration generation, - DateTimeOffset now, - string? preferredActor, - CancellationToken cancellationToken) - { - var identity = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionIdentityRecord.Columns} FROM agent_session_identities " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - if (identity is null) - { - var actor = preferredActor is null - ? await AgentActorAllocator.AllocateAsync(connection, transaction) - : MailAgentName.Normalize(preferredActor); - await AgentRegistry.UpsertWithinTransactionAsync( - connection, transaction, timeProvider, actor, string.Empty, generation.Harness, cancellationToken); - - identity = await connection.QueryFirstAsync( - """ - INSERT INTO agent_session_identities ( - harness, session_id, actor, role, actor_revision, created_at, last_seen_at) - VALUES (@harness, @sessionId, @actor, '', 1, @now, @now) - RETURNING - harness AS Harness, - session_id AS SessionId, - actor AS Actor, - role AS Role, - actor_revision AS ActorRevision, - created_at AS CreatedAt, - last_seen_at AS LastSeenAt - """, - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - actor, - now, - cancellationToken - }, - transaction); - } - else - { - await connection.ExecuteAsync( - "UPDATE agent_session_identities SET last_seen_at = @now " - + "WHERE harness = @harness AND session_id = @sessionId", - new { now, harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - await AgentRegistry.UpsertWithinTransactionAsync( - connection, transaction, timeProvider, identity.Actor, identity.Role, - generation.Harness, cancellationToken); - } - - return identity; - } - - private static Task EnsureImplicitActorWithinTransactionAsync( - SqliteConnection connection, - DbTransaction transaction, - string actor, - DateTimeOffset now, - CancellationToken cancellationToken) - => connection.ExecuteAsync( - """ - INSERT INTO agents (name, registered_at, last_seen_at, role, client, implicit) - VALUES (@actor, @now, @now, '', '', 1) - ON CONFLICT (name) DO UPDATE SET name = excluded.name - """, - new { actor, now, cancellationToken }, - transaction); - - public async Task ClaimAsync( - AgentSessionGeneration generation, - string actor, - bool forceRebind, - CancellationToken cancellationToken) - { - var normalizedActor = MailAgentName.Normalize(actor); - - await agentRegistry.EnsureImplicitAsync(normalizedActor, cancellationToken); - - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var row = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - - if (row is null) - { - throw new ExitException( - $"No session found for '{generation.Harness}' session '{generation.SessionId}' " - + "on this host. It may have ended, been reaped, or never started."); - } - - var previousBindingKind = row.BindingKind; - var previousAgentName = row.AgentName; - - var durableActor = await connection.QueryFirstOrDefaultAsync( - "SELECT actor FROM agent_session_identities " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - var effectivePreviousBindingKind = previousBindingKind == AgentSessionBindingKind.Explicit - && durableActor == previousAgentName - && durableActor != normalizedActor - ? AgentSessionBindingKind.None - : previousBindingKind; - - var (newBindingKind, resetLedger, changed) = ComputeClaimTransition( - effectivePreviousBindingKind, previousAgentName, normalizedActor, forceRebind, generation.SessionId); - - if (changed) - { - await ApplyBindingAsync( - connection, transaction, generation, normalizedActor, newBindingKind, resetLedger, cancellationToken); - } - - var updated = await connection.QueryFirstAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - await transaction.CommitAsync(cancellationToken); - - return new AgentSessionClaimResult( - updated.ToRecord(), - changed, - effectivePreviousBindingKind, - effectivePreviousBindingKind == AgentSessionBindingKind.None ? null : previousAgentName); - } - - /// - /// Throws when the agent registry does not contain the actor. - /// - private static async Task RequireKnownActorAsync( - SqliteConnection connection, - DbTransaction transaction, - string actor, - CancellationToken cancellationToken) - { - var known = await connection.QueryFirstOrDefaultAsync( - "SELECT name FROM agents WHERE name = @name", - new { name = actor, cancellationToken }, - transaction); - - if (known is null) - { - throw new ExitException( - $"Unknown actor '{actor}'. Run `nitro agent login` to allocate one, " - + "or `nitro agent list` to see the actors this workspace knows."); - } - } - - public async Task RegisterAsync( - AgentSessionGeneration generation, - string actor, - string role, - string client, - bool forceRebind, - CancellationToken cancellationToken) - { - var normalizedActor = MailAgentName.Normalize(actor); - var normalizedRole = AgentRole.Normalize(role); - var now = timeProvider.GetUtcNow(); - - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var row = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - - if (row is null) - { - throw new ExitException( - $"No session found for '{generation.Harness}' session '{generation.SessionId}' " - + "on this host. If hooks were never installed, run " - + $"`nitro agent hooks {HooksInstallCommandName(generation.Harness)} install` and " - + "start a new session; otherwise it may have ended or been reaped."); - } - - await RequireKnownActorAsync(connection, transaction, normalizedActor, cancellationToken); - - var agent = await AgentRegistry.UpsertWithinTransactionAsync( - connection, transaction, timeProvider, normalizedActor, normalizedRole, client, cancellationToken); - - var previousBindingKind = row.BindingKind; - var previousAgentName = row.AgentName; - - var durableActor = await connection.QueryFirstOrDefaultAsync( - "SELECT actor FROM agent_session_identities " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - var effectivePreviousBindingKind = previousBindingKind == AgentSessionBindingKind.Explicit - && durableActor == previousAgentName - && durableActor != normalizedActor - ? AgentSessionBindingKind.None - : previousBindingKind; - - var (newBindingKind, resetLedger, bindingChanged) = ComputeClaimTransition( - effectivePreviousBindingKind, previousAgentName, normalizedActor, forceRebind, generation.SessionId); - - if (bindingChanged) - { - await ApplyBindingAsync( - connection, transaction, generation, normalizedActor, newBindingKind, resetLedger, cancellationToken); - } - - var roleChanged = row.Role != normalizedRole; - - await connection.ExecuteAsync( - "UPDATE agent_sessions SET role = @role, last_beat_at = @now " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - role = normalizedRole, - now, - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - - var updated = await connection.QueryFirstAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - await transaction.CommitAsync(cancellationToken); - - return new AgentSessionRegisterResult( - agent, - updated.ToRecord(), - bindingChanged || roleChanged, - effectivePreviousBindingKind, - effectivePreviousBindingKind == AgentSessionBindingKind.None ? null : previousAgentName); - } - - public async Task RegisterAsync( - AgentSessionGeneration generation, - string? actor, - bool actorGiven, - string? role, - bool roleGiven, - CancellationToken cancellationToken) - => await RegisterAsync( - generation, actor, actorGiven, role, roleGiven, force: false, cancellationToken); - - public async Task RegisterAsync( - AgentSessionGeneration generation, - string? actor, - bool actorGiven, - string? role, - bool roleGiven, - bool force, - CancellationToken cancellationToken) - { - var now = timeProvider.GetUtcNow(); - - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = connection.BeginTransaction(deferred: false); - - var row = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - - if (row is null) - { - throw new ExitException( - $"No session found for '{generation.Harness}' session '{generation.SessionId}' " - + "on this host. If hooks were never installed, run " - + $"`nitro agent hooks {HooksInstallCommandName(generation.Harness)} install` and " - + "start a new session; otherwise it may have ended or been reaped."); - } - - var identity = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionIdentityRecord.Columns} FROM agent_session_identities " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction) - ?? await EnsureCodingIdentityWithinTransactionAsync( - connection, transaction, generation, now, preferredActor: null, cancellationToken); - - var normalizedActor = actorGiven - ? MailAgentName.Normalize(actor ?? string.Empty) - : identity.Actor; - - if (actorGiven) - { - await RequireKnownActorAsync(connection, transaction, normalizedActor, cancellationToken); - } - - if (actorGiven) - { - var known = await connection.QueryFirstOrDefaultAsync( - "SELECT name FROM agents WHERE name = @name", - new { name = normalizedActor, cancellationToken }, - transaction); - - if (known is null) - { - throw new ExitException( - $"Unknown actor '{normalizedActor}'. Run `nitro agent login` to allocate one, " - + "or `nitro agent list` to see the actors this workspace knows."); - } - } - var normalizedRole = roleGiven ? AgentRole.Normalize(role) : identity.Role; - - var conflictingIdentity = await connection.QueryFirstOrDefaultAsync( - """ - SELECT - harness AS Harness, - session_id AS SessionId, - actor AS Actor, - role AS Role, - actor_revision AS ActorRevision, - created_at AS CreatedAt, - last_seen_at AS LastSeenAt - FROM agent_session_identities - WHERE actor = @actor - AND NOT (harness = @harness AND session_id = @sessionId) - """, - new - { - actor = normalizedActor, - harness = generation.Harness, - sessionId = generation.SessionId, - cancellationToken - }, - transaction); - - if (conflictingIdentity is not null && !force) - { - throw new ExitException( - $"Actor '{normalizedActor}' is already assigned to another session."); - } - - if (conflictingIdentity is not null) - { - await connection.ExecuteAsync( - "DELETE FROM agent_sessions WHERE harness = @harness AND session_id = @sessionId", - new - { - harness = conflictingIdentity.Harness, - sessionId = conflictingIdentity.SessionId, - cancellationToken - }, - transaction); - await connection.ExecuteAsync( - "DELETE FROM agent_session_identities WHERE harness = @harness AND session_id = @sessionId", - new - { - harness = conflictingIdentity.Harness, - sessionId = conflictingIdentity.SessionId, - cancellationToken - }, - transaction); - } - - var agent = await AgentRegistry.UpsertWithinTransactionAsync( - connection, transaction, timeProvider, normalizedActor, normalizedRole, - generation.Harness, cancellationToken); - - var previousBindingKind = row.BindingKind; - var previousAgentName = row.AgentName; - var actorChanged = identity.Actor != normalizedActor; - var roleChanged = identity.Role != normalizedRole; - - await connection.ExecuteAsync( - """ - UPDATE agent_session_identities SET - actor = @actor, - role = @role, - actor_revision = actor_revision + CASE WHEN actor <> @actor THEN 1 ELSE 0 END, - last_seen_at = @now - WHERE harness = @harness AND session_id = @sessionId - """, - new - { - actor = normalizedActor, - role = normalizedRole, - now, - harness = generation.Harness, - sessionId = generation.SessionId, - cancellationToken - }, - transaction); - - await connection.ExecuteAsync( - "UPDATE agent_sessions SET agent_name = @actor, binding_kind = 'explicit', " - + "role = @role, last_beat_at = @now " - + "WHERE harness = @harness AND session_id = @sessionId", - new - { - actor = normalizedActor, - role = normalizedRole, - now, - harness = generation.Harness, - sessionId = generation.SessionId, - cancellationToken - }, - transaction); - - if (actorChanged) - { - await connection.ExecuteAsync( - "DELETE FROM session_deliveries WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - } - - var updated = await connection.QueryFirstAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - await transaction.CommitAsync(cancellationToken); - - return new AgentSessionRegisterResult( - agent, updated.ToRecord(), actorChanged || roleChanged, previousBindingKind, previousAgentName); - } - - public async Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - var row = await connection.QueryFirstOrDefaultAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND host = @host AND session_id = @sessionId", - new { harness, host, sessionId, cancellationToken }); - - return row?.ToRecord(); - } - - /// - /// Computes the explicit binding transition and whether delivery state must reset. - /// Changing an existing explicit actor requires . - /// - private static (string NewBindingKind, bool ResetLedger, bool Changed) ComputeClaimTransition( - string previousBindingKind, - string? previousAgentName, - string normalizedActor, - bool forceRebind, - string sessionId) - => (previousBindingKind, previousAgentName) switch - { - (AgentSessionBindingKind.None, _) => - (AgentSessionBindingKind.Explicit, true, true), - - (AgentSessionBindingKind.Env, var current) when current == normalizedActor => - (AgentSessionBindingKind.Explicit, false, true), - - (AgentSessionBindingKind.Env, _) => - (AgentSessionBindingKind.Explicit, true, true), - - (AgentSessionBindingKind.Explicit, var current) when current == normalizedActor => - (AgentSessionBindingKind.Explicit, false, false), - - (AgentSessionBindingKind.Explicit, _) when !forceRebind => - throw new ExitException( - $"Session '{sessionId}' is already explicitly claimed by " - + $"'{previousAgentName}'. Use --force-rebind to reclaim it as '{normalizedActor}'."), - - _ => (AgentSessionBindingKind.Explicit, true, true) - }; - - /// - /// Updates the matching session's actor binding. - /// When is true, clears its delivery reservations and block budget. - /// - private static async Task ApplyBindingAsync( - SqliteConnection connection, - DbTransaction transaction, - AgentSessionGeneration generation, - string normalizedActor, - string newBindingKind, - bool resetLedger, - CancellationToken cancellationToken) - { - await connection.ExecuteAsync( - "UPDATE agent_sessions SET agent_name = @agentName, binding_kind = @bindingKind " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - agentName = normalizedActor, - bindingKind = newBindingKind, - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - - if (resetLedger) - { - await connection.ExecuteAsync( - "DELETE FROM session_deliveries WHERE harness = @harness AND session_id = @sessionId", - new { harness = generation.Harness, sessionId = generation.SessionId, cancellationToken }, - transaction); - - await connection.ExecuteAsync( - "UPDATE agent_sessions SET block_budget_used = 0 " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host", - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - cancellationToken - }, - transaction); - } - } - - public async Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - "DELETE FROM agent_sessions WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - return rowsAffected > 0; - } - - public async Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - await using var reader = await command.ExecuteReaderAsync(cancellationToken); - - if (!await reader.ReadAsync(cancellationToken)) - { - return null; - } - - return AgentSessionRow.ReadFrom(reader).ToRecord(); - } - - public async Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET block_budget_used = 0 " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - public async Task IncrementBlockBudgetAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - await using var updateCommand = connection.CreateCommand(); - updateCommand.Transaction = (SqliteTransaction)transaction; - updateCommand.CommandText = - "UPDATE agent_sessions SET block_budget_used = block_budget_used + 1 " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - updateCommand.Parameters.AddWithValue("@harness", generation.Harness); - updateCommand.Parameters.AddWithValue("@sessionId", generation.SessionId); - updateCommand.Parameters.AddWithValue("@host", generation.Host); - - var rowsAffected = await updateCommand.ExecuteNonQueryAsync(cancellationToken); - - if (rowsAffected == 0) - { - await transaction.RollbackAsync(cancellationToken); - return null; - } - - await using var selectCommand = connection.CreateCommand(); - selectCommand.Transaction = (SqliteTransaction)transaction; - selectCommand.CommandText = - "SELECT block_budget_used FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - selectCommand.Parameters.AddWithValue("@harness", generation.Harness); - selectCommand.Parameters.AddWithValue("@sessionId", generation.SessionId); - selectCommand.Parameters.AddWithValue("@host", generation.Host); - - var updated = (int)(long)(await selectCommand.ExecuteScalarAsync(cancellationToken))!; - - await transaction.CommitAsync(cancellationToken); - - return updated; - } - - public async Task> ReapAsync(CancellationToken cancellationToken) - { - var host = await ResolveHostAsync(cancellationToken); - var cutoff = timeProvider.GetUtcNow() - s_staleAfter; - - await using var connection = await ConnectAsync(cancellationToken); - - var candidates = await connection.QueryAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions WHERE host = @host", - new { host, cancellationToken }); - - var reaped = new List(); - - foreach (var candidate in candidates) - { - var record = candidate.ToRecord(); - - if (record.LastBeatAt > cutoff) - { - continue; - } - - if (OnStaleReapCandidateCapturedAsync is { } onStaleReapCandidateCapturedAsync) - { - await onStaleReapCandidateCapturedAsync(record, cancellationToken); - } - - // Delete only if the recorded host and heartbeat still match. - var rowsAffected = await connection.ExecuteAsync( - "DELETE FROM agent_sessions WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host AND last_beat_at = @lastBeatAt", - new - { - harness = record.Harness, - sessionId = record.SessionId, - host = record.Host, - lastBeatAt = record.LastBeatAt, - cancellationToken - }); - - if (rowsAffected > 0) - { - reaped.Add(record); - - if (record.Harness == AgentSessionHarness.Copilot) - { - await connection.ExecuteAsync( - "DELETE FROM agent_session_identities " - + "WHERE harness = @harness AND session_id = @sessionId", - new - { - harness = record.Harness, - sessionId = record.SessionId, - cancellationToken - }); - } - } - } - - return reaped; - } - - public async Task> ListAsync(CancellationToken cancellationToken) - { - await ReapAsync(cancellationToken); - - var host = await ResolveHostAsync(cancellationToken); - - await using var connection = await ConnectAsync(cancellationToken); - - var rows = await connection.QueryAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions ORDER BY harness, session_id"); - - return rows.Select(row => - { - var record = row.ToRecord(); - return new AgentSessionView(record, ComputeState(record, host)); - }).ToList(); - } - - /// - /// Returns remote for another host, unreachable for a local session without an - /// endpoint, or online otherwise. - /// - private static string ComputeState(AgentSessionRecord record, string host) - => record.Host != host - ? AgentSessionState.Remote - : record.EndpointKind == AgentSessionEndpointKind.None - ? AgentSessionState.Unreachable - : AgentSessionState.Online; - - public async Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - { - var now = timeProvider.GetUtcNow(); - - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET last_beat_at = @now " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@now", now); - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - return rowsAffected > 0; - } - - public async Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET harness_version = @harnessVersion " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@harnessVersion", harnessVersion); - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - return rowsAffected > 0; - } - - /// - /// Reaps stale local sessions, then returns each surviving session with its agent - /// identity when available and its computed presence state. - /// - public async Task> ListParticipantsAsync( - CancellationToken cancellationToken) - { - await ReapAsync(cancellationToken); - - var host = await ResolveHostAsync(cancellationToken); - - await using var connection = await ConnectAsync(cancellationToken); - - var rows = await connection.QueryAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions ORDER BY harness, session_id"); - - var resolvedAgents = new Dictionary(StringComparer.Ordinal); - var participants = new List(); - - foreach (var row in rows) - { - var session = row.ToRecord(); - AgentRecord? agent = null; - - if (session.AgentName is { } agentName) - { - if (!resolvedAgents.TryGetValue(agentName, out agent)) - { - agent = await agentRegistry.GetAsync(agentName, cancellationToken); - - if (agent is not null) - { - resolvedAgents[agentName] = agent; - } - } - } - - participants.Add(new AgentSessionParticipant(session, agent, ComputeState(session, host))); - } - - return participants; - } - - public async Task> ListIdentitiesAsync( - CancellationToken cancellationToken) - { - var participants = await ListParticipantsAsync(cancellationToken); - var bySession = participants.ToDictionary( - participant => (participant.Session.Harness, participant.Session.SessionId)); - - await using var connection = await ConnectAsync(cancellationToken); - var identities = await connection.QueryAsync( - $"SELECT {AgentSessionIdentityRecord.Columns} FROM agent_session_identities " - + "ORDER BY actor"); - - return identities - .Select(identity => new AgentSessionIdentityView( - identity, - bySession.GetValueOrDefault((identity.Harness, identity.SessionId)))) - .ToList(); - } - - public async Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - { - await ReapAsync(cancellationToken); - - var host = await ResolveHostAsync(cancellationToken); - - await using var connection = await ConnectAsync(cancellationToken); - - var rows = await connection.QueryAsync( - $"SELECT {AgentSessionRecord.Columns} FROM agent_sessions " - + "WHERE agent_name = @agentName AND host = @host " - + "ORDER BY harness, session_id", - new { agentName, host, cancellationToken }); - - return rows.Select(row => row.ToRecord()).ToList(); - } - - public async Task TryClaimPingCooldownAsync( - AgentSessionRecord session, - string attemptId, - DateTimeOffset now, - TimeSpan cooldown, - CancellationToken cancellationToken) - { - var cutoff = now - cooldown; - - await using var connection = await ConnectAsync(cancellationToken); - - var rowsAffected = await connection.ExecuteAsync( - """ - UPDATE agent_sessions SET - last_ping_at = @now, - last_ping_attempt = @attemptId, - last_ping_result = NULL, - last_ping_detail = NULL - WHERE harness = @harness AND session_id = @sessionId - AND host = @host - AND (last_ping_at IS NULL OR last_ping_at <= @cutoff); - """, - new - { - now, - attemptId, - harness = session.Harness, - sessionId = session.SessionId, - host = session.Host, - cutoff, - cancellationToken - }); - - return rowsAffected > 0; - } - - public async Task WritePingResultAsync( - string harness, - string sessionId, - string attemptId, - string result, - string? detail, - CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await connection.ExecuteAsync( - """ - UPDATE agent_sessions SET last_ping_result = @result, last_ping_detail = @detail - WHERE harness = @harness AND session_id = @sessionId AND last_ping_attempt = @attemptId; - """, - new { result, detail, harness, sessionId, attemptId, cancellationToken }); - } - - public async Task SetRoleAsync( - AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - { - var normalizedRole = AgentRole.Normalize(role); - - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET role = @role " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@role", normalizedRole); - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - return rowsAffected > 0; - } - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => SetSessionFlagAsync(generation, "announcement_pending", value: true, cancellationToken); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => ClaimSessionFlagAsync(generation, "announcement_pending", cancellationToken); - - public Task IsAnnouncementPendingAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => PeekSessionFlagAsync(generation, "announcement_pending", cancellationToken); - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => SetSessionFlagAsync(generation, "idle_push_armed", value: true, cancellationToken); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => ClaimSessionFlagAsync(generation, "idle_push_armed", cancellationToken); - - /// - /// Sets the named flag for the matching session; a missing session is unchanged. - /// must be a trusted session flag column name. - /// - private async Task SetSessionFlagAsync( - AgentSessionGeneration generation, string column, bool value, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - $"UPDATE agent_sessions SET {column} = @value " - + "WHERE harness = @harness AND session_id = @sessionId " - + "AND host = @host"; - command.Parameters.AddWithValue("@value", value ? 1 : 0); - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - /// - /// Clears the named flag for the matching session and returns whether it was set. - /// must be a trusted session flag column name. - /// - private async Task ClaimSessionFlagAsync( - AgentSessionGeneration generation, string column, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - $"UPDATE agent_sessions SET {column} = 0 " - + "WHERE harness = @harness AND session_id = @sessionId " - + $"AND host = @host AND {column} = 1"; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - return rowsAffected > 0; - } - - /// - /// Returns whether the named flag is set for the matching session, or false when - /// none matches. must be a trusted session flag column name. - /// - private async Task PeekSessionFlagAsync( - AgentSessionGeneration generation, string column, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await using var command = connection.CreateCommand(); - command.CommandText = - $"SELECT {column} FROM agent_sessions " - + "WHERE harness = @harness AND session_id = @sessionId AND host = @host"; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - - var result = await command.ExecuteScalarAsync(cancellationToken); - - return result is not null && (long)result != 0; - } - - private async Task ResolveHostAsync(CancellationToken cancellationToken) - => await instanceIdProvider.GetIdAsync(globalConfigDirectoryProvider.GetDirectory(), cancellationToken); - - private static bool IsSameGeneration(AgentSessionRow existing, AgentSessionGeneration generation) - => existing.Host == generation.Host; - - /// - /// Returns the hooks command name for the harness, mapping claude-code to claude. - /// - private static string HooksInstallCommandName(string harness) => harness switch - { - AgentSessionHarness.ClaudeCode => "claude", - _ => harness - }; - - /// - /// Normalizes invalid or absent endpoints to kind none, an empty address, - /// and no credential. Credentials are retained only for valid opencode-server - /// endpoints belonging to the opencode harness. - /// - private static (string Kind, string Addr, string? Secret) NormalizeEndpoint( - string harness, - string endpointKind, - string endpointAddr, - string? endpointSecret) - { - if (endpointKind == AgentSessionEndpointKind.OpencodeServer) - { - return EndpointAddress.IsValidOpencodeServerUrl(endpointAddr) - ? (endpointKind, endpointAddr, harness == AgentSessionHarness.Opencode ? endpointSecret : null) - : (AgentSessionEndpointKind.None, string.Empty, null); - } - - if (endpointKind == AgentSessionEndpointKind.None || !EndpointAddress.IsValid(endpointAddr)) - { - return (AgentSessionEndpointKind.None, string.Empty, null); - } - - return (endpointKind, endpointAddr, null); - } - - private async Task ConnectAsync(CancellationToken cancellationToken) - { - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); - - return await database.ConnectAsync(workspaceDirectory, cancellationToken); - } - - internal sealed class AgentSessionRow - { - public required string Harness { get; init; } - public required string SessionId { get; init; } - public string? AgentName { get; init; } - public required string BindingKind { get; init; } - public required string Host { get; init; } - public required string Cwd { get; init; } - public required string WorkspacePath { get; init; } - public required string EndpointKind { get; init; } - public required string EndpointAddr { get; init; } - public string? EndpointSecret { get; init; } - public required string StartedAt { get; init; } - public required string LastBeatAt { get; init; } - public required int BlockBudgetUsed { get; init; } - public string? LastPingAt { get; init; } - public string? LastPingAttempt { get; init; } - public string? LastPingResult { get; init; } - public string? LastPingDetail { get; init; } - public required string Role { get; init; } - public required string HarnessVersion { get; init; } - - /// - /// Reads the current row using the column names declared by . - /// - public static AgentSessionRow ReadFrom(DbDataReader reader) => new() - { - Harness = reader.GetString(reader.GetOrdinal("Harness")), - SessionId = reader.GetString(reader.GetOrdinal("SessionId")), - AgentName = reader.IsDBNull(reader.GetOrdinal("AgentName")) - ? null - : reader.GetString(reader.GetOrdinal("AgentName")), - BindingKind = reader.GetString(reader.GetOrdinal("BindingKind")), - Host = reader.GetString(reader.GetOrdinal("Host")), - Cwd = reader.GetString(reader.GetOrdinal("Cwd")), - WorkspacePath = reader.GetString(reader.GetOrdinal("WorkspacePath")), - EndpointKind = reader.GetString(reader.GetOrdinal("EndpointKind")), - EndpointAddr = reader.GetString(reader.GetOrdinal("EndpointAddr")), - EndpointSecret = reader.IsDBNull(reader.GetOrdinal("EndpointSecret")) - ? null - : reader.GetString(reader.GetOrdinal("EndpointSecret")), - StartedAt = reader.GetString(reader.GetOrdinal("StartedAt")), - LastBeatAt = reader.GetString(reader.GetOrdinal("LastBeatAt")), - BlockBudgetUsed = reader.GetInt32(reader.GetOrdinal("BlockBudgetUsed")), - LastPingAt = reader.IsDBNull(reader.GetOrdinal("LastPingAt")) - ? null - : reader.GetString(reader.GetOrdinal("LastPingAt")), - LastPingAttempt = reader.IsDBNull(reader.GetOrdinal("LastPingAttempt")) - ? null - : reader.GetString(reader.GetOrdinal("LastPingAttempt")), - LastPingResult = reader.IsDBNull(reader.GetOrdinal("LastPingResult")) - ? null - : reader.GetString(reader.GetOrdinal("LastPingResult")), - LastPingDetail = reader.IsDBNull(reader.GetOrdinal("LastPingDetail")) - ? null - : reader.GetString(reader.GetOrdinal("LastPingDetail")), - Role = reader.GetString(reader.GetOrdinal("Role")), - HarnessVersion = reader.GetString(reader.GetOrdinal("HarnessVersion")) - }; - - public AgentSessionRecord ToRecord() => new() - { - Harness = Harness, - SessionId = SessionId, - AgentName = AgentName, - BindingKind = BindingKind, - Host = Host, - Cwd = Cwd, - WorkspacePath = WorkspacePath, - EndpointKind = EndpointKind, - EndpointAddr = EndpointAddr, - EndpointSecret = EndpointSecret, - StartedAt = DateTimeOffset.Parse(StartedAt, CultureInfo.InvariantCulture), - LastBeatAt = DateTimeOffset.Parse(LastBeatAt, CultureInfo.InvariantCulture), - BlockBudgetUsed = BlockBudgetUsed, - LastPingAt = LastPingAt is null ? null : DateTimeOffset.Parse(LastPingAt, CultureInfo.InvariantCulture), - LastPingAttempt = LastPingAttempt, - LastPingResult = LastPingResult, - LastPingDetail = LastPingDetail, - Role = Role, - HarnessVersion = HarnessVersion - }; - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionSchema.cs deleted file mode 100644 index efe824fffc0..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionSchema.cs +++ /dev/null @@ -1,79 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Defines session presence, per-channel delivery reservations, and the four -/// workspace ping-lease slots. -/// -internal static class AgentSessionSchema -{ - /// - /// The columns and constraints of the session presence table. - /// - private const string AgentSessionsColumns = - """ - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode', 'nitro-board')), - session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'opencode-server', 'db-watch', 'none')), - endpoint_addr TEXT NOT NULL, - endpoint_secret TEXT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - role TEXT NOT NULL DEFAULT '', - harness_version TEXT NOT NULL DEFAULT '', - announcement_pending INTEGER NOT NULL DEFAULT 0 CHECK (announcement_pending IN (0, 1)), - idle_push_armed INTEGER NOT NULL DEFAULT 0 CHECK (idle_push_armed IN (0, 1)), - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), - PRIMARY KEY (harness, session_id) - """; - - public const string Create = - """ - CREATE TABLE IF NOT EXISTS agent_sessions ( - """ - + AgentSessionsColumns - + """ - - ); - - CREATE INDEX IF NOT EXISTS idx_agent_sessions_name ON agent_sessions (agent_name); - - CREATE TABLE IF NOT EXISTS session_deliveries ( - harness TEXT NOT NULL, - session_id TEXT NOT NULL, - message_id TEXT NOT NULL, - channel TEXT NOT NULL CHECK (channel IN ('digest', 'gate', 'ping')), - delivered_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, message_id, channel), - FOREIGN KEY (harness, session_id) - REFERENCES agent_sessions (harness, session_id) ON DELETE CASCADE - ); - - CREATE TABLE IF NOT EXISTS ping_leases ( - slot INTEGER PRIMARY KEY CHECK (slot BETWEEN 1 AND 4), - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL - ); - """; - - /// - /// Returns SQL to create the session presence table under . - /// - public static string CreateAgentSessionsTable(string tableName) => - $""" - CREATE TABLE "{tableName}" ( - {AgentSessionsColumns} - ); - """; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionStartRequest.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionStartRequest.cs new file mode 100644 index 00000000000..64e6e8331e5 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionStartRequest.cs @@ -0,0 +1,25 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// The harness-supplied fields for starting or resuming an agent session. +/// +internal sealed record AgentSessionStartRequest +{ + public required string Harness { get; init; } + public required string SessionId { get; init; } + public required string HarnessVersion { get; init; } + public required string Cwd { get; init; } + public required string WorkspacePath { get; init; } + public required string EndpointKind { get; init; } + + /// + /// Empty only when is none. + /// + public required string EndpointAddr { get; init; } + + /// + /// The credential for endpoints that require one, or null when the + /// endpoint has no credential. + /// + public string? EndpointSecret { get; init; } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionStartResult.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionStartResult.cs new file mode 100644 index 00000000000..74124a9a49f --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionStartResult.cs @@ -0,0 +1,45 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// The action took for a harness session. +/// +internal enum AgentSessionStartKind +{ + /// + /// A new agent was minted for a harness session id not seen before. + /// + Minted, + + /// + /// An existing, non-deleted agent row was reused for a known harness session id. + /// + Reused, + + /// + /// The harness session id belongs to a deleted agent; nothing was written. + /// + Ignored +} + +/// +/// The result of : which action was taken, and +/// the resulting row, or null when the session was ignored. +/// +internal sealed record AgentSessionStartResult +{ + public required AgentSessionStartKind Kind { get; init; } + + /// + /// Null only when is . + /// + public AgentRow? Row { get; init; } + + public static AgentSessionStartResult Minted(AgentRow row) => + new() { Kind = AgentSessionStartKind.Minted, Row = row }; + + public static AgentSessionStartResult Reused(AgentRow row) => + new() { Kind = AgentSessionStartKind.Reused, Row = row }; + + public static AgentSessionStartResult Ignored { get; } = + new() { Kind = AgentSessionStartKind.Ignored, Row = null }; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionState.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionState.cs deleted file mode 100644 index 39e0f93e953..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionState.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Session presence values: online for a local session with an endpoint, unreachable -/// for a local session without one, and remote for another Nitro instance. -/// Unobservable is retained as a legacy value. -/// -internal static class AgentSessionState -{ - public const string Online = "online"; - public const string Unreachable = "unreachable"; - public const string Unobservable = "unobservable"; - public const string Remote = "remote"; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionView.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionView.cs deleted file mode 100644 index 1d9b45efc1d..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentSessionView.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// An paired with its computed -/// , as returned by -/// . -/// -internal sealed record AgentSessionView(AgentSessionRecord Session, string State); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentState.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentState.cs new file mode 100644 index 00000000000..ebb34f7db81 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentState.cs @@ -0,0 +1,12 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// The presence of an agent, derived from its row at read or render time and never stored. +/// +internal enum AgentState +{ + Online, + Idle, + Unreachable, + Offline +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentStateResolver.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentStateResolver.cs new file mode 100644 index 00000000000..a38f85daa32 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentStateResolver.cs @@ -0,0 +1,61 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Derives an agent's from its row, at read or render time. +/// +internal static class AgentStateResolver +{ + /// + /// The window after during which an agent counts as online + /// rather than idle. + /// + public static readonly TimeSpan OnlineWindow = TimeSpan.FromMinutes(30); + + /// + /// The width of the clock-aligned window that groups agents by last-seen time for ordering. + /// + public static readonly TimeSpan LastSeenWindow = TimeSpan.FromMinutes(5); + + /// + /// Floors to the start of its , aligned + /// to the UTC clock (for example 10:00, 10:05, 10:10) rather than to + /// itself. + /// + public static DateTimeOffset LastSeenWindowStart(DateTimeOffset value) + { + var utc = value.ToUniversalTime(); + var windowTicks = LastSeenWindow.Ticks; + var flooredTicks = utc.Ticks - (utc.Ticks % windowTicks); + return new DateTimeOffset(flooredTicks, TimeSpan.Zero); + } + + /// + /// Resolves the state of as of . A login-only + /// row (no endpoint) resolves to regardless of its age, + /// checked before the idle window so it never reports idle instead. + /// + public static AgentState Resolve(AgentRow row, DateTimeOffset now) + { + if (row.DeletedAt is not null) + { + return AgentState.Offline; + } + + if (row.EndedAt is not null) + { + return AgentState.Offline; + } + + if (row.EndpointKind == AgentSessionEndpointKind.None) + { + return AgentState.Unreachable; + } + + if (now - row.LastSeenAt > OnlineWindow) + { + return AgentState.Idle; + } + + return AgentState.Online; + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentStore.cs new file mode 100644 index 00000000000..aebf80baa95 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/AgentStore.cs @@ -0,0 +1,657 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using Dapper; +using Microsoft.Data.Sqlite; + +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +internal sealed class AgentStore( + IFileSystem fileSystem, + TimeProvider timeProvider, + AgentDatabase database) : IAgentStore +{ + public async Task LoginAsync(CancellationToken cancellationToken) + { + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = connection.BeginTransaction(deferred: false); + + var name = await AgentActorAllocator.AllocateAsync(connection, transaction); + + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = + $""" + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + RETURNING {AgentRow.Columns}; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", now); + + var row = await ReadFirstAsync(command, cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return row; + } + + public async Task StartSessionAsync( + AgentSessionStartRequest request, + CancellationToken cancellationToken) + { + EnsureAgentHarness(request.Harness); + + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = connection.BeginTransaction(deferred: false); + + var existing = await FindBySessionWithinTransactionAsync( + connection, transaction, request.Harness, request.SessionId, cancellationToken); + + if (existing?.IsDeleted == true) + { + await transaction.CommitAsync(cancellationToken); + return AgentSessionStartResult.Ignored; + } + + if (existing is not null) + { + await using var updateCommand = connection.CreateCommand(); + updateCommand.Transaction = transaction; + updateCommand.CommandText = + $""" + UPDATE agents SET + ended_at = NULL, + harness_version = CASE WHEN @harnessVersion <> '' THEN @harnessVersion ELSE harness_version END, + cwd = @cwd, + workspace_path = @workspacePath, + endpoint_kind = @endpointKind, + endpoint_addr = @endpointAddr, + endpoint_secret = @endpointSecret, + last_seen_at = @now + WHERE harness = @harness AND session_id = @sessionId + RETURNING {AgentRow.Columns}; + """; + AddSessionRequestParameters(updateCommand, request, now); + + var reused = await ReadFirstAsync(updateCommand, cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return AgentSessionStartResult.Reused(reused); + } + + var name = await AgentActorAllocator.AllocateAsync(connection, transaction); + + await using var insertCommand = connection.CreateCommand(); + insertCommand.Transaction = transaction; + insertCommand.CommandText = + $""" + INSERT INTO agents ( + name, role, harness, harness_version, session_id, cwd, workspace_path, + registered_at, started_at, last_seen_at, endpoint_kind, endpoint_addr, endpoint_secret) + VALUES ( + @name, '', @harness, @harnessVersion, @sessionId, @cwd, @workspacePath, + @now, @now, @now, @endpointKind, @endpointAddr, @endpointSecret) + RETURNING {AgentRow.Columns}; + """; + insertCommand.Parameters.AddWithValue("@name", name); + AddSessionRequestParameters(insertCommand, request, now); + + var minted = await ReadFirstAsync(insertCommand, cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return AgentSessionStartResult.Minted(minted); + } + + public async Task TouchSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + { + EnsureAgentHarness(harness); + + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + "UPDATE agents SET last_seen_at = @now " + + "WHERE harness = @harness AND session_id = @sessionId AND deleted_at IS NULL"; + command.Parameters.AddWithValue("@now", now); + command.Parameters.AddWithValue("@harness", harness); + command.Parameters.AddWithValue("@sessionId", sessionId); + + var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); + + return rowsAffected > 0; + } + + public async Task TouchAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + + var rowsAffected = await connection.ExecuteAsync( + "UPDATE agents SET last_seen_at = @now WHERE name = @name AND deleted_at IS NULL", + new { now, name = normalizedName }); + + return rowsAffected > 0; + } + + public async Task EndSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + { + EnsureAgentHarness(harness); + + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + "UPDATE agents SET ended_at = @now " + + "WHERE harness = @harness AND session_id = @sessionId AND deleted_at IS NULL"; + command.Parameters.AddWithValue("@now", now); + command.Parameters.AddWithValue("@harness", harness); + command.Parameters.AddWithValue("@sessionId", sessionId); + + var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); + + return rowsAffected > 0; + } + + public async Task SetRoleAsync(string name, string role, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var normalizedRole = AgentRole.Normalize(role); + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + $""" + UPDATE agents SET role = @role, last_seen_at = @now + WHERE name = @name AND deleted_at IS NULL + RETURNING {AgentRow.Columns}; + """; + command.Parameters.AddWithValue("@role", normalizedRole); + command.Parameters.AddWithValue("@now", now); + command.Parameters.AddWithValue("@name", normalizedName); + + return await ReadFirstOrDefaultAsync(command, cancellationToken); + } + + public async Task FindAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {AgentRow.Columns} FROM agents WHERE name = @name"; + command.Parameters.AddWithValue("@name", normalizedName); + + return await ReadFirstOrDefaultAsync(command, cancellationToken); + } + + public async Task FindBySessionAsync( + string harness, string sessionId, CancellationToken cancellationToken) + { + EnsureAgentHarness(harness); + + await using var connection = await ConnectAsync(cancellationToken); + + return await FindBySessionWithinTransactionAsync(connection, null, harness, sessionId, cancellationToken); + } + + public async Task> ListAsync(CancellationToken cancellationToken) + { + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {AgentRow.Columns} FROM agents WHERE deleted_at IS NULL"; + + return await ReadAllAsync(command, cancellationToken); + } + + public async Task SetEndpointAsync( + string name, + string endpointKind, + string endpointAddr, + string? endpointSecret, + CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = connection.BeginTransaction(deferred: false); + + await using var selectCommand = connection.CreateCommand(); + selectCommand.Transaction = transaction; + selectCommand.CommandText = "SELECT harness FROM agents WHERE name = @name AND deleted_at IS NULL"; + selectCommand.Parameters.AddWithValue("@name", normalizedName); + + var harnessResult = await selectCommand.ExecuteScalarAsync(cancellationToken); + + if (harnessResult is null) + { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + var harness = harnessResult is DBNull ? string.Empty : (string)harnessResult; + var (kind, addr, secret) = EndpointAddress.Normalize(harness, endpointKind, endpointAddr, endpointSecret); + + await using var updateCommand = connection.CreateCommand(); + updateCommand.Transaction = transaction; + updateCommand.CommandText = + "UPDATE agents SET endpoint_kind = @kind, endpoint_addr = @addr, endpoint_secret = @secret " + + "WHERE name = @name AND deleted_at IS NULL"; + updateCommand.Parameters.AddWithValue("@kind", kind); + updateCommand.Parameters.AddWithValue("@addr", addr); + updateCommand.Parameters.AddWithValue("@secret", (object?)secret ?? DBNull.Value); + updateCommand.Parameters.AddWithValue("@name", normalizedName); + + await updateCommand.ExecuteNonQueryAsync(cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return true; + } + + public async Task ResetBlockBudgetAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET block_budget_used = 0 WHERE name = @name AND deleted_at IS NULL"; + command.Parameters.AddWithValue("@name", normalizedName); + + await command.ExecuteNonQueryAsync(cancellationToken); + + return 0; + } + + public async Task IncrementBlockBudgetAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); + + await using var updateCommand = connection.CreateCommand(); + updateCommand.Transaction = transaction; + updateCommand.CommandText = + "UPDATE agents SET block_budget_used = block_budget_used + 1 " + + "WHERE name = @name AND deleted_at IS NULL"; + updateCommand.Parameters.AddWithValue("@name", normalizedName); + + var rowsAffected = await updateCommand.ExecuteNonQueryAsync(cancellationToken); + + if (rowsAffected == 0) + { + await transaction.RollbackAsync(cancellationToken); + return 0; + } + + await using var selectCommand = connection.CreateCommand(); + selectCommand.Transaction = transaction; + selectCommand.CommandText = "SELECT block_budget_used FROM agents WHERE name = @name"; + selectCommand.Parameters.AddWithValue("@name", normalizedName); + + var updated = (long)(await selectCommand.ExecuteScalarAsync(cancellationToken))!; + + await transaction.CommitAsync(cancellationToken); + + return (int)updated; + } + + public async Task TryClaimPingCooldownAsync( + string name, TimeSpan cooldown, string attemptId, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var now = timeProvider.GetUtcNow(); + var cutoff = now - cooldown; + + await using var connection = await ConnectAsync(cancellationToken); + + var rowsAffected = await connection.ExecuteAsync( + """ + UPDATE agents SET + last_ping_at = @now, + last_ping_attempt = @attemptId, + last_ping_result = NULL, + last_ping_detail = NULL + WHERE name = @name AND deleted_at IS NULL + AND (last_ping_at IS NULL OR last_ping_at <= @cutoff); + """, + new { now, attemptId, name = normalizedName, cutoff }); + + return rowsAffected > 0; + } + + public async Task WritePingResultAsync( + string name, string attemptId, string result, string? detail, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + await connection.ExecuteAsync( + "UPDATE agents SET last_ping_result = @result, last_ping_detail = @detail " + + "WHERE name = @name AND deleted_at IS NULL AND last_ping_attempt = @attemptId", + new { result, detail, name = normalizedName, attemptId }); + } + + public Task ArmAnnouncementAsync(string name, CancellationToken cancellationToken) + => SetAgentFlagAsync(name, "announcement_pending", value: true, cancellationToken); + + public Task ClaimAnnouncementAsync(string name, CancellationToken cancellationToken) + => ClaimAgentFlagAsync(name, "announcement_pending", cancellationToken); + + public Task IsAnnouncementPendingAsync(string name, CancellationToken cancellationToken) + => PeekAgentFlagAsync(name, "announcement_pending", cancellationToken); + + public Task RearmIdlePushAsync(string name, CancellationToken cancellationToken) + => SetAgentFlagAsync(name, "idle_push_armed", value: true, cancellationToken); + + public Task ClaimIdlePushAsync(string name, CancellationToken cancellationToken) + => ClaimAgentFlagAsync(name, "idle_push_armed", cancellationToken); + + public async Task RecordHarnessVersionAsync( + string name, string harnessVersion, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + var rowsAffected = await connection.ExecuteAsync( + "UPDATE agents SET harness_version = @harnessVersion " + + "WHERE name = @name AND deleted_at IS NULL", + new { harnessVersion, name = normalizedName }); + + return rowsAffected > 0; + } + + public async Task DeleteAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var now = timeProvider.GetUtcNow(); + var reason = $"Agent '{normalizedName}' was deleted"; + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); + + var deleted = await DeleteAgentRowWithinTransactionAsync( + connection, transaction, normalizedName, now, cancellationToken); + + if (!deleted) + { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + await DeleteAgentSideRowsWithinTransactionAsync(connection, transaction, normalizedName, cancellationToken); + + await TaskStore.ReleaseAssigneeWithinTransactionAsync( + connection, transaction, normalizedName, reason, now, cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return true; + } + + public async Task DeleteInactiveAsync(CancellationToken cancellationToken) + { + var now = timeProvider.GetUtcNow(); + + await using var connection = await ConnectAsync(cancellationToken); + await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); + + await using var selectCommand = connection.CreateCommand(); + selectCommand.Transaction = transaction; + selectCommand.CommandText = $"SELECT {AgentRow.Columns} FROM agents WHERE deleted_at IS NULL"; + + var candidates = await ReadAllAsync(selectCommand, cancellationToken); + + var deletedCount = 0; + + foreach (var candidate in candidates) + { + var state = AgentStateResolver.Resolve(candidate, now); + + if (state != AgentState.Offline && state != AgentState.Idle) + { + continue; + } + + var deleted = await DeleteAgentRowWithinTransactionAsync( + connection, transaction, candidate.Name, now, cancellationToken); + + if (!deleted) + { + continue; + } + + await DeleteAgentSideRowsWithinTransactionAsync( + connection, transaction, candidate.Name, cancellationToken); + + await TaskStore.ReleaseAssigneeWithinTransactionAsync( + connection, transaction, candidate.Name, $"Agent '{candidate.Name}' was deleted", now, + cancellationToken); + + deletedCount++; + } + + await transaction.CommitAsync(cancellationToken); + + return deletedCount; + } + + /// + /// Stamps deleted_at and clears the agent's endpoint and transient state. + /// Returns false, changing nothing, when no matching non-deleted row exists. + /// + private static async Task DeleteAgentRowWithinTransactionAsync( + SqliteConnection connection, + SqliteTransaction transaction, + string name, + DateTimeOffset now, + CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = + """ + UPDATE agents SET + deleted_at = @now, + endpoint_kind = 'none', + endpoint_addr = '', + endpoint_secret = NULL, + last_ping_at = NULL, + last_ping_attempt = NULL, + last_ping_result = NULL, + last_ping_detail = NULL, + announcement_pending = 0, + idle_push_armed = 0, + block_budget_used = 0 + WHERE name = @name AND deleted_at IS NULL + """; + command.Parameters.AddWithValue("@now", now); + command.Parameters.AddWithValue("@name", name); + + var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); + + return rowsAffected > 0; + } + + /// + /// Removes the agent's wake and ping side rows: its delivery reservations, ping gate, + /// wake outbox entry, owned wake batches, and wake target entries. + /// + private static async Task DeleteAgentSideRowsWithinTransactionAsync( + SqliteConnection connection, + SqliteTransaction transaction, + string name, + CancellationToken cancellationToken) + { + string[] statements = + [ + "DELETE FROM agent_deliveries WHERE agent = @name", + "DELETE FROM agent_ping_gates WHERE agent = @name", + "DELETE FROM mail_wake_targets WHERE agent = @name", + "DELETE FROM mail_wake_batches WHERE actor = @name", + "DELETE FROM mail_wake_outbox WHERE actor = @name" + ]; + + foreach (var statement in statements) + { + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = statement; + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + } + + /// + /// Sets the named flag for the matching agent; a missing or deleted agent is unchanged. + /// must be a trusted agent flag column name. + /// + private async Task SetAgentFlagAsync( + string name, string column, bool value, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = $"UPDATE agents SET {column} = @value WHERE name = @name AND deleted_at IS NULL"; + command.Parameters.AddWithValue("@value", value ? 1 : 0); + command.Parameters.AddWithValue("@name", normalizedName); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Clears the named flag for the matching agent and returns whether it was set. + /// must be a trusted agent flag column name. + /// + private async Task ClaimAgentFlagAsync(string name, string column, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + $"UPDATE agents SET {column} = 0 WHERE name = @name AND deleted_at IS NULL AND {column} = 1"; + command.Parameters.AddWithValue("@name", normalizedName); + + var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); + + return rowsAffected > 0; + } + + /// + /// Returns whether the named flag is set for the matching agent, or false when none + /// matches. must be a trusted agent flag column name. + /// + private async Task PeekAgentFlagAsync(string name, string column, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + await using var connection = await ConnectAsync(cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {column} FROM agents WHERE name = @name AND deleted_at IS NULL"; + command.Parameters.AddWithValue("@name", normalizedName); + + var result = await command.ExecuteScalarAsync(cancellationToken); + + return result is not null && (long)result != 0; + } + + private static void EnsureAgentHarness(string harness) + { + if (!AgentSessionHarness.IsAgentHarness(harness)) + { + throw ThrowHelper.UnknownAgentHarness(harness); + } + } + + private static async Task FindBySessionWithinTransactionAsync( + SqliteConnection connection, + SqliteTransaction? transaction, + string harness, + string sessionId, + CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = $"SELECT {AgentRow.Columns} FROM agents WHERE harness = @harness AND session_id = @sessionId"; + command.Parameters.AddWithValue("@harness", harness); + command.Parameters.AddWithValue("@sessionId", sessionId); + + return await ReadFirstOrDefaultAsync(command, cancellationToken); + } + + private static void AddSessionRequestParameters( + SqliteCommand command, AgentSessionStartRequest request, DateTimeOffset now) + { + command.Parameters.AddWithValue("@harness", request.Harness); + command.Parameters.AddWithValue("@sessionId", request.SessionId); + command.Parameters.AddWithValue("@harnessVersion", request.HarnessVersion); + command.Parameters.AddWithValue("@cwd", request.Cwd); + command.Parameters.AddWithValue("@workspacePath", request.WorkspacePath); + command.Parameters.AddWithValue("@endpointKind", request.EndpointKind); + command.Parameters.AddWithValue("@endpointAddr", request.EndpointAddr); + command.Parameters.AddWithValue("@endpointSecret", (object?)request.EndpointSecret ?? DBNull.Value); + command.Parameters.AddWithValue("@now", now); + } + + private static async Task ReadFirstAsync(SqliteCommand command, CancellationToken cancellationToken) + { + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + await reader.ReadAsync(cancellationToken); + return AgentRow.ReadFrom(reader); + } + + private static async Task ReadFirstOrDefaultAsync( + SqliteCommand command, CancellationToken cancellationToken) + { + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + return await reader.ReadAsync(cancellationToken) ? AgentRow.ReadFrom(reader) : null; + } + + private static async Task> ReadAllAsync( + SqliteCommand command, CancellationToken cancellationToken) + { + var rows = new List(); + + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + rows.Add(AgentRow.ReadFrom(reader)); + } + + return rows; + } + + private async Task ConnectAsync(CancellationToken cancellationToken) + { + var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) + ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); + + return await database.ConnectAsync(workspaceDirectory, cancellationToken); + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ClaudeSessionActivityReader.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ClaudeSessionActivityReader.cs deleted file mode 100644 index ea92bc03d6f..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ClaudeSessionActivityReader.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Text.Json; - -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed class ClaudeSessionActivityReader(Func? sessionFileReader = null) - : IClaudeSessionActivityReader -{ - private readonly Func _sessionFileReader = sessionFileReader ?? ReadSessionFile; - - public string? GetStatus(string sessionId) - { - var json = _sessionFileReader(sessionId); - - if (json is null) - { - return null; - } - - try - { - using var document = JsonDocument.Parse(json); - - var root = document.RootElement; - - return root.ValueKind == JsonValueKind.Object - && root.TryGetProperty("status", out var status) - && status.ValueKind == JsonValueKind.String - ? status.GetString() - : null; - } - catch (JsonException) - { - return null; - } - } - - /// - /// Returns the contents of a session file with the matching session id, or null - /// when no readable matching file is found. - /// - private static string? ReadSessionFile(string sessionId) - { - var directory = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude", "sessions"); - - return ReadSessionFile(directory, sessionId); - } - - internal static string? ReadSessionFile(string directory, string sessionId) - { - try - { - foreach (var path in Directory.EnumerateFiles(directory, "*.json")) - { - var json = File.ReadAllText(path); - - try - { - using var document = JsonDocument.Parse(json); - - if (document.RootElement.ValueKind == JsonValueKind.Object - && document.RootElement.TryGetProperty("sessionId", out var id) - && id.ValueKind == JsonValueKind.String - && id.GetString() == sessionId) - { - return json; - } - } - catch (JsonException) - { - } - } - } - catch (IOException) - { - } - catch (UnauthorizedAccessException) - { - } - - return null; - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/EndpointAddress.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/EndpointAddress.cs index 2d5b1c38b5c..655820a4532 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/EndpointAddress.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/EndpointAddress.cs @@ -20,6 +20,32 @@ public static bool IsValidOpencodeServerUrl(string value) public static bool IsTrustedOpencodeServerUrl(string value, bool serverBound) => serverBound && IsValidOpencodeServerUrl(value); + /// + /// Normalizes invalid or absent endpoints to kind none, an empty address, + /// and no credential. Credentials are retained only for valid opencode-server + /// endpoints belonging to the opencode harness. + /// + public static (string Kind, string Addr, string? Secret) Normalize( + string harness, + string endpointKind, + string endpointAddr, + string? endpointSecret) + { + if (endpointKind == AgentSessionEndpointKind.OpencodeServer) + { + return IsValidOpencodeServerUrl(endpointAddr) + ? (endpointKind, endpointAddr, harness == AgentSessionHarness.Opencode ? endpointSecret : null) + : (AgentSessionEndpointKind.None, string.Empty, null); + } + + if (endpointKind == AgentSessionEndpointKind.None || !IsValid(endpointAddr)) + { + return (AgentSessionEndpointKind.None, string.Empty, null); + } + + return (endpointKind, endpointAddr, null); + } + [GeneratedRegex(@"^[A-Za-z0-9._-]{1,128}$")] private static partial Regex Pattern(); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentDeliveryLedger.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentDeliveryLedger.cs new file mode 100644 index 00000000000..903c5093f4b --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentDeliveryLedger.cs @@ -0,0 +1,38 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Manages independent notification reservations per agent, message, and channel. +/// Reservations precede delivery and remain claimed until released. +/// +internal interface IAgentDeliveryLedger +{ + /// + /// Returns input message ids with reservations across any channel for + /// , preserving input order. Empty input returns an empty result. + /// + Task> FindDeliveredAsync( + string agent, + IReadOnlyList messageIds, + CancellationToken cancellationToken); + + /// + /// Claims previously unreserved messages for the agent and channel, returning + /// new claims in input order without duplicates. Empty input returns an empty result. + /// + Task> ReserveAsync( + string agent, + IReadOnlyList messageIds, + string channel, + DateTimeOffset deliveredAt, + CancellationToken cancellationToken); + + /// + /// Releases the supplied message reservations for the agent and channel. + /// Empty input changes nothing. + /// + Task ReleaseAsync( + string agent, + IReadOnlyList messageIds, + string channel, + CancellationToken cancellationToken); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ISessionPingGateStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentPingGateStore.cs similarity index 55% rename from src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ISessionPingGateStore.cs rename to src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentPingGateStore.cs index e2dc0f1f2f8..4dbf26dea2d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ISessionPingGateStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentPingGateStore.cs @@ -1,18 +1,17 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// Manages one shared transport lease for each harness, session id, and host tuple. +/// Manages one shared transport lease for each agent. /// -internal interface ISessionPingGateStore +internal interface IAgentPingGateStore { /// - /// Atomically claims the gate for , - /// stealing it if the current holder's lease has already expired. - /// Returns false, claiming nothing, when the gate is currently held by - /// an unexpired attempt. + /// Atomically claims the gate for , stealing it if the + /// current holder's lease has already expired. Returns false, claiming nothing, + /// when the gate is currently held by an unexpired attempt. /// Task TryAcquireAsync( - AgentSessionGeneration generation, + string agent, string attemptId, DateTimeOffset now, TimeSpan leaseDuration, @@ -23,18 +22,15 @@ Task TryAcquireAsync( /// Returns false when the attempt does not own the gate or its lease has expired. /// Task TryRenewAsync( - AgentSessionGeneration generation, + string agent, string attemptId, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken); /// - /// Releases the matching session gate only when it still belongs to + /// Releases the matching agent's gate only when it still belongs to /// ; a missing or reassigned gate is unchanged. /// - Task ReleaseAsync( - AgentSessionGeneration generation, - string attemptId, - CancellationToken cancellationToken); + Task ReleaseAsync(string agent, string attemptId, CancellationToken cancellationToken); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentRegistry.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentRegistry.cs deleted file mode 100644 index ab3fe316215..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentRegistry.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Stores and queries agent identities shared by workspace features. -/// -internal interface IAgentRegistry -{ - /// - /// Registers the normalized name, role, and client, refreshes last-seen time, and - /// clears the implicit flag. Empty role or client values clear those fields. - /// - Task RegisterAsync( - string name, - string role, - string client, - CancellationToken cancellationToken); - - /// - /// Allocates and records an unused actor name without binding it to a session. - /// - Task AllocateAsync(CancellationToken cancellationToken); - - /// - /// Marks the normalized actor as active, refreshing last-seen time and clearing the - /// implicit flag without changing existing role or client values. A new actor has - /// an empty role and client. - /// - Task TouchAsync( - string name, - CancellationToken cancellationToken); - - /// - /// Normalizes the given name and returns the agent with that name, or - /// null. - /// - Task GetAsync( - string name, - CancellationToken cancellationToken); - - /// - /// Returns the normalized actor unchanged if it exists, or creates an implicit - /// identity with an empty role and client and both timestamps set to now. - /// - Task EnsureImplicitAsync( - string name, - CancellationToken cancellationToken); - - /// - /// Returns all agent identities, including implicit ones, ordered by name. Non-null - /// filters restrict results to the normalized role and a last-seen time strictly - /// before . - /// - Task> ListAsync( - string? role, - DateTimeOffset? staleBefore, - CancellationToken cancellationToken); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentSessionRegistry.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentSessionRegistry.cs deleted file mode 100644 index 5af7d49f3b1..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentSessionRegistry.cs +++ /dev/null @@ -1,256 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Manages session presence, actor bindings, heartbeats, and notification state -/// using harness session ids and Nitro instance ids. -/// -internal interface IAgentSessionRegistry -{ - /// - /// Starts or refreshes presence; coding harnesses reuse a durable actor or create one - /// from (allocating when null), while other harnesses use - /// that value as an optional binding. A matching host preserves state except for - /// heartbeat and actor reconciliation; a different host replaces presence and - /// clears delivery reservations, block budget, and ping state. - /// - Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? envActor, - CancellationToken cancellationToken); - - /// - /// Starts or refreshes a session with an optional endpoint credential. - /// The default implementation ignores . - /// - Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? endpointSecret, - string? envActor, - CancellationToken cancellationToken) - => StartAsync( - generation, - cwd, - workspacePath, - endpointKind, - endpointAddr, - envActor, - cancellationToken); - - /// - /// Claims the matching session for the normalized actor. Throws - /// when no session matches or changing a protected explicit binding requires - /// and it is false. - /// - Task ClaimAsync( - AgentSessionGeneration generation, - string actor, - bool forceRebind, - CancellationToken cancellationToken); - - /// - /// Deletes the session matching and returns whether - /// a row was deleted; a missing or differently owned session is unchanged. - /// - Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Returns the session matching the harness, session id, and host in - /// , or null when none matches. - /// - Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Resets the matching session's block budget to zero; a missing session is unchanged. - /// - Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Atomically increments block_budget_used by one for the row - /// matching exactly and returns the new - /// value. Returns null when no row matches that generation. - /// - Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Reaps current-instance sessions whose heartbeat has reached the stale cutoff - /// and returns the deleted records. Sessions owned by another instance are retained. - /// - Task> ReapAsync(CancellationToken cancellationToken); - - /// - /// Reaps stale current-instance rows, then returns every surviving row - /// with its computed . - /// - Task> ListAsync(CancellationToken cancellationToken); - - /// - /// Updates only the matching session's heartbeat to now. - /// Returns false when no session matches. - /// - Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Updates only the matching session's harness version. - /// Returns false when no session matches. - /// - Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken); - - /// - /// Updates only the matching session's normalized role, preserving the agent identity - /// role. Returns false when no session matches. - /// - Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken); - - /// - /// Reaps stale local sessions, then returns each surviving session with its agent - /// identity when available and its computed presence state. - /// - Task> ListParticipantsAsync(CancellationToken cancellationToken); - - async Task> ListIdentitiesAsync(CancellationToken cancellationToken) - { - var participants = await ListParticipantsAsync(cancellationToken); - - return participants - .Where(participant => participant.Session.AgentName is not null) - .Select(participant => new AgentSessionIdentityView( - new AgentSessionIdentityRecord - { - Harness = participant.Session.Harness, - SessionId = participant.Session.SessionId, - Actor = participant.Session.AgentName!, - Role = participant.Session.Role, - ActorRevision = 1, - CreatedAt = participant.Session.StartedAt.ToString("O"), - LastSeenAt = participant.Session.LastBeatAt.ToString("O") - }, - participant)) - .ToList(); - } - - /// - /// Atomically registers the known actor and normalized role and applies the session - /// claim transition. Throws for an unknown actor, a missing - /// session, or a protected explicit binding that cannot be changed without - /// . - /// - Task RegisterAsync( - AgentSessionGeneration generation, - string actor, - string role, - string client, - bool forceRebind, - CancellationToken cancellationToken); - - async Task RegisterAsync( - AgentSessionGeneration generation, - string? actor, - bool actorGiven, - string? role, - bool roleGiven, - CancellationToken cancellationToken) - { - var current = await FindByGenerationAsync(generation, cancellationToken) - ?? throw new ExitException("The current session is no longer connected."); - - return await RegisterAsync( - generation, - actorGiven - ? actor ?? string.Empty - : current.AgentName ?? throw new ExitException("The current session has no actor."), - roleGiven ? role ?? string.Empty : current.Role, - generation.Harness, - forceRebind: true, - cancellationToken); - } - - async Task RegisterAsync( - AgentSessionGeneration generation, - string? actor, - bool actorGiven, - string? role, - bool roleGiven, - bool force, - CancellationToken cancellationToken) - { - if (force) - { - throw new ExitException("This session registry does not support forced actor takeover."); - } - - return await RegisterAsync( - generation, actor, actorGiven, role, roleGiven, cancellationToken); - } - - /// - /// Returns the row matching , , and exactly. Null when no - /// row matches. - /// - Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken); - - /// - /// Reaps stale local sessions, then returns surviving current-instance sessions - /// bound to . - /// - Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken); - - /// - /// Claims the matching session's ping cooldown for , - /// clearing the previous result and detail. Returns false when no session matches - /// or the previous attempt is newer than minus . - /// - Task TryClaimPingCooldownAsync( - AgentSessionRecord session, - string attemptId, - DateTimeOffset now, - TimeSpan cooldown, - CancellationToken cancellationToken); - - /// - /// Records the ping result and detail only when the harness, session id, and - /// current attempt id match; an outdated completion changes nothing. - /// - Task WritePingResultAsync( - string harness, - string sessionId, - string attemptId, - string result, - string? detail, - CancellationToken cancellationToken); - - /// - /// Marks the matching session's actor announcement as pending. - /// A missing session is unchanged. - /// - Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Atomically clears the matching session's pending announcement and returns true. - /// Returns false when no session matches or no announcement is pending. - /// - Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Arms one idle push for the matching session. A missing session is unchanged. - /// - Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); - - /// - /// Atomically consumes the matching session's armed idle push and returns true. - /// Returns false when no session matches or no push is armed. - /// - Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentStore.cs new file mode 100644 index 00000000000..c71af1de481 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IAgentStore.cs @@ -0,0 +1,155 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Reads and writes the unified agents table: identity, harness session binding, +/// role, and presence. +/// +internal interface IAgentStore +{ + /// + /// Mints a login-only agent with an empty role and no harness or session. + /// + Task LoginAsync(CancellationToken cancellationToken); + + /// + /// Starts or resumes a harness session. Reuses the row for a known, non-deleted + /// harness session id, mints a new agent for an unknown one, or returns + /// without writing anything when the + /// harness session id belongs to a deleted agent. + /// + Task StartSessionAsync( + AgentSessionStartRequest request, + CancellationToken cancellationToken); + + /// + /// Refreshes last-seen time for the agent bound to the given harness session id. + /// Returns false, writing nothing, when no matching non-deleted row exists. + /// + Task TouchSessionAsync(string harness, string sessionId, CancellationToken cancellationToken); + + /// + /// Normalizes the given name and refreshes its last-seen time. Returns false, + /// writing nothing, when no matching non-deleted row exists. + /// + Task TouchAsync(string name, CancellationToken cancellationToken); + + /// + /// Marks the agent bound to the given harness session id as ended. Returns false, + /// writing nothing, when no matching non-deleted row exists. + /// + Task EndSessionAsync(string harness, string sessionId, CancellationToken cancellationToken); + + /// + /// Normalizes the given name and role, writes the role, and refreshes last-seen + /// time. Returns null, writing nothing, when no matching non-deleted row exists. + /// + Task SetRoleAsync(string name, string role, CancellationToken cancellationToken); + + /// + /// Normalizes the given name and returns the matching row, including a deleted one, + /// or null when it does not exist. + /// + Task FindAsync(string name, CancellationToken cancellationToken); + + /// + /// Returns the row bound to the given harness session id, including a deleted one, + /// or null when it does not exist. + /// + Task FindBySessionAsync(string harness, string sessionId, CancellationToken cancellationToken); + + /// + /// Returns every non-deleted agent row, in no particular order. + /// + Task> ListAsync(CancellationToken cancellationToken); + + /// + /// Normalizes and writes the agent's transport endpoint, retaining the credential only + /// for an opencode harness's opencode-server endpoint. Returns false, writing nothing, + /// when no matching non-deleted row exists. + /// + Task SetEndpointAsync( + string name, + string endpointKind, + string endpointAddr, + string? endpointSecret, + CancellationToken cancellationToken); + + /// + /// Resets the agent's block budget to zero. Returns 0, writing nothing, when no matching + /// non-deleted row exists. + /// + Task ResetBlockBudgetAsync(string name, CancellationToken cancellationToken); + + /// + /// Atomically increments the agent's block budget by one and returns the new value. + /// Returns 0, writing nothing, when no matching non-deleted row exists. + /// + Task IncrementBlockBudgetAsync(string name, CancellationToken cancellationToken); + + /// + /// Claims the agent's ping cooldown for , clearing the + /// previous result and detail. Returns false, writing nothing, when no matching + /// non-deleted row exists or the previous attempt is newer than now minus + /// . + /// + Task TryClaimPingCooldownAsync( + string name, TimeSpan cooldown, string attemptId, CancellationToken cancellationToken); + + /// + /// Records the ping result and detail only when the agent name and its current ping + /// attempt id match. A stale attempt id, a missing agent, or a deleted agent changes + /// nothing. + /// + Task WritePingResultAsync( + string name, string attemptId, string result, string? detail, CancellationToken cancellationToken); + + /// + /// Marks the agent's actor announcement as pending. A missing or deleted agent is unchanged. + /// + Task ArmAnnouncementAsync(string name, CancellationToken cancellationToken); + + /// + /// Atomically clears the agent's pending announcement and returns whether one was pending. + /// Returns false when no matching non-deleted row exists or none is pending. + /// + Task ClaimAnnouncementAsync(string name, CancellationToken cancellationToken); + + /// + /// Returns whether the agent has a pending announcement. Returns false when no matching + /// non-deleted row exists. + /// + Task IsAnnouncementPendingAsync(string name, CancellationToken cancellationToken); + + /// + /// Arms one idle push for the agent. A missing or deleted agent is unchanged. + /// + Task RearmIdlePushAsync(string name, CancellationToken cancellationToken); + + /// + /// Atomically consumes the agent's armed idle push and returns whether one was armed. + /// Returns false when no matching non-deleted row exists or none is armed. + /// + Task ClaimIdlePushAsync(string name, CancellationToken cancellationToken); + + /// + /// Updates the agent's harness version. Returns false, writing nothing, when no matching + /// non-deleted row exists. + /// + Task RecordHarnessVersionAsync(string name, string harnessVersion, CancellationToken cancellationToken); + + /// + /// Soft-deletes the named agent: stamps deleted_at, clears its endpoint and + /// transient state, drops its wake and ping side rows, and returns its in-progress + /// tasks to open and unassigned. Returns false, writing nothing, when no matching + /// non-deleted row exists. There is no undelete. + /// + Task DeleteAsync(string name, CancellationToken cancellationToken); + + /// + /// Soft-deletes every agent currently resolving to or + /// , applying the same effect as to + /// each. Online and unreachable agents are left untouched. Returns the number of agents + /// deleted. + /// + Task DeleteInactiveAsync(CancellationToken cancellationToken); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IClaudeSessionActivityReader.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IClaudeSessionActivityReader.cs deleted file mode 100644 index ade43b6d419..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IClaudeSessionActivityReader.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Reads Claude session activity from its session file without caching it. -/// -internal interface IClaudeSessionActivityReader -{ - /// - /// Returns the status field ("idle" or "busy", whatever Claude - /// Code currently writes) from the session file carrying . Returns null when no file carries it, or on any - /// parse failure: this is a best-effort display enrichment, never a - /// source of truth. - /// - string? GetStatus(string sessionId); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeBatchStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeBatchStore.cs index b614db98be3..94ddd8a582c 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeBatchStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeBatchStore.cs @@ -3,27 +3,27 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// /// Atomic conditional primitives over mail_wake_batches, /// mail_wake_targets, and the claim/settle side of -/// mail_wake_outbox. Every mutation is owner/attempt/expiry fenced: -/// it only applies when the caller still holds the exact claim it is acting -/// on, so a renewal or completion lost to a fresher claimant becomes a -/// silent no-op rather than corrupting state a new owner has since taken -/// over. Does not decide which actor to claim next, which sessions belong in -/// a batch, or how to react to a target's outcome; those policies belong to -/// the caller (the direct-first wake dispatcher). +/// mail_wake_outbox. Every mutation is owner/attempt/expiry fenced +/// and additionally requires the caller's owner id to be the current +/// mail_wake_daemons leader lease holder, so a stale or demoted +/// leader's writes become a silent no-op. Does not decide which actor to +/// claim next, which agents belong in a batch, or how to react to a +/// target's outcome; those policies belong to the caller (the direct-first +/// wake dispatcher). /// internal interface IMailWakeBatchStore { /// - /// Claims due, unsettled work for the instance and actor, replacing any expired + /// Claims due, unsettled work for the actor, replacing any expired /// batch and recording the current requested generation and supplied targets. - /// Returns null when no work is due or an unexpired active batch exists. + /// Returns null when no work is due, an unexpired active batch exists, + /// or the caller does not hold the current leader lease. /// Task TryClaimAsync( - string nitroInstanceId, string actor, string ownerId, string attemptId, - IReadOnlyList targets, + IReadOnlyList targets, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken); @@ -77,7 +77,7 @@ Task TryReleaseAsync( /// Task TryRecordTargetOutcomeAsync( string batchId, - AgentSessionGeneration target, + string target, string ownerId, string attemptId, string status, diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeDaemonLeaderStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeDaemonLeaderStore.cs index 479fac975df..86b102305f4 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeDaemonLeaderStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/IMailWakeDaemonLeaderStore.cs @@ -1,42 +1,35 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// Manages shared mail-wake leadership leases, one per Nitro instance. +/// Manages the single shared mail-wake leadership lease for this workspace. /// internal interface IMailWakeDaemonLeaderStore { /// - /// Claims absent or expired leadership and returns its new epoch, starting at 1. - /// Returns null while any unexpired lease exists, including one held by the same owner. + /// Claims the lease when no row exists yet or the existing lease has expired, + /// stamping as the new holder. Returns false, claiming + /// nothing, while any unexpired lease exists, including one held by + /// itself. /// - Task TryAcquireAsync( - string nitroInstanceId, - string ownerId, + Task TryAcquireAsync( + string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken); /// - /// Sets the matching leader lease's expiry and last error; null clears the error. - /// Returns false when the owner or epoch differs or the lease has expired. + /// Extends the lease's expiry for its current holder. Returns false, changing + /// nothing, when does not hold an unexpired lease. /// Task TryRenewAsync( - string nitroInstanceId, - string ownerId, - long epoch, + string token, DateTimeOffset now, TimeSpan leaseDuration, - string? lastError, CancellationToken cancellationToken); /// - /// Sets the matching owner and epoch's lease expiry to . - /// Returns false when no matching leadership row exists. + /// Expires the lease immediately for its current holder. Returns false, changing + /// nothing, when does not hold the lease. /// - Task TryReleaseAsync( - string nitroInstanceId, - string ownerId, - long epoch, - DateTimeOffset now, - CancellationToken cancellationToken); + Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/INitroInstanceIdProvider.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/INitroInstanceIdProvider.cs deleted file mode 100644 index ef2b566e36b..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/INitroInstanceIdProvider.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Resolves the Nitro instance id used to identify the owner of session presence. -/// -internal interface INitroInstanceIdProvider -{ - /// - /// Returns a hash of the platform machine identifier when available, otherwise a - /// generated id persisted under . - /// Concurrent first use shares the same persisted fallback id. - /// - Task GetIdAsync(string globalConfigDirectory, CancellationToken cancellationToken); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ISessionDeliveryLedger.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ISessionDeliveryLedger.cs deleted file mode 100644 index 21e028f2e7f..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/ISessionDeliveryLedger.cs +++ /dev/null @@ -1,54 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Manages independent notification reservations per session, message, and channel. -/// Reservations precede delivery and remain claimed until released or cleared with session state. -/// -internal interface ISessionDeliveryLedger -{ - /// - /// Returns input message ids with reservations across any channel for the supplied - /// generation's harness and session id, preserving input order. Host is not part of - /// the lookup; empty input returns an empty result. - /// - Task> FindDeliveredAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - CancellationToken cancellationToken) - => Task.FromException>(new NotSupportedException()); - - /// - /// Claims previously unreserved messages for the session and channel, returning - /// new claims in input order without duplicates. Empty input returns an empty result. - /// - Task> ReserveAsync( - string harness, - string sessionId, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken); - - /// - /// Claims messages for the session and channel only when its host matches - /// . Returns new claims in input order, or an empty - /// result for empty input or a missing or differently owned session. - /// - Task> ReserveAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken); - - /// - /// Releases the supplied message reservations for the channel only when the - /// session host matches . Empty input or a missing - /// or differently owned session changes nothing. - /// - Task ReleaseAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - CancellationToken cancellationToken); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchClaim.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchClaim.cs index 444340c7900..914c4af7629 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchClaim.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchClaim.cs @@ -1,7 +1,7 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// The claimed batch id, captured outbox generation, and target session identities. +/// The claimed batch id, captured outbox generation, and target agent names. /// internal sealed record MailWakeBatchClaim( - string BatchId, long ClaimedGeneration, IReadOnlyList Targets); + string BatchId, long ClaimedGeneration, IReadOnlyList Targets); diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchStore.cs index 819a517717a..c0dd3ade522 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeBatchStore.cs @@ -6,11 +6,10 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; internal sealed class MailWakeBatchStore(IFileSystem fileSystem, AgentDatabase database) : IMailWakeBatchStore { public async Task TryClaimAsync( - string nitroInstanceId, string actor, string ownerId, string attemptId, - IReadOnlyList targets, + IReadOnlyList targets, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) @@ -20,13 +19,13 @@ internal sealed class MailWakeBatchStore(IFileSystem fileSystem, AgentDatabase d var outbox = await connection.QueryFirstOrDefaultAsync( """ - SELECT requested_generation AS RequestedGeneration, settled_generation AS SettledGeneration, - due_at AS DueAt - FROM mail_wake_outbox - WHERE nitro_instance_id = @nitroInstanceId AND actor = @actor - """, - new { nitroInstanceId, actor, cancellationToken }, - transaction); + SELECT requested_generation AS RequestedGeneration, settled_generation AS SettledGeneration, + due_at AS DueAt + FROM mail_wake_outbox + WHERE actor = @actor + """, + new { actor }, + transaction: transaction); if (outbox is null || outbox.SettledGeneration >= outbox.RequestedGeneration @@ -39,20 +38,19 @@ FROM mail_wake_outbox // Expired active batches are released before another batch is claimed. await connection.ExecuteAsync( """ - UPDATE mail_wake_batches SET status = 'released', last_error = 'lease expired' - WHERE nitro_instance_id = @nitroInstanceId AND actor = @actor AND status = 'active' - AND expires_at <= @now - """, - new { nitroInstanceId, actor, now, cancellationToken }, - transaction); + UPDATE mail_wake_batches SET status = 'released', last_error = 'lease expired' + WHERE actor = @actor AND status = 'active' AND expires_at <= @now + """, + new { actor, now }, + transaction: transaction); var activeBatchCount = await connection.ExecuteScalarAsync( """ - SELECT COUNT(*) FROM mail_wake_batches - WHERE nitro_instance_id = @nitroInstanceId AND actor = @actor AND status = 'active' - """, - new { nitroInstanceId, actor, cancellationToken }, - transaction); + SELECT COUNT(*) FROM mail_wake_batches + WHERE actor = @actor AND status = 'active' + """, + new { actor }, + transaction: transaction); if (activeBatchCount > 0) { @@ -60,50 +58,56 @@ SELECT COUNT(*) FROM mail_wake_batches return null; } + var isLeaseHolder = await connection.ExecuteScalarAsync( + """ + SELECT EXISTS ( + SELECT 1 FROM mail_wake_daemons + WHERE id = 1 AND owner_token = @ownerId AND expires_at > @now + ) + """, + new { ownerId, now }, + transaction: transaction); + + if (isLeaseHolder == 0) + { + await transaction.CommitAsync(cancellationToken); + return null; + } + var batchId = Guid.NewGuid().ToString("N"); var expiresAt = now + leaseDuration; await connection.ExecuteAsync( """ - INSERT INTO mail_wake_batches ( - batch_id, nitro_instance_id, actor, claimed_generation, owner_id, attempt_id, - status, claimed_at, expires_at - ) VALUES ( - @batchId, @nitroInstanceId, @actor, @claimedGeneration, @ownerId, @attemptId, - 'active', @now, @expiresAt - ) - """, - new - { - batchId, - nitroInstanceId, - actor, - claimedGeneration = outbox.RequestedGeneration, - ownerId, - attemptId, - now, - expiresAt, - cancellationToken - }, - transaction); - - foreach (var target in targets) - { - await connection.ExecuteAsync( - """ - INSERT INTO mail_wake_targets (batch_id, harness, session_id, host, status, updated_at) - VALUES (@batchId, @harness, @sessionId, @host, 'pending', @now) + INSERT INTO mail_wake_batches ( + batch_id, actor, claimed_generation, owner_id, attempt_id, + status, claimed_at, expires_at + ) VALUES ( + @batchId, @actor, @claimedGeneration, @ownerId, @attemptId, + 'active', @now, @expiresAt + ) """, new { batchId, - harness = target.Harness, - sessionId = target.SessionId, - host = target.Host, + actor, + claimedGeneration = outbox.RequestedGeneration, + ownerId, + attemptId, now, - cancellationToken + expiresAt }, - transaction); + transaction: transaction); + + foreach (var target in targets) + { + await connection.ExecuteAsync( + """ + INSERT INTO mail_wake_targets (batch_id, agent, status, updated_at) + VALUES (@batchId, @target, 'pending', @now) + """, + new { batchId, target, now }, + transaction: transaction); } await transaction.CommitAsync(cancellationToken); @@ -123,12 +127,16 @@ public async Task TryRenewAsync( var renewedBatchId = await connection.QueryFirstOrDefaultAsync( """ - UPDATE mail_wake_batches SET expires_at = @expiresAt - WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId - AND status = 'active' AND expires_at > @now - RETURNING batch_id - """, - new { batchId, ownerId, attemptId, now, expiresAt = now + leaseDuration, cancellationToken }); + UPDATE mail_wake_batches SET expires_at = @expiresAt + WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId + AND status = 'active' AND expires_at > @now + AND EXISTS ( + SELECT 1 FROM mail_wake_daemons + WHERE id = 1 AND owner_token = @ownerId AND expires_at > @now + ) + RETURNING batch_id + """, + new { batchId, ownerId, attemptId, now, expiresAt = now + leaseDuration }); return renewedBatchId is not null; } @@ -145,13 +153,17 @@ public async Task TryCompleteAsync( var completed = await connection.QueryFirstOrDefaultAsync( """ - UPDATE mail_wake_batches SET status = 'completed', completed_at = @now - WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId - AND status = 'active' AND expires_at > @now - RETURNING nitro_instance_id AS NitroInstanceId, actor AS Actor, claimed_generation AS ClaimedGeneration - """, - new { batchId, ownerId, attemptId, now, cancellationToken }, - transaction); + UPDATE mail_wake_batches SET status = 'completed', completed_at = @now + WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId + AND status = 'active' AND expires_at > @now + AND EXISTS ( + SELECT 1 FROM mail_wake_daemons + WHERE id = 1 AND owner_token = @ownerId AND expires_at > @now + ) + RETURNING actor AS Actor, claimed_generation AS ClaimedGeneration + """, + new { batchId, ownerId, attemptId, now }, + transaction: transaction); if (completed is null) { @@ -162,19 +174,17 @@ public async Task TryCompleteAsync( // Completion settles through the claimed generation without lowering existing settlement. await connection.ExecuteAsync( """ - UPDATE mail_wake_outbox - SET settled_generation = MAX(settled_generation, @claimedGeneration), updated_at = @now - WHERE nitro_instance_id = @nitroInstanceId AND actor = @actor - """, - new - { - claimedGeneration = completed.ClaimedGeneration, - now, - nitroInstanceId = completed.NitroInstanceId, - actor = completed.Actor, - cancellationToken - }, - transaction); + UPDATE mail_wake_outbox + SET settled_generation = MAX(settled_generation, @claimedGeneration), updated_at = @now + WHERE actor = @actor + """, + new + { + claimedGeneration = completed.ClaimedGeneration, + now, + actor = completed.Actor + }, + transaction: transaction); await transaction.CommitAsync(cancellationToken); return true; @@ -194,13 +204,17 @@ public async Task TryReleaseAsync( var released = await connection.QueryFirstOrDefaultAsync( """ - UPDATE mail_wake_batches SET status = 'released', last_error = @lastError - WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId - AND status = 'active' AND expires_at > @now - RETURNING nitro_instance_id AS NitroInstanceId, actor AS Actor - """, - new { batchId, ownerId, attemptId, now, lastError, cancellationToken }, - transaction); + UPDATE mail_wake_batches SET status = 'released', last_error = @lastError + WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId + AND status = 'active' AND expires_at > @now + AND EXISTS ( + SELECT 1 FROM mail_wake_daemons + WHERE id = 1 AND owner_token = @ownerId AND expires_at > @now + ) + RETURNING actor AS Actor + """, + new { batchId, ownerId, attemptId, now, lastError }, + transaction: transaction); if (released is null) { @@ -212,18 +226,11 @@ public async Task TryReleaseAsync( { await connection.ExecuteAsync( """ - UPDATE mail_wake_outbox SET due_at = @retryAt, updated_at = @now - WHERE nitro_instance_id = @nitroInstanceId AND actor = @actor - """, - new - { - retryAt = retryAtValue, - now, - nitroInstanceId = released.NitroInstanceId, - actor = released.Actor, - cancellationToken - }, - transaction); + UPDATE mail_wake_outbox SET due_at = @retryAt, updated_at = @now + WHERE actor = @actor + """, + new { retryAt = retryAtValue, now, actor = released.Actor }, + transaction: transaction); } await transaction.CommitAsync(cancellationToken); @@ -232,7 +239,7 @@ await connection.ExecuteAsync( public async Task TryRecordTargetOutcomeAsync( string batchId, - AgentSessionGeneration target, + string target, string ownerId, string attemptId, string status, @@ -246,36 +253,36 @@ public async Task TryRecordTargetOutcomeAsync( var updatedBatchId = await connection.QueryFirstOrDefaultAsync( """ - UPDATE mail_wake_targets SET - status = @status, - offered_generation = @offeredGeneration, - accepted_generation = @acceptedGeneration, - last_error = @lastError, - updated_at = @now - WHERE batch_id = @batchId AND harness = @harness AND session_id = @sessionId - AND host = @host - AND EXISTS ( - SELECT 1 FROM mail_wake_batches - WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId - AND status = 'active' AND expires_at > @now - ) - RETURNING batch_id - """, - new - { - batchId, - harness = target.Harness, - sessionId = target.SessionId, - host = target.Host, - status, - offeredGeneration, - acceptedGeneration, - lastError, - now, - ownerId, - attemptId, - cancellationToken - }); + UPDATE mail_wake_targets SET + status = @status, + offered_generation = @offeredGeneration, + accepted_generation = @acceptedGeneration, + last_error = @lastError, + updated_at = @now + WHERE batch_id = @batchId AND agent = @target + AND EXISTS ( + SELECT 1 FROM mail_wake_batches + WHERE batch_id = @batchId AND owner_id = @ownerId AND attempt_id = @attemptId + AND status = 'active' AND expires_at > @now + ) + AND EXISTS ( + SELECT 1 FROM mail_wake_daemons + WHERE id = 1 AND owner_token = @ownerId AND expires_at > @now + ) + RETURNING batch_id + """, + new + { + batchId, + target, + status, + offeredGeneration, + acceptedGeneration, + lastError, + now, + ownerId, + attemptId + }); return updatedBatchId is not null; } @@ -297,14 +304,12 @@ internal sealed class OutboxDueRow internal sealed class CompletedBatchRow { - public required string NitroInstanceId { get; init; } public required string Actor { get; init; } public required long ClaimedGeneration { get; init; } } internal sealed class ReleasedBatchRow { - public required string NitroInstanceId { get; init; } public required string Actor { get; init; } } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeDaemonLeaderStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeDaemonLeaderStore.cs index 1c3ed60ef1c..aa584c8d27d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeDaemonLeaderStore.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeDaemonLeaderStore.cs @@ -6,80 +6,63 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; internal sealed class MailWakeDaemonLeaderStore( IFileSystem fileSystem, AgentDatabase database) : IMailWakeDaemonLeaderStore { - public async Task TryAcquireAsync( - string nitroInstanceId, - string ownerId, + public async Task TryAcquireAsync( + string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) { await using var connection = await ConnectAsync(cancellationToken); - return await connection.QueryFirstOrDefaultAsync( + var acquired = await connection.QueryFirstOrDefaultAsync( """ - INSERT INTO mail_wake_daemons (nitro_instance_id, owner_id, epoch, leased_at, expires_at) - VALUES (@nitroInstanceId, @ownerId, 1, @now, @expiresAt) - ON CONFLICT (nitro_instance_id) DO UPDATE SET - owner_id = excluded.owner_id, - epoch = mail_wake_daemons.epoch + 1, - leased_at = excluded.leased_at, - expires_at = excluded.expires_at - WHERE mail_wake_daemons.expires_at <= @now - RETURNING epoch - """, - new { nitroInstanceId, ownerId, now, expiresAt = now + leaseDuration, cancellationToken }); + INSERT INTO mail_wake_daemons (id, owner_token, acquired_at, heartbeat_at, expires_at) + VALUES (1, @token, @now, @now, @expiresAt) + ON CONFLICT (id) DO UPDATE SET + owner_token = excluded.owner_token, + acquired_at = excluded.acquired_at, + heartbeat_at = excluded.heartbeat_at, + expires_at = excluded.expires_at + WHERE mail_wake_daemons.expires_at <= @now + RETURNING owner_token + """, + new { token, now, expiresAt = now + leaseDuration }); + + return acquired is not null; } public async Task TryRenewAsync( - string nitroInstanceId, - string ownerId, - long epoch, + string token, DateTimeOffset now, TimeSpan leaseDuration, - string? lastError, CancellationToken cancellationToken) { await using var connection = await ConnectAsync(cancellationToken); - var renewedEpoch = await connection.QueryFirstOrDefaultAsync( + var renewed = await connection.QueryFirstOrDefaultAsync( """ - UPDATE mail_wake_daemons SET expires_at = @expiresAt, leased_at = @now, last_error = @lastError - WHERE nitro_instance_id = @nitroInstanceId AND owner_id = @ownerId AND epoch = @epoch - AND expires_at > @now - RETURNING epoch - """, - new - { - nitroInstanceId, - ownerId, - epoch, - now, - expiresAt = now + leaseDuration, - lastError, - cancellationToken - }); + UPDATE mail_wake_daemons SET expires_at = @expiresAt, heartbeat_at = @now + WHERE id = 1 AND owner_token = @token AND expires_at > @now + RETURNING owner_token + """, + new { token, now, expiresAt = now + leaseDuration }); - return renewedEpoch is not null; + return renewed is not null; } - public async Task TryReleaseAsync( - string nitroInstanceId, - string ownerId, - long epoch, - DateTimeOffset now, - CancellationToken cancellationToken) + public async Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) { await using var connection = await ConnectAsync(cancellationToken); - var releasedEpoch = await connection.QueryFirstOrDefaultAsync( + var released = await connection.QueryFirstOrDefaultAsync( """ - UPDATE mail_wake_daemons SET expires_at = @now - WHERE nitro_instance_id = @nitroInstanceId AND owner_id = @ownerId AND epoch = @epoch - RETURNING epoch - """, - new { nitroInstanceId, ownerId, epoch, now, cancellationToken }); + UPDATE mail_wake_daemons SET expires_at = @now + WHERE id = 1 AND owner_token = @token + RETURNING owner_token + """, + new { token, now }); - return releasedEpoch is not null; + return released is not null; } private async Task ConnectAsync(CancellationToken cancellationToken) diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeSchema.cs index 5585f93c6b9..60a7c03b3c3 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeSchema.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/MailWakeSchema.cs @@ -1,40 +1,20 @@ namespace ChilliCream.Nitro.CommandLine.Services.Workspace; /// -/// Defines the durable wake outbox, claimed batches, target outcomes, and daemon -/// leadership leases. Each Nitro instance and actor can have at most one active batch. +/// Defines the durable wake outbox, claimed batches, target outcomes, and the single +/// daemon leadership lease. Each actor can have at most one active batch. /// internal static class MailWakeSchema { - /// - /// The columns and constraints of the wake target table. - /// - private const string MailWakeTargetsColumns = - """ - batch_id TEXT NOT NULL REFERENCES mail_wake_batches (batch_id) ON DELETE CASCADE, - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode', 'nitro-board')), - session_id TEXT NOT NULL, - host TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending' - CHECK (status IN ('pending', 'delivered', 'satisfied', 'delegated', 'skipped', 'failed')), - offered_generation INTEGER NULL CHECK (offered_generation IS NULL OR offered_generation >= 0), - accepted_generation INTEGER NULL CHECK (accepted_generation IS NULL OR accepted_generation >= 0), - last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200), - updated_at TEXT NOT NULL, - PRIMARY KEY (batch_id, harness, session_id, host) - """; - public const string Create = """ CREATE TABLE IF NOT EXISTS mail_wake_outbox ( - nitro_instance_id TEXT NOT NULL, - actor TEXT NOT NULL REFERENCES agents (name), + actor TEXT NOT NULL PRIMARY KEY REFERENCES agents (name), requested_generation INTEGER NOT NULL DEFAULT 0 CHECK (requested_generation >= 0), settled_generation INTEGER NOT NULL DEFAULT 0 CHECK (settled_generation >= 0 AND settled_generation <= requested_generation), due_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - PRIMARY KEY (nitro_instance_id, actor) + updated_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_mail_wake_outbox_due @@ -43,8 +23,7 @@ ON mail_wake_outbox (due_at) CREATE TABLE IF NOT EXISTS mail_wake_batches ( batch_id TEXT PRIMARY KEY, - nitro_instance_id TEXT NOT NULL, - actor TEXT NOT NULL, + actor TEXT NOT NULL REFERENCES mail_wake_outbox (actor), claimed_generation INTEGER NOT NULL CHECK (claimed_generation >= 0), owner_id TEXT NOT NULL, attempt_id TEXT NOT NULL, @@ -52,12 +31,11 @@ claimed_generation INTEGER NOT NULL CHECK (claimed_generation >= 0), claimed_at TEXT NOT NULL, expires_at TEXT NOT NULL, completed_at TEXT NULL, - last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200), - FOREIGN KEY (nitro_instance_id, actor) REFERENCES mail_wake_outbox (nitro_instance_id, actor) + last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200) ); CREATE UNIQUE INDEX IF NOT EXISTS idx_mail_wake_batches_one_active_per_actor - ON mail_wake_batches (nitro_instance_id, actor) + ON mail_wake_batches (actor) WHERE status = 'active'; CREATE INDEX IF NOT EXISTS idx_mail_wake_batches_expires @@ -65,29 +43,23 @@ ON mail_wake_batches (expires_at) WHERE status = 'active'; CREATE TABLE IF NOT EXISTS mail_wake_targets ( - """ - + MailWakeTargetsColumns - + """ - + batch_id TEXT NOT NULL REFERENCES mail_wake_batches (batch_id) ON DELETE CASCADE, + agent TEXT NOT NULL REFERENCES agents (name), + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'delivered', 'satisfied', 'delegated', 'skipped', 'failed')), + offered_generation INTEGER NULL CHECK (offered_generation IS NULL OR offered_generation >= 0), + accepted_generation INTEGER NULL CHECK (accepted_generation IS NULL OR accepted_generation >= 0), + last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200), + updated_at TEXT NOT NULL, + PRIMARY KEY (batch_id, agent) ); CREATE TABLE IF NOT EXISTS mail_wake_daemons ( - nitro_instance_id TEXT PRIMARY KEY, - owner_id TEXT NOT NULL, - epoch INTEGER NOT NULL CHECK (epoch >= 1), - leased_at TEXT NOT NULL, - expires_at TEXT NOT NULL, - last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200) - ); - """; - - /// - /// Returns SQL to create wake targets under . - /// - public static string CreateMailWakeTargetsTable(string tableName) => - $""" - CREATE TABLE "{tableName}" ( - {MailWakeTargetsColumns} + id INTEGER PRIMARY KEY CHECK (id = 1), + owner_token TEXT NOT NULL, + acquired_at TEXT NOT NULL, + heartbeat_at TEXT NOT NULL, + expires_at TEXT NOT NULL ); """; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/NitroInstanceIdProvider.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/NitroInstanceIdProvider.cs deleted file mode 100644 index b31d25ee730..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/NitroInstanceIdProvider.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; - -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed partial class NitroInstanceIdProvider( - IFileSystem fileSystem, - Func? machineIdReader = null) : INitroInstanceIdProvider -{ - private const string FallbackFileName = "instance-id"; - - private static readonly string[] s_linuxMachineIdPaths = ["/etc/machine-id", "/var/lib/dbus/machine-id"]; - - private readonly Func _machineIdReader = machineIdReader ?? ReadPlatformMachineId; - - public async Task GetIdAsync(string globalConfigDirectory, CancellationToken cancellationToken) - { - var machineId = _machineIdReader(); - - return machineId is not null - ? HashMachineId(machineId) - : await GetOrCreateFallbackIdAsync(globalConfigDirectory, cancellationToken); - } - - /// - /// Returns the platform machine identifier, or null when it is unavailable or reading it fails. - /// - private static string? ReadPlatformMachineId() - { - try - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return ReadLinuxMachineId(); - } - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return ReadWindowsMachineGuid(); - } - - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return ReadMacPlatformUuid(); - } - } - catch - { - return null; - } - - return null; - } - - private static string? ReadLinuxMachineId() - { - foreach (var path in s_linuxMachineIdPaths) - { - if (File.Exists(path)) - { - var content = File.ReadAllText(path).Trim(); - - if (content.Length > 0) - { - return content; - } - } - } - - return null; - } - - private static string? ReadWindowsMachineGuid() - { - using var process = Process.Start(new ProcessStartInfo("reg") - { - ArgumentList = { "query", """HKLM\SOFTWARE\Microsoft\Cryptography""", "/v", "MachineGuid" }, - RedirectStandardOutput = true, - UseShellExecute = false - }); - - if (process is null) - { - return null; - } - - var output = ReadWithTimeout(process); - - if (output is null) - { - return null; - } - - var match = WindowsMachineGuidPattern().Match(output); - - return match.Success ? match.Groups[1].Value : null; - } - - [GeneratedRegex(@"MachineGuid\s+REG_SZ\s+(\S+)")] - private static partial Regex WindowsMachineGuidPattern(); - - private static string? ReadMacPlatformUuid() - { - using var process = Process.Start(new ProcessStartInfo("ioreg") - { - ArgumentList = { "-rd1", "-c", "IOPlatformExpertDevice" }, - RedirectStandardOutput = true, - UseShellExecute = false - }); - - if (process is null) - { - return null; - } - - var output = ReadWithTimeout(process); - - if (output is null) - { - return null; - } - - var match = MacPlatformUuidPattern().Match(output); - - return match.Success ? match.Groups[1].Value : null; - } - - [GeneratedRegex(""""IOPlatformUUID"\s*=\s*"([^"]+)"""")] - private static partial Regex MacPlatformUuidPattern(); - - /// - /// Returns standard output when reading and process exit complete within two seconds. - /// On timeout, attempts to terminate the process and returns null. - /// - private static string? ReadWithTimeout(Process process) - { - var stopwatch = Stopwatch.StartNew(); - var readTask = process.StandardOutput.ReadToEndAsync(); - - if (!readTask.Wait(2000)) - { - TryKill(process); - return null; - } - - var remaining = Math.Max(0, 2000 - (int)stopwatch.ElapsedMilliseconds); - - if (!process.WaitForExit(remaining)) - { - TryKill(process); - return null; - } - - return readTask.GetAwaiter().GetResult(); - } - - private static void TryKill(Process process) - { - try - { - process.Kill(entireProcessTree: true); - } - catch - { - // Process termination is best effort. - } - } - - private static string HashMachineId(string machineId) - { - var hash = SHA256.HashData(Encoding.UTF8.GetBytes(machineId)); - - return Convert.ToHexString(hash).ToLowerInvariant(); - } - - /// - /// Returns the persisted fallback id or atomically creates one when absent. - /// If another process creates it first, returns that id. - /// - private async Task GetOrCreateFallbackIdAsync( - string globalConfigDirectory, - CancellationToken cancellationToken) - { - var path = Path.Combine(globalConfigDirectory, FallbackFileName); - - if (fileSystem.FileExists(path)) - { - return (await fileSystem.ReadAllTextAsync(path, cancellationToken)).Trim(); - } - - if (!fileSystem.DirectoryExists(globalConfigDirectory)) - { - fileSystem.CreateDirectory(globalConfigDirectory); - } - - var candidate = Guid.NewGuid().ToString("N"); - - try - { - await fileSystem.CreateFileAtomicAsync(path, candidate, cancellationToken); - - return candidate; - } - catch (IOException) - { - return (await fileSystem.ReadAllTextAsync(path, cancellationToken)).Trim(); - } - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/PingLeaseSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/PingLeaseSchema.cs new file mode 100644 index 00000000000..cd5805cab26 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/PingLeaseSchema.cs @@ -0,0 +1,17 @@ +namespace ChilliCream.Nitro.CommandLine.Services.Workspace; + +/// +/// Defines the four workspace-wide ping-lease slots. +/// +internal static class PingLeaseSchema +{ + public const string Create = + """ + CREATE TABLE IF NOT EXISTS ping_leases ( + slot INTEGER PRIMARY KEY CHECK (slot BETWEEN 1 AND 4), + attempt_id TEXT NOT NULL, + acquired_at TEXT NOT NULL, + expires_at TEXT NOT NULL + ); + """; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionDeliveryLedger.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionDeliveryLedger.cs deleted file mode 100644 index dfd8137a9b3..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionDeliveryLedger.cs +++ /dev/null @@ -1,193 +0,0 @@ -using Microsoft.Data.Sqlite; - -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed class SessionDeliveryLedger(IFileSystem fileSystem, AgentDatabase database) : ISessionDeliveryLedger -{ - public async Task> FindDeliveredAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - CancellationToken cancellationToken) - { - if (messageIds.Count == 0) - { - return []; - } - - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); - - await using var connection = await database.ConnectAsync(workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - """ - SELECT DISTINCT message_id - FROM session_deliveries - WHERE harness = @harness AND session_id = @sessionId AND message_id IN ( - """ - + string.Join(", ", messageIds.Select((_, index) => $"@messageId{index}")) - + ");"; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - - for (var i = 0; i < messageIds.Count; i++) - { - command.Parameters.AddWithValue($"@messageId{i}", messageIds[i]); - } - - var delivered = new HashSet(StringComparer.Ordinal); - await using var reader = await command.ExecuteReaderAsync(cancellationToken); - - while (await reader.ReadAsync(cancellationToken)) - { - delivered.Add(reader.GetString(0)); - } - - return messageIds.Where(delivered.Contains).ToArray(); - } - - public async Task> ReserveAsync( - string harness, - string sessionId, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - { - if (messageIds.Count == 0) - { - return []; - } - - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); - - await using var connection = await database.ConnectAsync(workspaceDirectory, cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var reserved = new List(messageIds.Count); - - foreach (var messageId in messageIds) - { - await using var command = connection.CreateCommand(); - command.Transaction = (SqliteTransaction)transaction; - command.CommandText = - """ - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES (@harness, @sessionId, @messageId, @channel, @deliveredAt) - ON CONFLICT DO NOTHING; - """; - command.Parameters.AddWithValue("@harness", harness); - command.Parameters.AddWithValue("@sessionId", sessionId); - command.Parameters.AddWithValue("@messageId", messageId); - command.Parameters.AddWithValue("@channel", channel); - command.Parameters.AddWithValue("@deliveredAt", deliveredAt); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - if (rowsAffected > 0) - { - reserved.Add(messageId); - } - } - - await transaction.CommitAsync(cancellationToken); - - return reserved; - } - - public async Task> ReserveAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - { - if (messageIds.Count == 0) - { - return []; - } - - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); - - await using var connection = await database.ConnectAsync(workspaceDirectory, cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - var reserved = new List(messageIds.Count); - - foreach (var messageId in messageIds) - { - await using var command = connection.CreateCommand(); - command.Transaction = (SqliteTransaction)transaction; - command.CommandText = - """ - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - SELECT @harness, @sessionId, @messageId, @channel, @deliveredAt - WHERE EXISTS ( - SELECT 1 FROM agent_sessions - WHERE harness = @harness AND session_id = @sessionId AND host = @host) - ON CONFLICT DO NOTHING; - """; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - command.Parameters.AddWithValue("@messageId", messageId); - command.Parameters.AddWithValue("@channel", channel); - command.Parameters.AddWithValue("@deliveredAt", deliveredAt); - - var rowsAffected = await command.ExecuteNonQueryAsync(cancellationToken); - - if (rowsAffected > 0) - { - reserved.Add(messageId); - } - } - - await transaction.CommitAsync(cancellationToken); - - return reserved; - } - - public async Task ReleaseAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - CancellationToken cancellationToken) - { - if (messageIds.Count == 0) - { - return; - } - - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); - - await using var connection = await database.ConnectAsync(workspaceDirectory, cancellationToken); - await using var transaction = await connection.BeginTransactionAsync(cancellationToken); - - foreach (var messageId in messageIds) - { - await using var command = connection.CreateCommand(); - command.Transaction = (SqliteTransaction)transaction; - command.CommandText = - """ - DELETE FROM session_deliveries - WHERE harness = @harness AND session_id = @sessionId - AND message_id = @messageId AND channel = @channel - AND EXISTS ( - SELECT 1 FROM agent_sessions - WHERE harness = @harness AND session_id = @sessionId AND host = @host); - """; - command.Parameters.AddWithValue("@harness", generation.Harness); - command.Parameters.AddWithValue("@sessionId", generation.SessionId); - command.Parameters.AddWithValue("@host", generation.Host); - command.Parameters.AddWithValue("@messageId", messageId); - command.Parameters.AddWithValue("@channel", channel); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - await transaction.CommitAsync(cancellationToken); - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionDeliveryRecord.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionDeliveryRecord.cs deleted file mode 100644 index 385b07c3802..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionDeliveryRecord.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// A notification reservation for one session, message, and channel. -/// A reservation does not confirm that delivery succeeded. -/// -internal sealed record SessionDeliveryRecord -{ - /// - /// The column list matching this type's properties, for use in SELECT - /// statements against the session_deliveries table. - /// - public const string Columns = - "harness AS Harness, session_id AS SessionId, message_id AS MessageId, " - + "channel AS Channel, delivered_at AS DeliveredAt"; - - public required string Harness { get; init; } - public required string SessionId { get; init; } - public required string MessageId { get; init; } - - /// - /// One of "digest", "gate", or "ping". - /// - public required string Channel { get; init; } - - public required DateTimeOffset DeliveredAt { get; init; } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionPingGateSchema.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionPingGateSchema.cs deleted file mode 100644 index b0f8359174c..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionPingGateSchema.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -/// -/// Defines transport leases keyed by harness, session id, and host. -/// Deleting session presence does not remove these leases. -/// -internal static class SessionPingGateSchema -{ - /// - /// The columns and constraints of the session transport lease table. - /// - private const string SessionPingGatesColumns = - """ - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode', 'nitro-board')), - session_id TEXT NOT NULL, - host TEXT NOT NULL, - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, host) - """; - - public const string Create = - """ - CREATE TABLE IF NOT EXISTS session_ping_gates ( - """ - + SessionPingGatesColumns - + """ - - ); - - CREATE INDEX IF NOT EXISTS idx_session_ping_gates_expires ON session_ping_gates (expires_at); - """; - - /// - /// Returns SQL to create session transport leases under . - /// - public static string CreateSessionPingGatesTable(string tableName) => - $""" - CREATE TABLE "{tableName}" ( - {SessionPingGatesColumns} - ); - """; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionPingGateStore.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionPingGateStore.cs deleted file mode 100644 index 4f658c697bd..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/SessionPingGateStore.cs +++ /dev/null @@ -1,105 +0,0 @@ -using Dapper; -using Microsoft.Data.Sqlite; - -namespace ChilliCream.Nitro.CommandLine.Services.Workspace; - -internal sealed class SessionPingGateStore(IFileSystem fileSystem, AgentDatabase database) : ISessionPingGateStore -{ - public async Task TryAcquireAsync( - AgentSessionGeneration generation, - string attemptId, - DateTimeOffset now, - TimeSpan leaseDuration, - CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - // An unexpired gate remains claimed by its current attempt. - var claimed = await connection.QueryFirstOrDefaultAsync( - """ - INSERT INTO session_ping_gates ( - harness, session_id, host, attempt_id, acquired_at, expires_at - ) - VALUES ( - @harness, @sessionId, @host, @attemptId, @now, @expiresAt - ) - ON CONFLICT (harness, session_id, host) DO UPDATE SET - attempt_id = excluded.attempt_id, - acquired_at = excluded.acquired_at, - expires_at = excluded.expires_at - WHERE session_ping_gates.expires_at <= @now - RETURNING attempt_id - """, - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - attemptId, - now, - expiresAt = now + leaseDuration, - cancellationToken - }); - - return claimed is not null; - } - - public async Task TryRenewAsync( - AgentSessionGeneration generation, - string attemptId, - DateTimeOffset now, - TimeSpan leaseDuration, - CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - var renewed = await connection.QueryFirstOrDefaultAsync( - """ - UPDATE session_ping_gates SET expires_at = @expiresAt - WHERE harness = @harness AND session_id = @sessionId AND host = @host - AND attempt_id = @attemptId AND expires_at > @now - RETURNING attempt_id - """, - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - attemptId, - now, - expiresAt = now + leaseDuration, - cancellationToken - }); - - return renewed is not null; - } - - public async Task ReleaseAsync( - AgentSessionGeneration generation, string attemptId, CancellationToken cancellationToken) - { - await using var connection = await ConnectAsync(cancellationToken); - - await connection.ExecuteAsync( - """ - DELETE FROM session_ping_gates - WHERE harness = @harness AND session_id = @sessionId AND host = @host - AND attempt_id = @attemptId - """, - new - { - harness = generation.Harness, - sessionId = generation.SessionId, - host = generation.Host, - attemptId, - cancellationToken - }); - } - - private async Task ConnectAsync(CancellationToken cancellationToken) - { - var workspaceDirectory = AgentWorkspace.Find(fileSystem, fileSystem.GetCurrentDirectory()) - ?? throw new ExitException("No agent workspace found. Run `nitro agent init` first."); - - return await database.ConnectAsync(workspaceDirectory, cancellationToken); - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/TakeoverLedger.cs b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/TakeoverLedger.cs index 31066f5013a..e7a8184cb76 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/TakeoverLedger.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Services/Workspace/TakeoverLedger.cs @@ -36,8 +36,7 @@ public async Task RecordAsync( transaction); await connection.ExecuteAsync( - new CommandDefinition( - """ + """ INSERT INTO agent_takeovers ( id, from_actor, to_actor, actor, created_at, forced, role, reason ) @@ -56,20 +55,17 @@ INSERT INTO agent_takeovers ( creation.Role, creation.Reason }, - transaction, - cancellationToken: cancellationToken)); + transaction); foreach (var item in items) { await connection.ExecuteAsync( - new CommandDefinition( - """ + """ INSERT INTO agent_takeover_items (takeover_id, kind, item_id) VALUES (@TakeoverId, @Kind, @ItemId); """, new { TakeoverId = id, item.Kind, item.ItemId }, - transaction, - cancellationToken: cancellationToken)); + transaction); } await transaction.CommitAsync(cancellationToken); @@ -108,6 +104,8 @@ public async Task> QueryAsync( if (filter.MessageId is not null) { + // message_sender items only exist on takeovers recorded before senders + // stopped moving; they stay in this filter so old ledger rows still match. where.Add( """ EXISTS ( @@ -280,21 +278,22 @@ private static async Task CreateTakeoverIdAsync( CancellationToken cancellationToken, DbTransaction transaction) { - var takeoverCount = await connection.ExecuteScalarAsync( - new CommandDefinition( - "SELECT COUNT(*) FROM agent_takeovers", - transaction: transaction, - cancellationToken: cancellationToken)); + await using var countCommand = connection.CreateCommand(); + countCommand.Transaction = (SqliteTransaction)transaction; + countCommand.CommandText = "SELECT COUNT(*) FROM agent_takeovers"; + + var takeoverCount = (long)(await countCommand.ExecuteScalarAsync(cancellationToken))!; for (var attempt = 0; attempt < MaxIdAttempts; attempt++) { var id = IdPrefix + CreateIdSuffix(seed, takeoverCount, attempt); - var exists = await connection.ExecuteScalarAsync( - new CommandDefinition( - "SELECT COUNT(*) FROM agent_takeovers WHERE id = @Id", - new { Id = id }, - transaction, - cancellationToken: cancellationToken)); + + await using var existsCommand = connection.CreateCommand(); + existsCommand.Transaction = (SqliteTransaction)transaction; + existsCommand.CommandText = "SELECT COUNT(*) FROM agent_takeovers WHERE id = @Id"; + existsCommand.Parameters.AddWithValue("@Id", id); + + var exists = (long)(await existsCommand.ExecuteScalarAsync(cancellationToken))!; if (exists == 0) { diff --git a/src/Nitro/CommandLine/src/CommandLine/ThrowHelper.cs b/src/Nitro/CommandLine/src/CommandLine/ThrowHelper.cs index 2ce325abe33..c1611e69340 100644 --- a/src/Nitro/CommandLine/src/CommandLine/ThrowHelper.cs +++ b/src/Nitro/CommandLine/src/CommandLine/ThrowHelper.cs @@ -26,4 +26,23 @@ public static ExitException MutationReturnedNoData() public static ArgumentOutOfRangeException NegativeLimit(int limit) => new(nameof(limit), limit, "Limit must be zero or greater."); + + public static ArgumentException UnknownAgentHarness(string harness) + => new($"'{harness}' is not an agent harness.", nameof(harness)); + + public static ExitException UnknownMailRecipient(string name) + => Exit($"Unknown agent '{name}'. Look the name up with 'nitro agent list'."); + + public static ExitException DeletedMailRecipient(string name) + => Exit($"Agent '{name}' was deleted. Look the name up with 'nitro agent list'."); + + public static ExitException NoReplyRecipientsRemaining(IEnumerable<(string Name, bool WasDeleted)> skipped) + { + var reasons = skipped.Select( + recipient => recipient.WasDeleted + ? $"'{recipient.Name}' was deleted" + : $"'{recipient.Name}' is unknown"); + + return Exit($"No recipients left: {string.Join(", ", reasons)}."); + } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentAges.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentAges.cs new file mode 100644 index 00000000000..f1e4b2638ef --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentAges.cs @@ -0,0 +1,38 @@ +using System.Globalization; +using ChilliCream.Nitro.CommandLine.Tui.Mail; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// Formats an agent's age fields (started, last seen, ended) for display, building on +/// : a relative duration gets an " ago" suffix, a fresh +/// timestamp reads as "just now", and an absolute date is shown alone. +/// +internal static class AgentAges +{ + private const string NowLabel = "now"; + private const string JustNowLabel = "just now"; + private const string AgoSuffix = " ago"; + private const string IsoDateFormat = "yyyy-MM-dd"; + + /// + /// Formats the elapsed time between and . + /// "now" becomes "just now", a relative duration ("26m", "3h", "2d") gets an " ago" + /// suffix, and an absolute date is returned as-is. + /// + public static string Format(DateTimeOffset value, DateTimeOffset now) + { + var formatted = MailAges.Format(value, now); + + if (formatted == NowLabel) + { + return JustNowLabel; + } + + return IsAbsoluteDate(formatted) ? formatted : formatted + AgoSuffix; + } + + private static bool IsAbsoluteDate(string formatted) => + DateTime.TryParseExact( + formatted, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out _); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailBody.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailBody.cs deleted file mode 100644 index 74595cf7e35..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailBody.cs +++ /dev/null @@ -1,183 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Tasks; -using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tui.Details; -using ChilliCream.Nitro.CommandLine.Tui.Theming; -using ChilliCream.Nitro.CommandLine.Tui.Widgets; - -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// Composes an 's body lines in Session, Identity, Tasks, and Sent mail -/// order, with a blank separator line between non-empty sections. Identity, Tasks, and Sent mail are -/// omitted for an unbound session. -/// -internal static class AgentDetailBody -{ - private const string EmptyRole = "-"; - - public static IReadOnlyList Build(AgentDetailModel model, DateTimeOffset now, int width) - { - ArgumentNullException.ThrowIfNull(model); - - var sections = new List> - { - SessionSection(model.Participant), - IdentitySection(model.Participant?.Agent), - TasksSection(model.Tasks, width), - SentMailSection(model.SentMail, now, width) - }; - - var lines = new List(); - var separatorPending = false; - - foreach (var section in sections) - { - if (section.Count == 0) - { - continue; - } - - if (separatorPending) - { - lines.Add(new TaskDetailBodyLine(string.Empty, false)); - } - - lines.AddRange(section); - separatorPending = true; - } - - return lines; - } - - private static IReadOnlyList SessionSection(AgentSessionParticipant? participant) - { - if (participant is null) - { - return []; - } - - var session = participant.Session; - var roleStyle = AgentRowBadge.RoleStyle(session.Role).ToMarkup(); - var presenceStyle = AgentRowBadge.PresenceStyle(participant.State).ToMarkup(); - - var body = new List - { - new($"Actor: {session.AgentName ?? AgentParticipantRow.UnboundLabel}", false), - new($"Role: {StyledValue(roleStyle, session.Role.Length == 0 ? EmptyRole : session.Role)}", true), - new($"State: {StyledValue(presenceStyle, participant.State)}", true), - new( - $"Harness: {session.Harness}" - + (session.HarnessVersion.Length > 0 ? $" {session.HarnessVersion}" : ""), - false), - new($"Session id: {session.SessionId}", false), - new($"Host: {session.Host}", false), - new($"Cwd: {session.Cwd}", false), - new($"Workspace: {session.WorkspacePath}", false), - new($"Endpoint: {FormatEndpoint(session)}", false), - new($"Started: {TaskDates.Format(session.StartedAt)}", false), - new($"Last heard: {TaskDates.Format(session.LastBeatAt)}", false) - }; - - return WithStyledHeader("Session", body); - } - - private static string FormatEndpoint(AgentSessionRecord session) - => session.EndpointKind == AgentSessionEndpointKind.None - ? "none" - : $"{session.EndpointKind} {session.EndpointAddr}"; - - private static IReadOnlyList IdentitySection(AgentRecord? agent) - { - if (agent is null) - { - return []; - } - - var roleStyle = AgentRowBadge.RoleStyle(agent.Role).ToMarkup(); - var clientStyle = ThemeTokens.GetStyle("agents.list.client").ToMarkup(); - - var body = new List - { - new($"Name: {agent.Name}", false), - new($"Role: {StyledValue(roleStyle, agent.Role.Length == 0 ? EmptyRole : agent.Role)}", true), - new($"Client: {StyledValue(clientStyle, agent.Client.Length == 0 ? "-" : agent.Client)}", true), - new($"Implicit: {(agent.Implicit ? "yes" : "no")}", false), - new($"Registered: {TaskDates.Format(agent.RegisteredAt)}", false), - new($"Last seen: {TaskDates.Format(agent.LastSeenAt)}", false) - }; - - return WithStyledHeader("Identity", body); - } - - /// - /// Escapes the value and applies the supplied style when non-empty. - /// - private static string StyledValue(string styleMarkup, string value) - { - var text = Markup.Escape(value); - return styleMarkup.Length == 0 ? text : $"[{styleMarkup}]{text}[/]"; - } - - private static IReadOnlyList TasksSection(IReadOnlyList tasks, int width) - { - if (tasks.Count == 0) - { - return []; - } - - var body = tasks - .Select(task => new TaskDetailBodyLine( - TaskBadge.Render(task.Id, task.Title, task.Status, task.Priority, task.Type, selected: false, width), - IsMarkup: true)) - .ToList(); - - return WithStyledHeader("Tasks", body); - } - - private static IReadOnlyList SentMailSection( - IReadOnlyList messages, DateTimeOffset now, int width) - { - if (messages.Count == 0) - { - return []; - } - - var body = messages - .Select(message => new TaskDetailBodyLine( - AgentSentMailRowBadge.Render(message, now, width), - IsMarkup: true)) - .ToList(); - - return WithStyledHeader("Sent mail", body); - } - - /// - /// Prefixes non-empty content with a styled section header and a blank line. - /// Empty content produces no lines. - /// - private static IReadOnlyList WithStyledHeader( - string header, IReadOnlyList body) - { - if (body.Count == 0) - { - return []; - } - - var lines = new List(body.Count + 2) - { - StyledHeader(header), - new TaskDetailBodyLine(string.Empty, false) - }; - - lines.AddRange(body); - return lines; - } - - private static TaskDetailBodyLine StyledHeader(string header) - { - var style = ThemeTokens.GetStyle("detail.section.header").ToMarkup(); - var text = Markup.Escape(header); - var content = style.Length == 0 ? $"[bold]{text}[/]" : $"[{style}]{text}[/]"; - return new TaskDetailBodyLine(content, IsMarkup: true); - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailModel.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailModel.cs deleted file mode 100644 index 70779124edc..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailModel.cs +++ /dev/null @@ -1,105 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Services.Tasks; -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// The selected participant, its bound identity, assigned tasks, and recent sent -/// mail. An unbound session has no tasks or sent mail. -/// -internal sealed class AgentDetailModel -{ - /// - /// The cap on how many sent messages are loaded. - /// - private const int SentMailLimit = 20; - - private readonly ITaskStore _taskStore; - private readonly IMailStore _mailStore; - - public AgentDetailModel(ITaskStore taskStore, IMailStore mailStore) - { - _taskStore = taskStore ?? throw new ArgumentNullException(nameof(taskStore)); - _mailStore = mailStore ?? throw new ArgumentNullException(nameof(mailStore)); - } - - /// - /// The key of the participant last passed to , or - /// null before the first load or after . - /// - public AgentSessionKey? CurrentKey { get; private set; } - - /// - /// The currently loaded participant, or null before the first load or - /// after . - /// - public AgentSessionParticipant? Participant { get; private set; } - - /// - /// Non-terminal tasks assigned to the bound actor, with in-progress tasks first, - /// then open tasks, then other states in store order. Empty for an unbound session. - /// - public IReadOnlyList Tasks { get; private set; } = []; - - /// - /// The loaded participant's bound actor's most recent sent messages, - /// empty for an unbound session, newest first, capped at - /// . - /// - public IReadOnlyList SentMail { get; private set; } = []; - - /// - /// Loads 's session diagnostics, and, when - /// its session is bound to an actor, that actor's assigned tasks and - /// sent mail, replacing whichever participant was previously loaded. - /// - public async Task LoadAsync(AgentSessionParticipant participant, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(participant); - - CurrentKey = AgentSessionKey.From(participant.Session); - Participant = participant; - - if (participant.Session.AgentName is not { } actor) - { - Tasks = []; - SentMail = []; - return; - } - - var tasks = await _taskStore.QueryTasksAsync( - new TaskFilter { Assignee = actor }, - cancellationToken).ConfigureAwait(false); - Tasks = OrderTasks(tasks); - - SentMail = await _mailStore.QuerySentAsync(actor, SentMailLimit, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Resets the model to its unloaded state: no current key, participant, tasks, or sent mail. - /// - public void Clear() - { - CurrentKey = null; - Participant = null; - Tasks = []; - SentMail = []; - } - - /// - /// Stably reorders tasks so in-progress tasks come first, then open, - /// then everything else, preserving the store's own order within each - /// group. - /// - private static IReadOnlyList OrderTasks(IReadOnlyList tasks) - => tasks.OrderBy(StatusRank).ToList(); - - private static int StatusRank(TaskItem task) => task.Status switch - { - TaskStates.InProgress => 0, - TaskStates.Open => 1, - _ => 2 - }; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailView.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailView.cs deleted file mode 100644 index a0f886479dc..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentDetailView.cs +++ /dev/null @@ -1,172 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Tui.Details; -using ChilliCream.Nitro.CommandLine.Tui.Theming; -using ChilliCream.Nitro.CommandLine.Tui.Widgets; -using Spectre.Console.Rendering; - -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// Renders the participant's Session, Identity, Tasks, and Sent mail sections in a -/// scrollable panel and maintains the scroll position. -/// -internal sealed class AgentDetailView -{ - /// - /// Border and padding columns the panel spends on either side of its - /// content. - /// - private const int PanelChromeWidth = 4; - - /// - /// Border rows the panel spends above and below its content; the header - /// is drawn on the top border row. - /// - private const int PanelChromeHeight = 2; - - /// - /// The maximum number of passes used to reserve viewport indicator rows. - /// - private const int MaxIndicatorSettlePasses = 3; - - private const string NoSessionMessage = "No session selected."; - - private readonly AgentDetailModel _model; - private readonly TimeProvider _timeProvider; - private readonly Viewport _bodyViewport = new(0, 0); - - public AgentDetailView(AgentDetailModel model, TimeProvider? timeProvider = null) - { - _model = model ?? throw new ArgumentNullException(nameof(model)); - _timeProvider = timeProvider ?? TimeProvider.System; - } - - /// - /// Scrolls the body down one line. - /// - public void ScrollDown() => _bodyViewport.ScrollBy(1); - - /// - /// Scrolls the body up one line. - /// - public void ScrollUp() => _bodyViewport.ScrollBy(-1); - - /// - /// Scrolls the body to its first line. - /// - public void ScrollToTop() => _bodyViewport.ScrollBy(int.MinValue / 2); - - /// - /// Scrolls the body to its last line. - /// - public void ScrollToBottom() => _bodyViewport.ScrollBy(int.MaxValue / 2); - - /// - /// Renders the loaded participant's sections into the given content - /// area. - /// - public IRenderable Render(int width, int height, bool focused) - { - if (width <= 0 || height <= 0) - { - return new Markup(string.Empty); - } - - var safeWidth = Math.Max(1, width); - var interiorWidth = Math.Max(1, safeWidth - PanelChromeWidth); - var interiorHeight = Math.Max(1, height - PanelChromeHeight); - - var now = _timeProvider.GetUtcNow(); - var lines = AgentDetailBody.Build(_model, now, interiorWidth); - - IRenderable content = lines.Count == 0 - ? Align.Center(new Markup(Markup.Escape(NoSessionMessage)), VerticalAlignment.Middle) - : new Rows(RenderVisibleLines(lines, interiorHeight).Select(Row)); - - var borderToken = focused ? "board.column.border.focused" : "board.column.border"; - - return new Panel(content) - { - Header = new PanelHeader(BuildHeader()), - Border = BoxBorder.Rounded, - BorderStyle = ThemeTokens.GetStyle(borderToken), - Width = safeWidth, - Height = Math.Max(1, height) - }; - } - - private string BuildHeader() - => _model.Participant is { } participant - ? Markup.Escape(participant.Session.AgentName ?? AgentParticipantRow.UnboundLabel) - : "Session detail"; - - /// - /// Slices the body's visible window, reserving rows for "N more above/below" indicators once the - /// lines no longer fit , and pads the result with blank lines to - /// that height. - /// - private IReadOnlyList RenderVisibleLines(IReadOnlyList lines, int interiorHeight) - { - var reservedRows = 0; - - for (var pass = 0; pass < MaxIndicatorSettlePasses; pass++) - { - var windowHeight = Math.Max(0, interiorHeight - reservedRows); - _bodyViewport.Update(lines.Count, windowHeight); - - var needed = (_bodyViewport.HiddenAbove > 0 ? 1 : 0) + (_bodyViewport.HiddenBelow > 0 ? 1 : 0); - - if (needed == reservedRows) - { - break; - } - - reservedRows = needed; - } - - var (start, count) = _bodyViewport.Slice(); - var visible = new List(interiorHeight); - - if (_bodyViewport.HiddenAbove > 0) - { - visible.Add(FormatIndicator(_bodyViewport.HiddenAbove, "above")); - } - - for (var i = start; i < start + count; i++) - { - var line = lines[i]; - visible.Add(line.IsMarkup ? line.Content : Markup.Escape(line.Content)); - } - - if (_bodyViewport.HiddenBelow > 0) - { - visible.Add(FormatIndicator(_bodyViewport.HiddenBelow, "below")); - } - - return PadToHeight(visible, interiorHeight); - } - - /// - /// Wraps one already-escaped display line as markup. A blank line is rendered as a single space. - /// - private static IRenderable Row(string line) => new Markup(line.Length == 0 ? " " : line); - - private static IReadOnlyList PadToHeight(IReadOnlyList lines, int height) - { - if (lines.Count >= height) - { - return lines; - } - - var padded = new List(height); - padded.AddRange(lines); - - while (padded.Count < height) - { - padded.Add(string.Empty); - } - - return padded; - } - - private static string FormatIndicator(int hiddenCount, string direction) => $" {hiddenCount} more {direction}"; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentItemDetailMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentItemDetailMode.cs new file mode 100644 index 00000000000..d3f3cb073ae --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentItemDetailMode.cs @@ -0,0 +1,120 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Tui.Details; +using ChilliCream.Nitro.CommandLine.Tui.Mail; +using ChilliCream.Nitro.CommandLine.Tui.Memory; +using Spectre.Console.Rendering; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// A read-only nested view drilled into from a popover row or its show-more list: a mail +/// thread, a ticket, or a memory entry, loaded once and rendered with the owning tab's own +/// detail renderer. Scrolls one line at a time and exposes the drilled item's id for the +/// popover's copy-id gesture. +/// +internal sealed class AgentItemDetailMode +{ + private readonly Func _render; + private readonly Action _scrollDown; + private readonly Action _scrollUp; + + private AgentItemDetailMode(string copyId, Func render, Action scrollDown, Action scrollUp) + { + CopyId = copyId; + _render = render; + _scrollDown = scrollDown; + _scrollUp = scrollUp; + } + + /// + /// The id the popover's copy-id gesture copies: the thread, task, or memory id. + /// + public string CopyId { get; } + + /// + /// Loads the mail thread with the given id and renders it with the Mail tab's thread + /// renderer, oldest message first. Never marks any message read. + /// + public static AgentItemDetailMode ForThread(IMailStore mailStore, string threadId) + { + ArgumentNullException.ThrowIfNull(mailStore); + ArgumentException.ThrowIfNullOrEmpty(threadId); + + var messages = mailStore.GetThreadMessagesAsync(threadId, CancellationToken.None).GetAwaiter().GetResult(); + var view = new MailDetailView(); + + return new AgentItemDetailMode( + threadId, + (width, height) => view.RenderThread(messages, width, height, focused: true), + view.ScrollDown, + view.ScrollUp); + } + + /// + /// Loads the task with the given id and renders it with the Tasks tab's detail + /// renderer: body, comments, and sidebar. + /// + public static AgentItemDetailMode ForTask(ITaskStore taskStore, string taskId) + { + ArgumentNullException.ThrowIfNull(taskStore); + ArgumentException.ThrowIfNullOrEmpty(taskId); + + var model = new TaskDetailModel(taskStore); + model.LoadAsync(taskId, CancellationToken.None).GetAwaiter().GetResult(); + var view = new TaskDetailView(model); + + return new AgentItemDetailMode( + taskId, + (width, height) => view.Render(width, height, focused: true), + view.ScrollDown, + view.ScrollUp); + } + + /// + /// Loads the curated memory or journal entry with the given id and kind and renders it + /// with the Memory tab's detail renderer. + /// + public static AgentItemDetailMode ForMemory(IMemoryStore memoryStore, MemoryParticipationKind kind, string id) + { + ArgumentNullException.ThrowIfNull(memoryStore); + ArgumentException.ThrowIfNullOrEmpty(id); + + var view = new MemoryDetailView(); + + if (kind == MemoryParticipationKind.Curated) + { + var record = memoryStore.GetRequiredAsync(id, CancellationToken.None).GetAwaiter().GetResult(); + + return new AgentItemDetailMode( + id, + (width, height) => view.RenderCurated(record, width, height, focused: true), + view.ScrollDown, + view.ScrollUp); + } + + var entry = memoryStore.GetRequiredJournalEntryAsync(id, CancellationToken.None).GetAwaiter().GetResult(); + + return new AgentItemDetailMode( + id, + (width, height) => view.RenderJournal(entry, width, height, focused: true), + view.ScrollDown, + view.ScrollUp); + } + + /// + /// Renders the item at the given size. + /// + public IRenderable Render(int width, int height) => _render(width, height); + + /// + /// Scrolls the item's body down one line. + /// + public void ScrollDown() => _scrollDown(); + + /// + /// Scrolls the item's body up one line. + /// + public void ScrollUp() => _scrollUp(); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentParticipantRow.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentParticipantRow.cs deleted file mode 100644 index bb26232216b..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentParticipantRow.cs +++ /dev/null @@ -1,20 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// A live participant and its optional Claude activity. -/// supplies activity only for online Claude Code sessions. -/// -internal sealed record AgentParticipantRow(AgentSessionParticipant Participant, string? Activity) -{ - /// - /// The label shown in place of an actor name for a session with no bound identity. - /// - public const string UnboundLabel = "(unbound)"; - - /// - /// The key selects and diffs this row by. - /// - public AgentSessionKey Key => AgentSessionKey.From(Participant.Session); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverListMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverListMode.cs new file mode 100644 index 00000000000..3b3442afc5f --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverListMode.cs @@ -0,0 +1,172 @@ +using ChilliCream.Nitro.CommandLine.Tui.Widgets; +using Spectre.Console.Rendering; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// A terminal outcome of that the hosting +/// is expected to act on. +/// +internal enum AgentPopoverListAction +{ + /// + /// The key was consumed without a host-level effect. + /// + None, + + /// + /// Escape was pressed; the host should pop back to the summary popover. + /// + Back, + + /// + /// Enter was pressed on a row; the host should open . + /// + OpenSelected +} + +/// +/// The full, unlimited list opened from one of the agent popover's show-more rows: the same +/// row format as the summary section, filling the whole overlay area and scrollable with +/// j/k or the arrows. Escape reports back to to pop back to +/// the summary; Enter reports back to open the selected row's detail. +/// +internal sealed class AgentPopoverListMode +{ + private const int PanelChromeWidth = 4; + private const int PanelChromeHeight = 2; + private const string EmptyMessage = "Nothing here yet."; + + private readonly string _sectionName; + private readonly IReadOnlyList> _rows; + private readonly IReadOnlyList _items; + private readonly TimeProvider _timeProvider; + private readonly Viewport _viewport = new(0, 0); + + private int _selected; + + /// + /// Builds a list for the kind (for example "Mail") from + /// , one formatter per row taking the current time and the content + /// width it should render at, and , the same rows' underlying + /// participation entries in the same order. The panel title shows the kind alongside the + /// total row count. + /// + public AgentPopoverListMode( + string sectionName, + IReadOnlyList> rows, + IReadOnlyList items, + TimeProvider timeProvider, + int selected = 0) + { + ArgumentNullException.ThrowIfNull(sectionName); + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(timeProvider); + + _sectionName = sectionName; + _rows = rows; + _items = items; + _timeProvider = timeProvider; + _selected = rows.Count == 0 ? 0 : Math.Clamp(selected, 0, rows.Count - 1); + } + + /// + /// The index of the currently highlighted row. + /// + public int Selected => _selected; + + /// + /// The participation entry behind the currently highlighted row, or null when the list + /// is empty. + /// + public object? SelectedItem => _selected >= 0 && _selected < _items.Count ? _items[_selected] : null; + + /// + /// Handles one raw key: j/k and the arrows move the highlight, Enter reports opening the + /// highlighted row's detail, and Escape reports popping back to the summary. + /// + public AgentPopoverListAction HandleKey(ConsoleKeyInfo info) + { + switch (info.Key) + { + case ConsoleKey.J: + case ConsoleKey.DownArrow: + if (_rows.Count > 0) + { + _selected = Math.Min(_selected + 1, _rows.Count - 1); + } + + return AgentPopoverListAction.None; + + case ConsoleKey.K: + case ConsoleKey.UpArrow: + if (_rows.Count > 0) + { + _selected = Math.Max(_selected - 1, 0); + } + + return AgentPopoverListAction.None; + + case ConsoleKey.Enter: + return _rows.Count > 0 ? AgentPopoverListAction.OpenSelected : AgentPopoverListAction.None; + + case ConsoleKey.Escape: + return AgentPopoverListAction.Back; + + default: + return AgentPopoverListAction.None; + } + } + + /// + /// Renders the list as a header panel filling the entire given area. + /// + public IRenderable Render(int width, int height) + { + if (width <= 0 || height <= 0) + { + return new Markup(string.Empty); + } + + var contentWidth = Math.Max(0, width - PanelChromeWidth); + var interiorHeight = Math.Max(0, height - PanelChromeHeight); + var now = _timeProvider.GetUtcNow(); + + _viewport.Update(_rows.Count, interiorHeight); + _viewport.EnsureVisible(_selected); + var (start, count) = _viewport.Slice(); + + var lines = new List(Math.Max(interiorHeight, 0)); + + if (_rows.Count == 0) + { + lines.Add(DisplayWidth.Truncate(EmptyMessage, contentWidth)); + } + + for (var i = 0; i < count; i++) + { + var index = start + i; + var line = _rows[index](now, contentWidth); + + lines.Add(index == _selected ? AgentPopoverView.Highlight(line) : line); + } + + while (lines.Count < interiorHeight) + { + lines.Add(string.Empty); + } + + var panel = ColumnPane.Render(_sectionName, _rows.Count, lines, focused: true); + panel.Width = Math.Max(1, width); + panel.Height = Math.Max(1, height); + + return panel; + } + + /// + /// Formats every row's full text as of , used to detect a row age + /// change between ticks without going through a render pass. + /// + internal IEnumerable FormatRows(DateTimeOffset now) => _rows.Select(row => row(now, int.MaxValue)); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverModel.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverModel.cs new file mode 100644 index 00000000000..5475dfcd9f1 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverModel.cs @@ -0,0 +1,520 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tui.Input; +using ChilliCream.Nitro.CommandLine.Tui.Shell; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; +using Spectre.Console.Rendering; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// Which participation section a popover row or show-more row belongs to. +/// +internal enum AgentPopoverSection +{ + Mail, + Tickets, + Memory +} + +/// +/// A tab-specific request payload carried by , interpreted +/// by . +/// +internal abstract record AgentPopoverRequest +{ + private AgentPopoverRequest() + { + } + + /// + /// The delete confirmation should open for the agent named , + /// the same flow the Agents table's d key starts. + /// + public sealed record DeleteRequested(string Name) : AgentPopoverRequest; + + /// + /// The popover's own agent's session id should be copied, the same flow the Agents + /// table's y key starts, regardless of which row the table currently has selected. + /// + public sealed record CopyRequested(string Name, string? SessionId) : AgentPopoverRequest; + + /// + /// A drilled-into item's id should be copied: a mail thread id, a ticket id, or a + /// memory id. + /// + public sealed record CopyItemRequested(string Id) : AgentPopoverRequest; +} + +/// +/// Loads one agent's identity plus its last mail, ticket, and memory participation, and +/// drives the centered detail overlay opened from the Agents tab: cursor navigation across +/// item and show-more rows, a nested full list per section, a nested read-only detail view +/// for any mail thread, ticket, or memory item, and the delete and copy-id gestures the +/// Agents table also exposes. Reloads on and recomputes presence and ages +/// on every , both driven by the hosting shell. +/// +internal sealed class AgentPopoverModel : IPopover +{ + private const int SectionLimit = 10; + private const int PanelChromeWidth = 4; + private const int PanelChromeHeight = 2; + + /// + /// Footer hints while the summary view is active. + /// + public static readonly IReadOnlyList SummaryHints = + [ + new KeyHint("j/k", "move"), + new KeyHint("enter", "open"), + new KeyHint("d", "delete"), + new KeyHint("y", "copy id"), + new KeyHint("esc", "close") + ]; + + /// + /// Footer hints while a show-more list is active. + /// + public static readonly IReadOnlyList ListHints = + [ + new KeyHint("j/k", "move"), + new KeyHint("enter", "open"), + new KeyHint("esc", "back") + ]; + + /// + /// Footer hints while a nested item detail view is active. + /// + public static readonly IReadOnlyList DetailHints = + [ + new KeyHint("j/k", "scroll"), + new KeyHint("y", "copy id"), + new KeyHint("esc", "back") + ]; + + private readonly string _agentName; + private readonly IAgentStore _agentStore; + private readonly IMailStore _mailStore; + private readonly ITaskStore _taskStore; + private readonly IMemoryStore _memoryStore; + private readonly TimeProvider _timeProvider; + + private IReadOnlyList _mail = []; + private IReadOnlyList _tickets = []; + private IReadOnlyList _memory = []; + private string _lastAgeSignature = string.Empty; + private int _cursor; + private AgentPopoverListMode? _listMode; + private AgentPopoverSection? _listSection; + private AgentItemDetailMode? _detailMode; + + public AgentPopoverModel( + string agentName, + IAgentStore agentStore, + IMailStore mailStore, + ITaskStore taskStore, + IMemoryStore memoryStore, + TimeProvider timeProvider) + { + ArgumentException.ThrowIfNullOrEmpty(agentName); + ArgumentNullException.ThrowIfNull(agentStore); + ArgumentNullException.ThrowIfNull(mailStore); + ArgumentNullException.ThrowIfNull(taskStore); + ArgumentNullException.ThrowIfNull(memoryStore); + ArgumentNullException.ThrowIfNull(timeProvider); + + _agentName = agentName; + _agentStore = agentStore; + _mailStore = mailStore; + _taskStore = taskStore; + _memoryStore = memoryStore; + _timeProvider = timeProvider; + } + + /// + /// The agent's current row, or null only when it could not be found at all (the + /// header then shows a not-found message instead of crashing). + /// + public AgentRow? Agent { get; private set; } + + /// + /// The current footer hints: while a nested item detail is + /// open, while a show-more list is open, otherwise + /// . + /// + public IReadOnlyList Hints => _detailMode is not null + ? DetailHints + : _listMode is null ? SummaryHints : ListHints; + + /// + /// Loads (or reloads) the agent row and its last 10 mail, ticket, and memory + /// participation rows, blocking the caller. Keeps the cursor clamped to the reloaded + /// row count. + /// + public void Load(CancellationToken cancellationToken = default) => + LoadAsync(cancellationToken).GetAwaiter().GetResult(); + + private async Task LoadAsync(CancellationToken cancellationToken) + { + var agent = await _agentStore.FindAsync(_agentName, cancellationToken); + + if (agent is not null) + { + Agent = agent; + } + + _mail = await _mailStore.QueryParticipationThreadsAsync(_agentName, SectionLimit, cancellationToken); + _tickets = await _taskStore.QueryParticipationAsync(_agentName, SectionLimit, cancellationToken); + _memory = await _memoryStore.QueryParticipationAsync(_agentName, SectionLimit, cancellationToken); + + _cursor = Math.Clamp(_cursor, 0, Math.Max(0, TotalSelectableRows - 1)); + + // An open show-more list holds its own snapshot of the section it lists, so a reload + // (a DataChangedEvent) rebuilds it too, keeping its selected row. + if (_listMode is { } openList && _listSection is { } section) + { + _listMode = BuildListMode(section, openList.Selected); + } + + _lastAgeSignature = ComputeAgeSignature(_timeProvider.GetUtcNow()); + } + + /// + /// Recomputes the agent's resolved state and formatted ages as of now. Returns + /// whether anything the render depends on changed since the last call. + /// + public bool Tick() + { + var signature = ComputeAgeSignature(_timeProvider.GetUtcNow()); + + if (signature == _lastAgeSignature) + { + return false; + } + + _lastAgeSignature = signature; + return true; + } + + /// + /// Builds a signature from every line currently visible: the show-more list's rows when + /// one is open, otherwise the summary's resolved state plus its rendered lines. + /// + private string ComputeAgeSignature(DateTimeOffset now) + { + if (_listMode is { } listMode) + { + return string.Join('\u0001', listMode.FormatRows(now)); + } + + if (Agent is null) + { + return string.Empty; + } + + var lines = AgentPopoverView.BuildLines(Agent, _mail, _tickets, _memory, now, int.MaxValue, Locate(_cursor)).Lines; + + return AgentStateResolver.Resolve(Agent, now) + '\u0001' + string.Join('\u0001', lines); + } + + private int TotalSelectableRows => _mail.Count + 1 + _tickets.Count + 1 + _memory.Count + 1; + + /// + /// Handles one raw key: while a nested item detail is open, keys scroll it, y reports + /// copying its id, and Escape closes it back to wherever it was opened from; while a + /// show-more list is open (and no detail is), keys route there; otherwise j/k and the + /// arrows move the cursor, Enter opens the selected row's detail or full list, d and y + /// report the same delete and copy gestures the Agents table exposes, and Escape closes + /// the popover. + /// + public PopoverResult? HandleKey(ConsoleKeyInfo info) + { + if (_detailMode is not null) + { + return HandleDetailKey(info); + } + + if (_listMode is { } listMode) + { + HandleListKey(listMode, info); + return null; + } + + switch (info.Key) + { + case ConsoleKey.J: + case ConsoleKey.DownArrow: + MoveCursor(1); + return null; + + case ConsoleKey.K: + case ConsoleKey.UpArrow: + MoveCursor(-1); + return null; + + case ConsoleKey.Enter: + OpenSelectedRow(); + return null; + + case ConsoleKey.D when info.Modifiers == ConsoleModifiers.None: + return new PopoverResult.Request(new AgentPopoverRequest.DeleteRequested(_agentName)); + + case ConsoleKey.Y when info.Modifiers == ConsoleModifiers.None: + return new PopoverResult.Request( + new AgentPopoverRequest.CopyRequested(Agent?.Name ?? _agentName, Agent?.SessionId)); + + case ConsoleKey.Escape: + return new PopoverResult.Closed(); + + default: + return null; + } + } + + /// + /// Routes one raw key to the open nested item detail: j/k and the arrows scroll, y + /// reports copying its id, and Escape closes it back to wherever it was opened from. + /// + private PopoverResult? HandleDetailKey(ConsoleKeyInfo info) + { + switch (info.Key) + { + case ConsoleKey.J: + case ConsoleKey.DownArrow: + _detailMode!.ScrollDown(); + return null; + + case ConsoleKey.K: + case ConsoleKey.UpArrow: + _detailMode!.ScrollUp(); + return null; + + case ConsoleKey.Y when info.Modifiers == ConsoleModifiers.None: + return new PopoverResult.Request(new AgentPopoverRequest.CopyItemRequested(_detailMode!.CopyId)); + + case ConsoleKey.Escape: + _detailMode = null; + return null; + + default: + return null; + } + } + + /// + /// Routes one raw key to the open show-more list: Escape pops back to the summary, and + /// Enter opens the highlighted row's item detail. + /// + private void HandleListKey(AgentPopoverListMode listMode, ConsoleKeyInfo info) + { + switch (listMode.HandleKey(info)) + { + case AgentPopoverListAction.Back: + _listMode = null; + _listSection = null; + break; + + case AgentPopoverListAction.OpenSelected: + _detailMode = BuildDetail(listMode.SelectedItem); + break; + } + } + + private void MoveCursor(int delta) + { + var total = TotalSelectableRows; + + if (total > 0) + { + _cursor = Math.Clamp(_cursor + delta, 0, total - 1); + } + } + + /// + /// Opens the show-more list for the cursor's section when it sits on the show-more row, + /// otherwise opens the cursor's item as a nested detail view. + /// + private void OpenSelectedRow() + { + var location = Locate(_cursor); + + if (location.IsShowMore) + { + _listSection = location.Section; + _listMode = BuildListMode(location.Section, selected: 0); + return; + } + + _detailMode = BuildDetail(ItemAt(location)); + } + + /// + /// The raw participation entry the summary's points at, or + /// null for a show-more row or an out-of-range index. + /// + private object? ItemAt((AgentPopoverSection Section, bool IsShowMore, int ItemIndex) location) + { + if (location.IsShowMore || location.ItemIndex < 0) + { + return null; + } + + return location.Section switch + { + AgentPopoverSection.Mail when location.ItemIndex < _mail.Count => _mail[location.ItemIndex], + AgentPopoverSection.Tickets when location.ItemIndex < _tickets.Count => _tickets[location.ItemIndex], + AgentPopoverSection.Memory when location.ItemIndex < _memory.Count => _memory[location.ItemIndex], + _ => null + }; + } + + /// + /// Builds the nested detail view for one mail, ticket, or memory participation entry, + /// or null when is null or an unrecognized kind. + /// + private AgentItemDetailMode? BuildDetail(object? item) => item switch + { + MailThreadSummary mail => AgentItemDetailMode.ForThread(_mailStore, mail.ThreadId), + TaskItem task => AgentItemDetailMode.ForTask(_taskStore, task.Id), + MemoryParticipationEntry memory => AgentItemDetailMode.ForMemory(_memoryStore, memory.Kind, memory.Id), + _ => null + }; + + private AgentPopoverListMode BuildListMode(AgentPopoverSection section, int selected) => section switch + { + AgentPopoverSection.Mail => BuildMailListMode(selected), + AgentPopoverSection.Tickets => BuildTicketListMode(selected), + _ => BuildMemoryListMode(selected) + }; + + /// + /// Resolves which section and row (or show-more row) points + /// at, given the current item counts. + /// + private (AgentPopoverSection Section, bool IsShowMore, int ItemIndex) Locate(int cursor) + { + var offset = 0; + + foreach (var (section, count) in Sections()) + { + if (cursor < offset + count) + { + return (section, false, cursor - offset); + } + + offset += count; + + if (cursor == offset) + { + return (section, true, -1); + } + + offset += 1; + } + + return (AgentPopoverSection.Memory, true, -1); + } + + private IEnumerable<(AgentPopoverSection Section, int Count)> Sections() + { + yield return (AgentPopoverSection.Mail, _mail.Count); + yield return (AgentPopoverSection.Tickets, _tickets.Count); + yield return (AgentPopoverSection.Memory, _memory.Count); + } + + private AgentPopoverListMode BuildMailListMode(int selected) + { + var items = _mailStore.QueryParticipationThreadsAsync(_agentName, null, CancellationToken.None) + .GetAwaiter().GetResult(); + + var rows = items + .Select(item => (Func)( + (now, width) => AgentPopoverView.FormatMailRow(item, now, width))) + .ToList(); + + return new AgentPopoverListMode("Mail", rows, [.. items.Cast()], _timeProvider, selected); + } + + private AgentPopoverListMode BuildTicketListMode(int selected) + { + var items = _taskStore.QueryParticipationAsync(_agentName, null, CancellationToken.None) + .GetAwaiter().GetResult(); + + var rows = items + .Select(item => (Func)( + (_, width) => AgentPopoverView.FormatTicketRow(item, width))) + .ToList(); + + return new AgentPopoverListMode("Tickets", rows, [.. items.Cast()], _timeProvider, selected); + } + + private AgentPopoverListMode BuildMemoryListMode(int selected) + { + var items = _memoryStore.QueryParticipationAsync(_agentName, null, CancellationToken.None) + .GetAwaiter().GetResult(); + + var rows = items + .Select(item => (Func)( + (now, width) => AgentPopoverView.FormatMemoryRow(item, now, width))) + .ToList(); + + return new AgentPopoverListMode("Memory", rows, [.. items.Cast()], _timeProvider, selected); + } + + /// + /// Renders the nested item detail or the show-more list at full size when one is open, + /// otherwise the centered summary overlay at about 80% of the given area. + /// + public IRenderable Render(int width, int height) + { + if (width <= 0 || height <= 0) + { + return new Markup(string.Empty); + } + + if (_detailMode is { } detailMode) + { + return detailMode.Render(width, height); + } + + if (_listMode is { } listMode) + { + return listMode.Render(width, height); + } + + var panelWidth = Math.Max(1, Math.Min(width, (int)(width * 0.8))); + var panelHeight = Math.Max(1, Math.Min(height, (int)(height * 0.8))); + var contentWidth = Math.Max(0, panelWidth - PanelChromeWidth); + var interiorHeight = Math.Max(0, panelHeight - PanelChromeHeight); + + var now = _timeProvider.GetUtcNow(); + var selected = Locate(_cursor); + var built = AgentPopoverView.BuildLines(Agent, _mail, _tickets, _memory, now, contentWidth, selected); + + var viewport = new Viewport(built.Lines.Count, interiorHeight); + viewport.EnsureVisible(built.SelectedLineIndex); + var (start, count) = viewport.Slice(); + + var visible = new List(interiorHeight); + + for (var i = 0; i < count; i++) + { + visible.Add(built.Lines[start + i]); + } + + while (visible.Count < interiorHeight) + { + visible.Add(string.Empty); + } + + var panel = ColumnPane.RenderWithHeader(Agent?.Name ?? _agentName, visible, focused: true); + panel.Width = panelWidth; + panel.Height = panelHeight; + + return new Align(panel, HorizontalAlignment.Center, VerticalAlignment.Middle) + .Width(width) + .Height(height); + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverView.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverView.cs new file mode 100644 index 00000000000..1a3e872e50c --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentPopoverView.cs @@ -0,0 +1,232 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tui.Mail; +using ChilliCream.Nitro.CommandLine.Tui.Theming; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// The result of : every markup line the popover's +/// summary view shows, and the index of the line matching the current cursor. +/// +internal readonly record struct AgentPopoverBuiltLines(IReadOnlyList Lines, int SelectedLineIndex); + +/// +/// Pure formatting for the agent detail popover: the header block, the Mail, Tickets, and +/// Memory sections, and the row formats a section's show-more list reuses verbatim. +/// +internal static class AgentPopoverView +{ + private const string ShowMoreLabel = "โ€บ show more"; + private const string BubbleGlyph = "โ—"; + + /// + /// A blank spacer row. A single space, not an empty string, so the panel's row renderer + /// keeps it as a line instead of collapsing it away. + /// + private const string BlankLine = " "; + + /// + /// Builds every line of the popover's summary view: a leading blank line, the header + /// block, a blank line, and the Mail, Tickets, and Memory sections in order, each ending + /// in a show-more row and followed by a blank line, except the last section. + /// marks the row that should render highlighted, and its + /// line index is returned so the caller can keep it in view. + /// + public static AgentPopoverBuiltLines BuildLines( + AgentRow? agent, + IReadOnlyList mail, + IReadOnlyList tickets, + IReadOnlyList memory, + DateTimeOffset now, + int width, + (AgentPopoverSection Section, bool IsShowMore, int ItemIndex) selected) + { + var lines = new List(); + + if (agent is null) + { + lines.Add(DisplayWidth.Truncate("Agent not found.", Math.Max(0, width))); + return new AgentPopoverBuiltLines(lines, 0); + } + + lines.Add(BlankLine); + AppendHeader(lines, agent, now); + lines.Add(BlankLine); + + var selectedLineIndex = 0; + + AppendSection( + lines, "Mail (last 10)", AgentPopoverSection.Mail, mail.Count, "No mail yet", + i => FormatMailRow(mail[i], now, width), selected, ref selectedLineIndex); + lines.Add(BlankLine); + + AppendSection( + lines, "Tickets (last 10)", AgentPopoverSection.Tickets, tickets.Count, "No tickets yet", + i => FormatTicketRow(tickets[i], width), selected, ref selectedLineIndex); + lines.Add(BlankLine); + + AppendSection( + lines, "Memory (last 10)", AgentPopoverSection.Memory, memory.Count, "No memory yet", + i => FormatMemoryRow(memory[i], now, width), selected, ref selectedLineIndex); + + return new AgentPopoverBuiltLines(lines, selectedLineIndex); + } + + private static void AppendHeader(List lines, AgentRow agent, DateTimeOffset now) + { + var state = AgentStateResolver.Resolve(agent, now); + var stateStyle = AgentRowBadge.PresenceStyle(state).ToMarkup(); + var stateText = state switch + { + AgentState.Online => "Online", + AgentState.Idle => "Idle", + AgentState.Unreachable => "Unreachable", + _ => "Offline" + }; + + lines.Add(FormatHeaderLine("State", Stylize(stateStyle, $"{BubbleGlyph} {stateText}"))); + lines.Add(FormatHeaderLine("Role", agent.Role.Length == 0 ? "-" : Markup.Escape(agent.Role))); + lines.Add(FormatHeaderLine("Harness", Markup.Escape(FormatHarness(agent)))); + lines.Add(FormatHeaderLine( + "Session id", agent.SessionId is { Length: > 0 } sessionId ? Markup.Escape(sessionId) : "-")); + lines.Add(FormatHeaderLine("Started", Markup.Escape(FormatAge(agent.StartedAt, now)))); + lines.Add(FormatHeaderLine("Last Seen", Markup.Escape(FormatAge(agent.LastSeenAt, now)))); + + if (agent.EndedAt is { } endedAt) + { + lines.Add(FormatHeaderLine("Ended", Markup.Escape(FormatAge(endedAt, now)))); + } + } + + private static string FormatHarness(AgentRow agent) + { + if (agent.Harness is not { Length: > 0 } harness) + { + return "-"; + } + + return agent.HarnessVersion.Length == 0 ? harness : $"{harness} {agent.HarnessVersion}"; + } + + private static string FormatAge(DateTimeOffset value, DateTimeOffset now) => AgentAges.Format(value, now); + + private static string FormatHeaderLine(string label, string valueMarkup) + { + var labelStyle = ThemeTokens.GetStyle("agents.popover.label").ToMarkup(); + return $"{Stylize(labelStyle, Markup.Escape(label) + ":")} {valueMarkup}"; + } + + private static void AppendSection( + List lines, + string title, + AgentPopoverSection section, + int itemCount, + string emptyMessage, + Func formatRow, + (AgentPopoverSection Section, bool IsShowMore, int ItemIndex) selected, + ref int selectedLineIndex) + { + var titleStyle = ThemeTokens.GetStyle("agents.popover.section.title").ToMarkup(); + lines.Add(Stylize(titleStyle, Markup.Escape(title))); + + if (itemCount == 0) + { + var emptyStyle = ThemeTokens.GetStyle("agents.popover.row.empty").ToMarkup(); + lines.Add(Stylize(emptyStyle, Markup.Escape(emptyMessage))); + } + else + { + for (var i = 0; i < itemCount; i++) + { + var line = formatRow(i); + + if (selected is { IsShowMore: false } && selected.Section == section && selected.ItemIndex == i) + { + selectedLineIndex = lines.Count; + line = Highlight(line); + } + + lines.Add(line); + } + } + + var showMoreStyle = ThemeTokens.GetStyle("agents.popover.show-more").ToMarkup(); + var showMoreLine = Stylize(showMoreStyle, ShowMoreLabel); + + if (selected is { IsShowMore: true } && selected.Section == section) + { + selectedLineIndex = lines.Count; + showMoreLine = Highlight(showMoreLine); + } + + lines.Add(showMoreLine); + } + + /// + /// Formats one mail participation row: age, subject, last sender and recipients, and + /// message count, bold when unread for this agent. Truncated to . + /// + public static string FormatMailRow(MailThreadSummary summary, DateTimeOffset now, int width) + { + var age = MailAges.Format(summary.LastMessageAt, now); + var recipients = string.Join(", ", summary.LastRecipients); + var content = + $"{age} {summary.Subject} {summary.LastSender} -> {recipients} ({summary.MessageCount})"; + var escaped = Markup.Escape(DisplayWidth.Truncate(content, Math.Max(0, width))); + + return summary.UnreadCount is > 0 + ? Stylize(ThemeTokens.GetStyle("agents.popover.row.unread").ToMarkup(), escaped) + : escaped; + } + + /// + /// Formats one ticket participation row: id, status, and title, dimmed when closed or + /// archived. Truncated to . + /// + public static string FormatTicketRow(TaskItem task, int width) + { + var content = $"{task.Id} {task.Status} {task.Title}"; + var escaped = Markup.Escape(DisplayWidth.Truncate(content, Math.Max(0, width))); + + return task.Status is TaskStates.Closed or TaskStates.Archived + ? Stylize(ThemeTokens.GetStyle("agents.popover.row.dimmed").ToMarkup(), escaped) + : escaped; + } + + /// + /// Formats one memory participation row: kind, the type for a curated memory, age, and + /// the body's first line. Truncated to . + /// + public static string FormatMemoryRow(MemoryParticipationEntry entry, DateTimeOffset now, int width) + { + var kind = entry.Kind == MemoryParticipationKind.Curated ? "curated" : "journal"; + var typeSuffix = entry.Kind == MemoryParticipationKind.Curated && entry.Type is { Length: > 0 } type + ? $" {type}" + : string.Empty; + var age = MailAges.Format(entry.CreatedAt, now); + var content = $"{kind}{typeSuffix} {age} {FirstLine(entry.Body)}"; + + return Markup.Escape(DisplayWidth.Truncate(content, Math.Max(0, width))); + } + + private static string FirstLine(string body) + { + var index = body.IndexOf('\n'); + var line = index < 0 ? body : body[..index]; + + return line.EndsWith('\r') ? line[..^1] : line; + } + + /// + /// Wraps , which may already carry its own style tags, in the + /// shared selection highlight style. + /// + public static string Highlight(string line) => + Stylize(ThemeTokens.GetStyle("selection.highlight").ToMarkup(), line); + + private static string Stylize(string styleMarkup, string content) => + styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentRowBadge.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentRowBadge.cs index 1417771020a..2f07dc14536 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentRowBadge.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentRowBadge.cs @@ -1,167 +1,255 @@ using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tui.Mail; using ChilliCream.Nitro.CommandLine.Tui.Theming; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; namespace ChilliCream.Nitro.CommandLine.Tui.Agents; /// -/// Renders a participant's actor, presence, harness, role, and session ages with -/// selection and implicit-identity markers. Rows bound to implicit identities -/// use the implicit-identity style. +/// Renders the Agents table's header row and each agent row: a presence bubble and name, +/// role, harness, and age columns. Name and Role are never dropped; narrow widths drop the +/// Started column first, then Harness, then Last Seen, identically for the header and the +/// rows so the two always agree. When even Name and Role no longer fit, Role is truncated +/// first, then Name, with an ellipsis. Built on the shared and +/// table widget. /// internal static class AgentRowBadge { private const string SelectedPrefix = "> "; private const string UnselectedPrefix = " "; - private const string ImplicitMarker = "i"; - private const string ExplicitMarker = " "; private const string EmptyRole = "-"; + private const string BubbleGlyph = "โ—"; + + private const string NameHeader = "NAME"; + private const string RoleHeader = "ROLE"; + private const string HarnessHeader = "HARNESS"; + private const string StartedHeader = "STARTED"; + private const string LastSeenHeader = "LAST SEEN"; + + private const int MinNameWidth = 12; + private const int MinRoleWidth = 12; + private const int MinHarnessWidth = 12; + private const int MinStartedWidth = 10; + private const int MinLastSeenWidth = 10; + + // Started drops first, then Harness, then Last Seen; Name and Role have no drop priority + // so they are never dropped. This is the display order the columns render in. + private static readonly IReadOnlyList s_columns = + [ + new TableColumnSpec(NameHeader, MinNameWidth), + new TableColumnSpec(RoleHeader, MinRoleWidth), + new TableColumnSpec(HarnessHeader, MinHarnessWidth, DropPriority: 1), + new TableColumnSpec(StartedHeader, MinStartedWidth, DropPriority: 0), + new TableColumnSpec(LastSeenHeader, MinLastSeenWidth, DropPriority: 2) + ]; + + // Same columns, with Role ordered before Name, used only to plan widths: TableLayout.Plan + // truncates the first never-dropped column that is still visible once every droppable + // column is gone, so putting Role first here makes Role truncate before Name while the + // rendered column order above stays Name, then Role. + private static readonly IReadOnlyList s_widthPlanColumns = + [ + new TableColumnSpec(RoleHeader, MinRoleWidth), + new TableColumnSpec(NameHeader, MinNameWidth), + new TableColumnSpec(HarnessHeader, MinHarnessWidth, DropPriority: 1), + new TableColumnSpec(StartedHeader, MinStartedWidth, DropPriority: 0), + new TableColumnSpec(LastSeenHeader, MinLastSeenWidth, DropPriority: 2) + ]; /// - /// The column widths a set of rows agree on: each column padded to the - /// widest value among those rows. + /// The column widths a set of rows agree on: each column padded to at least its minimum + /// width, and wider still when its header title or a row's value needs more room. /// - public readonly record struct Widths( - int Actor, int Presence, int Harness, int Role, int StartedAge, int LastHeardAge); + public readonly record struct Widths(int Name, int Role, int Harness, int Started, int LastSeen); /// - /// Computes across . + /// Computes across , with each column no + /// narrower than its minimum width or its header title. /// - public static Widths ComputeWidths(IReadOnlyList rows, DateTimeOffset now) + public static Widths ComputeWidths(IReadOnlyList rows, DateTimeOffset now) { - var actorWidth = 0; - var presenceWidth = 0; - var harnessWidth = 0; - var roleWidth = 0; - var startedWidth = 0; - var lastHeardWidth = 0; + var rowValues = new List>(rows.Count); foreach (var row in rows) { - var session = row.Participant.Session; - actorWidth = Math.Max(actorWidth, DisplayWidth.Measure(ActorText(session))); - presenceWidth = Math.Max(presenceWidth, DisplayWidth.Measure(PresenceText(row))); - harnessWidth = Math.Max(harnessWidth, DisplayWidth.Measure(session.Harness)); - roleWidth = Math.Max(roleWidth, DisplayWidth.Measure(RoleText(session))); - startedWidth = Math.Max(startedWidth, DisplayWidth.Measure(MailAges.Format(session.StartedAt, now))); - lastHeardWidth = Math.Max(lastHeardWidth, DisplayWidth.Measure(MailAges.Format(session.LastBeatAt, now))); + rowValues.Add( + [ + row.Name, + RoleText(row), + AgentHarnessDisplay.Name(row.Harness), + FormatAge(row.StartedAt, now), + FormatAge(row.LastSeenAt, now) + ]); } - return new Widths(actorWidth, presenceWidth, harnessWidth, roleWidth, startedWidth, lastHeardWidth); + var widths = TableLayout.ComputeWidths(s_columns, rowValues); + return new Widths(widths[0], widths[1], widths[2], widths[3], widths[4]); } /// - /// Builds the markup line for one participant row, padding actor/presence/role/ages to - /// and truncating the role with an ellipsis so the line fits within - /// display columns. A of 0 or less produces - /// an empty line. + /// Builds the markup line for one agent row. Columns are padded to . + /// When the full set of columns does not fit within display + /// columns, Started is dropped first, then Harness, then Last Seen; Name and Role always + /// remain, with Role truncated first and then Name as a last resort. A + /// of 0 or less produces an empty line. /// public static string Render( - AgentParticipantRow row, DateTimeOffset now, bool selected, int maxWidth, Widths widths) + AgentRow row, DateTimeOffset now, bool selected, int maxWidth, Widths widths) { if (maxWidth <= 0) { return string.Empty; } - var session = row.Participant.Session; var prefix = selected ? SelectedPrefix : UnselectedPrefix; - var isImplicit = row.Participant.Agent?.Implicit ?? false; - var marker = isImplicit ? ImplicitMarker : ExplicitMarker; - var actor = DisplayWidth.PadRight(ActorText(session), widths.Actor); - var presenceBadge = DisplayWidth.PadRight(PresenceText(row), widths.Presence); - var harness = DisplayWidth.PadRight(session.Harness, widths.Harness); - var startedAge = DisplayWidth.PadRight(MailAges.Format(session.StartedAt, now), widths.StartedAge); - var lastHeardAge = DisplayWidth.PadRight(MailAges.Format(session.LastBeatAt, now), widths.LastHeardAge); - - // Terminal-cell width of everything but the role, including its following separator. - var fixedPlainWidth = DisplayWidth.Measure(prefix) + DisplayWidth.Measure(marker) + 1 - + DisplayWidth.Measure(actor) + 1 - + DisplayWidth.Measure(presenceBadge) + 1 - + DisplayWidth.Measure(harness) + 1 - + DisplayWidth.Measure("started ") + DisplayWidth.Measure(startedAge) + 1 - + DisplayWidth.Measure("heard ") + DisplayWidth.Measure(lastHeardAge) + 1; - - var roleText = DisplayWidth.PadRight(RoleText(session), widths.Role); - var roleBudget = Math.Max(0, maxWidth - fixedPlainWidth); - var truncatedRole = DisplayWidth.Truncate(roleText, roleBudget); - var actorStyle = ThemeTokens.GetStyle("agents.list.name").ToMarkup(); - var presenceStyle = PresenceStyle(row.Participant.State).ToMarkup(); + var state = AgentStateResolver.Resolve(row, now); + var bubbleStyle = PresenceStyle(state).ToMarkup(); + var nameStyle = ThemeTokens.GetStyle("agents.list.name").ToMarkup(); + var roleStyle = RoleStyle(row.Role).ToMarkup(); var harnessStyle = ThemeTokens.GetStyle("agents.list.harness").ToMarkup(); - var roleStyle = RoleStyle(session.Role).ToMarkup(); var ageStyle = ThemeTokens.GetStyle("agents.list.age").ToMarkup(); - var line = fixedPlainWidth > maxWidth - ? RenderNarrow( - prefix, - marker, - maxWidth, - actor, - actorStyle, - presenceBadge, - presenceStyle, - harness, - harnessStyle, - $"started {startedAge}", - ageStyle, - $"heard {lastHeardAge}", - ageStyle) - : $"{Markup.Escape(prefix)}{Markup.Escape(marker)} " - + $"{Stylize(actorStyle, Markup.Escape(actor))} " - + $"{Stylize(presenceStyle, Markup.Escape(presenceBadge))} " - + $"{Stylize(harnessStyle, Markup.Escape(harness))} " - + $"{Stylize(roleStyle, Markup.Escape(truncatedRole))} " - + $"{Stylize(ageStyle, $"started {Markup.Escape(startedAge)}")} " - + $"{Stylize(ageStyle, $"heard {Markup.Escape(lastHeardAge)}")}"; - - if (isImplicit) + var cells = new TableCellSpec[] { - var implicitStyle = ThemeTokens.GetStyle("agents.list.implicit").ToMarkup(); - line = Stylize(implicitStyle, line); - } + new(row.Name, nameStyle), + new(RoleText(row), roleStyle), + new(AgentHarnessDisplay.Name(row.Harness), harnessStyle), + new(FormatAge(row.StartedAt, now), ageStyle), + new(FormatAge(row.LastSeenAt, now), ageStyle) + }; + + var budget = maxWidth - PrefixWidth(prefix); + var layout = PlanLayout(budget, widths); + var line = TableRenderer.RenderRow( + prefix, new TableCellSpec(BubbleGlyph, bubbleStyle), cells, s_columns, layout); if (selected) { var highlightStyle = ThemeTokens.GetStyle("selection.highlight").ToMarkup(); - line = Stylize(highlightStyle, line); + line = TableRenderer.Stylize(highlightStyle, line); } return line; } - private static string ActorText(AgentSessionRecord session) - => session.AgentName is { Length: > 0 } actor ? actor : AgentParticipantRow.UnboundLabel; + /// + /// Builds the header title line shown above the rows: NAME, ROLE, HARNESS, STARTED, LAST + /// SEEN, aligned to with the cursor and bubble cells left blank. + /// Columns are dropped using the same thresholds as , so the header + /// always agrees with the rows below it. A of 0 or less + /// produces an empty line. + /// + public static string RenderHeader(int maxWidth, Widths widths) + { + if (maxWidth <= 0) + { + return string.Empty; + } + + var headerStyle = ThemeTokens.GetStyle("agents.list.header").ToMarkup(); + var blankBubble = new string(' ', DisplayWidth.Measure(BubbleGlyph)); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var layout = PlanLayout(budget, widths); + + return TableRenderer.RenderRow( + UnselectedPrefix, new TableCellSpec(blankBubble), BuildHeaderCells(headerStyle), s_columns, layout); + } + + /// + /// Builds the dashed rule line under the header, filling + /// display columns. A of 0 or less produces an empty line. + /// + public static string RenderRule(int maxWidth) + { + var ruleStyle = ThemeTokens.GetStyle("agents.list.age").ToMarkup(); + return TableRenderer.RenderRule(maxWidth, ruleStyle); + } /// - /// The presence badge text: a single glyph for the state, plus the Claude activity read-through's - /// first letter in parentheses when known. + /// Appends the Agents table's fixed top block to : a blank line, the + /// header row and the rule, keeping only the first of the + /// three. A of 0 or less appends nothing. /// - private static string PresenceText(AgentParticipantRow row) + public static void AddHeaderLines(List lines, int headerLineCount, int maxWidth, Widths widths) { - var glyph = PresenceGlyph(row.Participant.State); + if (maxWidth <= 0) + { + return; + } - return row.Activity is { Length: > 0 } activity - ? $"{glyph}({char.ToLowerInvariant(activity[0])})" - : glyph; + var headerStyle = ThemeTokens.GetStyle("agents.list.header").ToMarkup(); + var ruleStyle = ThemeTokens.GetStyle("agents.list.age").ToMarkup(); + var blankBubble = new string(' ', DisplayWidth.Measure(BubbleGlyph)); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var layout = PlanLayout(budget, widths); + + TableRenderer.RenderTopBlock( + lines, + headerLineCount, + maxWidth, + UnselectedPrefix, + new TableCellSpec(blankBubble), + s_columns, + layout, + headerStyle, + ruleStyle); } - private static string PresenceGlyph(string state) => state switch + private static TableCellSpec[] BuildHeaderCells(string headerStyle) => + [ + new(NameHeader, headerStyle), + new(RoleHeader, headerStyle), + new(HarnessHeader, headerStyle), + new(StartedHeader, headerStyle), + new(LastSeenHeader, headerStyle) + ]; + + private static int PrefixWidth(string prefix) => + DisplayWidth.Measure(prefix) + DisplayWidth.Measure(BubbleGlyph) + 1; + + /// + /// Plans column visibility and widths for display columns, in the + /// display order Name, Role, Harness, Started, Last Seen. + /// + private static IReadOnlyList PlanLayout(int budget, Widths widths) { - AgentSessionState.Online => "โ—", - AgentSessionState.Unreachable => "โ—", - AgentSessionState.Unobservable => "โ—Œ", - AgentSessionState.Remote => "โ—‡", - _ => "โ—‹" // Any unrecognized state. - }; + IReadOnlyList planWidths = [widths.Role, widths.Name, widths.Harness, widths.Started, widths.LastSeen]; + var planLayout = TableLayout.Plan(budget, s_widthPlanColumns, planWidths).ToArray(); + var role = planLayout[0]; + var name = planLayout[1]; + + // TableLayout.Plan only truncates the first still-visible column once every droppable + // column is gone, which is Role here. When Role alone does not free enough room, also + // shrink Name to what is left so the row still fits within budget. + if (role.Visible && name.Visible) + { + var used = role.Width + name.Width + DisplayWidth.Measure(TableLayout.Gutter); + + if (used > budget) + { + var nameWidth = Math.Max(0, budget - role.Width - DisplayWidth.Measure(TableLayout.Gutter)); + planLayout[1] = new ColumnLayout(true, nameWidth); + } + } + + return [planLayout[1], planLayout[0], planLayout[2], planLayout[3], planLayout[4]]; + } /// - /// Resolves the theme style for a presence state: a dedicated + /// Resolves the theme style for an agent's presence state: a dedicated /// agents.list.presence.<state> token, falling back to the /// base agents.list.presence token. /// - public static Style PresenceStyle(string state) + public static Style PresenceStyle(AgentState state) { - var perState = ThemeTokens.GetStyle($"agents.list.presence.{state}"); + var token = state switch + { + AgentState.Online => "agents.list.presence.online", + AgentState.Idle => "agents.list.presence.idle", + AgentState.Unreachable => "agents.list.presence.unreachable", + _ => "agents.list.presence.offline" + }; + + var perState = ThemeTokens.GetStyle(token); return perState != Style.Plain ? perState : ThemeTokens.GetStyle("agents.list.presence"); } @@ -185,64 +273,7 @@ public static Style RoleStyle(string role) return ThemeTokens.GetStyle("agents.list.role"); } - private static string RoleText(AgentSessionRecord session) => session.Role.Length == 0 ? EmptyRole : session.Role; - - private static string RenderNarrow( - string prefix, - string marker, - int maxWidth, - string actor, - string actorStyle, - string presence, - string presenceStyle, - string harness, - string harnessStyle, - string startedAge, - string ageStyle, - string lastHeardAge, - string lastHeardAgeStyle) - { - var prefixText = DisplayWidth.Slice($"{prefix}{marker} ", maxWidth); - var line = Markup.Escape(prefixText); - var remaining = maxWidth - DisplayWidth.Measure(prefixText); - var hasColumn = false; - - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, actor, actorStyle); - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, presence, presenceStyle); - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, harness, harnessStyle); - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, startedAge, ageStyle); - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, lastHeardAge, lastHeardAgeStyle); - - return line; - } - - private static void AppendNarrowColumn( - ref string line, - ref int remaining, - ref bool hasColumn, - string value, - string styleMarkup) - { - var separatorWidth = hasColumn ? 1 : 0; - var valueBudget = remaining - separatorWidth; - - if (valueBudget <= 0) - { - return; - } - - var truncatedValue = DisplayWidth.Truncate(value, valueBudget); - - if (truncatedValue.Length == 0) - { - return; - } - - line += (hasColumn ? " " : string.Empty) + Stylize(styleMarkup, Markup.Escape(truncatedValue)); - remaining -= separatorWidth + DisplayWidth.Measure(truncatedValue); - hasColumn = true; - } + private static string RoleText(AgentRow row) => row.Role.Length == 0 ? EmptyRole : row.Role; - private static string Stylize(string styleMarkup, string content) => - styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; + private static string FormatAge(DateTimeOffset value, DateTimeOffset now) => AgentAges.Format(value, now); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSearchForm.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSearchForm.cs new file mode 100644 index 00000000000..c4579f1d1a9 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSearchForm.cs @@ -0,0 +1,53 @@ +using ChilliCream.Nitro.CommandLine.Tui.Input; +using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; +using Spectre.Console.Rendering; +using Form = ChilliCream.Nitro.CommandLine.Tui.Widgets.Form.Form; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// The Agents tab's search box: one text field pre-filled with +/// , applied as a case-insensitive name filter. +/// +internal sealed class AgentSearchForm +{ + public const string TextFieldId = "text"; + public const string ApplyButtonId = "apply"; + public const string CancelButtonId = "cancel"; + + /// + /// The footer hints displayed while the search form captures input. + /// + public static readonly IReadOnlyList Hints = + [ + new KeyHint("ctrl+s", "search"), + new KeyHint("esc", "cancel") + ]; + + private readonly Form _form; + private readonly TextField _textField; + + public AgentSearchForm(string initialText) + { + ArgumentNullException.ThrowIfNull(initialText); + + _textField = new TextField(TextFieldId, "Search by name", initialValue: initialText); + + var buttons = new FormButtons( + [ + new FormButtonSpec(ApplyButtonId, "Search", ButtonKind.Primary), + new FormButtonSpec(CancelButtonId, "Cancel", ButtonKind.Secondary) + ]); + + _form = new Form("Search agents", [_textField], buttons); + } + + /// + /// The field's current text. + /// + public string Text => _textField.GetValue() is FormValue.Text { Value: var value } ? value : ""; + + public FormResult? HandleKey(ConsoleKeyInfo info) => _form.HandleKey(info); + + public IRenderable Render(int width, int height) => _form.Render(width, height); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSentMailRowBadge.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSentMailRowBadge.cs deleted file mode 100644 index 5cb9e77e346..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSentMailRowBadge.cs +++ /dev/null @@ -1,59 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Mail; - -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// Renders one sent-message row for the agent detail view's sent mail section as a single Spectre -/// markup line: age, subject, and recipients. Carries no selection prefix or unread marker. -/// -internal static class AgentSentMailRowBadge -{ - private const string NoRecipients = "-"; - private const string Arrow = "-> "; - private const string Ellipsis = "โ€ฆ"; - - /// - /// The maximum character budget for the recipients column. - /// - private const int MaxRecipientsBudget = 24; - - /// - /// Builds the markup line for one sent-message row, truncating the - /// subject and recipients with an ellipsis so the whole line fits within - /// display columns. A - /// of 0 or less produces an empty line. - /// - public static string Render(MailMessage message, DateTimeOffset now, int maxWidth) - { - if (maxWidth <= 0) - { - return string.Empty; - } - - var age = MailAges.Format(message.CreatedAt, now); - var recipients = string.Join(", ", message.Recipients.OrderBy(r => r.Ordinal).Select(r => r.Name)); - var recipientsText = recipients.Length == 0 ? NoRecipients : recipients; - - // Terminal-cell width of everything but the subject and recipients. - var fixedPlainWidth = DisplayWidth.Measure(age) + 2 + DisplayWidth.Measure(Arrow); - var remaining = Math.Max(0, maxWidth - fixedPlainWidth); - var recipientsBudget = Math.Min(MaxRecipientsBudget, (remaining + 1) / 2); - var truncatedRecipients = DisplayWidth.Truncate(recipientsText, recipientsBudget); - - var subjectBudget = Math.Max(0, remaining - DisplayWidth.Measure(truncatedRecipients)); - var truncatedSubject = DisplayWidth.Truncate(message.Subject, subjectBudget); - - return fixedPlainWidth > maxWidth - ? RenderNarrow(age, maxWidth) - : $"{Markup.Escape(age)} {Markup.Escape(truncatedSubject)} {Arrow}{Markup.Escape(truncatedRecipients)}"; - } - - private static string RenderNarrow(string age, int maxWidth) - { - var remaining = maxWidth - DisplayWidth.Measure(Ellipsis); - var prefix = DisplayWidth.Slice($"{age} {Arrow}", remaining); - - return Markup.Escape(prefix) + Ellipsis; - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSessionKey.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSessionKey.cs deleted file mode 100644 index 0cbd57fbf54..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentSessionKey.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// The harness and session id identifying a participant across list refreshes. -/// -internal readonly record struct AgentSessionKey(string Harness, string SessionId) -{ - public static AgentSessionKey From(AgentSessionRecord session) => new(session.Harness, session.SessionId); -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsFocus.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsFocus.cs deleted file mode 100644 index 025ae63ab51..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsFocus.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Agents; - -/// -/// Which pane of the agents tab currently holds focus. -/// -internal enum AgentsFocus -{ - List, - Detail -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsKeyMap.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsKeyMap.cs new file mode 100644 index 00000000000..e3246abbd45 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsKeyMap.cs @@ -0,0 +1,71 @@ +using ChilliCream.Nitro.CommandLine.Tui.Input; +using CursorDirection = ChilliCream.Nitro.CommandLine.Tui.Input.CursorDirection; + +namespace ChilliCream.Nitro.CommandLine.Tui.Agents; + +/// +/// Builds the Agents tab's key bindings for navigation, delete actions, search, and +/// exit requests. Bound only to this tab, not the global key table. +/// +internal static class AgentsKeyMap +{ + /// + /// Builds the default bindings. is read when d is + /// pressed, so the delete message always names the row selected at that moment. + /// + public static KeyMap CreateDefault(Func selectedName) => new( + [ + new KeyBinding( + new KeyChord(ConsoleKey.J, ConsoleModifiers.None, 'j'), + () => new TuiMessage.MoveCursor(CursorDirection.Down), + new KeyHint("hjkl", "move")), + new KeyBinding( + new KeyChord(ConsoleKey.DownArrow, ConsoleModifiers.None, '\0'), + () => new TuiMessage.MoveCursor(CursorDirection.Down)), + new KeyBinding( + new KeyChord(ConsoleKey.K, ConsoleModifiers.None, 'k'), + () => new TuiMessage.MoveCursor(CursorDirection.Up)), + new KeyBinding( + new KeyChord(ConsoleKey.UpArrow, ConsoleModifiers.None, '\0'), + () => new TuiMessage.MoveCursor(CursorDirection.Up)), + new KeyBinding( + new KeyChord(ConsoleKey.G, ConsoleModifiers.None, 'g'), + () => new TuiMessage.MoveToEdge(EdgeTarget.Top)), + new KeyBinding( + new KeyChord(ConsoleKey.G, ConsoleModifiers.Shift, 'G'), + () => new TuiMessage.MoveToEdge(EdgeTarget.Bottom)), + new KeyBinding( + new KeyChord(ConsoleKey.Enter, ConsoleModifiers.None, '\r'), + () => new TuiMessage.OpenSelected(), + new KeyHint("enter", "open")), + new KeyBinding( + new KeyChord(ConsoleKey.D, ConsoleModifiers.None, 'd'), + () => new TuiMessage.DeleteAgentRequested(selectedName() ?? string.Empty), + new KeyHint("d", "delete")), + new KeyBinding( + new KeyChord(ConsoleKey.D, ConsoleModifiers.Shift, 'D'), + () => new TuiMessage.DeleteOfflineAgentsRequested(), + new KeyHint("D", "delete offline")), + new KeyBinding( + new KeyChord(ConsoleKey.Y, ConsoleModifiers.None, 'y'), + () => new TuiMessage.CopySelectedId(), + new KeyHint("y", "copy id")), + new KeyBinding( + new KeyChord(ConsoleKey.R, ConsoleModifiers.None, 'r'), + () => new TuiMessage.RefreshRequested(), + new KeyHint("r", "refresh")), + new KeyBinding( + new KeyChord(ConsoleKey.Oem2, ConsoleModifiers.None, '/'), + () => new TuiMessage.SearchRequested(), + new KeyHint("/", "search")), + new KeyBinding( + new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, '\u0003'), + () => new TuiMessage.QuitRequested()), + new KeyBinding( + new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, '\u001b'), + () => new TuiMessage.Back()), + new KeyBinding( + new KeyChord(ConsoleKey.Q, ConsoleModifiers.None, 'q'), + () => new TuiMessage.QuitRequested()) + ]); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsMode.cs index 756d402a80d..7a723ba3a6b 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsMode.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsMode.cs @@ -1,76 +1,89 @@ using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Memory; using ChilliCream.Nitro.CommandLine.Services.Tasks; using ChilliCream.Nitro.CommandLine.Services.Workspace; using ChilliCream.Nitro.CommandLine.Tui.Input; using ChilliCream.Nitro.CommandLine.Tui.Shell; using ChilliCream.Nitro.CommandLine.Tui.Widgets; +using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; using Spectre.Console.Rendering; using CursorDirection = ChilliCream.Nitro.CommandLine.Tui.Input.CursorDirection; namespace ChilliCream.Nitro.CommandLine.Tui.Agents; /// -/// Displays live participants beside the selected participant's details. -/// Enter focuses the detail pane; horizontal navigation toggles pane focus, and -/// vertical navigation moves the list selection or scrolls the focused detail pane. +/// Displays every non-deleted agent as one full-width table: a presence bubble and name, +/// role, harness, and started/last-seen ages. State and ages are recomputed from +/// on every render, so bubbles and ages change without +/// a database event. Delete and delete-inactive are requested here but confirmed and applied +/// by the hosting shell. /// -internal sealed class AgentsMode : ITuiMode +internal sealed class AgentsMode : ITuiMode, IRawKeyCapturingMode { - /// - /// Border and padding columns the list pane's panel spends on either - /// side of its content. - /// private const int PanelChromeWidth = 4; - - /// - /// Border rows the list pane's panel spends above and below its - /// content; the header is drawn on the top border row. - /// private const int PanelChromeHeight = 2; - - /// - /// The maximum number of passes used to reserve viewport indicator rows. - /// private const int MaxIndicatorSettlePasses = 3; + private const int HeaderLineCount = TableRenderer.TopBlockLineCount; - /// - /// The fraction of the frame width the list pane occupies; the detail pane takes the remainder. - /// - private const int ListWidthNumerator = 1; - private const int ListWidthDenominator = 2; + private const string EmptyStateMessage = + "No agents yet. Start a harness with Nitro hooks installed, or run nitro agent login."; + private readonly IAgentStore _agentStore; private readonly TimeProvider _timeProvider; private readonly AgentsState _state; - private readonly AgentDetailModel _detailModel; - private readonly AgentDetailView _detailView; private readonly Viewport _listViewport = new(0, 0); + private AgentSearchForm? _searchForm; + private readonly IMailStore _mailStore; + private readonly ITaskStore _taskStore; + private readonly IMemoryStore _memoryStore; + public AgentsMode( - ITaskStore taskStore, + IAgentStore agentStore, IMailStore mailStore, - IAgentSessionRegistry sessionRegistry, - IClaudeSessionActivityReader activityReader, + ITaskStore taskStore, + IMemoryStore memoryStore, TimeProvider? timeProvider = null) { - ArgumentNullException.ThrowIfNull(taskStore); + ArgumentNullException.ThrowIfNull(agentStore); ArgumentNullException.ThrowIfNull(mailStore); - ArgumentNullException.ThrowIfNull(sessionRegistry); - ArgumentNullException.ThrowIfNull(activityReader); + ArgumentNullException.ThrowIfNull(taskStore); + ArgumentNullException.ThrowIfNull(memoryStore); + _agentStore = agentStore; + _mailStore = mailStore; + _taskStore = taskStore; + _memoryStore = memoryStore; _timeProvider = timeProvider ?? TimeProvider.System; - _state = new AgentsState(sessionRegistry, activityReader); - _detailModel = new AgentDetailModel(taskStore, mailStore); - _detailView = new AgentDetailView(_detailModel, _timeProvider); + _state = new AgentsState(agentStore, _timeProvider); + KeyMap = AgentsKeyMap.CreateDefault(() => _state.SelectedAgent?.Name); } /// - /// The mode's current live state: the loaded participants, selection, - /// and pane focus. + /// The mode's current live state: the loaded rows, search filter, and selection. /// public AgentsState State => _state; /// - public KeyMap? KeyMap => null; + public KeyMap? KeyMap { get; } + + /// + public bool IsInputCapturing => _searchForm is not null; + + /// + public IReadOnlyList CapturingHints => _searchForm is not null ? AgentSearchForm.Hints : []; + + /// + /// The Agents tab hosts its own d/D/search bindings and hides the global tab's + /// unrelated zoom, edit, back, and quit hints so its footer lists only its own keys. + /// + public IReadOnlyCollection SuppressedGlobalHints { get; } = + [ + new KeyHint("z", "zoom"), + new KeyHint("e", "edit"), + new KeyHint("esc", "back"), + new KeyHint("q", "quit") + ]; /// public void OnEnter() => RefreshBlocking(); @@ -81,151 +94,223 @@ public void OnResize(int width, int height) // Layout and viewport state are recomputed from Render's parameters every frame. } + /// + /// Counts the agents currently resolving to or + /// , for the shell's delete-inactive confirmation. + /// + public int CountInactiveAgents() => _state.CountInactive(_timeProvider.GetUtcNow()); + + /// + /// Recomputes state and ages as of now, re-sorting when they changed and preserving the + /// selected agent by name. Returns whether anything the render depends on changed since + /// the last tick or render. + /// + public bool Tick() => _state.Resettle(_timeProvider.GetUtcNow()); + /// public IReadOnlyList Handle(TuiMessage message) => message switch { - TuiMessage.MoveCursor(CursorDirection.Up) => MoveOrScroll(-1), - TuiMessage.MoveCursor(CursorDirection.Down) => MoveOrScroll(1), - TuiMessage.MoveCursor(CursorDirection.Left) => TogglePane(), - TuiMessage.MoveCursor(CursorDirection.Right) => TogglePane(), - TuiMessage.MoveToEdge(var edge) => MoveOrScrollToEdge(edge), - TuiMessage.OpenSelected => FocusDetail(), + TuiMessage.MoveCursor(CursorDirection.Up) => Move(-1), + TuiMessage.MoveCursor(CursorDirection.Down) => Move(1), + TuiMessage.MoveToEdge(var edge) => MoveToEdge(edge), + // Reached only when TryCreatePopover found no selected agent to open: the shell falls + // back to dispatching OpenSelected here for the no-selection toast. + TuiMessage.OpenSelected => OpenSelectedFallback(), TuiMessage.RefreshRequested => Refresh(), TuiMessage.CopySelectedId => CopySelectedId(), + TuiMessage.SearchRequested => OpenSearchForm(), _ => [] }; /// - public IRenderable Render(int width, int height) + public IPopover? TryCreatePopover() { - if (width <= 0 || height <= 0) + if (_state.SelectedAgent is not { } agent) { - return new Markup(string.Empty); + return null; } - var listWidth = Math.Max(1, width * ListWidthNumerator / ListWidthDenominator); - var detailWidth = Math.Max(1, width - listWidth); - - return new Layout("agents").SplitColumns( - new Layout("list", RenderListPane(listWidth, height)).Size(listWidth), - new Layout("detail", RenderDetailPane(detailWidth, height))); + return new AgentPopoverModel(agent.Name, _agentStore, _mailStore, _taskStore, _memoryStore, _timeProvider); } + /// + public IReadOnlyList HandlePopoverRequest(PopoverResult.Request request) => request.Payload switch + { + AgentPopoverRequest.DeleteRequested deleteRequested => + [new TuiMessage.DeleteAgentRequested(deleteRequested.Name)], + AgentPopoverRequest.CopyRequested copyRequested => + [BuildCopyIdToast(copyRequested.Name, copyRequested.SessionId)], + AgentPopoverRequest.CopyItemRequested copyItemRequested => + [new TuiMessage.ShowToast(copyItemRequested.Id, ToastStyle.Info)], + _ => [] + }; + /// - /// Up/Down moves the list selection (and reloads the detail pane for - /// the newly selected participant) while the list has focus, or scrolls - /// the detail body while the detail pane has focus. + /// Handles one raw key while is true, routed here by + /// the host instead of through the semantic dispatch. /// - private IReadOnlyList MoveOrScroll(int delta) + public IReadOnlyList HandleRawKey(ConsoleKeyInfo info) + => _searchForm is not null ? HandleSearchFormKey(info) : []; + + /// + public IRenderable Render(int width, int height) { - if (_state.Focus == AgentsFocus.List) + if (width <= 0 || height <= 0) { - if (_state.Rows.Count > 0) - { - _state.SelectedRow = Math.Clamp(_state.SelectedRow + delta, 0, _state.Rows.Count - 1); - ReloadDetailIfNeeded(); - } + return new Markup(string.Empty); } - else if (delta > 0) + + if (_searchForm is { } searchForm) { - _detailView.ScrollDown(); + return searchForm.Render(width, height); } - else + + return RenderListPane(width, height); + } + + private IReadOnlyList Move(int delta) + { + if (_state.Rows.Count > 0) { - _detailView.ScrollUp(); + _state.SelectedRow = Math.Clamp(_state.SelectedRow + delta, 0, _state.Rows.Count - 1); } return []; } - private IReadOnlyList MoveOrScrollToEdge(EdgeTarget edge) + private IReadOnlyList MoveToEdge(EdgeTarget edge) { - if (_state.Focus == AgentsFocus.List) + if (_state.Rows.Count > 0) { - if (_state.Rows.Count > 0) - { - _state.SelectedRow = edge == EdgeTarget.Top ? 0 : _state.Rows.Count - 1; - ReloadDetailIfNeeded(); - } - } - else if (edge == EdgeTarget.Top) - { - _detailView.ScrollToTop(); + _state.SelectedRow = edge == EdgeTarget.Top ? 0 : _state.Rows.Count - 1; } - else + + return []; + } + + private IReadOnlyList Refresh() + { + RefreshBlocking(); + return []; + } + + /// + /// Reports the no-selection toast the shell shows when + /// found no agent to open; a no-op when an agent is selected (the popover already opened). + /// + private IReadOnlyList OpenSelectedFallback() => + _state.SelectedAgent is null + ? [new TuiMessage.ShowToast("No agent selected.", ToastStyle.Warn)] + : []; + + private IReadOnlyList CopySelectedId() + { + if (_state.SelectedAgent is not { } agent) { - _detailView.ScrollToBottom(); + return [new TuiMessage.ShowToast("No agent selected.", ToastStyle.Warn)]; } - return []; + return [BuildCopyIdToast(agent.Name, agent.SessionId)]; } /// - /// Left and Right both flip focus between the two panes. + /// Builds the toast for copying an agent's session id: the id itself, or a login-only + /// hint when is null or empty. /// - private IReadOnlyList TogglePane() + public static TuiMessage.ShowToast BuildCopyIdToast(string name, string? sessionId) => + sessionId is { Length: > 0 } + ? new TuiMessage.ShowToast(sessionId, ToastStyle.Info) + : new TuiMessage.ShowToast($"'{name}' is login-only and has no session.", ToastStyle.Info); + + private IReadOnlyList OpenSearchForm() { - _state.Focus = _state.Focus == AgentsFocus.List ? AgentsFocus.Detail : AgentsFocus.List; + _searchForm = new AgentSearchForm(_state.SearchText); return []; } - private IReadOnlyList FocusDetail() + private IReadOnlyList HandleSearchFormKey(ConsoleKeyInfo info) { - _state.Focus = AgentsFocus.Detail; - return []; + var result = _searchForm!.HandleKey(info); + + return result switch + { + null => [], + FormResult.Cancelled => CloseSearchForm(), + FormResult.ButtonActivated { ButtonId: AgentSearchForm.CancelButtonId } => CloseSearchForm(), + FormResult.Submitted => ApplySearch(), + _ => [] + }; } - private IReadOnlyList Refresh() + private IReadOnlyList CloseSearchForm() { - RefreshBlocking(); + _searchForm = null; return []; } - private IReadOnlyList CopySelectedId() + private IReadOnlyList ApplySearch() { - var sessionId = _state.SelectedParticipant?.Participant.Session.SessionId; - - return sessionId is null - ? [new TuiMessage.ShowToast("No session selected.", ToastStyle.Warn)] - : [new TuiMessage.ShowToast(sessionId, ToastStyle.Info)]; + var text = _searchForm!.Text; + _searchForm = null; + _state.ApplySearch(text); + return []; } private IRenderable RenderListPane(int width, int height) { - var focused = _state.Focus == AgentsFocus.List; var safeWidth = Math.Max(1, width); var contentWidth = Math.Max(0, safeWidth - PanelChromeWidth); var interiorHeight = Math.Max(0, height - PanelChromeHeight); + var now = _timeProvider.GetUtcNow(); - var lines = RenderListLines(contentWidth, interiorHeight, focused); - var panel = ColumnPane.Render("Agents", _state.Rows.Count, lines, focused); + var lines = RenderListLines(contentWidth, interiorHeight, now); + var header = $"Agents ({_state.CountOnline(now)} online / {_state.TotalCount})"; + var panel = ColumnPane.RenderWithHeader(header, lines, focused: true); panel.Width = safeWidth; panel.Height = Math.Max(1, height); return panel; } - private IRenderable RenderDetailPane(int width, int height) - => _detailView.Render(width, height, _state.Focus == AgentsFocus.Detail); - /// - /// Renders the visible rows, padded with blank lines to , with "N - /// more above/below" indicators once the participants no longer fit. Column widths are computed - /// from this call's visible slice. + /// Renders the header block (a blank line, the header row, and its rule), then the visible + /// rows, padded with blank lines to , with "N more + /// above/below" indicators once the rows no longer fit. Column widths are computed from + /// this call's visible slice and the header titles, so the header and rows always agree on + /// where each column starts. Shows the empty-state message below the header block when + /// there are no agents at all. /// - private IReadOnlyList RenderListLines(int contentWidth, int interiorHeight, bool focused) + private IReadOnlyList RenderListLines(int contentWidth, int interiorHeight, DateTimeOffset now) { if (interiorHeight <= 0) { return []; } + var headerLineCount = Math.Min(HeaderLineCount, interiorHeight); + var rowsHeight = Math.Max(0, interiorHeight - headerLineCount); + var lines = new List(interiorHeight); + + if (_state.TotalCount == 0) + { + var widths = AgentRowBadge.ComputeWidths([], now); + AddHeaderLines(lines, headerLineCount, contentWidth, widths); + + if (rowsHeight > 0) + { + lines.Add(DisplayWidth.Truncate(EmptyStateMessage, contentWidth)); + } + + PadTo(lines, interiorHeight); + return lines; + } + var rows = _state.Rows; var reservedRows = 0; for (var pass = 0; pass < MaxIndicatorSettlePasses; pass++) { - var windowHeight = Math.Max(0, interiorHeight - reservedRows); + var windowHeight = Math.Max(0, rowsHeight - reservedRows); _listViewport.Update(rows.Count, windowHeight); _listViewport.EnsureVisible(_state.SelectedRow); @@ -240,16 +325,15 @@ private IReadOnlyList RenderListLines(int contentWidth, int interiorHeig } var (start, visibleCount) = _listViewport.Slice(); - var now = _timeProvider.GetUtcNow(); - var visibleRows = new List(visibleCount); + var visibleRows = new List(visibleCount); for (var i = 0; i < visibleCount; i++) { visibleRows.Add(rows[start + i]); } - var widths = AgentRowBadge.ComputeWidths(visibleRows, now); - var lines = new List(interiorHeight); + var rowWidths = AgentRowBadge.ComputeWidths(visibleRows, now); + AddHeaderLines(lines, headerLineCount, contentWidth, rowWidths); if (_listViewport.HiddenAbove > 0) { @@ -258,8 +342,8 @@ private IReadOnlyList RenderListLines(int contentWidth, int interiorHeig for (var i = 0; i < visibleCount; i++) { - var selected = focused && start + i == _state.SelectedRow; - lines.Add(AgentRowBadge.Render(visibleRows[i], now, selected, contentWidth, widths)); + var selected = start + i == _state.SelectedRow; + lines.Add(AgentRowBadge.Render(visibleRows[i], now, selected, contentWidth, rowWidths)); } if (_listViewport.HiddenBelow > 0) @@ -267,52 +351,29 @@ private IReadOnlyList RenderListLines(int contentWidth, int interiorHeig lines.Add(FormatIndicator(_listViewport.HiddenBelow, "below")); } - while (lines.Count < interiorHeight) - { - lines.Add(string.Empty); - } - + PadTo(lines, interiorHeight); return lines; } - private static string FormatIndicator(int hiddenCount, string direction) => $" {hiddenCount} more {direction}"; - - private void RefreshBlocking() - { - _state.RefreshAsync(CancellationToken.None).GetAwaiter().GetResult(); - RefreshDetail(); - } - /// - /// Loads details when the selected participant differs from the loaded one. - /// Does nothing when no participant is selected or its key is unchanged. + /// Appends the header block to : a blank line, the header title + /// row, and its rule, up to of + /// (later lines are dropped first when the interior is too + /// short to hold all of them). /// - private void ReloadDetailIfNeeded() - { - var selected = _state.SelectedParticipant; + private static void AddHeaderLines( + List lines, int headerLineCount, int contentWidth, AgentRowBadge.Widths widths) => + AgentRowBadge.AddHeaderLines(lines, headerLineCount, contentWidth, widths); - if (selected is null || _detailModel.CurrentKey == selected.Key) + private static void PadTo(List lines, int height) + { + while (lines.Count < height) { - return; + lines.Add(string.Empty); } - - _detailModel.LoadAsync(selected.Participant, CancellationToken.None).GetAwaiter().GetResult(); } - /// - /// Reloads the detail pane for the currently selected participant, unconditionally, or clears it - /// when nothing is selected. - /// - private void RefreshDetail() - { - var selected = _state.SelectedParticipant; - - if (selected is null) - { - _detailModel.Clear(); - return; - } + private static string FormatIndicator(int hiddenCount, string direction) => $" {hiddenCount} more {direction}"; - _detailModel.LoadAsync(selected.Participant, CancellationToken.None).GetAwaiter().GetResult(); - } + private void RefreshBlocking() => _state.RefreshAsync(CancellationToken.None).GetAwaiter().GetResult(); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsState.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsState.cs index 6961f327a3f..06327a10132 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsState.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Agents/AgentsState.cs @@ -1,17 +1,28 @@ +using System.Text; using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tui.Mail; namespace ChilliCream.Nitro.CommandLine.Tui.Agents; /// -/// The loaded live participants, selected row, and focused pane. +/// The loaded agent rows, name search filter, and selection for the Agents tab. /// -internal sealed class AgentsState(IAgentSessionRegistry sessionRegistry, IClaudeSessionActivityReader activityReader) +internal sealed class AgentsState(IAgentStore store, TimeProvider timeProvider) { + private IReadOnlyList _allRows = []; + private string _lastSignature = string.Empty; + + /// + /// Every non-deleted agent matching , sorted by state group + /// (Online, Idle, Unreachable, Offline) as of the last or + /// call, then by last-seen window descending, then by name. + /// + public IReadOnlyList Rows { get; private set; } = []; + /// - /// Live participant rows in registry order by harness and session id, including - /// unbound sessions. Ended or reaped sessions are absent after refresh. + /// The total non-deleted agent count, independent of . /// - public IReadOnlyList Rows { get; private set; } = []; + public int TotalCount => _allRows.Count; /// /// The index of the selected row within . @@ -19,29 +30,29 @@ internal sealed class AgentsState(IAgentSessionRegistry sessionRegistry, IClaude public int SelectedRow { get; set; } /// - /// Which pane currently holds focus. + /// The current name search filter; empty shows every agent. /// - public AgentsFocus Focus { get; set; } = AgentsFocus.List; + public string SearchText { get; private set; } = string.Empty; /// - /// The row at , or null when the list is empty - /// or the row is out of range. + /// The row at , or null when there is no such row. /// - public AgentParticipantRow? SelectedParticipant + public AgentRow? SelectedAgent => SelectedRow >= 0 && SelectedRow < Rows.Count ? Rows[SelectedRow] : null; /// - /// Reloads every live participant from the registry. The selected row stays selected by its - /// ; otherwise it is clamped to the new list's bounds. + /// Reloads every non-deleted agent from the store, re-applies the search filter and + /// sort, and keeps the previously selected agent selected by name when it is still + /// present; otherwise clamps the selection to the new list's bounds. /// public async Task RefreshAsync(CancellationToken cancellationToken) { - var selectedKey = SelectedParticipant?.Key; + var selectedName = SelectedAgent?.Name; - var participants = await sessionRegistry.ListParticipantsAsync(cancellationToken); - Rows = participants.Select(ToRow).ToList(); + _allRows = await store.ListAsync(cancellationToken); + ApplyFilterAndSort(timeProvider.GetUtcNow()); - var preservedIndex = selectedKey is { } key ? IndexOf(Rows, key) : -1; + var preservedIndex = selectedName is null ? -1 : IndexOf(Rows, selectedName); SelectedRow = preservedIndex >= 0 ? preservedIndex @@ -49,24 +60,108 @@ public async Task RefreshAsync(CancellationToken cancellationToken) } /// - /// Attaches activity for an online Claude Code participant, or null activity - /// for other participants. + /// Applies a new name search filter, re-sorts, and selects the first matching row. /// - private AgentParticipantRow ToRow(AgentSessionParticipant participant) + public void ApplySearch(string text) { - var activity = participant.State == AgentSessionState.Online - && participant.Session.Harness == AgentSessionHarness.ClaudeCode - ? activityReader.GetStatus(participant.Session.SessionId) - : null; + SearchText = text.Trim(); + ApplyFilterAndSort(timeProvider.GetUtcNow()); + SelectedRow = 0; + } - return new AgentParticipantRow(participant, activity); + /// + /// Recomputes every loaded row's resolved state and formatted started/last-seen ages as + /// of . When any changed since the last call, re-applies the filter + /// and sort and preserves the selected agent by name, returning true; returns false + /// without touching or when nothing changed. + /// + public bool Resettle(DateTimeOffset now) + { + var signature = ComputeSignature(now); + + if (signature == _lastSignature) + { + return false; + } + + var selectedName = SelectedAgent?.Name; + + ApplyFilterAndSort(now); + + var preservedIndex = selectedName is null ? -1 : IndexOf(Rows, selectedName); + + SelectedRow = preservedIndex >= 0 + ? preservedIndex + : Math.Clamp(SelectedRow, 0, Math.Max(0, Rows.Count - 1)); + + return true; } - private static int IndexOf(IReadOnlyList rows, AgentSessionKey key) + /// + /// Counts the agents currently resolving to or + /// as of , among every non-deleted + /// agent, ignoring the search filter. + /// + public int CountInactive(DateTimeOffset now) + => _allRows.Count(row => + AgentStateResolver.Resolve(row, now) is AgentState.Offline or AgentState.Idle); + + /// + /// Counts the agents currently resolving to as of + /// , among every non-deleted agent, ignoring the search filter. + /// + public int CountOnline(DateTimeOffset now) + => _allRows.Count(row => AgentStateResolver.Resolve(row, now) == AgentState.Online); + + private void ApplyFilterAndSort(DateTimeOffset now) + { + _lastSignature = ComputeSignature(now); + + var filtered = SearchText.Length == 0 + ? _allRows + : _allRows.Where(row => row.Name.Contains(SearchText, StringComparison.OrdinalIgnoreCase)); + + Rows = filtered + .OrderBy(row => StateRank(AgentStateResolver.Resolve(row, now))) + .ThenByDescending(row => AgentStateResolver.LastSeenWindowStart(row.LastSeenAt)) + .ThenBy(row => row.Name, StringComparer.Ordinal) + .ToList(); + } + + /// + /// Builds a cheap signature of every loaded row's resolved state and formatted + /// started/last-seen ages as of , used to detect whether a tick + /// changed anything worth re-sorting and re-rendering. + /// + private string ComputeSignature(DateTimeOffset now) + { + var signature = new StringBuilder(); + + foreach (var row in _allRows) + { + signature + .Append(row.Name).Append('\u0001') + .Append(AgentStateResolver.Resolve(row, now)).Append('\u0001') + .Append(MailAges.Format(row.StartedAt, now)).Append('\u0001') + .Append(MailAges.Format(row.LastSeenAt, now)).Append('\u0002'); + } + + return signature.ToString(); + } + + private static int StateRank(AgentState state) => state switch + { + AgentState.Online => 0, + AgentState.Idle => 1, + AgentState.Unreachable => 2, + _ => 3 + }; + + private static int IndexOf(IReadOnlyList rows, string name) { for (var i = 0; i < rows.Count; i++) { - if (rows[i].Key == key) + if (rows[i].Name == name) { return i; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardLayout.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardLayout.cs index 212b71f35c0..dc1e6e33b3f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardLayout.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardLayout.cs @@ -24,9 +24,11 @@ internal static class BoardLayout private const int StackedPanelChromeHeight = 2; /// - /// The minimum interior row count required to give every stacked column equal height. + /// The minimum interior row count required to give every stacked column equal height: + /// the header block plus the three rows the indicator settle needs to keep the + /// selection visible. /// - private const int MinStackedInteriorHeight = 3; + private const int MinStackedInteriorHeight = BoardTaskRow.HeaderLineCount + 3; /// /// The smallest per-column height requires diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardMode.cs index cf80444938e..163307e5e9f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardMode.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardMode.cs @@ -112,73 +112,108 @@ public void OnResize(int width, int height) /// public IRenderable Render(int width, int height) { - var columns = _state.Columns; - - if (columns.Count == 0 || width <= 0 || height <= 0) + if (_state.Columns.Count == 0 || width <= 0 || height <= 0) { return new Markup(string.Empty); } - var decision = BoardLayout.Decide(width, height, columns.Count, _state.FocusedColumnIndex, _maximized); + var visibleIndices = _state.VisibleColumnIndices; + + if (visibleIndices.Count == 0) + { + return RenderEmptyBoard(width, height); + } + + var focusedPosition = Math.Max(0, IndexOf(visibleIndices, _state.FocusedColumnIndex)); + var decision = BoardLayout.Decide(width, height, visibleIndices.Count, focusedPosition, _maximized); return decision.Kind switch { - BoardLayoutKind.Maximized => RenderMaximized(decision), - BoardLayoutKind.Stacked => RenderStacked(decision), - _ => RenderGrid(decision) + BoardLayoutKind.Maximized => RenderMaximized(decision, visibleIndices, focusedPosition), + BoardLayoutKind.Stacked => RenderStacked(decision, visibleIndices), + _ => RenderGrid(decision, visibleIndices) }; } - private IRenderable RenderGrid(BoardLayoutDecision decision) + private IRenderable RenderGrid(BoardLayoutDecision decision, IReadOnlyList visibleIndices) { - var columns = _state.Columns; - var columnLayouts = new Layout[columns.Count]; + var columnLayouts = new Layout[visibleIndices.Count]; - for (var i = 0; i < columns.Count; i++) + for (var position = 0; position < visibleIndices.Count; position++) { - var slot = decision.Columns[i]; - var focused = i == _state.FocusedColumnIndex; - var panel = RenderColumnPanel(i, slot.Width, slot.Height, focused, headerSuffix: null); + var rawIndex = visibleIndices[position]; + var slot = decision.Columns[position]; + var focused = rawIndex == _state.FocusedColumnIndex; + var panel = RenderColumnPanel(rawIndex, slot.Width, slot.Height, focused, headerSuffix: null); - columnLayouts[i] = new Layout($"board-column-{i}", panel).Size(Math.Max(1, slot.Width)); + columnLayouts[position] = new Layout($"board-column-{rawIndex}", panel).Size(Math.Max(1, slot.Width)); } return new Layout("board").SplitColumns(columnLayouts); } - private IRenderable RenderMaximized(BoardLayoutDecision decision) + private IRenderable RenderMaximized( + BoardLayoutDecision decision, IReadOnlyList visibleIndices, int focusedPosition) { - var columns = _state.Columns; - var focused = _state.FocusedColumnIndex; - var slot = decision.Columns[focused]; - var suffix = $"{focused + 1}/{columns.Count}"; + var rawIndex = visibleIndices[focusedPosition]; + var slot = decision.Columns[focusedPosition]; + var suffix = $"{focusedPosition + 1}/{visibleIndices.Count}"; - return RenderColumnPanel(focused, slot.Width, slot.Height, focused: true, headerSuffix: suffix); + return RenderColumnPanel(rawIndex, slot.Width, slot.Height, focused: true, headerSuffix: suffix); } - private IRenderable RenderStacked(BoardLayoutDecision decision) + private IRenderable RenderStacked(BoardLayoutDecision decision, IReadOnlyList visibleIndices) { var columns = _state.Columns; - var rows = new List(Math.Max(0, columns.Count * 2 - 1)); + var rows = new List(Math.Max(0, visibleIndices.Count * 2 - 1)); - for (var i = 0; i < columns.Count; i++) + for (var position = 0; position < visibleIndices.Count; position++) { - if (i > 0) + if (position > 0) { // Insert one blank row between stacked column panels. rows.Add(new Text(string.Empty)); } - var slot = decision.Columns[i]; + var rawIndex = visibleIndices[position]; + var slot = decision.Columns[position]; + + var focused = rawIndex == _state.FocusedColumnIndex; rows.Add(slot.Expanded - ? RenderColumnPanel(i, slot.Width, slot.Height, focused: i == _state.FocusedColumnIndex, headerSuffix: null) - : new Markup(Markup.Escape($"{columns[i].Definition.Name} ({columns[i].Tasks.Count})"))); + ? RenderColumnPanel(rawIndex, slot.Width, slot.Height, focused, headerSuffix: null) + : new Markup(Markup.Escape($"{columns[rawIndex].Definition.Name} ({columns[rawIndex].Tasks.Count})"))); } return new Rows(rows); } + /// + /// Renders the single full-width panel shown when every column is empty. + /// + private IRenderable RenderEmptyBoard(int width, int height) + { + var safeWidth = Math.Max(1, width); + var interiorHeight = Math.Max(0, height - PanelChromeHeight); + var lines = new List(interiorHeight); + + if (interiorHeight > 0) + { + lines.Add("No tasks yet."); + } + + while (lines.Count < interiorHeight) + { + lines.Add(string.Empty); + } + + var panel = ColumnPane.RenderWithHeader($"{_state.View.Name} (0)", lines, focused: false); + panel.Width = safeWidth; + panel.Height = Math.Max(1, height); + + return panel; + } + /// /// Builds one column's bordered panel: its visible task lines, sized to /// and , with @@ -215,7 +250,7 @@ private IReadOnlyList ToggleMaximize() private IReadOnlyList FocusColumn(int delta) { - _state.FocusColumn(_state.FocusedColumnIndex + delta); + _state.FocusAdjacentVisibleColumn(delta); return []; } @@ -295,8 +330,12 @@ private static Viewport[] CreateViewports(int columnCount) } /// - /// Renders one column's visible rows, padded with blank lines to , - /// with "N more above/below" indicators once the column's tasks no longer fit. + /// Renders one column's task table: the fixed header block (a blank line, the header row, + /// and its rule), then the visible rows, padded with blank lines to + /// , with "N more above/below" indicators once the + /// column's tasks no longer fit. Column widths are computed from this call's visible + /// slice and the header titles, so the header and rows always agree on where each column + /// starts. /// private static IReadOnlyList RenderColumnLines( BoardColumnState column, @@ -310,11 +349,15 @@ private static IReadOnlyList RenderColumnLines( return []; } + var headerLineCount = Math.Min( + BoardTaskRow.HeaderLineCount, + column.Tasks.Count > 0 ? Math.Max(0, interiorHeight - 1) : interiorHeight); + var rowsHeight = Math.Max(0, interiorHeight - headerLineCount); var reservedRows = 0; for (var pass = 0; pass < MaxIndicatorSettlePasses; pass++) { - var windowHeight = Math.Max(0, interiorHeight - reservedRows); + var windowHeight = Math.Max(0, rowsHeight - reservedRows); viewport.Update(column.Tasks.Count, windowHeight); viewport.EnsureVisible(column.SelectedRow); @@ -329,7 +372,16 @@ private static IReadOnlyList RenderColumnLines( } var (start, visibleCount) = viewport.Slice(); + var visibleTasks = new List(visibleCount); + + for (var i = 0; i < visibleCount; i++) + { + visibleTasks.Add(column.Tasks[start + i]); + } + + var widths = BoardTaskRow.ComputeWidths(visibleTasks); var lines = new List(interiorHeight); + BoardTaskRow.AddHeaderLines(lines, headerLineCount, contentWidth, widths); if (viewport.HiddenAbove > 0) { @@ -338,10 +390,8 @@ private static IReadOnlyList RenderColumnLines( for (var i = 0; i < visibleCount; i++) { - var task = column.Tasks[start + i]; var selected = focused && start + i == column.SelectedRow; - lines.Add(TaskBadge.Render( - task.Id, task.Title, task.Status, task.Priority, task.Type, selected, contentWidth)); + lines.Add(BoardTaskRow.Render(visibleTasks[i], selected, contentWidth, widths)); } if (viewport.HiddenBelow > 0) @@ -371,4 +421,17 @@ private static int IndexOfTask(IReadOnlyList tasks, string id) return -1; } + + private static int IndexOf(IReadOnlyList values, int value) + { + for (var i = 0; i < values.Count; i++) + { + if (values[i] == value) + { + return i; + } + } + + return -1; + } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardState.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardState.cs index de1991a2149..93fcef53755 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardState.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardState.cs @@ -27,6 +27,18 @@ public BoardState(BoardView view, BoardDataLoader loader) /// public IReadOnlyList Columns { get; } + /// + /// The raw index of each column with at least one task, in display order. + /// + public IReadOnlyList VisibleColumnIndices + => [.. Enumerable.Range(0, Columns.Count).Where(i => Columns[i].Tasks.Count > 0)]; + + /// + /// The columns with at least one task, in display order. + /// + public IReadOnlyList VisibleColumns + => [.. VisibleColumnIndices.Select(i => Columns[i])]; + /// /// The index of the column that has focus. /// @@ -40,10 +52,32 @@ public void FocusColumn(int index) FocusedColumnIndex = Columns.Count == 0 ? 0 : Math.Clamp(index, 0, Columns.Count - 1); } + /// + /// Moves focus by positions among the visible columns, + /// clamped to the first or last visible column. Does nothing when no column is visible. + /// + public void FocusAdjacentVisibleColumn(int delta) + { + var visibleIndices = VisibleColumnIndices; + + if (visibleIndices.Count == 0) + { + return; + } + + var currentPosition = IndexOf(visibleIndices, FocusedColumnIndex); + var position = currentPosition < 0 + ? 0 + : Math.Clamp(currentPosition + delta, 0, visibleIndices.Count - 1); + + FocusedColumnIndex = visibleIndices[position]; + } + /// /// Reloads every column from the task store. Each column's selected task /// stays selected when it is still present in the reloaded list; - /// otherwise the selected row is clamped to the new list's bounds. + /// otherwise the selected row is clamped to the new list's bounds. When the + /// focused column no longer has a task, focus moves to the first visible column. /// public async Task RefreshAsync(CancellationToken cancellationToken) { @@ -60,6 +94,13 @@ public async Task RefreshAsync(CancellationToken cancellationToken) ? preservedIndex : Math.Clamp(column.SelectedRow, 0, Math.Max(0, tasks.Count - 1)); } + + var visibleIndices = VisibleColumnIndices; + + if (visibleIndices.Count > 0 && !visibleIndices.Contains(FocusedColumnIndex)) + { + FocusedColumnIndex = visibleIndices[0]; + } } private static int IndexOf(IReadOnlyList tasks, string taskId) @@ -74,4 +115,17 @@ private static int IndexOf(IReadOnlyList tasks, string taskId) return -1; } + + private static int IndexOf(IReadOnlyList values, int value) + { + for (var i = 0; i < values.Count; i++) + { + if (values[i] == value) + { + return i; + } + } + + return -1; + } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardTaskRow.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardTaskRow.cs new file mode 100644 index 00000000000..ec073183b19 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Board/BoardTaskRow.cs @@ -0,0 +1,239 @@ +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Tui.Theming; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; + +namespace ChilliCream.Nitro.CommandLine.Tui.Board; + +/// +/// Renders a board column's task table: a status glyph cell, type name, priority, id, and +/// title columns. Narrow widths drop priority first, then type; id and title are never +/// dropped, with title taking whatever width remains and truncating with an ellipsis. Built +/// on the shared and table widget, +/// reusing and for the cell +/// styling. +/// +internal static class BoardTaskRow +{ + private const string SelectedPrefix = "> "; + private const string UnselectedPrefix = " "; + + private const string TypeHeader = "TYPE"; + private const string PriorityHeader = "PRIO"; + private const string IdHeader = "ID"; + private const string TitleHeader = "TITLE"; + + private const int MinTypeWidth = 8; + private const int MinPriorityWidth = 4; + private const int MinIdWidth = 10; + + /// + /// The lines a column panel's task table top block spends on the blank line, header row, + /// and rule, before any task row is drawn. + /// + internal const int HeaderLineCount = TableRenderer.TopBlockLineCount; + + /// + /// The terminal-cell width every status glyph occupies, used to size the leading cell. + /// + private const int GlyphCellWidth = 1; + + /// + /// The header row's stand-in for the glyph cell: blank, but the same width as an actual + /// status glyph, so the header and rows agree on where the type column starts. + /// + private static readonly string s_blankGlyph = new(' ', GlyphCellWidth); + + // Priority drops first, then type; id has no drop priority so it is never dropped. Title + // is appended separately at render time, taking whatever width remains after id, type, + // and priority. + private static readonly IReadOnlyList s_columns = + [ + new TableColumnSpec(TypeHeader, MinTypeWidth, DropPriority: 1), + new TableColumnSpec(PriorityHeader, MinPriorityWidth, DropPriority: 0, Alignment: ColumnAlignment.Right), + new TableColumnSpec(IdHeader, MinIdWidth) + ]; + + /// + /// The column widths a set of rows agree on: type, priority, and id, each no narrower + /// than its minimum width or its header title. + /// + public readonly record struct Widths(int Type, int Priority, int Id); + + /// + /// Computes across , with each column no + /// narrower than its minimum width or its header title. + /// + public static Widths ComputeWidths(IReadOnlyList rows) + { + var rowValues = new List>(rows.Count); + + foreach (var row in rows) + { + rowValues.Add([TaskGlyphs.TypeName(row.Type), TaskPriorities.Format(row.Priority), row.Id]); + } + + var widths = TableLayout.ComputeWidths(s_columns, rowValues); + return new Widths(widths[0], widths[1], widths[2]); + } + + /// + /// Builds the markup line for one task row. Columns are padded to . + /// When the full set of columns does not fit within display + /// columns, priority is dropped first, then type; id always remains, and title fills + /// whatever space is left, truncated with an ellipsis. A of 0 + /// or less produces an empty line. + /// + public static string Render(TaskItem task, bool selected, int maxWidth, Widths widths) + { + if (maxWidth <= 0) + { + return string.Empty; + } + + var prefix = selected ? SelectedPrefix : UnselectedPrefix; + var glyph = TaskGlyphs.Status(task.Status); + var glyphStyle = ThemeTokens.GetStyle($"status.glyph.{task.Status}").ToMarkup(); + var typeStyle = ThemeTokens.GetStyle($"badge.type.{task.Type}").ToMarkup(); + var priorityStyle = TaskBadge.PriorityStyle(task.Priority); + + var cells = new TableCellSpec[] + { + new(TaskGlyphs.TypeName(task.Type), typeStyle), + new(TaskPriorities.Format(task.Priority), priorityStyle), + new(task.Id, string.Empty), + new(task.Title, string.Empty) + }; + + var budget = maxWidth - PrefixWidth(prefix); + var (columns, layout) = PlanWithTitle(budget, widths); + var line = TableRenderer.RenderRow(prefix, new TableCellSpec(glyph, glyphStyle), cells, columns, layout); + + if (selected) + { + var highlightStyle = ThemeTokens.GetStyle("selection.highlight").ToMarkup(); + line = TableRenderer.Stylize(highlightStyle, line); + } + + return line; + } + + /// + /// Builds the header title line shown above the rows: TYPE, PRIO, ID, TITLE, aligned to + /// with the cursor and glyph cells left blank. Columns are + /// dropped using the same thresholds as , so the header always agrees + /// with the rows below it. A of 0 or less produces an empty + /// line. + /// + public static string RenderHeader(int maxWidth, Widths widths) + { + if (maxWidth <= 0) + { + return string.Empty; + } + + var headerStyle = ThemeTokens.GetStyle("board.column.header").ToMarkup(); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var (columns, layout) = PlanWithTitle(budget, widths); + var headerCells = BuildHeaderCells(columns, headerStyle); + + return TableRenderer.RenderRow( + UnselectedPrefix, new TableCellSpec(s_blankGlyph), headerCells, columns, layout); + } + + /// + /// Builds the dashed rule line under the header, filling + /// display columns. A of 0 or less produces an empty line. + /// + public static string RenderRule(int maxWidth) + { + var ruleStyle = ThemeTokens.GetStyle("board.column.border").ToMarkup(); + return TableRenderer.RenderRule(maxWidth, ruleStyle); + } + + /// + /// Appends the task table's fixed top block to : a blank line, + /// the header row, and the rule, keeping only the first + /// of . A + /// of 0 or less appends nothing. + /// + public static void AddHeaderLines(List lines, int headerLineCount, int maxWidth, Widths widths) + { + if (maxWidth <= 0) + { + return; + } + + var headerStyle = ThemeTokens.GetStyle("board.column.header").ToMarkup(); + var ruleStyle = ThemeTokens.GetStyle("board.column.border").ToMarkup(); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var (columns, layout) = PlanWithTitle(budget, widths); + + TableRenderer.RenderTopBlock( + lines, + headerLineCount, + maxWidth, + UnselectedPrefix, + new TableCellSpec(s_blankGlyph), + columns, + layout, + headerStyle, + ruleStyle); + } + + /// + /// Plans type, priority, and id against , then appends a title + /// column sized to whatever width remains after the visible columns and their gutters. Id + /// is never dropped, so a gutter always separates it from the appended title column; that + /// gutter is reserved up front so the drop decision leaves room for it. + /// + private static (IReadOnlyList Columns, IReadOnlyList Layout) PlanWithTitle( + int budget, Widths widths) + { + var planBudget = Math.Max(0, budget - DisplayWidth.Measure(TableLayout.Gutter)); + var layout = TableLayout.Plan(planBudget, s_columns, ToWidthList(widths)); + var titleWidth = ComputeTitleWidth(budget, layout); + + var columns = new List(s_columns) { new(TitleHeader, 0, FixedWidth: titleWidth) }; + var fullLayout = new List(layout) { new(true, titleWidth) }; + + return (columns, fullLayout); + } + + private static int ComputeTitleWidth(int budget, IReadOnlyList layout) + { + var usedWidth = 0; + var visibleCount = 0; + + foreach (var column in layout) + { + if (!column.Visible) + { + continue; + } + + usedWidth += column.Width; + visibleCount++; + } + + // One gutter before each visible type/priority/id column and one more before title. + usedWidth += visibleCount * DisplayWidth.Measure(TableLayout.Gutter); + + return Math.Max(0, budget - usedWidth); + } + + private static TableCellSpec[] BuildHeaderCells(IReadOnlyList columns, string headerStyle) + { + var cells = new TableCellSpec[columns.Count]; + + for (var i = 0; i < columns.Count; i++) + { + cells[i] = new TableCellSpec(columns[i].Title, headerStyle); + } + + return cells; + } + + private static int PrefixWidth(string prefix) => DisplayWidth.Measure(prefix) + GlyphCellWidth + 1; + + private static IReadOnlyList ToWidthList(Widths widths) => [widths.Type, widths.Priority, widths.Id]; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Input/TuiMessage.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Input/TuiMessage.cs index 5215b24d99f..267c6595ba2 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Input/TuiMessage.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Input/TuiMessage.cs @@ -152,67 +152,10 @@ public sealed record CreateTaskRequested : TuiMessage; public sealed record CreateEpicRequested : TuiMessage; /// - /// The active mode's currently selected item should toggle between read - /// and unread. - /// - public sealed record ToggleReadRequested : TuiMessage; - - /// - /// The archive confirmation should open for the active mode's currently - /// selected item. - /// - public sealed record ArchiveRequested : TuiMessage; - - /// - /// The compose form should open. - /// - public sealed record ComposeRequested : TuiMessage; - - /// - /// The reply form should open for the active mode's currently selected - /// item. - /// - public sealed record ReplyRequested : TuiMessage; - - /// - /// The mail board's Inbox mailbox should become the active mailbox. - /// - public sealed record SelectInboxRequested : TuiMessage; - - /// - /// The mail board's Sent mailbox should become the active mailbox. - /// - public sealed record SelectSentRequested : TuiMessage; - - /// - /// The mail board's All mailbox should become the active mailbox. - /// - public sealed record SelectAllMailRequested : TuiMessage; - - /// - /// The mail board's Workspace mailbox should become the active mailbox. - /// - public sealed record SelectWorkspaceMailRequested : TuiMessage; - - /// - /// The mail board's agent filter quick picker should open, scoped to - /// . + /// The active mode's agent filter quick picker should open. /// public sealed record AgentFilterPickerRequested : TuiMessage; - /// - /// The mail board's list pane should toggle between - /// and (Shift+V). - /// - public sealed record ToggleListModeRequested : TuiMessage; - - /// - /// The mail board's list pane should enter its fold-prefix capture - /// state (the vim z prefix): the next raw key resolves one of - /// za/zo/zc/zR/zM, or is dropped when it matches none of them. - /// - public sealed record FoldPrefixRequested : TuiMessage; - /// /// The active mode's own inline search input should gain focus. /// @@ -229,4 +172,15 @@ public sealed record PromoteRequested : TuiMessage; /// selected curated memory. /// public sealed record ForgetRequested : TuiMessage; + + /// + /// The delete confirmation should open for the Agents tab's agent named + /// , an empty string when nothing is selected. + /// + public sealed record DeleteAgentRequested(string Name) : TuiMessage; + + /// + /// The delete-all-offline confirmation should open for the Agents tab. + /// + public sealed record DeleteOfflineAgentsRequested : TuiMessage; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailAction.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailAction.cs deleted file mode 100644 index 74c7e44ea42..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailAction.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// The lifecycle write a resulted from. -/// -internal enum MailAction -{ - MarkRead, - MarkUnread, - Archive -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailActionOutcome.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailActionOutcome.cs deleted file mode 100644 index 718c538aea5..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailActionOutcome.cs +++ /dev/null @@ -1,35 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Tui.Input; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// The outcome of one write against the -/// mail store. -/// -internal abstract record MailActionOutcome -{ - private MailActionOutcome() - { - } - - /// - /// The write succeeded. - /// - public sealed record Succeeded(MailAction Action, string ToastText) : MailActionOutcome; - - /// - /// The store rejected the write with an . - /// - public sealed record Failed(MailAction Action, string ToastText) : MailActionOutcome; - - /// - /// The shell toast this outcome should show: success styled for - /// , error styled for . - /// - public TuiMessage.ShowToast ToShowToast() => this switch - { - Succeeded succeeded => new TuiMessage.ShowToast(succeeded.ToastText, ToastStyle.Success), - Failed failed => new TuiMessage.ShowToast(failed.ToastText, ToastStyle.Error), - _ => throw new NotSupportedException() - }; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailComposeForm.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailComposeForm.cs deleted file mode 100644 index 4c85e0e6e58..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailComposeForm.cs +++ /dev/null @@ -1,110 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Input; -using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; -using Spectre.Console.Rendering; -using Form = ChilliCream.Nitro.CommandLine.Tui.Widgets.Form.Form; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// A form for comma-separated recipients, a required subject, and a message body. -/// Recipient names are validated by the mail store when submitted. -/// -internal sealed class MailComposeForm -{ - public const string ToFieldId = "to"; - public const string SubjectFieldId = "subject"; - public const string BodyFieldId = "body"; - - public const string SendButtonId = "send"; - public const string CancelButtonId = "cancel"; - - /// - /// The footer hints displayed while the compose form captures input. - /// - public static readonly IReadOnlyList Hints = - [ - new KeyHint("tab", "next field"), - new KeyHint("ctrl+s", "send"), - new KeyHint("esc", "cancel") - ]; - - private readonly Form _form; - private readonly TextField _toField; - private readonly TextField _subjectField; - private readonly TextAreaField _bodyField; - - public MailComposeForm() - { - _toField = new TextField( - ToFieldId, "To (comma-separated)", required: true, validator: RequireRecipients); - _subjectField = new TextField( - SubjectFieldId, "Subject", required: true, validator: RequireSubject); - _bodyField = new TextAreaField(BodyFieldId, "Body"); - - var buttons = new FormButtons( - [ - new FormButtonSpec(SendButtonId, "Send", ButtonKind.Primary), - new FormButtonSpec(CancelButtonId, "Cancel", ButtonKind.Secondary) - ]); - - _form = new Form("Compose", [_toField, _subjectField, _bodyField], buttons); - } - - /// - /// Whether any field contains text, including whitespace. - /// - public bool IsDirty - => Text(_toField).Length != 0 || Text(_subjectField).Length != 0 || Text(_bodyField).Length != 0; - - /// - /// Handles one raw key. Returns while the form is - /// still active, or the terminal once the - /// interaction ends. - /// - public FormResult? HandleKey(ConsoleKeyInfo info) => _form.HandleKey(info); - - /// - /// Renders the form as a titled, rounded panel centered within the given - /// area. - /// - public IRenderable Render(int width, int height) => _form.Render(width, height); - - /// - /// Builds a message creation from submitted form values with - /// . Does not write to the store. - /// - public static MailMessageCreation BuildCreation(IReadOnlyDictionary values, string actor) - { - ArgumentNullException.ThrowIfNull(values); - ArgumentException.ThrowIfNullOrEmpty(actor); - - return new MailMessageCreation - { - Sender = actor, - Subject = Text(values, SubjectFieldId), - Body = Text(values, BodyFieldId), - To = ParseRecipients(Text(values, ToFieldId)), - WakePolicy = MailWakePolicy.Enqueue - }; - } - - private static IReadOnlyList ParseRecipients(string value) - => value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - - private static string? RequireRecipients(FormValue value) - => value is FormValue.Text { Value: var text } && text.Trim().Length == 0 - ? "At least one recipient is required." - : null; - - private static string? RequireSubject(FormValue value) - => value is FormValue.Text { Value: var text } && text.Trim().Length == 0 - ? "Subject is required." - : null; - - private static string Text(FormField field) - => field.GetValue() is FormValue.Text { Value: var value } ? value : ""; - - private static string Text(IReadOnlyDictionary values, string id) - => values[id] is FormValue.Text { Value: var value } ? value : ""; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDataLoader.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDataLoader.cs index 72a21261a07..5c2461a4430 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDataLoader.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDataLoader.cs @@ -3,108 +3,13 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Mail; /// -/// Loads mailbox messages and thread summaries from the mail store. +/// Loads workspace thread summaries from the mail store. /// internal sealed class MailDataLoader(IMailStore store) { /// - /// Loads the actor's inbox for the given filter, newest first. - /// - public async Task> LoadInboxAsync( - string actor, - MailListFilter filter, - CancellationToken cancellationToken) - { - var storeFilter = new MailInboxFilter - { - Actor = actor, - UnreadOnly = filter == MailListFilter.Unread, - IncludeArchived = filter == MailListFilter.Archived - }; - - var messages = await store.QueryInboxAsync(storeFilter, cancellationToken).ConfigureAwait(false); - - return filter == MailListFilter.Archived - ? messages.Where(m => MailRecipientView.IsArchived(m, actor)).ToList() - : messages; - } - - /// - /// Loads every message the actor sent, regardless of recipient, newest - /// first. - /// - public Task> LoadSentAsync( - string actor, - CancellationToken cancellationToken) - => store.QuerySentAsync(actor, limit: null, cancellationToken); - - /// - /// Loads every message the actor sent or received, newest first. - /// - public Task> LoadAllAsync( - string actor, - CancellationToken cancellationToken) - => store.QueryWorkspaceMessagesAsync( - new MailWorkspaceFilter { Agent = actor }, cancellationToken); - - /// - /// Loads every message in the workspace, newest first, narrowed to - /// messages sent or received when given, or - /// across every agent when null. - /// - public Task> LoadWorkspaceAsync( - string? agent, - CancellationToken cancellationToken) - => store.QueryWorkspaceMessagesAsync(new MailWorkspaceFilter { Agent = agent }, cancellationToken); - - /// - /// Loads every message in the given thread, oldest first. - /// - public Task> LoadThreadAsync( - string threadId, - CancellationToken cancellationToken) - => store.GetThreadMessagesAsync(threadId, cancellationToken); - - /// - /// Loads inbox thread summaries newest activity first, applying the archived - /// filter when requested. Unread filtering is applied separately by - /// . - /// - public async Task> LoadInboxThreadsAsync( - string actor, - MailListFilter filter, - CancellationToken cancellationToken) - { - var includeArchived = filter == MailListFilter.Archived; - - var threads = await store.QueryInboxThreadsAsync(actor, includeArchived, cancellationToken) - .ConfigureAwait(false); - - return includeArchived - ? threads.Where(t => (t.ArchivedCount ?? 0) > 0).ToList() - : threads; - } - - /// - /// Loads summaries of threads the actor sent mail in, newest activity first. - /// - public Task> LoadSentThreadsAsync( - string actor, - CancellationToken cancellationToken) - => store.QuerySentThreadsAsync(actor, cancellationToken); - - /// - /// Loads summaries of threads the actor sent or received mail in, newest - /// activity first. - /// - public Task> LoadAllThreadsAsync( - string actor, - CancellationToken cancellationToken) - => store.QueryThreadsAsync(actor, cancellationToken); - - /// - /// Loads workspace thread summaries newest activity first, limited to threads - /// the supplied agent sent or received mail in, or all agents when null. + /// Loads every workspace thread summary, newest activity first, narrowed to threads + /// sent or received mail in, or across every agent when null. /// public Task> LoadWorkspaceThreadsAsync( string? agent, diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDetailView.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDetailView.cs index 34465c927b1..6c85721cdec 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDetailView.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDetailView.cs @@ -1,5 +1,4 @@ using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Services.Workspace; using ChilliCream.Nitro.CommandLine.Tui.Details; using ChilliCream.Nitro.CommandLine.Tui.Theming; using ChilliCream.Nitro.CommandLine.Tui.Widgets; @@ -8,8 +7,9 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Mail; /// -/// Renders the selected message or chronological thread in a scrollable detail -/// panel and maintains its scroll position. +/// Renders a mail thread's messages, oldest first, in a scrollable detail panel and +/// maintains its scroll position. Used by a host outside the Mail tab that has already +/// loaded a thread, such as the agent detail popover's mail drill-in. /// internal sealed class MailDetailView { @@ -31,10 +31,10 @@ internal sealed class MailDetailView private const int MaxIndicatorSettlePasses = 3; /// - /// The default when no client lookup is given, - /// resolving every name to no attribution. + /// The default when no harness lookup is given, resolving + /// every name to no attribution. /// - private static readonly IReadOnlyDictionary s_emptyClients = + private static readonly IReadOnlyDictionary s_emptyHarnesses = new Dictionary(); private readonly Viewport _bodyViewport = new(0, 0); @@ -50,30 +50,16 @@ internal sealed class MailDetailView public void ScrollUp() => _bodyViewport.ScrollBy(-1); /// - /// Scrolls the body to its first line. + /// Renders a thread's messages, oldest first, with the thread's subject as the header + /// and optional + /// attribution. A null lookup or an absent or empty harness entry adds no attribution. /// - public void ScrollToTop() => _bodyViewport.ScrollBy(int.MinValue / 2); - - /// - /// Scrolls the body to its last line. - /// - public void ScrollToBottom() => _bodyViewport.ScrollBy(int.MaxValue / 2); - - /// - /// Resets the body scroll position to the top. - /// - public void ResetScroll() => _bodyViewport.Update(0, 0); - - /// - /// Renders the selected message or thread with optional - /// attribution. A null lookup or an absent or empty client entry adds no attribution. - /// - public IRenderable Render( - MailState state, + public IRenderable RenderThread( + IReadOnlyList messages, int width, int height, bool focused, - IReadOnlyDictionary? clientsByName = null) + IReadOnlyDictionary? harnessesByName = null) { if (width <= 0 || height <= 0) { @@ -83,21 +69,19 @@ public IRenderable Render( var safeWidth = Math.Max(1, width); var interiorWidth = Math.Max(1, safeWidth - PanelChromeWidth); var interiorHeight = Math.Max(1, height - PanelChromeHeight); - var clients = clientsByName ?? s_emptyClients; + var harnesses = harnessesByName ?? s_emptyHarnesses; - var lines = state.ViewMode == MailViewMode.Thread - ? BuildThreadLines(state, interiorWidth, clients) - : BuildMessageLines(state, interiorWidth, clients); + var lines = BuildThreadLines(messages, interiorWidth, harnesses); IRenderable content = lines.Count == 0 - ? Align.Center(new Markup(Markup.Escape(NoMessageMessage(state))), VerticalAlignment.Middle) + ? Align.Center(new Markup(Markup.Escape("No messages.")), VerticalAlignment.Middle) : new Rows(RenderVisibleLines(lines, interiorHeight).Select(Row)); var borderToken = focused ? "board.column.border.focused" : "board.column.border"; return new Panel(content) { - Header = new PanelHeader(BuildHeader(state)), + Header = new PanelHeader(BuildThreadHeader(messages)), Border = BoxBorder.Rounded, BorderStyle = ThemeTokens.GetStyle(borderToken), Width = safeWidth, @@ -118,115 +102,29 @@ private static TaskDetailBodyLine SectionHeaderLine(string text) return new TaskDetailBodyLine(content, IsMarkup: true); } - /// - /// Returns a label-and-value line with the label styled as a detail section header. - /// - private static TaskDetailBodyLine FieldLine(string label, string value) - { - var style = ThemeTokens.GetStyle("detail.section.header").ToMarkup(); - var labelText = $"{label}:"; - var labelMarkup = style.Length == 0 ? labelText : $"[{style}]{labelText}[/]"; - return new TaskDetailBodyLine($"{labelMarkup} {Markup.Escape(value)}", IsMarkup: true); - } - - private static string BuildHeader(MailState state) - { - if (state.ViewMode == MailViewMode.Thread) - { - return state.ThreadMessages.Count > 0 - ? $"Thread: {Markup.Escape(state.ThreadMessages[0].Subject)}" - : "Thread"; - } - - return state.SelectedMessage is { } selected - ? $"[dim]{Markup.Escape(selected.Id)}[/] {Markup.Escape(selected.Subject)}" - : "Detail"; - } - - private static string NoMessageMessage(MailState state) - => state.Messages.Count == 0 ? "No messages." : "No message selected."; - - private static IReadOnlyList BuildMessageLines( - MailState state, int width, IReadOnlyDictionary clientsByName) - { - if (state.SelectedMessage is not { } message) - { - return []; - } - - var lines = new List - { - FieldLine("From", AttributeClient(message.Sender, clientsByName)), - FieldLine("To", string.Join(", ", RecipientNames(message, MailRecipientKinds.To))) - }; - - var cc = RecipientNames(message, MailRecipientKinds.Cc); - - if (cc.Count > 0) - { - lines.Add(FieldLine("Cc", string.Join(", ", cc))); - } - - lines.Add(FieldLine("Date", FormatTimestamp(message.CreatedAt))); - lines.AddRange(BuildRecipientStateLines(message, clientsByName)); - lines.Add(PlainLine(string.Empty)); - lines.AddRange(TaskDetailSections.WrapText(message.Body, width).Select(PlainLine)); - - return lines; - } + private static string BuildThreadHeader(IReadOnlyList messages) + => messages.Count > 0 ? $"Thread: {Markup.Escape(messages[0].Subject)}" : "Thread"; /// - /// Returns the name with a non-empty client attribution in parentheses, or the + /// Returns the name with a non-empty harness attribution in parentheses, or the /// name alone when no attribution is available. The returned text is unescaped. /// - private static string AttributeClient(string name, IReadOnlyDictionary clientsByName) - => clientsByName.TryGetValue(name, out var client) && client.Length > 0 - ? $"{name} ({client})" + private static string AttributeHarness(string name, IReadOnlyDictionary harnessesByName) + => harnessesByName.TryGetValue(name, out var harness) && harness.Length > 0 + ? $"{name} ({harness})" : name; - /// - /// Returns each recipient's read and archived state in recipient ordinal order, - /// with optional client attribution. - /// - private static IReadOnlyList BuildRecipientStateLines( - MailMessage message, IReadOnlyDictionary clientsByName) - => message.Recipients - .OrderBy(r => r.Ordinal) - .Select(r => FormatRecipientState(r, clientsByName)) - .ToList(); - - private static TaskDetailBodyLine FormatRecipientState( - MailRecipient recipient, IReadOnlyDictionary clientsByName) - { - var unread = recipient.ReadAt is null; - var state = recipient.ReadAt is { } readAt - ? $"read {FormatTimestamp(readAt)}" - : "unread"; - - var label = AttributeClient(recipient.Name, clientsByName); - var text = recipient.ArchivedAt is not null - ? $"{label}: {state}, archived" - : $"{label}: {state}"; - - var token = unread ? "mail.detail.recipient.unread" : "mail.detail.recipient.read"; - var style = ThemeTokens.GetStyle(token).ToMarkup(); - var escaped = Markup.Escape(text); - var content = style.Length == 0 ? escaped : $"[{style}]{escaped}[/]"; - - return new TaskDetailBodyLine(content, IsMarkup: true); - } - private static IReadOnlyList BuildThreadLines( - MailState state, int width, IReadOnlyDictionary clientsByName) + IReadOnlyList messages, int width, IReadOnlyDictionary harnessesByName) { - if (state.ThreadMessages.Count == 0) + if (messages.Count == 0) { return []; } var lines = new List(); - for (var i = 0; i < state.ThreadMessages.Count; i++) + for (var i = 0; i < messages.Count; i++) { if (i > 0) { @@ -234,22 +132,15 @@ private static IReadOnlyList BuildThreadLines( lines.Add(PlainLine(new string('-', Math.Clamp(width, 1, 40)))); } - var message = state.ThreadMessages[i]; + var message = messages[i]; lines.Add(SectionHeaderLine( - $"{AttributeClient(message.Sender, clientsByName)} - {FormatTimestamp(message.CreatedAt)}")); + $"{AttributeHarness(message.Sender, harnessesByName)} - {FormatTimestamp(message.CreatedAt)}")); lines.AddRange(TaskDetailSections.WrapText(message.Body, width).Select(PlainLine)); } return lines; } - private static IReadOnlyList RecipientNames(MailMessage message, string kind) - => message.Recipients - .Where(r => r.Kind == kind) - .OrderBy(r => r.Ordinal) - .Select(r => r.Name) - .ToList(); - private static string FormatTimestamp(DateTimeOffset value) => value.ToUniversalTime().ToString("yyyy-MM-dd HH:mm"); diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDiscardTarget.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDiscardTarget.cs deleted file mode 100644 index e3efa7bc28b..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailDiscardTarget.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// Which form a 's active discard confirmation -/// applies to. -/// -internal enum MailDiscardTarget -{ - Compose, - Reply -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailFocus.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailFocus.cs deleted file mode 100644 index f9880aa967a..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailFocus.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// Which pane of the mail board currently holds focus. -/// -internal enum MailFocus -{ - List, - Detail -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailKeyMap.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailKeyMap.cs index b883f8bed17..e17f1f0b6fd 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailKeyMap.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailKeyMap.cs @@ -4,31 +4,11 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Mail; /// -/// Builds the mail tab's key bindings for navigation, mailbox and view selection, -/// message actions, and exit requests. +/// Builds the Mail tab's key bindings for navigation, the agent filter picker, search, +/// and exit requests. Bound only to this tab, not the global key table. /// internal static class MailKeyMap { - /// - /// The read/unread footer hint, hidden when mail actions are read-only. - /// - public static readonly KeyHint ToggleReadHint = new("u", "read/unread"); - - /// - /// The footer hint for the a chord; see . - /// - public static readonly KeyHint ArchiveHint = new("a", "archive"); - - /// - /// The footer hint for the r chord; see . - /// - public static readonly KeyHint ReplyHint = new("r", "reply"); - - /// - /// The footer hint for the c chord; see . - /// - public static readonly KeyHint ComposeHint = new("c", "compose"); - public static KeyMap CreateDefault() => new( [ new KeyBinding( @@ -44,22 +24,6 @@ internal static class MailKeyMap new KeyBinding( new KeyChord(ConsoleKey.UpArrow, ConsoleModifiers.None, '\0'), () => new TuiMessage.MoveCursor(CursorDirection.Up)), - new KeyBinding( - new KeyChord(ConsoleKey.H, ConsoleModifiers.None, 'h'), - () => new TuiMessage.MoveCursor(CursorDirection.Left)), - new KeyBinding( - new KeyChord(ConsoleKey.LeftArrow, ConsoleModifiers.None, '\0'), - () => new TuiMessage.MoveCursor(CursorDirection.Left)), - new KeyBinding( - new KeyChord(ConsoleKey.L, ConsoleModifiers.None, 'l'), - () => new TuiMessage.MoveCursor(CursorDirection.Right)), - new KeyBinding( - new KeyChord(ConsoleKey.RightArrow, ConsoleModifiers.None, '\0'), - () => new TuiMessage.MoveCursor(CursorDirection.Right)), - new KeyBinding( - new KeyChord(ConsoleKey.Tab, ConsoleModifiers.None, '\t'), - () => new TuiMessage.MoveCursor(CursorDirection.Right), - new KeyHint("tab", "switch pane")), new KeyBinding( new KeyChord(ConsoleKey.G, ConsoleModifiers.None, 'g'), () => new TuiMessage.MoveToEdge(EdgeTarget.Top)), @@ -69,72 +33,28 @@ internal static class MailKeyMap new KeyBinding( new KeyChord(ConsoleKey.Enter, ConsoleModifiers.None, '\r'), () => new TuiMessage.OpenSelected(), - new KeyHint("enter", "focus detail")), - new KeyBinding( - new KeyChord(ConsoleKey.U, ConsoleModifiers.None, 'u'), - () => new TuiMessage.ToggleReadRequested(), - ToggleReadHint), - new KeyBinding( - new KeyChord(ConsoleKey.A, ConsoleModifiers.None, 'a'), - () => new TuiMessage.ArchiveRequested(), - ArchiveHint), - new KeyBinding( - new KeyChord(ConsoleKey.R, ConsoleModifiers.None, 'r'), - () => new TuiMessage.ReplyRequested(), - ReplyHint), - new KeyBinding( - new KeyChord(ConsoleKey.C, ConsoleModifiers.None, 'c'), - () => new TuiMessage.ComposeRequested(), - ComposeHint), - new KeyBinding( - new KeyChord(ConsoleKey.R, ConsoleModifiers.Shift, 'R'), - () => new TuiMessage.RefreshRequested()), - new KeyBinding( - new KeyChord(ConsoleKey.Y, ConsoleModifiers.None, 'y'), - () => new TuiMessage.CopySelectedId(), - new KeyHint("y", "copy id")), - new KeyBinding( - new KeyChord(ConsoleKey.F, ConsoleModifiers.None, 'f'), - () => new TuiMessage.CycleView(1), - new KeyHint("f", "filter")), - new KeyBinding( - new KeyChord(ConsoleKey.F, ConsoleModifiers.Shift, 'F'), - () => new TuiMessage.CycleView(-1)), - new KeyBinding( - new KeyChord(ConsoleKey.T, ConsoleModifiers.None, 't'), - () => new TuiMessage.ToggleMaximize(), - new KeyHint("t", "thread")), - new KeyBinding( - new KeyChord(ConsoleKey.V, ConsoleModifiers.Shift, 'V'), - () => new TuiMessage.ToggleListModeRequested(), - new KeyHint("V", "flat/threads")), - new KeyBinding( - new KeyChord(ConsoleKey.Z, ConsoleModifiers.None, 'z'), - () => new TuiMessage.FoldPrefixRequested(), - new KeyHint("za/zo/zc/zR/zM", "fold")), + new KeyHint("enter", "open")), new KeyBinding( new KeyChord(ConsoleKey.P, ConsoleModifiers.None, 'p'), () => new TuiMessage.AgentFilterPickerRequested(), new KeyHint("p", "filter agent")), new KeyBinding( - new KeyChord(ConsoleKey.I, ConsoleModifiers.Shift, 'I'), - () => new TuiMessage.SelectInboxRequested(), - new KeyHint("I", "inbox")), + new KeyChord(ConsoleKey.Oem2, ConsoleModifiers.None, '/'), + () => new TuiMessage.SearchRequested(), + new KeyHint("/", "search")), new KeyBinding( - new KeyChord(ConsoleKey.S, ConsoleModifiers.Shift, 'S'), - () => new TuiMessage.SelectSentRequested(), - new KeyHint("S/L/W", "sent/all/workspace")), - new KeyBinding( - new KeyChord(ConsoleKey.L, ConsoleModifiers.Shift, 'L'), - () => new TuiMessage.SelectAllMailRequested()), + new KeyChord(ConsoleKey.Y, ConsoleModifiers.None, 'y'), + () => new TuiMessage.CopySelectedId(), + new KeyHint("y", "copy id")), new KeyBinding( - new KeyChord(ConsoleKey.W, ConsoleModifiers.Shift, 'W'), - () => new TuiMessage.SelectWorkspaceMailRequested()), + new KeyChord(ConsoleKey.R, ConsoleModifiers.None, 'r'), + () => new TuiMessage.RefreshRequested(), + new KeyHint("r", "refresh")), new KeyBinding( - new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, ''), + new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, '\u0003'), () => new TuiMessage.QuitRequested()), new KeyBinding( - new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, ''), + new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, '\u001b'), () => new TuiMessage.Back(), new KeyHint("esc", "back")), new KeyBinding( diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailLifecycleActions.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailLifecycleActions.cs deleted file mode 100644 index ac65780749f..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailLifecycleActions.cs +++ /dev/null @@ -1,104 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Editing; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// Applies read-state and archive changes and builds archive confirmations. -/// Store rejections represented by become failed outcomes. -/// -internal static class MailLifecycleActions -{ - /// - /// The refusal toast for writes attempted in the Workspace mailbox. - /// - public const string WorkspaceReadOnlyMessage = - "Workspace is read-only. Press Shift+I for Inbox to make changes."; - - /// - /// Whether refuses every mutating gesture - /// under : always when it is null, and - /// otherwise when is . - /// - public static bool IsReadOnly(MailMailbox mailbox, string? actor) - => actor is null || mailbox == MailMailbox.Workspace; - - /// - /// Builds the confirmation dialog for archiving . - /// - public static ConfirmDialog CreateArchiveDialog(MailMessage message) - => new($"Archive message '{message.Id}': \"{message.Subject}\"?", "Archive"); - - /// - /// Marks read for . - /// - public static async Task MarkReadAsync( - IMailStore store, - MailMessage message, - string actor, - CancellationToken cancellationToken) - { - try - { - await store.MarkReadAsync([message.Id], actor, cancellationToken).ConfigureAwait(false); - return new MailActionOutcome.Succeeded(MailAction.MarkRead, $"Marked '{message.Id}' read."); - } - catch (ExitException ex) - { - return new MailActionOutcome.Failed(MailAction.MarkRead, ex.Message); - } - } - - /// - /// Marks unread for . - /// - public static async Task MarkUnreadAsync( - IMailStore store, - MailMessage message, - string actor, - CancellationToken cancellationToken) - { - try - { - await store.MarkUnreadAsync([message.Id], actor, cancellationToken).ConfigureAwait(false); - return new MailActionOutcome.Succeeded(MailAction.MarkUnread, $"Marked '{message.Id}' unread."); - } - catch (ExitException ex) - { - return new MailActionOutcome.Failed(MailAction.MarkUnread, ex.Message); - } - } - - /// - /// Marks an unread recipient copy read, or marks it unread otherwise. - /// The store rejects an actor who is not a recipient. - /// - public static Task ToggleReadAsync( - IMailStore store, - MailMessage message, - string actor, - CancellationToken cancellationToken) - => MailRecipientView.IsUnread(message, actor) - ? MarkReadAsync(store, message, actor, cancellationToken) - : MarkUnreadAsync(store, message, actor, cancellationToken); - - /// - /// Archives for . - /// - public static async Task ArchiveAsync( - IMailStore store, - MailMessage message, - string actor, - CancellationToken cancellationToken) - { - try - { - await store.ArchiveAsync([message.Id], actor, cancellationToken).ConfigureAwait(false); - return new MailActionOutcome.Succeeded(MailAction.Archive, $"Archived '{message.Id}'."); - } - catch (ExitException ex) - { - return new MailActionOutcome.Failed(MailAction.Archive, ex.Message); - } - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListFilter.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListFilter.cs deleted file mode 100644 index d9844dd9a82..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListFilter.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// The inbox filter the mail board's list pane cycles through. -/// -internal enum MailListFilter -{ - Inbox, - Unread, - Archived -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListMode.cs deleted file mode 100644 index 2ab05b27b93..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListMode.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// The list shape: thread summaries or a flat message list. -/// -internal enum MailListMode -{ - Threads, - Flat -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListRow.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListRow.cs deleted file mode 100644 index bad5e102b15..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailListRow.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// One row of : either a collapsed or expanded -/// thread rollup, or a message - a flat-mode row ( -/// false) or one of an expanded thread's indented children (true). -/// -internal abstract record MailListRow -{ - private MailListRow() - { - } - - /// - /// A thread rollup row. mirrors whether - /// the thread's messages follow as indented - /// rows immediately after this one in . - /// - public sealed record Thread(MailThreadSummary Summary, bool Expanded) : MailListRow; - - /// - /// A message row, indented beneath its thread when ThreadChild is true, - /// or shown in the flat list otherwise. - /// - public sealed record MessageRow(MailMessage Message, bool ThreadChild) : MailListRow; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMailbox.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMailbox.cs deleted file mode 100644 index 636c8fa7d10..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMailbox.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// The message collection displayed by the mail board. -/// -internal enum MailMailbox -{ - /// - /// Messages addressed to the actor, filtered by . - /// - Inbox, - - /// - /// Messages the actor sent, regardless of recipient. - /// - Sent, - - /// - /// Every message the actor sent or received. - /// - All, - - /// - /// Every message in the workspace, across every agent. - /// - Workspace -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMailboxExtensions.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMailboxExtensions.cs deleted file mode 100644 index e4b18c5cc76..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMailboxExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// Display metadata for . -/// -internal static class MailMailboxExtensions -{ - /// - /// The mailbox's display name, shown in the mail board's list header. - /// - public static string DisplayName(this MailMailbox mailbox) => mailbox switch - { - MailMailbox.Sent => "Sent", - MailMailbox.All => "All", - MailMailbox.Workspace => "Workspace", - _ => "Inbox" - }; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMode.cs index c4b0c075b43..959a2abf075 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMode.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailMode.cs @@ -1,979 +1,260 @@ -using System.Collections.Concurrent; -using System.Threading.Channels; using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; using ChilliCream.Nitro.CommandLine.Tui.Editing; using ChilliCream.Nitro.CommandLine.Tui.Input; -using ChilliCream.Nitro.CommandLine.Tui.Runtime; using ChilliCream.Nitro.CommandLine.Tui.Shell; -using ChilliCream.Nitro.CommandLine.Tui.Theming; using ChilliCream.Nitro.CommandLine.Tui.Widgets; using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; using Spectre.Console.Rendering; -using ConfirmDialog = ChilliCream.Nitro.CommandLine.Tui.Editing.ConfirmDialog; using CursorDirection = ChilliCream.Nitro.CommandLine.Tui.Input.CursorDirection; namespace ChilliCream.Nitro.CommandLine.Tui.Mail; /// -/// Displays mailboxes as thread or message lists with a detail pane. -/// Supports composing, replying, and recipient-state changes when the board has -/// an acting agent and the selected mailbox is writable. +/// Displays every thread in the workspace as one read-only, full-width table: subject, +/// from, to, message count, and last-activity columns. The board has no acting agent, so +/// every mail write (compose, reply, read/unread, archive) is unavailable here; Enter opens +/// the selected thread in a read-only popover instead. /// internal sealed class MailMode : ITuiMode, IRawKeyCapturingMode { - /// - /// Border and padding columns the list pane's panel spends on either - /// side of its content. - /// private const int PanelChromeWidth = 4; - - /// - /// Border rows the list pane's panel spends above and below its - /// content; the header is drawn on the top border row. - /// private const int PanelChromeHeight = 2; - - /// - /// The maximum number of passes used to reserve viewport indicator rows. - /// private const int MaxIndicatorSettlePasses = 3; + private const int HeaderLineCount = TableRenderer.TopBlockLineCount; - /// - /// The fraction of the frame width the list pane occupies; the detail - /// pane takes the remainder. - /// - private const int ListWidthNumerator = 3; - private const int ListWidthDenominator = 5; + private const string EmptyStateMessage = "No mail yet."; /// - /// The for the agent filter picker's "all agents" entry, - /// which clears rather than naming an agent. + /// The for the agent filter picker's "all agents" + /// entry, which clears rather than naming an agent. /// private const string AllAgentsOptionId = ""; - /// - /// The toast shown when the agent filter picker is requested outside - /// , where the filter has no effect. - /// - private const string AgentFilterRequiresWorkspaceMessage = - "Agent filter only applies to Workspace. Press Shift+W for Workspace."; - - /// - /// The toast shown when a fold gesture (z-prefix) is requested while - /// is , - /// where there is nothing to fold. - /// - private const string FoldRequiresThreadsMessage = - "Fold only applies to threaded view. Press Shift+V for threaded view."; - - /// - /// The dedupe key every - /// compose and reply submission shares: only one send may be in flight - /// at a time, regardless of which form it came from. - /// - private const string SendDedupeKey = "mail.send"; - - private const string SendingToastText = "Sendingโ€ฆ"; - private const string SendInFlightToastText = "A message is already sending. Try again shortly."; - - /// - /// Shown for a or - /// completion. - /// States the commit's outcome as unknown rather than asserting the - /// message was not stored. - /// - private const string SendOutcomeUnknownToastText = "Sending did not complete. The message's outcome is unknown."; - - /// - /// The shown while the fold prefix (z) is - /// pending its second key. - /// - private static readonly KeyHint[] s_foldPrefixHints = - [ - new("a/o/c", "toggle/open/close thread"), - new("R/M", "unfold/fold all") - ]; - - /// - /// The footer hints hides while - /// is active. - /// - private static readonly KeyHint[] s_workspaceReadOnlyHints = - [ - MailKeyMap.ToggleReadHint, - MailKeyMap.ArchiveHint, - MailKeyMap.ReplyHint, - MailKeyMap.ComposeHint - ]; - - private readonly IMailStore _store; - private readonly IAgentRegistry _agentRegistry; - private readonly MailState _state; - private readonly MailDetailView _detailView = new(); + private readonly IMailStore _mailStore; + private readonly IAgentStore _agentStore; private readonly TimeProvider _timeProvider; - private readonly CancellationToken _effectCancellationToken; + private readonly MailState _state; private readonly Viewport _listViewport = new(0, 0); - /// - /// Runs asynchronous compose and reply writes with wake intent for - /// . At most one send is in flight at a time. - /// - private readonly TuiEffectQueue _sendEffects = new(); - - /// - /// Store-commit notices awaiting display before the final send outcome is drained. - /// - private readonly ConcurrentQueue _storedNotices = new(); - - /// - /// Completions retained by the quit gate for processing on the next - /// call. - /// - private readonly List> _deferredCompletions = []; - - /// - /// Every registered agent's , keyed by - /// name (case-insensitively), loaded once per . - /// - private IReadOnlyDictionary _clientsByName = - new Dictionary(StringComparer.OrdinalIgnoreCase); - - private ConfirmDialog? _archiveDialog; - private MailMessage? _archiveTarget; - private MailComposeForm? _composeForm; - private MailReplyForm? _replyForm; - private MailComposeForm? _submittedComposeForm; - private MailReplyForm? _submittedReplyForm; - private ConfirmDialog? _discardDialog; - private MailDiscardTarget _discardTarget; + private MailSearchForm? _searchForm; private QuickPicker? _agentPicker; - private bool _foldPrefixPending; - /// - /// Builds a mail board over for . - /// - /// The mail store every read and write goes through. - /// - /// The acting agent, or null when the board has no identity: only - /// is then reachable, and every - /// write is refused. - /// - /// Resolves every registered agent's client attribution. - /// Defaults to . - /// - /// Passed to submitted effects; the current send and reply effects do not use it - /// to cancel their store writes. - /// - public MailMode( - IMailStore store, - string? actor, - IAgentRegistry agentRegistry, - TimeProvider? timeProvider = null, - CancellationToken effectCancellationToken = default) + public MailMode(IMailStore store, IAgentStore agentStore, TimeProvider? timeProvider = null) { ArgumentNullException.ThrowIfNull(store); - ArgumentNullException.ThrowIfNull(agentRegistry); + ArgumentNullException.ThrowIfNull(agentStore); - _store = store; - _agentRegistry = agentRegistry; - _state = new MailState(actor, new MailDataLoader(store)); + _mailStore = store; + _agentStore = agentStore; _timeProvider = timeProvider ?? TimeProvider.System; - _effectCancellationToken = effectCancellationToken; + _state = new MailState(new MailDataLoader(store)); } /// - /// The board's current live state: messages, filter, selection, and - /// focus. + /// The board's current live state: the loaded threads, filters, and selection. /// public MailState State => _state; - /// - /// The actor used to render read state: an empty name without an - /// identity, which matches no recipient, so nothing renders as - /// addressed to me. - /// - private string RenderActor => _state.Actor ?? string.Empty; - - /// - /// The acting agent for writes; throws when no identity is available. - /// - private string WritingActor - => _state.Actor ?? throw new InvalidOperationException("The board has no agent identity."); + /// + public KeyMap? KeyMap => null; - /// - /// Whether an overlay or pending fold prefix consumes raw key input. - /// - public bool IsInputCapturing - => _archiveDialog is not null - || _composeForm is not null - || _replyForm is not null - || _discardDialog is not null - || _agentPicker is not null - || _foldPrefixPending; + /// + public bool IsInputCapturing => _searchForm is not null || _agentPicker is not null; /// public IReadOnlyList CapturingHints - => _discardDialog is not null ? ConfirmDialog.Hints - : _archiveDialog is not null ? ConfirmDialog.Hints - : _composeForm is not null ? MailComposeForm.Hints - : _replyForm is not null ? MailReplyForm.Hints + => _searchForm is not null ? MailSearchForm.Hints : _agentPicker is not null ? QuickPicker.Hints - : _foldPrefixPending ? s_foldPrefixHints : []; - /// - /// The number of unread, unarchived messages addressed to the actor at the last - /// refresh, or zero without an acting agent. - /// - public int UnreadCount { get; private set; } - - /// - public KeyMap? KeyMap => null; - - /// - /// - /// Hides the u, a, r, and c hints from the footer while - /// is true for . - /// - public IReadOnlyCollection SuppressedGlobalHints - => MailLifecycleActions.IsReadOnly(_state.Mailbox, _state.Actor) ? s_workspaceReadOnlyHints : []; - /// public void OnEnter() => RefreshBlocking(); /// public void OnResize(int width, int height) { - // Layout is recomputed during rendering. + // Layout and viewport state are recomputed from Render's parameters every frame. } /// - /// - /// Drains send outcomes before handling the message. - /// - public IReadOnlyList Handle(TuiMessage message) - { - var completions = DrainEffectQueue(); - var handled = HandleCore(message); - return completions.Count == 0 ? handled : [.. completions, .. handled]; - } - - private IReadOnlyList HandleCore(TuiMessage message) => message switch - { - TuiMessage.MoveCursor(CursorDirection.Up) => MoveOrScroll(-1), - TuiMessage.MoveCursor(CursorDirection.Down) => MoveOrScroll(1), - TuiMessage.MoveCursor(CursorDirection.Left) => TogglePane(), - TuiMessage.MoveCursor(CursorDirection.Right) => TogglePane(), - TuiMessage.MoveToEdge(var edge) => MoveOrScrollToEdge(edge), - TuiMessage.OpenSelected => FocusDetail(), + public IReadOnlyList Handle(TuiMessage message) => message switch + { + TuiMessage.MoveCursor(CursorDirection.Up) => Move(-1), + TuiMessage.MoveCursor(CursorDirection.Down) => Move(1), + TuiMessage.MoveToEdge(var edge) => MoveToEdge(edge), + // Reached only when TryCreatePopover found no selected thread to open: the shell falls + // back to dispatching OpenSelected here for the no-selection toast. + TuiMessage.OpenSelected => OpenSelectedFallback(), TuiMessage.RefreshRequested => Refresh(), - TuiMessage.CycleView(var delta) => CycleFilter(delta), - TuiMessage.ToggleMaximize => ToggleThreadView(), TuiMessage.CopySelectedId => CopySelectedId(), - TuiMessage.ToggleReadRequested => ToggleRead(), - TuiMessage.ArchiveRequested => OpenArchiveDialog(), - TuiMessage.ComposeRequested => OpenComposeForm(), - TuiMessage.ReplyRequested => OpenReplyForm(), - TuiMessage.SelectInboxRequested => SelectMailbox(MailMailbox.Inbox), - TuiMessage.SelectSentRequested => SelectMailbox(MailMailbox.Sent), - TuiMessage.SelectAllMailRequested => SelectMailbox(MailMailbox.All), - TuiMessage.SelectWorkspaceMailRequested => SelectMailbox(MailMailbox.Workspace), + TuiMessage.SearchRequested => OpenSearchForm(), TuiMessage.AgentFilterPickerRequested => OpenAgentFilterPicker(), - TuiMessage.ToggleListModeRequested => ToggleListMode(), - TuiMessage.FoldPrefixRequested => OpenFoldPrefix(), - // Already turned into a toast by the drain in Handle. - TuiMessage.EffectCompleted => [], _ => [] }; - /// - /// Handles one raw key while is true, routed - /// here by the host instead of through the semantic dispatch. - /// - public IReadOnlyList HandleRawKey(ConsoleKeyInfo info) - { - if (_discardDialog is not null) - { - return HandleDiscardDialogKey(info); - } - - if (_archiveDialog is not null) - { - return HandleArchiveDialogKey(info); - } - - if (_composeForm is not null) - { - return HandleComposeFormKey(info); - } - - if (_replyForm is not null) - { - return HandleReplyFormKey(info); - } - - if (_agentPicker is not null) - { - return HandleAgentPickerKey(info); - } - - if (_foldPrefixPending) - { - return HandleFoldPrefixKey(info); - } - - return []; - } - /// - public IRenderable Render(int width, int height) + public IPopover? TryCreatePopover() { - if (width <= 0 || height <= 0) - { - return new Markup(string.Empty); - } - - if (_discardDialog is { } discardDialog) - { - return discardDialog.Render(width, height); - } - - if (_archiveDialog is { } archiveDialog) - { - return archiveDialog.Render(width, height); - } - - if (_composeForm is { } composeForm) - { - return composeForm.Render(width, height); - } - - if (_replyForm is { } replyForm) - { - return replyForm.Render(width, height); - } - - if (_agentPicker is { } agentPicker) + if (_state.SelectedThread is not { } thread) { - return agentPicker.Render(width, height); + return null; } - var listWidth = Math.Max(1, width * ListWidthNumerator / ListWidthDenominator); - var detailWidth = Math.Max(1, width - listWidth); - - return new Layout("mail").SplitColumns( - new Layout("list", RenderListPane(listWidth, height)).Size(listWidth), - new Layout("detail", RenderDetailPane(detailWidth, height))); + return new MailThreadPopoverModel(thread.ThreadId, _mailStore, _agentStore, _timeProvider, MoveSelection); } /// - /// Up/Down moves the list selection while the list has focus, or - /// scrolls the detail body while the detail pane has focus. + /// Moves the table selection rows away from the current one and + /// returns the thread landed on, or null at the first or last thread. /// - private IReadOnlyList MoveOrScroll(int delta) + private MailThreadSummary? MoveSelection(int delta) { - if (_state.Focus == MailFocus.List) - { - if (_state.Rows.Count > 0) - { - _state.SelectedRow = Math.Clamp(_state.SelectedRow + delta, 0, _state.Rows.Count - 1); - } - } - else if (delta > 0) - { - _detailView.ScrollDown(); - } - else - { - _detailView.ScrollUp(); - } - - return []; - } + var next = _state.SelectedRow + delta; - private IReadOnlyList MoveOrScrollToEdge(EdgeTarget edge) - { - if (_state.Focus == MailFocus.List) - { - if (_state.Rows.Count > 0) - { - _state.SelectedRow = edge == EdgeTarget.Top ? 0 : _state.Rows.Count - 1; - } - } - else if (edge == EdgeTarget.Top) - { - _detailView.ScrollToTop(); - } - else + if (next < 0 || next >= _state.Threads.Count) { - _detailView.ScrollToBottom(); + return null; } - return []; - } - - /// - /// Toggles focus between the list and detail panes. - /// - private IReadOnlyList TogglePane() - { - _state.Focus = _state.Focus == MailFocus.List ? MailFocus.Detail : MailFocus.List; - return _state.Focus == MailFocus.Detail ? MaybeMarkSelectedRead() : []; + _state.SelectedRow = next; + return _state.Threads[next]; } - private IReadOnlyList FocusDetail() - { - _state.Focus = MailFocus.Detail; - return MaybeMarkSelectedRead(); - } - - /// - /// Marks the selected unread message read when focusing its detail pane, unless - /// the mailbox is read-only. Returns a toast only when the write fails. - /// - private IReadOnlyList MaybeMarkSelectedRead() + /// + public IReadOnlyList HandlePopoverRequest(PopoverResult.Request request) => request.Payload switch { - if (MailLifecycleActions.IsReadOnly(_state.Mailbox, _state.Actor)) - { - return []; - } - - if (_state.SelectedMessage is not { } message || !MailRecipientView.IsUnread(message, WritingActor)) - { - return []; - } - - var outcome = MailLifecycleActions.MarkReadAsync(_store, message, WritingActor, CancellationToken.None) - .GetAwaiter().GetResult(); - - RefreshBlocking(); - - return outcome is MailActionOutcome.Failed ? [outcome.ToShowToast()] : []; - } + MailThreadPopoverRequest.CopyRequested copyRequested => + [new TuiMessage.ShowToast(copyRequested.ThreadId, ToastStyle.Info)], + _ => [] + }; /// - /// Toggles the selected message between read and unread for the actor. - /// Refused with a toast, rather than reaching the store, when - /// or when the actor has - /// no recipient row on the message. + /// Handles one raw key while is true, routed here by + /// the host instead of through the semantic dispatch. /// - private IReadOnlyList ToggleRead() - { - if (RefuseIfReadOnly() is { } refused) - { - return refused; - } - - if (_state.SelectedMessage is not { } message) - { - return [new TuiMessage.ShowToast("No message selected.", ToastStyle.Warn)]; - } - - if (MailRecipientView.FindRecipient(message, WritingActor) is null) - { - return [new TuiMessage.ShowToast(NotARecipientMessage(message), ToastStyle.Warn)]; - } - - var outcome = MailLifecycleActions.ToggleReadAsync(_store, message, WritingActor, CancellationToken.None) - .GetAwaiter().GetResult(); - - RefreshBlocking(); - - return [outcome.ToShowToast()]; - } + public IReadOnlyList HandleRawKey(ConsoleKeyInfo info) + => _searchForm is not null ? HandleSearchFormKey(info) + : _agentPicker is not null ? HandleAgentPickerKey(info) + : []; - /// - /// Opens the archive confirmation for the selected message. Refused - /// with a toast, rather than reaching the store, when - /// or when the actor has - /// no recipient row on the message; see . - /// - private IReadOnlyList OpenArchiveDialog() + /// + public IRenderable Render(int width, int height) { - if (RefuseIfReadOnly() is { } refused) - { - return refused; - } - - if (_state.SelectedMessage is not { } message) + if (width <= 0 || height <= 0) { - return [new TuiMessage.ShowToast("No message selected.", ToastStyle.Warn)]; + return new Markup(string.Empty); } - if (MailRecipientView.FindRecipient(message, WritingActor) is null) + if (_searchForm is { } searchForm) { - return [new TuiMessage.ShowToast(NotARecipientMessage(message), ToastStyle.Warn)]; + return searchForm.Render(width, height); } - _archiveTarget = message; - _archiveDialog = MailLifecycleActions.CreateArchiveDialog(message); - return []; - } - - private static string NotARecipientMessage(MailMessage message) - => $"'{message.Id}' has no read/unread or archive state here."; - - /// - /// Opens the compose form, or returns a refusal toast when the mailbox is read-only. - /// - private IReadOnlyList OpenComposeForm() - { - if (RefuseIfReadOnly() is { } refused) + if (_agentPicker is { } agentPicker) { - return refused; + return agentPicker.Render(width, height); } - _composeForm = new MailComposeForm(); - return []; + return RenderListPane(width, height); } - /// - /// Opens the reply form for the selected message. Refused the same as - /// every other mutating gesture when . - /// - private IReadOnlyList OpenReplyForm() + private IReadOnlyList Move(int delta) { - if (RefuseIfReadOnly() is { } refused) - { - return refused; - } - - if (_state.SelectedMessage is not { } message) + if (_state.Threads.Count > 0) { - return [new TuiMessage.ShowToast("No message selected.", ToastStyle.Warn)]; + _state.SelectedRow = Math.Clamp(_state.SelectedRow + delta, 0, _state.Threads.Count - 1); } - _replyForm = new MailReplyForm(message); return []; } - /// - /// Returns a refusal toast when the current mailbox is read-only, or null when - /// a write may proceed. - /// - private IReadOnlyList? RefuseIfReadOnly() + private IReadOnlyList MoveToEdge(EdgeTarget edge) { - if (_state.Actor is null) + if (_state.Threads.Count > 0) { - return [new TuiMessage.ShowToast(BoardIdentity.NoIdentityMessage, ToastStyle.Warn)]; + _state.SelectedRow = edge == EdgeTarget.Top ? 0 : _state.Threads.Count - 1; } - return MailLifecycleActions.IsReadOnly(_state.Mailbox, _state.Actor) - ? [new TuiMessage.ShowToast(MailLifecycleActions.WorkspaceReadOnlyMessage, ToastStyle.Warn)] - : null; - } - - private IReadOnlyList HandleArchiveDialogKey(ConsoleKeyInfo info) - { - var result = _archiveDialog!.HandleKey(info); - - return result switch - { - null => [], - ConfirmDialogResult.Cancelled => CancelArchiveDialog(), - ConfirmDialogResult.Confirmed => SubmitArchive(), - _ => [] - }; - } - - private IReadOnlyList CancelArchiveDialog() - { - _archiveDialog = null; - _archiveTarget = null; return []; } - private IReadOnlyList SubmitArchive() + private IReadOnlyList Refresh() { - var target = _archiveTarget!; - _archiveDialog = null; - _archiveTarget = null; - - var outcome = MailLifecycleActions.ArchiveAsync(_store, target, WritingActor, CancellationToken.None) - .GetAwaiter().GetResult(); - RefreshBlocking(); - - return [outcome.ToShowToast()]; - } - - private IReadOnlyList HandleComposeFormKey(ConsoleKeyInfo info) - { - var result = _composeForm!.HandleKey(info); - - return result switch - { - null => [], - FormResult.Cancelled => TryDiscardCompose(), - FormResult.ButtonActivated { ButtonId: MailComposeForm.CancelButtonId } => TryDiscardCompose(), - FormResult.Submitted submitted => SubmitCompose(submitted), - _ => [] - }; - } - - private IReadOnlyList TryDiscardCompose() - { - if (_composeForm!.IsDirty) - { - _discardTarget = MailDiscardTarget.Compose; - _discardDialog = CreateDiscardDialog(); - return []; - } - - _composeForm = null; - return []; - } - - /// - /// Submits the compose values for an asynchronous store write, retaining the form - /// until the outcome is known. A refused submission leaves the form open. - /// - private IReadOnlyList SubmitCompose(FormResult.Submitted submitted) - { - var creation = MailComposeForm.BuildCreation(submitted.Values, WritingActor); - - if (!_sendEffects.TrySubmit( - SendDedupeKey, (_, ct) => RunSendEffectAsync(creation, ct), _effectCancellationToken, out _)) - { - return [new TuiMessage.ShowToast(SendInFlightToastText, ToastStyle.Warn)]; - } - - _submittedComposeForm = _composeForm; - _composeForm = null; - return [new TuiMessage.ShowToast(SendingToastText, ToastStyle.Info)]; - } - - private IReadOnlyList HandleReplyFormKey(ConsoleKeyInfo info) - { - var result = _replyForm!.HandleKey(info); - - return result switch - { - null => [], - FormResult.Cancelled => TryDiscardReply(), - FormResult.ButtonActivated { ButtonId: MailReplyForm.CancelButtonId } => TryDiscardReply(), - FormResult.Submitted submitted => SubmitReply(submitted), - _ => [] - }; - } - - private IReadOnlyList TryDiscardReply() - { - if (_replyForm!.IsDirty) - { - _discardTarget = MailDiscardTarget.Reply; - _discardDialog = CreateDiscardDialog(); - return []; - } - - _replyForm = null; return []; } - /// - /// Submits the reply values for an asynchronous store write using the shared send - /// submission slot, retaining the form until the outcome is known. - /// - private IReadOnlyList SubmitReply(FormResult.Submitted submitted) + private IReadOnlyList CopySelectedId() { - var request = _replyForm!.BuildRequest(submitted.Values, WritingActor); - - if (!_sendEffects.TrySubmit( - SendDedupeKey, (_, ct) => RunReplyEffectAsync(request, ct), _effectCancellationToken, out _)) + if (_state.SelectedThread is not { } thread) { - return [new TuiMessage.ShowToast(SendInFlightToastText, ToastStyle.Warn)]; + return [new TuiMessage.ShowToast("No thread selected.", ToastStyle.Warn)]; } - _submittedReplyForm = _replyForm; - _replyForm = null; - return [new TuiMessage.ShowToast(SendingToastText, ToastStyle.Info)]; + return [new TuiMessage.ShowToast(thread.ThreadId, ToastStyle.Info)]; } /// - /// Stores the message and enqueues wake intent without cancellation, then posts a - /// stored notice and returns success. Converts to a - /// failed outcome; other exceptions propagate to the effect queue. + /// Reports the no-selection toast the shell shows when + /// found no thread to open; a no-op when a thread is selected (the popover already opened). /// - private async Task RunSendEffectAsync( - MailMessageCreation creation, CancellationToken _) - { - MailMessage message; + private IReadOnlyList OpenSelectedFallback() => + _state.SelectedThread is null + ? [new TuiMessage.ShowToast("No thread selected.", ToastStyle.Warn)] + : []; - try - { - message = await _store.SendMessageAsync(creation, CancellationToken.None).ConfigureAwait(false); - } - catch (ExitException ex) - { - return new MailSendOutcome.Failed(ex.Message); - } - - _storedNotices.Enqueue(new MailSendOutcome.Stored(message)); - _sendEffects.SignalWake(); - return new MailSendOutcome.Succeeded(message); - } - - /// - /// The reply form's counterpart to . - /// - private async Task RunReplyEffectAsync( - MailReplyRequest request, CancellationToken _) + private IReadOnlyList OpenSearchForm() { - MailMessage message; - - try - { - message = await _store.ReplyMessageAsync( - request.InReplyToId, request.Actor, request.Body, MailWakePolicy.Enqueue, CancellationToken.None) - .ConfigureAwait(false); - } - catch (ExitException ex) - { - return new MailSendOutcome.Failed(ex.Message); - } - - _storedNotices.Enqueue(new MailSendOutcome.Stored(message)); - _sendEffects.SignalWake(); - return new MailSendOutcome.Succeeded(message); - } - - /// - /// Processes queued store notices and send completions, refreshing mail after a - /// confirmed write. A rejected write restores the submitted form unless another - /// form of that kind is already open. - /// - private IReadOnlyList DrainEffectQueue() - { - var storedNotices = DrainStoredNotices(); - var drained = _sendEffects.DrainCompletions(); - List> completions; - - if (_deferredCompletions.Count == 0) - { - completions = [.. drained]; - } - else - { - completions = [.. _deferredCompletions, .. drained]; - _deferredCompletions.Clear(); - } - - if (storedNotices.Count == 0 && completions.Count == 0) - { - return []; - } - - var toasts = new List(storedNotices.Count + completions.Count); - var committed = storedNotices.Count > 0; - - if (completions.Count == 0) - { - foreach (var notice in storedNotices) - { - toasts.Add(notice.ToShowToast()); - } - } - - foreach (var completion in completions) - { - switch (completion) - { - case TuiEffectCompletion.Completed completed: - toasts.Add(completed.Result.ToShowToast()); - committed |= completed.Result is MailSendOutcome.Succeeded or MailSendOutcome.Reconciled; - - if (completed.Result is MailSendOutcome.Failed) - { - _composeForm ??= _submittedComposeForm; - _replyForm ??= _submittedReplyForm; - } - - break; - - default: - toasts.Add(new TuiMessage.ShowToast(SendOutcomeUnknownToastText, ToastStyle.Error)); - break; - } - - _submittedComposeForm = null; - _submittedReplyForm = null; - } - - if (committed) - { - RefreshBlocking(); - } - - return toasts; - } - - /// - /// Drains every notice posted to - /// since the last call. - /// - private IReadOnlyList DrainStoredNotices() - { - if (_storedNotices.IsEmpty) - { - return []; - } - - var drained = new List(); - - while (_storedNotices.TryDequeue(out var notice)) - { - drained.Add(notice); - } - - return drained; - } - - /// - /// Discards all queued store notices without producing toasts. - /// - private void ClearStoredNotices() - { - while (_storedNotices.TryDequeue(out _)) - { - } + _searchForm = new MailSearchForm(_state.SearchText); + return []; } - /// - /// Creates a quit gate that stops submissions, waits within the supplied bound, - /// and reports pending effects and unknown outcomes. Drained completions remain - /// available to ; a cancelled quit must resume send acceptance. - /// - public TuiQuitGate CreateQuitGate() => async (bound, cancellationToken) => - { - _sendEffects.StopAccepting(); - await _sendEffects.DrainPendingAsync(bound, cancellationToken).ConfigureAwait(false); - - ClearStoredNotices(); - var completions = _sendEffects.DrainCompletions(); - _deferredCompletions.AddRange(completions); - - var pendingCount = _sendEffects.PendingCount; - var outcomeUnknownCount = 0; - var operationIds = new List(_sendEffects.PendingOperationIds); - - foreach (var completion in completions) - { - switch (completion) - { - case TuiEffectCompletion.Completed { Result: MailSendOutcome.Reconciled }: - case TuiEffectCompletion.Faulted: - case TuiEffectCompletion.Cancelled: - outcomeUnknownCount++; - operationIds.Add(completion.OperationId); - break; - } - } - - return new TuiQuitGateReport(pendingCount, outcomeUnknownCount, operationIds); - }; - - /// - /// Resumes send acceptance after a cancelled quit confirmation. - /// - public void ResumeSendAcceptance() => _sendEffects.ResumeAccepting(); - - /// - /// Waits within the supplied bound for pending sends to finish without cancelling - /// the sends or requesting user confirmation. - /// - public Task ShieldPendingSendsAsync(TimeSpan bound, CancellationToken cancellationToken) - => _sendEffects.DrainPendingAsync(bound, cancellationToken); - - /// - /// Relays send-effect wake signals to the TUI event channel until cancellation. - /// - public Task RunSendEffectEventsAsync(ChannelWriter writer, CancellationToken cancellationToken) - => _sendEffects.RunAsync(writer, cancellationToken); - - private IReadOnlyList HandleDiscardDialogKey(ConsoleKeyInfo info) + private IReadOnlyList HandleSearchFormKey(ConsoleKeyInfo info) { - var result = _discardDialog!.HandleKey(info); + var result = _searchForm!.HandleKey(info); return result switch { null => [], - ConfirmDialogResult.Confirmed => ConfirmDiscard(), - ConfirmDialogResult.Cancelled => CancelDiscard(), + FormResult.Cancelled => CloseSearchForm(), + FormResult.ButtonActivated { ButtonId: MailSearchForm.CancelButtonId } => CloseSearchForm(), + FormResult.Submitted => ApplySearch(), _ => [] }; } - private IReadOnlyList ConfirmDiscard() - { - _discardDialog = null; - - if (_discardTarget == MailDiscardTarget.Compose) - { - _composeForm = null; - } - else - { - _replyForm = null; - } - - return []; - } - - private IReadOnlyList CancelDiscard() + private IReadOnlyList CloseSearchForm() { - _discardDialog = null; + _searchForm = null; return []; } - private static ConfirmDialog CreateDiscardDialog() - => new("Discard unsaved changes?", "Discard", ButtonKind.Danger); - - private IReadOnlyList Refresh() - { - RefreshBlocking(); - return []; - } - - private IReadOnlyList CycleFilter(int delta) - { - _state.CycleFilterAsync(delta, CancellationToken.None).GetAwaiter().GetResult(); - _detailView.ResetScroll(); - return []; - } - - private IReadOnlyList SelectMailbox(MailMailbox mailbox) + private IReadOnlyList ApplySearch() { - if (_state.Actor is null && mailbox != MailMailbox.Workspace) - { - return [new TuiMessage.ShowToast(BoardIdentity.NoIdentityMessage, ToastStyle.Warn)]; - } - - _state.SelectMailboxAsync(mailbox, CancellationToken.None).GetAwaiter().GetResult(); - _detailView.ResetScroll(); + var text = _searchForm!.Text; + _searchForm = null; + _state.ApplySearch(text); return []; } /// - /// Opens the Workspace agent filter picker with the current filter selected and - /// an entry to clear it. Returns a refusal toast outside the Workspace mailbox. + /// Opens the agent filter picker with the current filter selected and an entry to + /// clear it. /// private IReadOnlyList OpenAgentFilterPicker() { - if (_state.Mailbox != MailMailbox.Workspace) - { - return [new TuiMessage.ShowToast(AgentFilterRequiresWorkspaceMessage, ToastStyle.Warn)]; - } - - var agents = _agentRegistry.ListAsync(role: null, staleBefore: null, CancellationToken.None) - .GetAwaiter().GetResult(); + var agents = _agentStore.ListAsync(CancellationToken.None) + .GetAwaiter() + .GetResult() + .OrderBy(a => a.Name, StringComparer.OrdinalIgnoreCase) + .ToList(); _agentPicker = BuildAgentPicker(agents, _state.AgentFilter); return []; } - private static QuickPicker BuildAgentPicker(IReadOnlyList agents, string? selectedAgent) + private static QuickPicker BuildAgentPicker(IReadOnlyList agents, string? selectedAgent) { var options = new List { new(AllAgentsOptionId, "All agents") }; options.AddRange(agents.Select(a => new QuickPickerOption(a.Name, FormatAgentOptionMarkup(a)))); @@ -983,12 +264,14 @@ private static QuickPicker BuildAgentPicker(IReadOnlyList agents, s /// /// An agent picker row's markup: the name, plus its - /// in dim parentheses when non-empty. + /// display name in dim parentheses when non-empty. /// - private static string FormatAgentOptionMarkup(AgentRecord agent) + private static string FormatAgentOptionMarkup(AgentRow agent) { var name = Markup.Escape(agent.Name); - return agent.Client.Length == 0 ? name : $"{name} [dim]({Markup.Escape(agent.Client)})[/]"; + return agent.Harness is not { Length: > 0 } harness + ? name + : $"{name} [dim]({Markup.Escape(AgentHarnessDisplay.Name(harness))})[/]"; } private IReadOnlyList HandleAgentPickerKey(ConsoleKeyInfo info) @@ -1016,143 +299,20 @@ private IReadOnlyList ApplyAgentFilter(string selectedId) var agent = selectedId == AllAgentsOptionId ? null : selectedId; _state.SelectAgentFilterAsync(agent, CancellationToken.None).GetAwaiter().GetResult(); - _detailView.ResetScroll(); - - return []; - } - private IReadOnlyList ToggleThreadView() - { - if (_state.ViewMode == MailViewMode.Thread) - { - _state.ShowMessage(); - _detailView.ResetScroll(); - return []; - } - - var opened = _state.ShowThreadAsync(CancellationToken.None).GetAwaiter().GetResult(); - _detailView.ResetScroll(); - - return opened ? [] : [new TuiMessage.ShowToast("No message selected.", ToastStyle.Warn)]; - } - - /// - /// Toggles between thread and flat lists using the loaded list data. - /// Selecting a thread in the rebuilt list may load its messages. - /// - private IReadOnlyList ToggleListMode() - { - _state.ToggleListMode(); - _detailView.ResetScroll(); return []; } - /// - /// Enters the fold-prefix (z) capture state, refused with a toast when - /// is , - /// where there is nothing to fold. The next raw key is routed to - /// instead of the normal semantic dispatch. - /// - private IReadOnlyList OpenFoldPrefix() - { - if (_state.ListMode != MailListMode.Threads) - { - return [new TuiMessage.ShowToast(FoldRequiresThreadsMessage, ToastStyle.Warn)]; - } - - _foldPrefixPending = true; - return []; - } - - /// - /// Resolves the key following a fold prefix: a (toggle), o (open/expand), - /// c (close/collapse) act on the thread under the cursor (see - /// ); Shift+R/Shift+M unfold/fold every - /// thread and need no selection. Any other key, including Escape, - /// cancels the prefix with no action. - /// - private IReadOnlyList HandleFoldPrefixKey(ConsoleKeyInfo info) - { - _foldPrefixPending = false; - - switch (info.KeyChar) - { - case 'a': - if (CurrentRowThreadId() is { } toggleId) - { - _state.ToggleThreadFold(toggleId); - } - - break; - - case 'o': - if (CurrentRowThreadId() is { } openId) - { - _state.ExpandThread(openId); - } - - break; - - case 'c': - if (CurrentRowThreadId() is { } closeId) - { - _state.CollapseThread(closeId); - } - - break; - - case 'R': - _state.ExpandAllThreads(); - break; - - case 'M': - _state.CollapseAllThreads(); - break; - } - - return []; - } - - /// - /// The thread id the fold prefix's second key acts on: the selected - /// row's own thread id for a thread row, or its parent thread's id for - /// an expanded child message row; null when nothing is selected. - /// - private string? CurrentRowThreadId() - { - if (_state.SelectedRow < 0 || _state.SelectedRow >= _state.Rows.Count) - { - return null; - } - - return _state.Rows[_state.SelectedRow] switch - { - MailListRow.Thread t => t.Summary.ThreadId, - MailListRow.MessageRow m => m.Message.ThreadId, - _ => null - }; - } - - private IReadOnlyList CopySelectedId() - { - var id = _state.SelectedMessage?.Id; - - return id is null - ? [new TuiMessage.ShowToast("No message selected.", ToastStyle.Warn)] - : [new TuiMessage.ShowToast(id, ToastStyle.Info)]; - } - private IRenderable RenderListPane(int width, int height) { - var focused = _state.Focus == MailFocus.List; var safeWidth = Math.Max(1, width); var contentWidth = Math.Max(0, safeWidth - PanelChromeWidth); var interiorHeight = Math.Max(0, height - PanelChromeHeight); var now = _timeProvider.GetUtcNow(); - var lines = RenderListLines(contentWidth, interiorHeight, focused, now); - var count = _state.ListMode == MailListMode.Threads ? _state.Threads.Count : _state.Messages.Count; - var panel = BuildListPanel(HeaderName(_state), count, lines, focused); + var lines = RenderListLines(contentWidth, interiorHeight, now); + var header = BuildHeader(_state); + var panel = ColumnPane.RenderWithHeader(header, lines, focused: true); panel.Width = safeWidth; panel.Height = Math.Max(1, height); @@ -1160,70 +320,53 @@ private IRenderable RenderListPane(int width, int height) } /// - /// Renders the list panel with a distinct border accent for the Workspace mailbox. + /// The panel header: "Mail (N)", or "Mail: <agent> (N)" when the agent filter + /// picker has narrowed the threads to one agent. /// - private Panel BuildListPanel(string name, int count, IReadOnlyList lines, bool focused) - { - IRenderable content = lines.Count == 0 - ? new Markup(string.Empty) - : new Rows(lines.Select(line => (IRenderable)new Markup(line))); - - var borderToken = ResolveListBorderToken(_state.Mailbox, focused); - var headerText = Markup.Escape($"{name} ({count})"); - - return new Panel(content) - { - Header = new PanelHeader(headerText), - Border = BoxBorder.Rounded, - BorderStyle = ThemeTokens.GetStyle(borderToken) - }; - } + private static string BuildHeader(MailState state) => state.AgentFilter is { } agent + ? $"Mail: {agent} ({state.TotalCount})" + : $"Mail ({state.TotalCount})"; /// - /// The list pane's border token for : - /// 's own distinct accent, or the - /// plain board.column.border family every other mailbox and - /// every other board in the shell uses. + /// Renders the header block (a blank line, the header row, and its rule), then the visible + /// rows, padded with blank lines to , with "N more + /// above/below" indicators once the rows no longer fit. Column widths are computed from + /// this call's visible slice and the header titles, so the header and rows always agree on + /// where each column starts. Shows the empty-state message below the header block when + /// there is no mail at all. /// - internal static string ResolveListBorderToken(MailMailbox mailbox, bool focused) => mailbox switch - { - MailMailbox.Workspace when focused => "mail.mailbox.workspace.border.focused", - MailMailbox.Workspace => "mail.mailbox.workspace.border", - _ when focused => "board.column.border.focused", - _ => "board.column.border" - }; - - private IRenderable RenderDetailPane(int width, int height) - => _detailView.Render(_state, width, height, _state.Focus == MailFocus.Detail, _clientsByName); - - /// - /// Renders the heading and visible list rows with aligned columns, scroll - /// indicators, and blank padding. - /// - private IReadOnlyList RenderListLines( - int contentWidth, int interiorHeight, bool focused, DateTimeOffset now) + private IReadOnlyList RenderListLines(int contentWidth, int interiorHeight, DateTimeOffset now) { if (interiorHeight <= 0) { return []; } - var columns = MailTable.ComputeColumns(contentWidth, _state.ListMode == MailListMode.Threads); - var heading = MailTable.RenderHeading(columns); + var headerLineCount = Math.Min(HeaderLineCount, interiorHeight); + var rowsHeight = Math.Max(0, interiorHeight - headerLineCount); + var lines = new List(interiorHeight); - if (interiorHeight == 1) + if (_state.TotalCount == 0) { - return [heading]; + var widths = MailTable.ComputeWidths([], now); + MailTable.AddHeaderLines(lines, headerLineCount, contentWidth, widths); + + if (rowsHeight > 0) + { + lines.Add(DisplayWidth.Truncate(EmptyStateMessage, contentWidth)); + } + + PadTo(lines, interiorHeight); + return lines; } - var bodyHeight = interiorHeight - 1; - var rows = _state.Rows; + var threads = _state.Threads; var reservedRows = 0; for (var pass = 0; pass < MaxIndicatorSettlePasses; pass++) { - var windowHeight = Math.Max(0, bodyHeight - reservedRows); - _listViewport.Update(rows.Count, windowHeight); + var windowHeight = Math.Max(0, rowsHeight - reservedRows); + _listViewport.Update(threads.Count, windowHeight); _listViewport.EnsureVisible(_state.SelectedRow); var needed = (_listViewport.HiddenAbove > 0 ? 1 : 0) + (_listViewport.HiddenBelow > 0 ? 1 : 0); @@ -1237,7 +380,15 @@ private IReadOnlyList RenderListLines( } var (start, visibleCount) = _listViewport.Slice(); - var lines = new List(interiorHeight) { heading }; + var visibleThreads = new List(visibleCount); + + for (var i = 0; i < visibleCount; i++) + { + visibleThreads.Add(threads[start + i]); + } + + var rowWidths = MailTable.ComputeWidths(visibleThreads, now); + MailTable.AddHeaderLines(lines, headerLineCount, contentWidth, rowWidths); if (_listViewport.HiddenAbove > 0) { @@ -1246,9 +397,8 @@ private IReadOnlyList RenderListLines( for (var i = 0; i < visibleCount; i++) { - var index = start + i; - var selected = focused && index == _state.SelectedRow; - lines.Add(RenderRow(rows[index], selected, now, columns)); + var selected = start + i == _state.SelectedRow; + lines.Add(MailTable.Render(visibleThreads[i], now, selected, contentWidth, rowWidths)); } if (_listViewport.HiddenBelow > 0) @@ -1256,68 +406,19 @@ private IReadOnlyList RenderListLines( lines.Add(FormatIndicator(_listViewport.HiddenBelow, "below")); } - while (lines.Count < interiorHeight) - { - lines.Add(string.Empty); - } - + PadTo(lines, interiorHeight); return lines; } - /// - /// Renders a list row with the acting agent's unread highlight, resolved from the - /// thread summary or the message's recipient state. - /// - private string RenderRow(MailListRow row, bool selected, DateTimeOffset now, MailTable.Columns columns) => row switch - { - MailListRow.Thread t => MailTable.RenderThreadRow( - t.Summary, t.Expanded, _state.IsThreadUnreadToMe(t.Summary), selected, RenderActor, now, columns), - MailListRow.MessageRow m => MailTable.RenderMessageRow( - m.Message, m.ThreadChild, MailRecipientView.IsUnread(m.Message, RenderActor), selected, RenderActor, now, columns), - _ => string.Empty - }; - - private static string FormatIndicator(int hiddenCount, string direction) => $" {hiddenCount} more {direction}"; - - private static string FilterName(MailListFilter filter) => filter switch + private static void PadTo(List lines, int height) { - MailListFilter.Unread => "Unread", - MailListFilter.Archived => "Archived", - _ => "Inbox" - }; - - /// - /// The list pane's header name: the read-state filter's name within - /// ; the mailbox's own display name - /// suffixed with the selected agent within - /// when is set; or the plain mailbox - /// display name otherwise. - /// - private static string HeaderName(MailState state) - { - if (state.Mailbox == MailMailbox.Inbox) + while (lines.Count < height) { - return FilterName(state.Filter); + lines.Add(string.Empty); } - - return state.Mailbox == MailMailbox.Workspace && state.AgentFilter is { } agent - ? $"{state.Mailbox.DisplayName()}: {agent}" - : state.Mailbox.DisplayName(); } - private void RefreshBlocking() - { - _state.RefreshAsync(CancellationToken.None).GetAwaiter().GetResult(); - UnreadCount = _state.Actor is null - ? 0 - : _store.CountUnreadAsync(_state.Actor, CancellationToken.None).GetAwaiter().GetResult(); - - var agents = _agentRegistry.ListAsync(role: null, staleBefore: null, CancellationToken.None) - .GetAwaiter().GetResult(); - - // First-wins on duplicate names (case-insensitive). - _clientsByName = agents - .ToLookup(a => a.Name, a => a.Client, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - } + private static string FormatIndicator(int hiddenCount, string direction) => $" {hiddenCount} more {direction}"; + + private void RefreshBlocking() => _state.RefreshAsync(CancellationToken.None).GetAwaiter().GetResult(); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailReplyForm.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailReplyForm.cs deleted file mode 100644 index 6ff967f0e60..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailReplyForm.cs +++ /dev/null @@ -1,89 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Input; -using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; -using Spectre.Console.Rendering; -using Form = ChilliCream.Nitro.CommandLine.Tui.Widgets.Form.Form; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// A body-only reply form. The mail store determines reply-all recipients when -/// the request is submitted. -/// -internal sealed class MailReplyForm -{ - public const string BodyFieldId = "body"; - - public const string SendButtonId = "send"; - public const string CancelButtonId = "cancel"; - - /// - /// The footer hints displayed while the reply form captures input. - /// - public static readonly IReadOnlyList Hints = - [ - new KeyHint("ctrl+s", "send"), - new KeyHint("esc", "cancel") - ]; - - private readonly string _inReplyToId; - private readonly Form _form; - private readonly TextAreaField _bodyField; - - public MailReplyForm(MailMessage original) - { - ArgumentNullException.ThrowIfNull(original); - - _inReplyToId = original.Id; - _bodyField = new TextAreaField(BodyFieldId, "Body", required: true, validator: RequireBody); - - var buttons = new FormButtons( - [ - new FormButtonSpec(SendButtonId, "Reply", ButtonKind.Primary), - new FormButtonSpec(CancelButtonId, "Cancel", ButtonKind.Secondary) - ]); - - _form = new Form($"Reply: {original.Subject}", [_bodyField], buttons); - } - - /// - /// Whether the body contains text, including whitespace. - /// - public bool IsDirty => Text(_bodyField).Length != 0; - - /// - /// Handles one raw key. Returns while the form is - /// still active, or the terminal once the - /// interaction ends. - /// - public FormResult? HandleKey(ConsoleKeyInfo info) => _form.HandleKey(info); - - /// - /// Renders the form as a titled, rounded panel centered within the given - /// area. - /// - public IRenderable Render(int width, int height) => _form.Render(width, height); - - /// - /// Builds a reply request from the submitted body, acting agent, and original - /// message id without writing to the store. - /// - public MailReplyRequest BuildRequest(IReadOnlyDictionary values, string actor) - { - ArgumentNullException.ThrowIfNull(values); - ArgumentException.ThrowIfNullOrEmpty(actor); - - return new MailReplyRequest(_inReplyToId, actor, Text(values, BodyFieldId)); - } - - private static string? RequireBody(FormValue value) - => value is FormValue.Text { Value: var text } && text.Trim().Length == 0 - ? "Body is required." - : null; - - private static string Text(FormField field) - => field.GetValue() is FormValue.Text { Value: var value } ? value : ""; - - private static string Text(IReadOnlyDictionary values, string id) - => values[id] is FormValue.Text { Value: var value } ? value : ""; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailReplyRequest.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailReplyRequest.cs deleted file mode 100644 index e495d0099b6..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailReplyRequest.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// A submission snapshot: the message it replies -/// to, the acting agent, and the reply body, ready for -/// -/// with . -/// -internal sealed record MailReplyRequest(string InReplyToId, string Actor, string Body); diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailSearchForm.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailSearchForm.cs new file mode 100644 index 00000000000..d873d713b48 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailSearchForm.cs @@ -0,0 +1,54 @@ +using ChilliCream.Nitro.CommandLine.Tui.Input; +using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; +using Spectre.Console.Rendering; +using Form = ChilliCream.Nitro.CommandLine.Tui.Widgets.Form.Form; + +namespace ChilliCream.Nitro.CommandLine.Tui.Mail; + +/// +/// The Mail tab's search box: one text field pre-filled with +/// , applied as a case-insensitive filter over subject, +/// last sender, and last recipients. +/// +internal sealed class MailSearchForm +{ + public const string TextFieldId = "text"; + public const string ApplyButtonId = "apply"; + public const string CancelButtonId = "cancel"; + + /// + /// The footer hints displayed while the search form captures input. + /// + public static readonly IReadOnlyList Hints = + [ + new KeyHint("ctrl+s", "search"), + new KeyHint("esc", "cancel") + ]; + + private readonly Form _form; + private readonly TextField _textField; + + public MailSearchForm(string initialText) + { + ArgumentNullException.ThrowIfNull(initialText); + + _textField = new TextField(TextFieldId, "Search subject, from, or to", initialValue: initialText); + + var buttons = new FormButtons( + [ + new FormButtonSpec(ApplyButtonId, "Search", ButtonKind.Primary), + new FormButtonSpec(CancelButtonId, "Cancel", ButtonKind.Secondary) + ]); + + _form = new Form("Search mail", [_textField], buttons); + } + + /// + /// The field's current text. + /// + public string Text => _textField.GetValue() is FormValue.Text { Value: var value } ? value : ""; + + public FormResult? HandleKey(ConsoleKeyInfo info) => _form.HandleKey(info); + + public IRenderable Render(int width, int height) => _form.Render(width, height); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailSendOutcome.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailSendOutcome.cs deleted file mode 100644 index 1848ae3daea..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailSendOutcome.cs +++ /dev/null @@ -1,69 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Input; - -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// The storage outcome of a compose or reply submission. -/// is an intermediate commit notice; recipient notification -/// is separate from storage success. -/// -internal abstract record MailSendOutcome -{ - private MailSendOutcome() - { - } - - /// - /// An intermediate notice that the message and its wake intent were committed. - /// - public sealed record Stored(MailMessage Message) : MailSendOutcome; - - /// - /// The message was committed; this does not report recipient notification. - /// - public sealed record Succeeded(MailMessage Message) : MailSendOutcome; - - /// - /// The message was committed, but its notification outcome is unknown. - /// - public sealed record Reconciled(MailMessage Message) : MailSendOutcome; - - /// - /// The store rejected the write before anything committed: no message, - /// no wake generation. Carries the store's own - /// message. - /// - public sealed record Failed(string ToastText) : MailSendOutcome; - - /// - /// Returns an informational stored toast, a successful send toast, a warning for - /// an unknown notification outcome, or an error for a rejected write. - /// - public TuiMessage.ShowToast ToShowToast() => this switch - { - Stored stored => FormatStored(stored), - Succeeded succeeded => FormatSucceeded(succeeded), - Reconciled reconciled => - new TuiMessage.ShowToast($"Stored '{reconciled.Message.Id}'. Notification outcome unknown.", ToastStyle.Warn), - Failed failed => new TuiMessage.ShowToast(failed.ToastText, ToastStyle.Error), - _ => throw new NotSupportedException() - }; - - private static TuiMessage.ShowToast FormatStored(Stored stored) - { - var id = stored.Message.Id; - var recipients = string.Join(", ", stored.Message.Recipients.Select(r => r.Name)); - - // Info: not yet a terminal outcome. - return new TuiMessage.ShowToast($"Stored '{id}' to {recipients}.", ToastStyle.Info); - } - - private static TuiMessage.ShowToast FormatSucceeded(Succeeded succeeded) - { - var id = succeeded.Message.Id; - var recipients = string.Join(", ", succeeded.Message.Recipients.Select(r => r.Name)); - - return new TuiMessage.ShowToast($"Sent '{id}' to {recipients}.", ToastStyle.Success); - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailState.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailState.cs index d6711a911e5..494612cafcf 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailState.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailState.cs @@ -3,471 +3,106 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Mail; /// -/// The mail board's loaded messages and threads, mailbox filters, selection, -/// focus, and detail view mode. +/// The loaded workspace thread rows, agent filter, search filter, and selection for the +/// Mail tab. /// -internal sealed class MailState(string? actor, MailDataLoader loader) +internal sealed class MailState(MailDataLoader loader) { - /// - /// The acting agent, or null when the board has no identity. - /// - public string? Actor { get; } = actor; - - /// - /// The acting agent required by personal mailbox queries; throws when no identity - /// is available. - /// - private string RequiredActor - => Actor ?? throw new InvalidOperationException("The board has no agent identity."); - - /// - /// The selected mailbox, initially . - /// - public MailMailbox Mailbox { get; private set; } = MailMailbox.Workspace; - - /// - /// The read-state filter for Inbox messages and thread summaries. - /// Other mailboxes ignore this filter. - /// - public MailListFilter Filter { get; private set; } = MailListFilter.Inbox; - - /// - /// The agent whose sent or received mail is shown in Workspace, or null for all - /// agents. Leaving Workspace clears the filter. - /// - public string? AgentFilter { get; private set; } - - /// - /// The list shape, initially . - /// - public MailListMode ListMode { get; private set; } = MailListMode.Threads; + private IReadOnlyList _allThreads = []; /// - /// Messages loaded for the current mailbox and filters, newest first, regardless - /// of the active list shape. - /// - public IReadOnlyList Messages { get; private set; } = []; - - /// - /// Thread summaries loaded for the current mailbox and filters, newest activity - /// first, regardless of the active list shape. + /// Every workspace thread matching and , + /// as loaded by the last or + /// call: last-message time descending, then thread id descending. /// public IReadOnlyList Threads { get; private set; } = []; /// - /// The navigable message rows, or thread rows followed by any expanded messages. - /// - public IReadOnlyList Rows { get; private set; } = []; - - /// - /// The selected index in . Selecting a different row identity - /// resolves its detail content and view mode; selecting the same identity preserves - /// a manual view-mode override. - /// - public int SelectedRow - { - get => _selectedRow; - set - { - _selectedRow = value; - var key = _selectedRow >= 0 && _selectedRow < Rows.Count ? RowKey(Rows[_selectedRow]) : null; - - if (key == _syncedRowKey) - { - return; - } - - _syncedRowKey = key; - SyncSelectionBlocking(); - } - } - - /// - /// Which pane currently holds focus. - /// - public MailFocus Focus { get; set; } = MailFocus.List; - - /// - /// What the detail pane currently renders. - /// - public MailViewMode ViewMode { get; private set; } = MailViewMode.Message; - - /// - /// The selected row's thread, loaded when is - /// . - /// - public IReadOnlyList ThreadMessages { get; private set; } = []; - - /// - /// The selected message row's message or the selected thread's latest message, - /// or null when no message is selected. - /// - public MailMessage? SelectedMessage { get; private set; } - - private int _selectedRow; - - /// - /// The last synchronized row identity, or null when none is selected. - /// - private string? _syncedRowKey; - - private readonly HashSet _expandedThreadIds = new(StringComparer.Ordinal); - private readonly Dictionary> _threadMessageCache = - new(StringComparer.Ordinal); - - /// - /// Workspace thread ids with unread mail addressed to the acting agent, - /// loaded from that agent's inbox thread summaries. - /// - private HashSet _workspaceUnreadToMeThreadIds = new(StringComparer.Ordinal); - - /// - /// Whether the thread has unread mail for the acting agent. - /// Workspace uses the separately loaded actor-specific thread ids. - /// - public bool IsThreadUnreadToMe(MailThreadSummary summary) - => Mailbox == MailMailbox.Workspace - ? _workspaceUnreadToMeThreadIds.Contains(summary.ThreadId) - : (summary.UnreadCount ?? 0) > 0; - - /// - /// Reloads and for the - /// current , , and - /// , preserving the selected row (by thread or - /// message id) when it is still present, or clamping to the reloaded - /// list's bounds otherwise. + /// The total thread count for the current , independent of + /// . /// - public Task RefreshAsync(CancellationToken cancellationToken) - => ReloadAsync(cancellationToken, resetToTop: false); + public int TotalCount => _allThreads.Count; /// - /// Jumps to when it differs from - /// : reloads and - /// and resets to the top. - /// A no-op when is already active. + /// The index of the selected row within . /// - public async Task SelectMailboxAsync(MailMailbox mailbox, CancellationToken cancellationToken) - { - if (Mailbox == mailbox) - { - return; - } - - if (Mailbox == MailMailbox.Workspace) - { - AgentFilter = null; - } - - Mailbox = mailbox; - await ReloadAsync(cancellationToken, resetToTop: true).ConfigureAwait(false); - } + public int SelectedRow { get; set; } /// - /// Sets and reloads, resetting - /// to the top the same way - /// does. Meaningful only within - /// . + /// The current subject/sender/recipient search filter; empty shows every thread. /// - public Task SelectAgentFilterAsync(string? agent, CancellationToken cancellationToken) - { - AgentFilter = agent; - return ReloadAsync(cancellationToken, resetToTop: true); - } + public string SearchText { get; private set; } = string.Empty; /// - /// Cycles the inbox filter by the supplied number of positions and reloads. - /// The filter affects both messages and threads in Inbox only. + /// The agent whose sent or received mail narrows , or null for + /// every agent. /// - public async Task CycleFilterAsync(int delta, CancellationToken cancellationToken) - { - var values = Enum.GetValues(); - var index = ((int)Filter + delta) % values.Length; - - if (index < 0) - { - index += values.Length; - } - - Filter = values[index]; - await RefreshAsync(cancellationToken).ConfigureAwait(false); - } - - /// - /// Toggles the list shape using loaded messages and thread summaries, preserving - /// the selected identity when present or clamping its index otherwise. - /// Resolving the selection may load the selected thread's messages. - /// - public void ToggleListMode() - { - ListMode = ListMode == MailListMode.Threads ? MailListMode.Flat : MailListMode.Threads; - RebuildRowsPreservingSelection(); - } - - /// - /// Expands the thread's message rows, loading its messages when needed. - /// An already expanded thread is unchanged. - /// - public void ExpandThread(string threadId) - { - if (_expandedThreadIds.Add(threadId)) - { - GetOrLoadThreadMessagesBlocking(threadId); - RebuildRowsPreservingSelection(); - } - } - - /// - /// Collapses the thread's indented message rows. A no-op when already - /// collapsed. - /// - public void CollapseThread(string threadId) - { - if (_expandedThreadIds.Remove(threadId)) - { - RebuildRowsPreservingSelection(); - } - } - - /// - /// Expands the thread when collapsed, or collapses it when expanded (za). - /// - public void ToggleThreadFold(string threadId) - { - if (_expandedThreadIds.Contains(threadId)) - { - CollapseThread(threadId); - } - else - { - ExpandThread(threadId); - } - } - - /// - /// Expands every thread currently in (zR). - /// - public void ExpandAllThreads() - { - foreach (var thread in Threads) - { - _expandedThreadIds.Add(thread.ThreadId); - GetOrLoadThreadMessagesBlocking(thread.ThreadId); - } - - RebuildRowsPreservingSelection(); - } - - /// - /// Collapses every thread (zM). - /// - public void CollapseAllThreads() - { - _expandedThreadIds.Clear(); - RebuildRowsPreservingSelection(); - } - - /// - /// Loads the selected message's thread and displays it until the selected row - /// identity changes or the view is changed manually. Returns false without - /// changing the view when no message is selected. - /// - public async Task ShowThreadAsync(CancellationToken cancellationToken) - { - if (SelectedMessage is not { } message) - { - return false; - } - - ViewMode = MailViewMode.Thread; - ThreadMessages = await loader.LoadThreadAsync(message.ThreadId, cancellationToken).ConfigureAwait(false); - return true; - } + public string? AgentFilter { get; private set; } /// - /// Displays the selected message alone until the selected row identity changes - /// or the view is changed manually. + /// The thread at , or null when there is no such row. /// - public void ShowMessage() - { - ViewMode = MailViewMode.Message; - ThreadMessages = []; - } + public MailThreadSummary? SelectedThread + => SelectedRow >= 0 && SelectedRow < Threads.Count ? Threads[SelectedRow] : null; /// - /// Reloads mailbox data and rebuilds the rows, resetting to the first row when - /// requested or retaining the selection when present. A retained selection gets - /// fresh content while preserving its detail view mode. + /// Reloads every workspace thread for from the mail store, + /// re-applies the search filter, and keeps the previously selected thread selected by + /// id when it is still present; otherwise clamps the selection to the new list's bounds. /// - private async Task ReloadAsync(CancellationToken cancellationToken, bool resetToTop) + public async Task RefreshAsync(CancellationToken cancellationToken) { - var previousKey = !resetToTop && Rows.Count > 0 && _selectedRow >= 0 && _selectedRow < Rows.Count - ? RowKey(Rows[_selectedRow]) - : null; + var selectedId = SelectedThread?.ThreadId; - Messages = await LoadMessagesAsync(cancellationToken).ConfigureAwait(false); - Threads = await LoadThreadsAsync(cancellationToken).ConfigureAwait(false); + _allThreads = await loader.LoadWorkspaceThreadsAsync(AgentFilter, cancellationToken).ConfigureAwait(false); + ApplySearchFilter(); - _workspaceUnreadToMeThreadIds = Mailbox == MailMailbox.Workspace && Actor is not null - ? (await loader.LoadInboxThreadsAsync(Actor, MailListFilter.Inbox, cancellationToken).ConfigureAwait(false)) - .Where(t => (t.UnreadCount ?? 0) > 0) - .Select(t => t.ThreadId) - .ToHashSet(StringComparer.Ordinal) - : []; + var preservedIndex = selectedId is null ? -1 : IndexOf(Threads, selectedId); - _threadMessageCache.Clear(); - RebuildRows(); - - var newIndex = previousKey is null ? -1 : IndexOfRow(Rows, previousKey); - SelectedRow = newIndex >= 0 - ? newIndex - : resetToTop - ? 0 - : Math.Clamp(_selectedRow, 0, Math.Max(0, Rows.Count - 1)); - - if (newIndex >= 0) - { - RefreshSelectedRowContent(); - } + SelectedRow = preservedIndex >= 0 + ? preservedIndex + : Math.Clamp(SelectedRow, 0, Math.Max(0, Threads.Count - 1)); } /// - /// Refreshes the selected message and any displayed thread without changing the - /// detail view mode. + /// Sets , reloads from the mail store, and selects the first row. /// - private void RefreshSelectedRowContent() + public async Task SelectAgentFilterAsync(string? agent, CancellationToken cancellationToken) { - if (_selectedRow < 0 || _selectedRow >= Rows.Count) - { - return; - } - - switch (Rows[_selectedRow]) - { - case MailListRow.Thread threadRow: - var threadMessages = GetOrLoadThreadMessagesBlocking(threadRow.Summary.ThreadId); - SelectedMessage = threadMessages.Count > 0 ? threadMessages[^1] : null; - - if (ViewMode == MailViewMode.Thread) - { - ThreadMessages = threadMessages; - } - - break; - - case MailListRow.MessageRow messageRow: - SelectedMessage = messageRow.Message; - - if (ViewMode == MailViewMode.Thread) - { - ThreadMessages = GetOrLoadThreadMessagesBlocking(messageRow.Message.ThreadId); - } - - break; - } - } - - /// - /// Rebuilds from the current or - /// (per ) and preserves the - /// selected row by identity across the rebuild, or clamps when the - /// previously-selected row is gone. - /// - private void RebuildRowsPreservingSelection() - { - var previousKey = Rows.Count > 0 && _selectedRow >= 0 && _selectedRow < Rows.Count - ? RowKey(Rows[_selectedRow]) - : null; - - RebuildRows(); - - var newIndex = previousKey is null ? -1 : IndexOfRow(Rows, previousKey); - SelectedRow = newIndex >= 0 ? newIndex : Math.Clamp(_selectedRow, 0, Math.Max(0, Rows.Count - 1)); - } - - private void RebuildRows() - { - if (ListMode == MailListMode.Flat) - { - Rows = Messages.Select(m => (MailListRow)new MailListRow.MessageRow(m, ThreadChild: false)).ToList(); - return; - } - - var rows = new List(Threads.Count); - - foreach (var thread in Threads) - { - var expanded = _expandedThreadIds.Contains(thread.ThreadId); - rows.Add(new MailListRow.Thread(thread, expanded)); - - if (expanded) - { - var children = GetOrLoadThreadMessagesBlocking(thread.ThreadId); - rows.AddRange(children.Select(m => (MailListRow)new MailListRow.MessageRow(m, ThreadChild: true))); - } - } - - Rows = rows; + AgentFilter = agent; + _allThreads = await loader.LoadWorkspaceThreadsAsync(AgentFilter, cancellationToken).ConfigureAwait(false); + ApplySearchFilter(); + SelectedRow = 0; } /// - /// Resolves , , and - /// for whatever row - /// now points at in . Called from 's setter. + /// Applies a new search filter over subject, last sender, and last recipients, and + /// selects the first matching row. /// - private void SyncSelectionBlocking() + public void ApplySearch(string text) { - var row = Rows.Count > 0 && _selectedRow >= 0 && _selectedRow < Rows.Count ? Rows[_selectedRow] : null; - - switch (row) - { - case MailListRow.Thread threadRow: - var messages = GetOrLoadThreadMessagesBlocking(threadRow.Summary.ThreadId); - ViewMode = MailViewMode.Thread; - ThreadMessages = messages; - SelectedMessage = messages.Count > 0 ? messages[^1] : null; - break; - - case MailListRow.MessageRow messageRow: - ViewMode = MailViewMode.Message; - ThreadMessages = []; - SelectedMessage = messageRow.Message; - break; - - default: - ViewMode = MailViewMode.Message; - ThreadMessages = []; - SelectedMessage = null; - break; - } + SearchText = text.Trim(); + ApplySearchFilter(); + SelectedRow = 0; } - private IReadOnlyList GetOrLoadThreadMessagesBlocking(string threadId) + private void ApplySearchFilter() { - if (_threadMessageCache.TryGetValue(threadId, out var cached)) - { - return cached; - } - - var messages = loader.LoadThreadAsync(threadId, CancellationToken.None).GetAwaiter().GetResult(); - _threadMessageCache[threadId] = messages; - return messages; + Threads = SearchText.Length == 0 + ? _allThreads + : _allThreads.Where(Matches).ToList(); } - /// - /// A row identity containing its kind and its thread or message id. - /// - private static string RowKey(MailListRow row) => row switch - { - MailListRow.Thread t => $"thread:{t.Summary.ThreadId}", - MailListRow.MessageRow m => $"message:{m.Message.Id}", - _ => "" - }; + private bool Matches(MailThreadSummary thread) + => thread.Subject.Contains(SearchText, StringComparison.OrdinalIgnoreCase) + || thread.LastSender.Contains(SearchText, StringComparison.OrdinalIgnoreCase) + || thread.LastRecipients.Any(name => name.Contains(SearchText, StringComparison.OrdinalIgnoreCase)); - private static int IndexOfRow(IReadOnlyList rows, string key) + private static int IndexOf(IReadOnlyList threads, string threadId) { - for (var i = 0; i < rows.Count; i++) + for (var i = 0; i < threads.Count; i++) { - if (RowKey(rows[i]) == key) + if (threads[i].ThreadId == threadId) { return i; } @@ -475,41 +110,4 @@ private static int IndexOfRow(IReadOnlyList rows, string key) return -1; } - - /// - /// Routes to the load method for : Inbox is the - /// only mailbox affects, and Workspace is the only - /// mailbox affects. - /// - private Task> LoadMessagesAsync(CancellationToken cancellationToken) => Mailbox switch - { - MailMailbox.Sent => loader.LoadSentAsync(RequiredActor, cancellationToken), - MailMailbox.All => loader.LoadAllAsync(RequiredActor, cancellationToken), - MailMailbox.Workspace => loader.LoadWorkspaceAsync(AgentFilter, cancellationToken), - _ => loader.LoadInboxAsync(RequiredActor, Filter, cancellationToken) - }; - - /// - /// Loads thread summaries for the current mailbox and filters. - /// - private async Task> LoadThreadsAsync(CancellationToken cancellationToken) - { - switch (Mailbox) - { - case MailMailbox.Sent: - return await loader.LoadSentThreadsAsync(RequiredActor, cancellationToken).ConfigureAwait(false); - - case MailMailbox.All: - return await loader.LoadAllThreadsAsync(RequiredActor, cancellationToken).ConfigureAwait(false); - - case MailMailbox.Workspace: - return await loader.LoadWorkspaceThreadsAsync(AgentFilter, cancellationToken).ConfigureAwait(false); - - default: - var threads = await loader.LoadInboxThreadsAsync(RequiredActor, Filter, cancellationToken).ConfigureAwait(false); - return Filter == MailListFilter.Unread - ? threads.Where(t => (t.UnreadCount ?? 0) > 0).ToList() - : threads; - } - } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailTable.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailTable.cs index 6922c7ac08b..cb65e4f6394 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailTable.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailTable.cs @@ -1,271 +1,203 @@ +using System.Globalization; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Tui.Theming; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; namespace ChilliCream.Nitro.CommandLine.Tui.Mail; /// -/// Renders aligned mail headings, thread summaries, and message rows as markup. +/// Renders the Mail table's header row and each thread row: subject, from, to, message +/// count, and last-activity columns. Narrow widths drop To first, then From, then +/// Messages, identically for the header and the rows so the two always agree. Built on +/// the shared and table widget. /// internal static class MailTable { private const string SelectedPrefix = "> "; private const string UnselectedPrefix = " "; - private const string ExpandedFoldGlyph = "โ–พ"; - private const string CollapsedFoldGlyph = "โ–ธ"; - private const string NoFoldGlyph = " "; - private const string UnreadToMeMarker = "โ—"; - private const string ReadMarker = " "; - /// - /// Thread-membership indicator for an indented, expanded-thread child - /// row, distinct from the from-me/direct/broadcast relationship glyph. - /// - private const string ThreadChildGlyph = "โ””"; - - private const int SelectionWidth = 2; - private const int FoldWidth = 2; - private const int MarkerWidth = 2; - private const int GlyphWidth = 2; - private const int FromWidth = 14; - private const int ToWidth = 14; - private const int AgeWidth = 10; - private const int CountWidth = 5; - private const int ColumnGap = 1; - private const int MinElasticWidth = 3; - - /// - /// The subject/preview elastic split: subject gets two fifths of - /// whatever remains after the fixed-width columns, preview gets the - /// rest. - /// - private const int SubjectShareNumerator = 2; - private const int SubjectShareDenominator = 5; + private const string SubjectHeader = "SUBJECT"; + private const string FromHeader = "FROM"; + private const string ToHeader = "TO"; + private const string MessagesHeader = "MESSAGES"; + private const string LastActivityHeader = "LAST ACTIVITY"; + + private const int MinSubjectWidth = 24; + private const int MinFromWidth = 10; + private const int MinToWidth = 10; + private const int MinMessagesWidth = 8; + private const int MinLastActivityWidth = 13; + + private const string NowLabel = "now"; + private const string JustNowLabel = "just now"; + private const string AgoSuffix = " ago"; + private const string IsoDateFormat = "yyyy-MM-dd"; + + // To drops first, then From, then Messages; Subject and Last Activity have no drop + // priority so they are never dropped. + private static readonly IReadOnlyList s_columns = + [ + new TableColumnSpec(SubjectHeader, MinSubjectWidth), + new TableColumnSpec(FromHeader, MinFromWidth, DropPriority: 1), + new TableColumnSpec(ToHeader, MinToWidth, DropPriority: 0), + new TableColumnSpec(MessagesHeader, MinMessagesWidth, DropPriority: 2, Alignment: ColumnAlignment.Right), + new TableColumnSpec(LastActivityHeader, MinLastActivityWidth) + ]; /// - /// The column widths and count-column visibility shared by a heading and its rows. + /// The column widths a set of rows agree on: each column padded to at least its minimum + /// width, and wider still when its header title or a row's value needs more room. /// - public readonly record struct Columns( - int PrefixWidth, int FromWidth, int ToWidth, int SubjectWidth, int PreviewWidth, int AgeWidth, - int CountWidth, bool ShowCount); + public readonly record struct Widths(int Subject, int From, int To, int Messages, int LastActivity); /// - /// Computes column widths with an optional count column, allocating remaining - /// space to Subject and Preview. Fixed columns can exceed the available width; - /// elastic columns shrink to zero. + /// Computes across , with each column no + /// narrower than its minimum width or its header title. /// - public static Columns ComputeColumns(int contentWidth, bool showCount) + public static Widths ComputeWidths(IReadOnlyList rows, DateTimeOffset now) { - const int prefixWidth = SelectionWidth + FoldWidth + MarkerWidth + GlyphWidth; - var countBudget = showCount ? CountWidth + ColumnGap : 0; + var rowValues = new List>(rows.Count); - var fixedWidth = prefixWidth - + FromWidth + ColumnGap - + ToWidth + ColumnGap - + AgeWidth + ColumnGap - + countBudget; - - // Reserve the remaining gap between the elastic columns. - var elastic = Math.Max(0, contentWidth - fixedWidth - ColumnGap); - var subjectWidth = elastic <= 0 ? 0 : Math.Min(elastic, Math.Max(MinElasticWidth, elastic * SubjectShareNumerator / SubjectShareDenominator)); - var previewWidth = Math.Max(0, elastic - subjectWidth); + foreach (var row in rows) + { + rowValues.Add( + [ + row.Subject, + row.LastSender, + FormatRecipients(row.LastRecipients), + FormatMessageCount(row.MessageCount), + FormatActivityAge(row.LastMessageAt, now) + ]); + } - return new Columns(prefixWidth, FromWidth, ToWidth, subjectWidth, previewWidth, AgeWidth, CountWidth, showCount); + var widths = TableLayout.ComputeWidths(s_columns, rowValues); + return new Widths(widths[0], widths[1], widths[2], widths[3], widths[4]); } /// - /// Renders the heading row: column labels aligned to , - /// styled via mail.row.heading. The prefix area (selection, fold, - /// unread, and relationship columns) carries no label. + /// Builds the markup line for one thread row. Columns are padded to . + /// When the full set of columns does not fit within display + /// columns, To is dropped first, then From, then Messages; Subject and Last Activity + /// always remain, with Subject truncated as a last resort. A + /// of 0 or less produces an empty line. /// - public static string RenderHeading(Columns columns) + public static string Render(MailThreadSummary row, DateTimeOffset now, bool selected, int maxWidth, Widths widths) { - var cells = new List + if (maxWidth <= 0) { - new string(' ', columns.PrefixWidth - 1), - Pad("From", columns.FromWidth), - Pad("To", columns.ToWidth), - Pad("Subject", columns.SubjectWidth), - Pad("Preview", columns.PreviewWidth), - Pad("Age", columns.AgeWidth) - }; + return string.Empty; + } + + var prefix = selected ? SelectedPrefix : UnselectedPrefix; + var subjectStyle = ThemeTokens.GetStyle("mail.list.subject").ToMarkup(); + var fromStyle = ThemeTokens.GetStyle("mail.list.from").ToMarkup(); + var toStyle = ThemeTokens.GetStyle("mail.list.to").ToMarkup(); + var messagesStyle = ThemeTokens.GetStyle("mail.list.messages").ToMarkup(); + var ageStyle = ThemeTokens.GetStyle("mail.list.age").ToMarkup(); - if (columns.ShowCount) + var cells = new TableCellSpec[] { - cells.Add(PadLeft("#", columns.CountWidth)); - } + new(row.Subject, subjectStyle), + new(row.LastSender, fromStyle), + new(FormatRecipients(row.LastRecipients), toStyle), + new(FormatMessageCount(row.MessageCount), messagesStyle), + new(FormatActivityAge(row.LastMessageAt, now), ageStyle) + }; - var plain = string.Join(' ', cells).TrimEnd(); - return Stylize(ThemeTokens.GetStyle("mail.row.heading").ToMarkup(), Markup.Escape(plain)); - } + var budget = maxWidth - PrefixWidth(prefix); + var layout = TableLayout.Plan(budget, s_columns, ToWidthList(widths)); + var line = TableRenderer.RenderRow(prefix, new TableCellSpec(string.Empty), cells, s_columns, layout); - /// - /// Renders a thread summary using the supplied expansion, selection, and - /// actor-specific unread state. - /// - public static string RenderThreadRow( - MailThreadSummary summary, - bool expanded, - bool unreadToMe, - bool selected, - string actor, - DateTimeOffset now, - Columns columns) - { - var prefix = BuildPrefix( - selected, - foldGlyph: expanded ? ExpandedFoldGlyph : CollapsedFoldGlyph, - unreadToMe, - glyph: ThreadRelationshipGlyph(summary, actor)); - - var from = Pad(summary.LastSender, columns.FromWidth); - var to = Pad(FormatOverflowList(summary.LastRecipients), columns.ToWidth); - var subject = Truncate(summary.Subject, columns.SubjectWidth); - var preview = Truncate(summary.BodyPreview, columns.PreviewWidth); - var age = MailAges.Format(summary.LastMessageAt, now); - - var fromMarkup = StylizeFrom(from, IsSelf(summary.LastSender, actor)); - var toMarkup = Stylize(ThemeTokens.GetStyle("mail.row.to").ToMarkup(), Markup.Escape(to)); - var subjectMarkup = StylizeSubject(Pad(subject, columns.SubjectWidth), unreadToMe); - var previewMarkup = Stylize( - ThemeTokens.GetStyle("mail.row.preview").ToMarkup(), Markup.Escape(Pad(preview, columns.PreviewWidth))); - var ageMarkup = Stylize(ThemeTokens.GetStyle("mail.row.age").ToMarkup(), Markup.Escape(Pad(age, columns.AgeWidth))); - - var line = $"{prefix}{fromMarkup} {toMarkup} {subjectMarkup} {previewMarkup} {ageMarkup}"; - - if (columns.ShowCount) + if (selected) { - var countMarkup = Stylize( - ThemeTokens.GetStyle("mail.row.thread.count").ToMarkup(), - Markup.Escape(PadLeft($"({summary.MessageCount})", columns.CountWidth))); - line += $" {countMarkup}"; + var highlightStyle = ThemeTokens.GetStyle("selection.highlight").ToMarkup(); + line = TableRenderer.Stylize(highlightStyle, line); } - return selected ? Stylize(ThemeTokens.GetStyle("selection.highlight").ToMarkup(), line) : line; + return line; } /// - /// Renders a message using the supplied selection and actor-specific unread state. - /// An expanded thread child uses the thread-membership glyph; the count column - /// is blank for all message rows. + /// Builds the header title line shown above the rows: SUBJECT, FROM, TO, MESSAGES, + /// LAST ACTIVITY, aligned to . Columns are dropped using the + /// same thresholds as , so the header always agrees with the rows + /// below it. A of 0 or less produces an empty line. /// - public static string RenderMessageRow( - MailMessage message, - bool threadChild, - bool unreadToMe, - bool selected, - string actor, - DateTimeOffset now, - Columns columns) + public static string RenderHeader(int maxWidth, Widths widths) { - var glyph = threadChild ? ThreadChildGlyph : MailRecipientView.GetRelationshipGlyph(message, actor).ToString(); - var glyphToken = threadChild ? "mail.row.thread.membership" : GlyphToken(MailRecipientView.GetRelationshipGlyph(message, actor)); - - var prefix = BuildPrefix( - selected, - foldGlyph: NoFoldGlyph, - unreadToMe, - glyphText: glyph, - glyphToken: glyphToken); - - var to = FormatOverflowList(RecipientNames(message)); - var preview = CreatePreview(message.Body); - - var from = Pad(message.Sender, columns.FromWidth); - var toPadded = Pad(to, columns.ToWidth); - var subject = Truncate(message.Subject, columns.SubjectWidth); - var age = MailAges.Format(message.CreatedAt, now); - - var fromMarkup = StylizeFrom(from, IsSelf(message.Sender, actor)); - var toMarkup = Stylize(ThemeTokens.GetStyle("mail.row.to").ToMarkup(), Markup.Escape(toPadded)); - var subjectMarkup = StylizeSubject(Pad(subject, columns.SubjectWidth), unreadToMe); - var previewMarkup = Stylize( - ThemeTokens.GetStyle("mail.row.preview").ToMarkup(), - Markup.Escape(Pad(Truncate(preview, columns.PreviewWidth), columns.PreviewWidth))); - var ageMarkup = Stylize(ThemeTokens.GetStyle("mail.row.age").ToMarkup(), Markup.Escape(Pad(age, columns.AgeWidth))); - - var line = $"{prefix}{fromMarkup} {toMarkup} {subjectMarkup} {previewMarkup} {ageMarkup}"; - - if (columns.ShowCount) + if (maxWidth <= 0) { - line += $" {new string(' ', columns.CountWidth)}"; + return string.Empty; } - return selected ? Stylize(ThemeTokens.GetStyle("selection.highlight").ToMarkup(), line) : line; + var headerStyle = ThemeTokens.GetStyle("mail.list.header").ToMarkup(); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var layout = TableLayout.Plan(budget, s_columns, ToWidthList(widths)); + + return TableRenderer.RenderRow( + UnselectedPrefix, new TableCellSpec(string.Empty), BuildHeaderCells(headerStyle), s_columns, layout); } - private static string BuildPrefix( - bool selected, - string foldGlyph, - bool unreadToMe, - char? glyph = null, - string? glyphText = null, - string? glyphToken = null) + /// + /// Builds the dashed rule line under the header, filling + /// display columns. A of 0 or less produces an empty line. + /// + public static string RenderRule(int maxWidth) { - var selectionText = selected ? SelectedPrefix : UnselectedPrefix; - var foldMarkup = Stylize(ThemeTokens.GetStyle("mail.row.thread.fold").ToMarkup(), Markup.Escape(Pad(foldGlyph, FoldWidth - 1))); - var markerText = unreadToMe ? UnreadToMeMarker : ReadMarker; - var markerMarkup = unreadToMe - ? Stylize(ThemeTokens.GetStyle("mail.row.unread-to-me").ToMarkup(), Markup.Escape(Pad(markerText, MarkerWidth - 1))) - : Markup.Escape(Pad(markerText, MarkerWidth - 1)); - - var resolvedGlyphText = glyphText ?? glyph?.ToString() ?? " "; - var resolvedGlyphToken = glyphToken ?? (glyph is { } g ? GlyphToken(g) : string.Empty); - var glyphMarkup = resolvedGlyphToken.Length == 0 - ? Markup.Escape(Pad(resolvedGlyphText, GlyphWidth - 1)) - : Stylize(ThemeTokens.GetStyle(resolvedGlyphToken).ToMarkup(), Markup.Escape(Pad(resolvedGlyphText, GlyphWidth - 1))); - - return $"{Markup.Escape(selectionText)}{foldMarkup} {markerMarkup} {glyphMarkup} "; + var ruleStyle = ThemeTokens.GetStyle("mail.list.age").ToMarkup(); + return TableRenderer.RenderRule(maxWidth, ruleStyle); } - private static char ThreadRelationshipGlyph(MailThreadSummary summary, string actor) + /// + /// Appends the Mail table's fixed top block to : a blank line, the + /// header row and the rule, keeping only the first of the + /// three. A of 0 or less appends nothing. + /// + public static void AddHeaderLines(List lines, int headerLineCount, int maxWidth, Widths widths) { - if (IsSelf(summary.LastSender, actor)) - { - return MailRecipientView.FromActorGlyph; - } - - var isRecipient = summary.LastRecipients.Any(r => IsSelf(r, actor)); - - if (!isRecipient) + if (maxWidth <= 0) { - return MailRecipientView.BlankGlyph; + return; } - return summary.LastRecipients.Count == 1 ? MailRecipientView.DirectGlyph : MailRecipientView.BroadcastGlyph; + var headerStyle = ThemeTokens.GetStyle("mail.list.header").ToMarkup(); + var ruleStyle = ThemeTokens.GetStyle("mail.list.age").ToMarkup(); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var layout = TableLayout.Plan(budget, s_columns, ToWidthList(widths)); + + TableRenderer.RenderTopBlock( + lines, + headerLineCount, + maxWidth, + UnselectedPrefix, + new TableCellSpec(string.Empty), + s_columns, + layout, + headerStyle, + ruleStyle); } - private static bool IsSelf(string name, string actor) => string.Equals(name, actor, StringComparison.OrdinalIgnoreCase); + private static TableCellSpec[] BuildHeaderCells(string headerStyle) => + [ + new(SubjectHeader, headerStyle), + new(FromHeader, headerStyle), + new(ToHeader, headerStyle), + new(MessagesHeader, headerStyle), + new(LastActivityHeader, headerStyle) + ]; - private static string GlyphToken(char glyph) => glyph switch - { - MailRecipientView.FromActorGlyph => "mail.row.glyph.from-me", - MailRecipientView.DirectGlyph => "mail.row.glyph.direct", - MailRecipientView.BroadcastGlyph => "mail.row.glyph.broadcast", - _ => string.Empty - }; + private static int PrefixWidth(string prefix) => DisplayWidth.Measure(prefix) + 1; - private static string StylizeFrom(string paddedText, bool isSelf) - { - var token = isSelf ? "mail.row.from.me" : "mail.row.from"; - return Stylize(ThemeTokens.GetStyle(token).ToMarkup(), Markup.Escape(paddedText)); - } + private static IReadOnlyList ToWidthList(Widths widths) => + [widths.Subject, widths.From, widths.To, widths.Messages, widths.LastActivity]; - private static string StylizeSubject(string paddedText, bool unreadToMe) - { - var token = unreadToMe ? "mail.row.unread-to-me" : string.Empty; - return token.Length == 0 - ? Markup.Escape(paddedText) - : Stylize(ThemeTokens.GetStyle(token).ToMarkup(), Markup.Escape(paddedText)); - } - - private static IReadOnlyList RecipientNames(MailMessage message) - => message.Recipients.OrderBy(r => r.Ordinal).Select(r => r.Name).ToArray(); + private static string FormatMessageCount(int count) => count.ToString(CultureInfo.InvariantCulture); /// - /// Returns the first name with a count of additional names, or an empty string - /// for an empty list. + /// Returns the first recipient name with a count of additional names, or an empty + /// string for an empty list. /// - private static string FormatOverflowList(IReadOnlyList names) + private static string FormatRecipients(IReadOnlyList names) { if (names.Count == 0) { @@ -277,18 +209,23 @@ private static string FormatOverflowList(IReadOnlyList names) } /// - /// Returns the body with each run of whitespace replaced by a single space and - /// leading and trailing whitespace removed. + /// Formats the elapsed time between and : + /// "just now" under a minute, a relative duration ("26m", "3h", "2d") with an " ago" + /// suffix, or an absolute date once the thread's last activity is a week or older. /// - private static string CreatePreview(string body) - => string.Join(' ', body.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); - - private static string Stylize(string styleMarkup, string content) => - styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; + private static string FormatActivityAge(DateTimeOffset value, DateTimeOffset now) + { + var formatted = MailAges.Format(value, now); - private static string Pad(string value, int width) => DisplayWidth.PadRight(value, width); + if (formatted == NowLabel) + { + return JustNowLabel; + } - private static string PadLeft(string value, int width) => DisplayWidth.PadLeft(value, width); + return IsAbsoluteDate(formatted) ? formatted : formatted + AgoSuffix; + } - private static string Truncate(string value, int width) => DisplayWidth.Truncate(value, width); + private static bool IsAbsoluteDate(string formatted) => + DateTime.TryParseExact( + formatted, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out _); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailThreadPopover.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailThreadPopover.cs new file mode 100644 index 00000000000..7325066f23f --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailThreadPopover.cs @@ -0,0 +1,370 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tui.Details; +using ChilliCream.Nitro.CommandLine.Tui.Input; +using ChilliCream.Nitro.CommandLine.Tui.Shell; +using ChilliCream.Nitro.CommandLine.Tui.Theming; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; +using Spectre.Console.Rendering; + +namespace ChilliCream.Nitro.CommandLine.Tui.Mail; + +/// +/// A tab-specific request payload carried by , interpreted +/// by . +/// +internal abstract record MailThreadPopoverRequest +{ + private MailThreadPopoverRequest() + { + } + + /// + /// The popover's own thread id should be copied, the same flow the Mail table's y key + /// starts. + /// + public sealed record CopyRequested(string ThreadId) : MailThreadPopoverRequest; +} + +/// +/// Loads one workspace thread's messages and drives the read-only detail overlay opened from +/// the Mail tab: a header of participants, message count, and ages, then every message oldest +/// first with its recipients and wrapped body. Never marks anything read. Reloads on +/// and recomputes ages on every , both driven by the +/// hosting shell. +/// +internal sealed class MailThreadPopoverModel : IPopover +{ + private const int PanelChromeWidth = 4; + private const int PanelChromeHeight = 2; + + /// + /// The popover's footer hints. + /// + public static readonly IReadOnlyList DefaultHints = + [ + new KeyHint("up/down", "prev/next"), + new KeyHint("pgup/pgdn", "scroll"), + new KeyHint("y", "copy id"), + new KeyHint("esc", "close") + ]; + + private readonly IMailStore _mailStore; + private readonly IAgentStore _agentStore; + private readonly TimeProvider _timeProvider; + private readonly Func _moveSelection; + private readonly Viewport _bodyViewport = new(0, 0); + + private string _threadId; + private IReadOnlyList _messages = []; + private IReadOnlyDictionary _agentsBySender = new Dictionary(); + private string _lastAgeSignature = string.Empty; + + public MailThreadPopoverModel( + string threadId, + IMailStore mailStore, + IAgentStore agentStore, + TimeProvider timeProvider, + Func moveSelection) + { + ArgumentException.ThrowIfNullOrEmpty(threadId); + ArgumentNullException.ThrowIfNull(mailStore); + ArgumentNullException.ThrowIfNull(agentStore); + ArgumentNullException.ThrowIfNull(timeProvider); + ArgumentNullException.ThrowIfNull(moveSelection); + + _threadId = threadId; + _mailStore = mailStore; + _agentStore = agentStore; + _timeProvider = timeProvider; + _moveSelection = moveSelection; + } + + /// + public IReadOnlyList Hints => DefaultHints; + + /// + /// Loads (or reloads) the thread's messages, oldest first, and resolves each distinct + /// sender's agent row for harness attribution, blocking the caller. + /// + public void Load(CancellationToken cancellationToken = default) => + LoadAsync(cancellationToken).GetAwaiter().GetResult(); + + private async Task LoadAsync(CancellationToken cancellationToken) + { + _messages = await _mailStore.GetThreadMessagesAsync(_threadId, cancellationToken); + + var agentsBySender = new Dictionary(); + + foreach (var sender in _messages.Select(m => m.Sender).Distinct()) + { + agentsBySender[sender] = await _agentStore.FindAsync(sender, cancellationToken); + } + + _agentsBySender = agentsBySender; + _lastAgeSignature = ComputeAgeSignature(_timeProvider.GetUtcNow()); + } + + /// + /// Recomputes every message's and the header's formatted age as of now. Returns whether + /// anything the render depends on changed since the last call. + /// + public bool Tick() + { + var signature = ComputeAgeSignature(_timeProvider.GetUtcNow()); + + if (signature == _lastAgeSignature) + { + return false; + } + + _lastAgeSignature = signature; + return true; + } + + private string ComputeAgeSignature(DateTimeOffset now) + { + if (_messages.Count == 0) + { + return string.Empty; + } + + var started = MailAges.Format(_messages[0].CreatedAt, now); + var lastActivity = MailAges.Format(_messages[^1].CreatedAt, now); + var perMessage = string.Join('\u0001', _messages.Select(m => MailAges.Format(m.CreatedAt, now))); + + return $"{started}\u0001{lastActivity}\u0001{perMessage}"; + } + + /// + /// Handles one raw key: Up/Down and j/k move to the previous or next table row and reload + /// onto it, PageUp/PageDown and Ctrl+U/Ctrl+D scroll the body, g/G jump to the first or last + /// line, y reports copying the thread id, and Escape closes the popover. + /// + public PopoverResult? HandleKey(ConsoleKeyInfo info) + { + switch (info.Key) + { + case ConsoleKey.DownArrow: + case ConsoleKey.J: + return MoveSelection(1); + + case ConsoleKey.UpArrow: + case ConsoleKey.K: + return MoveSelection(-1); + + case ConsoleKey.PageDown: + case ConsoleKey.D when info.Modifiers == ConsoleModifiers.Control: + ScrollByPage(1); + return null; + + case ConsoleKey.PageUp: + case ConsoleKey.U when info.Modifiers == ConsoleModifiers.Control: + ScrollByPage(-1); + return null; + + case ConsoleKey.G when info.Modifiers == ConsoleModifiers.None: + _bodyViewport.ScrollBy(int.MinValue / 2); + return null; + + case ConsoleKey.G when info.Modifiers == ConsoleModifiers.Shift: + _bodyViewport.ScrollBy(int.MaxValue / 2); + return null; + + case ConsoleKey.Y when info.Modifiers == ConsoleModifiers.None: + return new PopoverResult.Request(new MailThreadPopoverRequest.CopyRequested(_threadId)); + + case ConsoleKey.Escape: + return new PopoverResult.Closed(); + + default: + return null; + } + } + + /// + /// Moves to the thread steps away from the current one in the + /// owning table, reloads onto it, and resets the body scroll to the top. Does nothing at + /// the first or last thread. + /// + private PopoverResult? MoveSelection(int delta) + { + if (_moveSelection(delta) is not { } next) + { + return null; + } + + _threadId = next.ThreadId; + Load(); + _bodyViewport.ScrollBy(int.MinValue / 2); + return null; + } + + private void ScrollByPage(int direction) => + _bodyViewport.ScrollBy(direction * Math.Max(1, _bodyViewport.WindowHeight / 2)); + + /// + /// Renders the centered detail overlay at about 80% of the given area. + /// + public IRenderable Render(int width, int height) + { + if (width <= 0 || height <= 0) + { + return new Markup(string.Empty); + } + + var panelWidth = Math.Max(1, Math.Min(width, (int)(width * 0.8))); + var panelHeight = Math.Max(1, Math.Min(height, (int)(height * 0.8))); + var contentWidth = Math.Max(0, panelWidth - PanelChromeWidth); + var interiorHeight = Math.Max(0, panelHeight - PanelChromeHeight); + + var now = _timeProvider.GetUtcNow(); + var lines = MailThreadPopoverView.BuildLines(_messages, _agentsBySender, now, contentWidth); + + _bodyViewport.Update(lines.Count, interiorHeight); + var (start, count) = _bodyViewport.Slice(); + + var visible = new List(interiorHeight); + + for (var i = 0; i < count; i++) + { + visible.Add(lines[start + i]); + } + + while (visible.Count < interiorHeight) + { + visible.Add(string.Empty); + } + + var header = MailThreadPopoverView.BuildHeader(_messages); + var panel = ColumnPane.RenderWithHeader(header, visible, focused: true); + panel.Width = panelWidth; + panel.Height = panelHeight; + + return new Align(panel, HorizontalAlignment.Center, VerticalAlignment.Middle) + .Width(width) + .Height(height); + } +} + +/// +/// Pure formatting for the mail thread popover: the panel title, the participants and +/// activity header, and each message's speaker line, recipients, and wrapped body. +/// +internal static class MailThreadPopoverView +{ + /// + /// A blank spacer row. A single space, not an empty string, so the panel's row renderer + /// keeps it as a line instead of collapsing it away. + /// + private const string BlankLine = " "; + + /// + /// The panel title: the thread's subject, or a placeholder when it has no messages. + /// + public static string BuildHeader(IReadOnlyList messages) => + messages.Count > 0 ? Markup.Escape(messages[0].Subject) : "Thread"; + + /// + /// Builds every line of the popover: a leading blank line, the header block + /// (Participants, Messages, Started, Last activity), a blank line, then each message + /// oldest first with its speaker line, its To and Cc lines when present, and its wrapped + /// body, with a blank line between messages. + /// + public static IReadOnlyList BuildLines( + IReadOnlyList messages, + IReadOnlyDictionary agentsBySender, + DateTimeOffset now, + int width) + { + var lines = new List(); + + if (messages.Count == 0) + { + lines.Add("No messages."); + return lines; + } + + lines.Add(BlankLine); + AppendHeaderFields(lines, messages, now); + lines.Add(BlankLine); + + for (var i = 0; i < messages.Count; i++) + { + if (i > 0) + { + lines.Add(BlankLine); + } + + AppendMessage(lines, messages[i], agentsBySender, now, width); + } + + return lines; + } + + private static void AppendHeaderFields( + List lines, IReadOnlyList messages, DateTimeOffset now) + { + var participants = messages + .SelectMany(m => m.Recipients.Select(r => r.Name).Append(m.Sender)) + .Distinct() + .OrderBy(name => name, StringComparer.Ordinal); + + lines.Add(FormatField("Participants", string.Join(", ", participants))); + lines.Add(FormatField("Messages", messages.Count.ToString())); + lines.Add(FormatField("Started", MailAges.Format(messages[0].CreatedAt, now))); + lines.Add(FormatField("Last activity", MailAges.Format(messages[^1].CreatedAt, now))); + } + + private static void AppendMessage( + List lines, + MailMessage message, + IReadOnlyDictionary agentsBySender, + DateTimeOffset now, + int width) + { + var titleStyle = ThemeTokens.GetStyle("detail.section.header").ToMarkup(); + lines.Add(Stylize(titleStyle, Markup.Escape(FormatSpeakerLine(message, agentsBySender, now)))); + + var to = FormatRecipients(message, MailRecipientKinds.To); + + if (to.Length > 0) + { + lines.Add(FormatField("To", to)); + } + + var cc = FormatRecipients(message, MailRecipientKinds.Cc); + + if (cc.Length > 0) + { + lines.Add(FormatField("Cc", cc)); + } + + foreach (var bodyLine in TaskDetailSections.WrapText(message.Body, width)) + { + var escaped = Markup.Escape(bodyLine); + lines.Add(escaped.Length == 0 ? BlankLine : escaped); + } + } + + private static string FormatSpeakerLine( + MailMessage message, IReadOnlyDictionary agentsBySender, DateTimeOffset now) + { + var agent = agentsBySender.GetValueOrDefault(message.Sender); + var name = agent?.Harness is { Length: > 0 } harness + ? $"{message.Sender} ({AgentHarnessDisplay.Name(harness)})" + : message.Sender; + + return $"{name} ยท {MailAges.Format(message.CreatedAt, now)}"; + } + + private static string FormatRecipients(MailMessage message, string kind) => string.Join( + ", ", + message.Recipients.Where(r => r.Kind == kind).OrderBy(r => r.Ordinal).Select(r => r.Name)); + + private static string FormatField(string label, string value) => + $"[dim]{Markup.Escape(label)}:[/] {Markup.Escape(value)}"; + + private static string Stylize(string styleMarkup, string content) => + styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailViewMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailViewMode.cs deleted file mode 100644 index 795ca04c236..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Mail/MailViewMode.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Mail; - -/// -/// What the mail board's detail pane currently renders: the selected -/// message alone, or its whole thread in chronological order. -/// -internal enum MailViewMode -{ - Message, - Thread -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryCollectionFilter.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryCollectionFilter.cs index 5cf8f84d610..fef9d232332 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryCollectionFilter.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryCollectionFilter.cs @@ -1,10 +1,13 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// The memory collection the list pane currently shows: curated memories or journal entries. +/// The memory kind the Memory tab's table currently shows: every entry, curated memories +/// only, or journal entries only. Also tags a by its own kind, where +/// it is always or , never . /// internal enum MemoryCollectionFilter { + All, Curated, Journal } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDataLoader.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDataLoader.cs index 11e342403a3..13922162d4a 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDataLoader.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDataLoader.cs @@ -3,8 +3,9 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// Loads up to 200 curated memories or journal entries for the parsed query. -/// Type and tag filters apply only to curated memories. +/// Loads up to 200 curated memories or up to 200 journal entries for the parsed query, for +/// to merge into one table. Type and tag filters apply only to +/// curated memories. /// internal sealed class MemoryDataLoader(IMemoryStore store) { diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDetailView.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDetailView.cs index c12afb63ca4..9962bee602d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDetailView.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryDetailView.cs @@ -7,8 +7,10 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// Renders the selected memory's metadata and wrapped body as plain text in a -/// scrollable detail panel. +/// Renders a curated memory's or a journal entry's metadata and wrapped body as plain text in +/// a scrollable detail panel and maintains its scroll position. Used by a host outside the +/// Memory tab that has already loaded the item, such as the agent detail popover's memory +/// drill-in. /// internal sealed class MemoryDetailView { @@ -22,37 +24,54 @@ internal sealed class MemoryDetailView public void ScrollUp() => _bodyViewport.ScrollBy(-1); - public void ScrollToTop() => _bodyViewport.ScrollBy(int.MinValue / 2); + /// + /// Renders a curated memory's type, tags, and creation and modification metadata, with + /// the body wrapped below. + /// + public IRenderable RenderCurated(MemoryRecord record, int width, int height, bool focused) + { + if (width <= 0 || height <= 0) + { + return new Markup(string.Empty); + } - public void ScrollToBottom() => _bodyViewport.ScrollBy(int.MaxValue / 2); + var interiorWidth = Math.Max(1, Math.Max(1, width) - PanelChromeWidth); + var header = $"[dim]{Markup.Escape(record.Id)}[/]"; + + return RenderPanel(BuildCuratedLines(record, interiorWidth), header, "No item selected.", width, height, focused); + } /// - /// Resets the body scroll position to the top. + /// Renders a journal entry's creation metadata, with the body wrapped below. /// - public void ResetScroll() => _bodyViewport.Update(0, 0); - - public IRenderable Render(MemoryState state, int width, int height, bool focused) + public IRenderable RenderJournal(MemoryJournalEntry entry, int width, int height, bool focused) { if (width <= 0 || height <= 0) { return new Markup(string.Empty); } + var interiorWidth = Math.Max(1, Math.Max(1, width) - PanelChromeWidth); + var header = $"[dim]{Markup.Escape(entry.Id)}[/]"; + + return RenderPanel(BuildJournalLines(entry, interiorWidth), header, "No item selected.", width, height, focused); + } + + private IRenderable RenderPanel( + IReadOnlyList lines, string header, string emptyMessage, int width, int height, bool focused) + { var safeWidth = Math.Max(1, width); - var interiorWidth = Math.Max(1, safeWidth - PanelChromeWidth); var interiorHeight = Math.Max(1, height - PanelChromeHeight); - var lines = BuildLines(state, interiorWidth); - IRenderable content = lines.Count == 0 - ? Align.Center(new Markup(Markup.Escape(NoSelectionMessage(state))), VerticalAlignment.Middle) + ? Align.Center(new Markup(Markup.Escape(emptyMessage)), VerticalAlignment.Middle) : new Rows(RenderVisibleLines(lines, interiorHeight).Select(Row)); var borderToken = focused ? "board.column.border.focused" : "board.column.border"; return new Panel(content) { - Header = new PanelHeader(BuildHeader(state)), + Header = new PanelHeader(header), Border = BoxBorder.Rounded, BorderStyle = ThemeTokens.GetStyle(borderToken), Width = safeWidth, @@ -60,34 +79,6 @@ public IRenderable Render(MemoryState state, int width, int height, bool focused }; } - private static string BuildHeader(MemoryState state) => state.Collection switch - { - MemoryCollectionFilter.Curated when state.SelectedCuratedRecord is { } record - => $"[dim]{Markup.Escape(record.Id)}[/]", - MemoryCollectionFilter.Journal when state.SelectedJournalEntry is { } entry - => $"[dim]{Markup.Escape(entry.Id)}[/]", - _ => "Detail" - }; - - private static string NoSelectionMessage(MemoryState state) - { - if (state.LoadError is { } error) - { - return error; - } - - return state.ItemCount == 0 - ? state.Collection == MemoryCollectionFilter.Curated ? "No curated memories." : "No journal entries." - : "No item selected."; - } - - private static IReadOnlyList BuildLines(MemoryState state, int width) => state.Collection switch - { - MemoryCollectionFilter.Curated when state.SelectedCuratedRecord is { } record => BuildCuratedLines(record, width), - MemoryCollectionFilter.Journal when state.SelectedJournalEntry is { } entry => BuildJournalLines(entry, width), - _ => [] - }; - private static IReadOnlyList BuildCuratedLines(MemoryRecord record, int width) { var lines = new List @@ -111,11 +102,7 @@ private static IReadOnlyList BuildCuratedLines(MemoryRecord record, int private static IReadOnlyList BuildJournalLines(MemoryJournalEntry entry, int width) { - var lines = new List - { - $"Created: {MemoryDates.Format(entry.CreatedAt)} by {entry.CreatedBy}", - "Not yet promoted, or already promoted (press p to promote either way; a repeat is idempotent)." - }; + var lines = new List { $"Created: {MemoryDates.Format(entry.CreatedAt)} by {entry.CreatedBy}" }; lines.Add(string.Empty); lines.AddRange(TaskDetailSections.WrapText(entry.Body, width)); diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryEntryPopover.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryEntryPopover.cs new file mode 100644 index 00000000000..2a56b082d2a --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryEntryPopover.cs @@ -0,0 +1,337 @@ +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Tui.Agents; +using ChilliCream.Nitro.CommandLine.Tui.Details; +using ChilliCream.Nitro.CommandLine.Tui.Input; +using ChilliCream.Nitro.CommandLine.Tui.Shell; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; +using Spectre.Console.Rendering; + +namespace ChilliCream.Nitro.CommandLine.Tui.Memory; + +/// +/// A tab-specific request payload carried by , interpreted +/// by . +/// +internal abstract record MemoryEntryPopoverRequest +{ + private MemoryEntryPopoverRequest() + { + } + + /// + /// The popover's own entry id should be copied, the same flow the Memory table's y key + /// starts. + /// + public sealed record CopyRequested(string EntryId) : MemoryEntryPopoverRequest; +} + +/// +/// Loads one curated memory or journal entry and drives the read-only detail overlay opened +/// from the Memory tab: an id title, a header block, and the wrapped body. Reloads on +/// and recomputes ages on every , both driven by the +/// hosting shell. +/// +internal sealed class MemoryEntryPopoverModel : IPopover +{ + private const int PanelChromeWidth = 4; + private const int PanelChromeHeight = 2; + + /// + /// The popover's footer hints. + /// + public static readonly IReadOnlyList DefaultHints = + [ + new KeyHint("up/down", "prev/next"), + new KeyHint("pgup/pgdn", "scroll"), + new KeyHint("y", "copy id"), + new KeyHint("esc", "close") + ]; + + private readonly IMemoryStore _memoryStore; + private readonly TimeProvider _timeProvider; + private readonly Func _moveSelection; + private readonly Viewport _bodyViewport = new(0, 0); + + private string _id; + private MemoryCollectionFilter _kind; + private MemoryRecord? _curated; + private MemoryJournalEntry? _journal; + private string _lastAgeSignature = string.Empty; + + public MemoryEntryPopoverModel( + string id, + MemoryCollectionFilter kind, + IMemoryStore memoryStore, + TimeProvider timeProvider, + Func moveSelection) + { + ArgumentException.ThrowIfNullOrEmpty(id); + ArgumentNullException.ThrowIfNull(memoryStore); + ArgumentNullException.ThrowIfNull(timeProvider); + ArgumentNullException.ThrowIfNull(moveSelection); + + _id = id; + _kind = kind; + _memoryStore = memoryStore; + _timeProvider = timeProvider; + _moveSelection = moveSelection; + } + + /// + public IReadOnlyList Hints => DefaultHints; + + /// + /// Loads (or reloads) the entry: for a curated memory + /// or for a journal entry, blocking the + /// caller. A null lookup, such as one forgotten since the popover opened, clears the loaded + /// entry and renders the missing state instead. + /// + public void Load(CancellationToken cancellationToken = default) => + LoadAsync(cancellationToken).GetAwaiter().GetResult(); + + private async Task LoadAsync(CancellationToken cancellationToken) + { + if (_kind == MemoryCollectionFilter.Curated) + { + _curated = await _memoryStore.FindAsync(_id, cancellationToken); + } + else + { + _journal = await _memoryStore.FindJournalEntryAsync(_id, cancellationToken); + } + + _lastAgeSignature = ComputeAgeSignature(_timeProvider.GetUtcNow()); + } + + /// + /// Recomputes the header's formatted ages as of now. Returns whether anything the render + /// depends on changed since the last call. + /// + public bool Tick() + { + var signature = ComputeAgeSignature(_timeProvider.GetUtcNow()); + + if (signature == _lastAgeSignature) + { + return false; + } + + _lastAgeSignature = signature; + return true; + } + + private string ComputeAgeSignature(DateTimeOffset now) + { + if (_curated is { } curated) + { + return $"{AgentAges.Format(curated.CreatedAt, now)}\u0001{AgentAges.Format(curated.UpdatedAt, now)}"; + } + + if (_journal is { } journal) + { + return AgentAges.Format(journal.CreatedAt, now); + } + + return string.Empty; + } + + /// + /// Handles one raw key: Up/Down and j/k move to the previous or next table row and reload + /// onto it, PageUp/PageDown and Ctrl+U/Ctrl+D scroll the body, g/G jump to the first or last + /// line, y reports copying the entry id, and Escape closes the popover. + /// + public PopoverResult? HandleKey(ConsoleKeyInfo info) + { + switch (info.Key) + { + case ConsoleKey.DownArrow: + case ConsoleKey.J: + return MoveSelection(1); + + case ConsoleKey.UpArrow: + case ConsoleKey.K: + return MoveSelection(-1); + + case ConsoleKey.PageDown: + case ConsoleKey.D when info.Modifiers == ConsoleModifiers.Control: + ScrollByPage(1); + return null; + + case ConsoleKey.PageUp: + case ConsoleKey.U when info.Modifiers == ConsoleModifiers.Control: + ScrollByPage(-1); + return null; + + case ConsoleKey.G when info.Modifiers == ConsoleModifiers.None: + _bodyViewport.ScrollBy(int.MinValue / 2); + return null; + + case ConsoleKey.G when info.Modifiers == ConsoleModifiers.Shift: + _bodyViewport.ScrollBy(int.MaxValue / 2); + return null; + + case ConsoleKey.Y when info.Modifiers == ConsoleModifiers.None: + return new PopoverResult.Request(new MemoryEntryPopoverRequest.CopyRequested(_id)); + + case ConsoleKey.Escape: + return new PopoverResult.Closed(); + + default: + return null; + } + } + + /// + /// Moves to the row steps away from the current one in the owning + /// table, reloads onto it, and resets the body scroll to the top. Does nothing at the first + /// or last row. + /// + private PopoverResult? MoveSelection(int delta) + { + if (_moveSelection(delta) is not { } next) + { + return null; + } + + _id = next.Id; + _kind = next.Kind; + Load(); + _bodyViewport.ScrollBy(int.MinValue / 2); + return null; + } + + private void ScrollByPage(int direction) => + _bodyViewport.ScrollBy(direction * Math.Max(1, _bodyViewport.WindowHeight / 2)); + + /// + /// Renders the centered detail overlay at about 80% of the given area. + /// + public IRenderable Render(int width, int height) + { + if (width <= 0 || height <= 0) + { + return new Markup(string.Empty); + } + + var panelWidth = Math.Max(1, Math.Min(width, (int)(width * 0.8))); + var panelHeight = Math.Max(1, Math.Min(height, (int)(height * 0.8))); + var contentWidth = Math.Max(0, panelWidth - PanelChromeWidth); + var interiorHeight = Math.Max(0, panelHeight - PanelChromeHeight); + + var now = _timeProvider.GetUtcNow(); + var lines = MemoryEntryPopoverView.BuildLines(_curated, _journal, now, contentWidth); + + _bodyViewport.Update(lines.Count, interiorHeight); + var (start, count) = _bodyViewport.Slice(); + + var visible = new List(interiorHeight); + + for (var i = 0; i < count; i++) + { + visible.Add(lines[start + i]); + } + + while (visible.Count < interiorHeight) + { + visible.Add(string.Empty); + } + + var header = MemoryEntryPopoverView.BuildHeader(_id); + var panel = ColumnPane.RenderWithHeader(header, visible, focused: true); + panel.Width = panelWidth; + panel.Height = panelHeight; + + return new Align(panel, HorizontalAlignment.Center, VerticalAlignment.Middle) + .Width(width) + .Height(height); + } +} + +/// +/// Pure formatting for the memory entry popover: the panel title and the Kind, Type, Tags, +/// Created, Updated, and Promoted from header fields, followed by the wrapped body. +/// +internal static class MemoryEntryPopoverView +{ + /// + /// A blank spacer row. A single space, not an empty string, so the panel's row renderer + /// keeps it as a line instead of collapsing it away. + /// + private const string BlankLine = " "; + + private const string CuratedKindText = "curated"; + private const string JournalKindText = "journal"; + private const string NoTags = "-"; + private const string MissingStateText = "This entry no longer exists."; + + /// + /// The panel title: the entry id. + /// + public static string BuildHeader(string id) => Markup.Escape(id); + + /// + /// Builds every line of the popover: a leading blank line, then either the header fields + /// for the loaded curated memory or journal entry followed by a blank line and the wrapped + /// body, or a single missing-state line when neither is loaded. + /// + public static IReadOnlyList BuildLines( + MemoryRecord? curated, MemoryJournalEntry? journal, DateTimeOffset now, int width) + { + var lines = new List { BlankLine }; + + if (curated is { } record) + { + AppendCuratedFields(lines, record, now); + lines.Add(BlankLine); + AppendBody(lines, record.Body, width); + } + else if (journal is { } entry) + { + AppendJournalFields(lines, entry, now); + lines.Add(BlankLine); + AppendBody(lines, entry.Body, width); + } + else + { + lines.Add(MissingStateText); + } + + return lines; + } + + private static void AppendCuratedFields(List lines, MemoryRecord record, DateTimeOffset now) + { + lines.Add(FormatField("Kind", CuratedKindText)); + lines.Add(FormatField("Type", record.Type)); + lines.Add(FormatField("Tags", record.Tags.Count == 0 ? NoTags : string.Join(", ", record.Tags))); + lines.Add(FormatField("Created", $"{AgentAges.Format(record.CreatedAt, now)} by {record.CreatedBy}")); + + if (record.UpdatedAt != record.CreatedAt) + { + lines.Add(FormatField("Updated", AgentAges.Format(record.UpdatedAt, now))); + } + + if (record.PromotedFrom is { } promotedFrom) + { + lines.Add(FormatField("Promoted from", promotedFrom)); + } + } + + private static void AppendJournalFields(List lines, MemoryJournalEntry entry, DateTimeOffset now) + { + lines.Add(FormatField("Kind", JournalKindText)); + lines.Add(FormatField("Created", $"{AgentAges.Format(entry.CreatedAt, now)} by {entry.CreatedBy}")); + } + + private static void AppendBody(List lines, string body, int width) + { + foreach (var bodyLine in TaskDetailSections.WrapText(body, width)) + { + var escaped = Markup.Escape(bodyLine); + lines.Add(escaped.Length == 0 ? BlankLine : escaped); + } + } + + private static string FormatField(string label, string value) => + $"[dim]{Markup.Escape(label)}:[/] {Markup.Escape(value)}"; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryFocus.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryFocus.cs deleted file mode 100644 index b84cf6ce985..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryFocus.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ChilliCream.Nitro.CommandLine.Tui.Memory; - -/// -/// Which pane of the memory tab currently holds focus. -/// -internal enum MemoryFocus -{ - List, - Detail -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryForgetOutcome.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryForgetOutcome.cs deleted file mode 100644 index e96b2a5b4aa..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryForgetOutcome.cs +++ /dev/null @@ -1,35 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Tui.Input; - -namespace ChilliCream.Nitro.CommandLine.Tui.Memory; - -/// -/// The outcome of one write -/// against the memory store. -/// -internal abstract record MemoryForgetOutcome -{ - private MemoryForgetOutcome() - { - } - - /// - /// The delete succeeded. - /// - public sealed record Succeeded(string ToastText) : MemoryForgetOutcome; - - /// - /// The store rejected the write with an . - /// - public sealed record Failed(string ToastText) : MemoryForgetOutcome; - - /// - /// The shell toast this outcome should show: success styled for - /// , error styled for . - /// - public TuiMessage.ShowToast ToShowToast() => this switch - { - Succeeded succeeded => new TuiMessage.ShowToast(succeeded.ToastText, ToastStyle.Success), - Failed failed => new TuiMessage.ShowToast(failed.ToastText, ToastStyle.Error), - _ => throw new NotSupportedException() - }; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryJournalRowBadge.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryJournalRowBadge.cs deleted file mode 100644 index cbf2a3b7a3c..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryJournalRowBadge.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System.Globalization; -using ChilliCream.Nitro.CommandLine.Services.Memory; -using ChilliCream.Nitro.CommandLine.Tui.Theming; - -namespace ChilliCream.Nitro.CommandLine.Tui.Memory; - -/// -/// Renders a journal row with a selection prefix, UTC capture time, and body preview. -/// -internal static class MemoryJournalRowBadge -{ - private const string SelectedPrefix = "> "; - private const string UnselectedPrefix = " "; - - public readonly record struct Widths(int Day); - - /// - /// Computes across , the rows about to be rendered. - /// - public static Widths ComputeWidths(IReadOnlyList rows) - { - var dayWidth = 0; - - foreach (var entry in rows) - { - dayWidth = Math.Max(dayWidth, DisplayWidth.Measure(FormatDay(entry.CreatedAt))); - } - - return new Widths(dayWidth); - } - - /// - /// Builds the markup line for one journal entry row, padding - /// scope/day to and truncating a first-line - /// preview of the body so the whole line still fits within - /// display columns. A - /// of 0 or less produces an empty line. - /// - public static string Render( - MemoryJournalEntry entry, bool selected, int maxWidth, Widths widths) - { - if (maxWidth <= 0) - { - return string.Empty; - } - - var prefix = selected ? SelectedPrefix : UnselectedPrefix; - var day = DisplayWidth.PadRight(FormatDay(entry.CreatedAt), widths.Day); - var preview = FirstLine(entry.Body); - - var fixedPlainWidth = DisplayWidth.Measure(prefix) + DisplayWidth.Measure(day) + 1; - var previewBudget = Math.Max(0, maxWidth - fixedPlainWidth); - var truncatedPreview = DisplayWidth.Truncate(preview, previewBudget); - - var ageStyle = ThemeTokens.GetStyle("memory.list.age").ToMarkup(); - - var line = fixedPlainWidth > maxWidth - ? RenderNarrow(prefix, maxWidth, day, ageStyle) - : $"{Markup.Escape(prefix)}" - + $"{Stylize(ageStyle, Markup.Escape(day))} " - + Markup.Escape(truncatedPreview); - - if (selected) - { - var highlightStyle = ThemeTokens.GetStyle("selection.highlight").ToMarkup(); - line = Stylize(highlightStyle, line); - } - - return line; - } - - private static string FormatDay(DateTimeOffset createdAt) - => createdAt.ToUniversalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture); - - private static string FirstLine(string body) - { - var newlineIndex = body.IndexOfAny(['\r', '\n']); - return (newlineIndex < 0 ? body : body[..newlineIndex]).Trim(); - } - - private static string Stylize(string styleMarkup, string content) => - styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; - - private static string RenderNarrow(string prefix, int maxWidth, string day, string ageStyle) - { - var prefixText = DisplayWidth.Slice(prefix, maxWidth); - var remaining = maxWidth - DisplayWidth.Measure(prefixText); - var truncatedDay = DisplayWidth.Truncate(day, remaining); - - return Markup.Escape(prefixText) + Stylize(ageStyle, Markup.Escape(truncatedDay)); - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryKeyMap.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryKeyMap.cs index d3ca19df005..4aacd664552 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryKeyMap.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryKeyMap.cs @@ -4,8 +4,8 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// Builds the memory tab's key bindings for navigation, collection selection, -/// search, promotion, deletion, and exit requests. +/// Builds the Memory tab's key bindings for navigation, the kind filter, search, and exit +/// requests. Bound only to this tab, not the global key table. /// internal static class MemoryKeyMap { @@ -24,22 +24,6 @@ internal static class MemoryKeyMap new KeyBinding( new KeyChord(ConsoleKey.UpArrow, ConsoleModifiers.None, '\0'), () => new TuiMessage.MoveCursor(CursorDirection.Up)), - new KeyBinding( - new KeyChord(ConsoleKey.H, ConsoleModifiers.None, 'h'), - () => new TuiMessage.MoveCursor(CursorDirection.Left)), - new KeyBinding( - new KeyChord(ConsoleKey.LeftArrow, ConsoleModifiers.None, '\0'), - () => new TuiMessage.MoveCursor(CursorDirection.Left)), - new KeyBinding( - new KeyChord(ConsoleKey.L, ConsoleModifiers.None, 'l'), - () => new TuiMessage.MoveCursor(CursorDirection.Right)), - new KeyBinding( - new KeyChord(ConsoleKey.RightArrow, ConsoleModifiers.None, '\0'), - () => new TuiMessage.MoveCursor(CursorDirection.Right)), - new KeyBinding( - new KeyChord(ConsoleKey.Tab, ConsoleModifiers.None, '\t'), - () => new TuiMessage.MoveCursor(CursorDirection.Right), - new KeyHint("tab", "switch pane")), new KeyBinding( new KeyChord(ConsoleKey.G, ConsoleModifiers.None, 'g'), () => new TuiMessage.MoveToEdge(EdgeTarget.Top)), @@ -49,35 +33,28 @@ internal static class MemoryKeyMap new KeyBinding( new KeyChord(ConsoleKey.Enter, ConsoleModifiers.None, '\r'), () => new TuiMessage.OpenSelected(), - new KeyHint("enter", "focus detail")), + new KeyHint("enter", "open")), new KeyBinding( new KeyChord(ConsoleKey.F, ConsoleModifiers.None, 'f'), () => new TuiMessage.CycleView(1), - new KeyHint("f", "curated/journal")), + new KeyHint("f", "all/curated/journal")), new KeyBinding( new KeyChord(ConsoleKey.Oem2, ConsoleModifiers.None, '/'), () => new TuiMessage.SearchRequested(), new KeyHint("/", "search")), - new KeyBinding( - new KeyChord(ConsoleKey.P, ConsoleModifiers.None, 'p'), - () => new TuiMessage.PromoteRequested(), - new KeyHint("p", "promote")), - new KeyBinding( - new KeyChord(ConsoleKey.D, ConsoleModifiers.None, 'd'), - () => new TuiMessage.ForgetRequested(), - new KeyHint("d", "forget")), - new KeyBinding( - new KeyChord(ConsoleKey.R, ConsoleModifiers.Shift, 'R'), - () => new TuiMessage.RefreshRequested()), new KeyBinding( new KeyChord(ConsoleKey.Y, ConsoleModifiers.None, 'y'), () => new TuiMessage.CopySelectedId(), new KeyHint("y", "copy id")), new KeyBinding( - new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, ''), + new KeyChord(ConsoleKey.R, ConsoleModifiers.None, 'r'), + () => new TuiMessage.RefreshRequested(), + new KeyHint("r", "refresh")), + new KeyBinding( + new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, '\u0003'), () => new TuiMessage.QuitRequested()), new KeyBinding( - new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, ''), + new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, '\u001b'), () => new TuiMessage.Back(), new KeyHint("esc", "back")), new KeyBinding( diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryLifecycleActions.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryLifecycleActions.cs deleted file mode 100644 index 81b07e8dc21..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryLifecycleActions.cs +++ /dev/null @@ -1,38 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Memory; -using ChilliCream.Nitro.CommandLine.Tui.Editing; -using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; - -namespace ChilliCream.Nitro.CommandLine.Tui.Memory; - -/// -/// Builds deletion confirmations and permanently deletes curated memories. -/// -internal static class MemoryLifecycleActions -{ - /// - /// Builds the confirmation dialog for permanently deleting . - /// - public static ConfirmDialog CreateForgetDialog(MemoryRecord record) - => new( - $"Permanently delete memory '{record.Id}'? Git history may still retain its content.", - "Delete", - ButtonKind.Danger); - - /// - /// Permanently deletes the curated memory, returning a failed outcome when the - /// store throws . - /// - public static async Task ForgetAsync( - IMemoryStore store, MemoryRecord record, CancellationToken cancellationToken) - { - try - { - await store.ForgetAsync(record.Id, cancellationToken).ConfigureAwait(false); - return new MemoryForgetOutcome.Succeeded($"Deleted memory '{record.Id}'."); - } - catch (ExitException ex) - { - return new MemoryForgetOutcome.Failed(ex.Message); - } - } -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryMode.cs index 713f69665e8..b1a85f11654 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryMode.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryMode.cs @@ -1,256 +1,191 @@ using ChilliCream.Nitro.CommandLine.Services.Memory; -using ChilliCream.Nitro.CommandLine.Tui.Editing; using ChilliCream.Nitro.CommandLine.Tui.Input; using ChilliCream.Nitro.CommandLine.Tui.Shell; using ChilliCream.Nitro.CommandLine.Tui.Widgets; using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; using Spectre.Console.Rendering; -using ConfirmDialog = ChilliCream.Nitro.CommandLine.Tui.Editing.ConfirmDialog; using CursorDirection = ChilliCream.Nitro.CommandLine.Tui.Input.CursorDirection; namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// Displays searchable curated memories and journal entries with a detail pane. -/// Supports promoting journal entries and permanently deleting curated memories. +/// Displays every curated memory and journal entry in the workspace as one read-only, +/// full-width table: kind, type, tags, and age columns. The board has no acting agent, +/// so promoting a journal entry or forgetting a curated memory is unavailable here; Enter opens +/// the selected row in a read-only popover instead. /// internal sealed class MemoryMode : ITuiMode, IRawKeyCapturingMode { private const int PanelChromeWidth = 4; private const int PanelChromeHeight = 2; private const int MaxIndicatorSettlePasses = 3; - private const int ListWidthNumerator = 2; - private const int ListWidthDenominator = 5; + private const int HeaderLineCount = TableRenderer.TopBlockLineCount; - private readonly IMemoryStore _store; - private readonly MemoryState _state; - private readonly MemoryDetailView _detailView = new(); + private const string EmptyStateMessage = "No memory yet."; + + private readonly IMemoryStore _memoryStore; private readonly TimeProvider _timeProvider; - private readonly Func _hasIdentity; + private readonly MemoryState _state; private readonly Viewport _listViewport = new(0, 0); private MemorySearchForm? _searchForm; - private MemoryPromoteForm? _promoteForm; - private ConfirmDialog? _forgetDialog; - private MemoryRecord? _forgetTarget; - private ConfirmDialog? _discardDialog; - private bool _pendingRefresh; - - public MemoryMode( - IMemoryStore store, - TimeProvider? timeProvider = null, - Func? hasIdentity = null) + + public MemoryMode(IMemoryStore store, TimeProvider? timeProvider = null) { ArgumentNullException.ThrowIfNull(store); - _store = store; - _state = new MemoryState(new MemoryDataLoader(store)); + _memoryStore = store; _timeProvider = timeProvider ?? TimeProvider.System; - _hasIdentity = hasIdentity ?? (static () => false); + _state = new MemoryState(new MemoryDataLoader(store)); } /// - /// The loaded memory items, collection, search text, selection, and focus. + /// The board's current live state: the loaded rows, kind filter, and selection. /// public MemoryState State => _state; /// - public bool IsInputCapturing - => _discardDialog is not null - || _forgetDialog is not null - || _promoteForm is not null - || _searchForm is not null; + public KeyMap? KeyMap => null; /// - public IReadOnlyList CapturingHints - => _discardDialog is not null ? ConfirmDialog.Hints - : _forgetDialog is not null ? ConfirmDialog.Hints - : _promoteForm is not null ? MemoryPromoteForm.Hints - : _searchForm is not null ? MemorySearchForm.Hints - : []; + public bool IsInputCapturing => _searchForm is not null; /// - public KeyMap? KeyMap => null; + public IReadOnlyList CapturingHints => _searchForm is not null ? MemorySearchForm.Hints : []; /// - /// - /// Schedules a refresh for the next or call. - /// - public void OnEnter() => _pendingRefresh = true; + public void OnEnter() => RefreshBlocking(); /// public void OnResize(int width, int height) { - // Layout is recomputed during rendering. + // Layout and viewport state are recomputed from Render's parameters every frame. } /// - public IReadOnlyList Handle(TuiMessage message) - { - EnsureLoaded(); + public IReadOnlyList Handle(TuiMessage message) => message switch + { + TuiMessage.MoveCursor(CursorDirection.Up) => Move(-1), + TuiMessage.MoveCursor(CursorDirection.Down) => Move(1), + TuiMessage.MoveToEdge(var edge) => MoveToEdge(edge), + // Reached only when TryCreatePopover found no selected row to open: the shell falls + // back to dispatching OpenSelected here for the no-selection toast. + TuiMessage.OpenSelected => OpenSelectedFallback(), + TuiMessage.RefreshRequested => Refresh(), + TuiMessage.CycleView(var delta) => CycleFilter(delta), + TuiMessage.CopySelectedId => CopySelectedId(), + TuiMessage.SearchRequested => OpenSearchForm(), + _ => [] + }; - return message switch + /// + public IPopover? TryCreatePopover() + { + if (_state.SelectedItem is not { } item) { - TuiMessage.MoveCursor(CursorDirection.Up) => MoveOrScroll(-1), - TuiMessage.MoveCursor(CursorDirection.Down) => MoveOrScroll(1), - TuiMessage.MoveCursor(CursorDirection.Left) => TogglePane(), - TuiMessage.MoveCursor(CursorDirection.Right) => TogglePane(), - TuiMessage.MoveToEdge(var edge) => MoveOrScrollToEdge(edge), - TuiMessage.OpenSelected => FocusDetail(), - TuiMessage.RefreshRequested => Refresh(), - TuiMessage.CycleView(var delta) => CycleCollection(delta), - TuiMessage.SearchRequested => OpenSearchForm(), - TuiMessage.PromoteRequested => OpenPromoteForm(), - TuiMessage.ForgetRequested => OpenForgetDialog(), - TuiMessage.CopySelectedId => CopySelectedId(), - _ => [] - }; + return null; + } + + return new MemoryEntryPopoverModel(item.Id, item.Kind, _memoryStore, _timeProvider, MoveSelection); } /// - /// Handles one raw key while is true, routed - /// here by the host instead of through the semantic dispatch. + /// Moves the table selection rows away from the current one and + /// returns the row landed on, or null at the first or last row. /// - public IReadOnlyList HandleRawKey(ConsoleKeyInfo info) + private MemoryRow? MoveSelection(int delta) { - if (_discardDialog is not null) - { - return HandleDiscardDialogKey(info); - } + var next = _state.SelectedRow + delta; - if (_forgetDialog is not null) + if (next < 0 || next >= _state.Rows.Count) { - return HandleForgetDialogKey(info); + return null; } - if (_promoteForm is not null) - { - return HandlePromoteFormKey(info); - } + _state.SelectedRow = next; + return _state.Rows[next]; + } - if (_searchForm is not null) - { - return HandleSearchFormKey(info); - } + /// + public IReadOnlyList HandlePopoverRequest(PopoverResult.Request request) => request.Payload switch + { + MemoryEntryPopoverRequest.CopyRequested copyRequested => + [new TuiMessage.ShowToast(copyRequested.EntryId, ToastStyle.Info)], + _ => [] + }; - return []; - } + /// + /// Handles one raw key while is true, routed here by + /// the host instead of through the semantic dispatch. + /// + public IReadOnlyList HandleRawKey(ConsoleKeyInfo info) + => _searchForm is not null ? HandleSearchFormKey(info) : []; /// public IRenderable Render(int width, int height) { - EnsureLoaded(); - if (width <= 0 || height <= 0) { return new Markup(string.Empty); } - if (_discardDialog is { } discardDialog) - { - return discardDialog.Render(width, height); - } - - if (_forgetDialog is { } forgetDialog) - { - return forgetDialog.Render(width, height); - } - - if (_promoteForm is { } promoteForm) - { - return promoteForm.Render(width, height); - } - if (_searchForm is { } searchForm) { return searchForm.Render(width, height); } - var listWidth = Math.Max(1, width * ListWidthNumerator / ListWidthDenominator); - var detailWidth = Math.Max(1, width - listWidth); - - return new Layout("memory").SplitColumns( - new Layout("list", RenderListPane(listWidth, height)).Size(listWidth), - new Layout("detail", RenderDetailPane(detailWidth, height))); + return RenderListPane(width, height); } - private IReadOnlyList MoveOrScroll(int delta) + private IReadOnlyList Move(int delta) { - if (_state.Focus == MemoryFocus.List) - { - if (_state.ItemCount > 0) - { - var selectedRow = Math.Clamp(_state.SelectedRow + delta, 0, _state.ItemCount - 1); - - if (selectedRow != _state.SelectedRow) - { - _state.SelectedRow = selectedRow; - _detailView.ResetScroll(); - } - } - } - else if (delta > 0) + if (_state.Rows.Count > 0) { - _detailView.ScrollDown(); - } - else - { - _detailView.ScrollUp(); + _state.SelectedRow = Math.Clamp(_state.SelectedRow + delta, 0, _state.Rows.Count - 1); } return []; } - private IReadOnlyList MoveOrScrollToEdge(EdgeTarget edge) + private IReadOnlyList MoveToEdge(EdgeTarget edge) { - if (_state.Focus == MemoryFocus.List) - { - if (_state.ItemCount > 0) - { - var selectedRow = edge == EdgeTarget.Top ? 0 : _state.ItemCount - 1; - - if (selectedRow != _state.SelectedRow) - { - _state.SelectedRow = selectedRow; - _detailView.ResetScroll(); - } - } - } - else if (edge == EdgeTarget.Top) - { - _detailView.ScrollToTop(); - } - else + if (_state.Rows.Count > 0) { - _detailView.ScrollToBottom(); + _state.SelectedRow = edge == EdgeTarget.Top ? 0 : _state.Rows.Count - 1; } return []; } - private IReadOnlyList TogglePane() + private IReadOnlyList Refresh() { - _state.Focus = _state.Focus == MemoryFocus.List ? MemoryFocus.Detail : MemoryFocus.List; + RefreshBlocking(); return []; } - private IReadOnlyList FocusDetail() + private IReadOnlyList CycleFilter(int delta) { - _state.Focus = MemoryFocus.Detail; + _state.CycleFilterAsync(delta, CancellationToken.None).GetAwaiter().GetResult(); return []; } - private IReadOnlyList Refresh() - { - RefreshBlocking(); - return []; - } + /// + /// Reports the no-selection toast the shell shows when + /// found no row to open; a no-op when a row is selected (the popover already opened). + /// + private IReadOnlyList OpenSelectedFallback() => + _state.SelectedItem is null + ? [new TuiMessage.ShowToast("No item selected.", ToastStyle.Warn)] + : []; - private IReadOnlyList CycleCollection(int delta) + private IReadOnlyList CopySelectedId() { - _state.CycleCollectionAsync(delta, CancellationToken.None).GetAwaiter().GetResult(); - _detailView.ResetScroll(); - return []; + if (_state.SelectedItem is not { } item) + { + return [new TuiMessage.ShowToast("No item selected.", ToastStyle.Warn)]; + } + + return [new TuiMessage.ShowToast(item.Id, ToastStyle.Info)]; } private IReadOnlyList OpenSearchForm() @@ -283,275 +218,105 @@ private IReadOnlyList ApplySearch() { var text = _searchForm!.Text; _searchForm = null; - _state.ApplySearchAsync(text, CancellationToken.None).GetAwaiter().GetResult(); - _detailView.ResetScroll(); - - return []; - } - - private IReadOnlyList OpenPromoteForm() - { - if (RefuseIfIdentityUnavailable() is { } refusal) - { - return refusal; - } - - if (_state.SelectedJournalEntry is not { } entry) - { - return [new TuiMessage.ShowToast("No journal entry selected.", ToastStyle.Warn)]; - } - - _promoteForm = new MemoryPromoteForm(entry); - return []; - } - - private IReadOnlyList HandlePromoteFormKey(ConsoleKeyInfo info) - { - var result = _promoteForm!.HandleKey(info); - - return result switch - { - null => [], - FormResult.Cancelled => TryDiscardPromote(), - FormResult.ButtonActivated { ButtonId: MemoryPromoteForm.CancelButtonId } => TryDiscardPromote(), - FormResult.Submitted submitted => SubmitPromote(submitted), - _ => [] - }; - } - - private IReadOnlyList TryDiscardPromote() - { - if (_promoteForm!.IsDirty) - { - _discardDialog = CreateDiscardDialog(); - return []; - } - - _promoteForm = null; - return []; - } - - private IReadOnlyList SubmitPromote(FormResult.Submitted submitted) - { - if (RefuseIfIdentityUnavailable() is { } refusal) - { - return refusal; - } - - var outcome = _promoteForm!.SubmitAsync(_store, submitted.Values, CancellationToken.None) - .GetAwaiter().GetResult(); - - if (outcome is not MemoryPromoteOutcome.Succeeded) - { - return [outcome.ToShowToast()]; - } - - _promoteForm = null; - RefreshBlocking(); - - return [outcome.ToShowToast()]; - } - - private IReadOnlyList OpenForgetDialog() - { - if (RefuseIfIdentityUnavailable() is { } refusal) - { - return refusal; - } - - if (_state.SelectedCuratedRecord is not { } record) - { - return [new TuiMessage.ShowToast("No curated memory selected.", ToastStyle.Warn)]; - } - - _forgetTarget = record; - _forgetDialog = MemoryLifecycleActions.CreateForgetDialog(record); - return []; - } - - private IReadOnlyList HandleForgetDialogKey(ConsoleKeyInfo info) - { - var result = _forgetDialog!.HandleKey(info); - - return result switch - { - null => [], - ConfirmDialogResult.Cancelled => CancelForgetDialog(), - ConfirmDialogResult.Confirmed => SubmitForget(), - _ => [] - }; - } - - private IReadOnlyList CancelForgetDialog() - { - _forgetDialog = null; - _forgetTarget = null; - return []; - } - - private IReadOnlyList SubmitForget() - { - if (RefuseIfIdentityUnavailable() is { } refusal) - { - return refusal; - } - - var target = _forgetTarget!; - _forgetDialog = null; - _forgetTarget = null; - - var outcome = MemoryLifecycleActions.ForgetAsync(_store, target, CancellationToken.None) - .GetAwaiter().GetResult(); - - RefreshBlocking(); - - return [outcome.ToShowToast()]; - } - - private IReadOnlyList? RefuseIfIdentityUnavailable() => - _hasIdentity() - ? null - : [new TuiMessage.ShowToast(BoardIdentity.NoIdentityMessage, ToastStyle.Warn)]; - - private IReadOnlyList HandleDiscardDialogKey(ConsoleKeyInfo info) - { - var result = _discardDialog!.HandleKey(info); - - return result switch - { - null => [], - ConfirmDialogResult.Confirmed => ConfirmDiscard(), - ConfirmDialogResult.Cancelled => CancelDiscard(), - _ => [] - }; - } - - private IReadOnlyList ConfirmDiscard() - { - _discardDialog = null; - _promoteForm = null; - return []; - } - - private IReadOnlyList CancelDiscard() - { - _discardDialog = null; return []; } - private static ConfirmDialog CreateDiscardDialog() - => new("Discard unsaved changes?", "Discard", ButtonKind.Danger); - - private IReadOnlyList CopySelectedId() - { - var id = _state.Collection == MemoryCollectionFilter.Curated - ? _state.SelectedCuratedRecord?.Id - : _state.SelectedJournalEntry?.Id; - - return id is null - ? [new TuiMessage.ShowToast("No item selected.", ToastStyle.Warn)] - : [new TuiMessage.ShowToast(id, ToastStyle.Info)]; - } - private IRenderable RenderListPane(int width, int height) { - var focused = _state.Focus == MemoryFocus.List; var safeWidth = Math.Max(1, width); var contentWidth = Math.Max(0, safeWidth - PanelChromeWidth); var interiorHeight = Math.Max(0, height - PanelChromeHeight); + var now = _timeProvider.GetUtcNow(); - var lines = RenderListLines(contentWidth, interiorHeight, focused); - var panel = ColumnPane.Render(ListTitle(), _state.ItemCount, lines, focused); + var lines = RenderListLines(contentWidth, interiorHeight, now); + var header = BuildHeader(_state); + var panel = ColumnPane.RenderWithHeader(header, lines, focused: true); panel.Width = safeWidth; panel.Height = Math.Max(1, height); return panel; } - private string ListTitle() + /// + /// The panel header: "Memory (N)", "Curated (N)", or "Journal (N)" for the active kind + /// filter, with " (filtered)" appended once a search is set. + /// + private static string BuildHeader(MemoryState state) { - var collectionName = _state.Collection == MemoryCollectionFilter.Curated ? "Curated" : "Journal"; - - if (_state.Collection == MemoryCollectionFilter.Curated) + var label = state.Filter switch { - var suffix = _state.SearchText.Length > 0 ? " (filtered)" : ""; - return collectionName + suffix; - } + MemoryCollectionFilter.Curated => "Curated", + MemoryCollectionFilter.Journal => "Journal", + _ => "Memory" + }; - var parsed = MemoryQueryParser.Parse(_state.SearchText); - var filteredSuffix = parsed.Text.Length > 0 ? " (filtered)" : ""; - var ignoredSuffix = parsed.Type is not null || parsed.Tags.Count > 0 ? " (type/tag ignored)" : ""; - return collectionName + filteredSuffix + ignoredSuffix; + var suffix = state.SearchText.Length > 0 ? " (filtered)" : ""; + return $"{label} ({state.Rows.Count}){suffix}"; } - private IRenderable RenderDetailPane(int width, int height) - => _detailView.Render(_state, width, height, _state.Focus == MemoryFocus.Detail); - - private IReadOnlyList RenderListLines(int contentWidth, int interiorHeight, bool focused) - => _state.Collection == MemoryCollectionFilter.Curated - ? RenderCuratedListLines(contentWidth, interiorHeight, focused) - : RenderJournalListLines(contentWidth, interiorHeight, focused); - - private IReadOnlyList RenderCuratedListLines(int contentWidth, int interiorHeight, bool focused) + /// + /// Renders the header block (a blank line, the header row, and its rule), then the visible + /// rows, padded with blank lines to , with "N more + /// above/below" indicators once the rows no longer fit. Column widths are computed from + /// this call's visible slice and the header titles, so the header and rows always agree on + /// where each column starts. Shows the empty-state message below the header block when + /// there is no memory at all. + /// + private IReadOnlyList RenderListLines(int contentWidth, int interiorHeight, DateTimeOffset now) { if (interiorHeight <= 0) { return []; } - var records = _state.CuratedRecords; - var (start, visibleCount) = SliceViewport(records.Count, interiorHeight); - var now = _timeProvider.GetUtcNow(); - - var visibleRecords = new List(visibleCount); + var headerLineCount = Math.Min(HeaderLineCount, interiorHeight); + var rowsHeight = Math.Max(0, interiorHeight - headerLineCount); + var lines = new List(interiorHeight); - for (var i = 0; i < visibleCount; i++) + if (_state.Rows.Count == 0) { - visibleRecords.Add(records[start + i]); - } + var widths = MemoryRowBadge.ComputeWidths([], now); + MemoryRowBadge.AddHeaderLines(lines, headerLineCount, contentWidth, widths); - var widths = MemoryRowBadge.ComputeWidths(visibleRecords, now); - var lines = new List(interiorHeight); + if (rowsHeight > 0) + { + lines.Add(DisplayWidth.Truncate(_state.LoadError ?? EmptyStateMessage, contentWidth)); + } - if (_listViewport.HiddenAbove > 0) - { - lines.Add(FormatIndicator(_listViewport.HiddenAbove, "above")); + PadTo(lines, interiorHeight); + return lines; } - for (var i = 0; i < visibleCount; i++) - { - var selected = focused && start + i == _state.SelectedRow; - lines.Add(MemoryRowBadge.Render(visibleRecords[i], now, selected, contentWidth, widths)); - } + var rows = _state.Rows; + var reservedRows = 0; - if (_listViewport.HiddenBelow > 0) + for (var pass = 0; pass < MaxIndicatorSettlePasses; pass++) { - lines.Add(FormatIndicator(_listViewport.HiddenBelow, "below")); - } + var windowHeight = Math.Max(0, rowsHeight - reservedRows); + _listViewport.Update(rows.Count, windowHeight); + _listViewport.EnsureVisible(_state.SelectedRow); - return PadLines(lines, interiorHeight); - } + var needed = (_listViewport.HiddenAbove > 0 ? 1 : 0) + (_listViewport.HiddenBelow > 0 ? 1 : 0); - private IReadOnlyList RenderJournalListLines(int contentWidth, int interiorHeight, bool focused) - { - if (interiorHeight <= 0) - { - return []; - } + if (needed == reservedRows) + { + break; + } - var entries = _state.JournalEntries; - var (start, visibleCount) = SliceViewport(entries.Count, interiorHeight); + reservedRows = needed; + } - var visibleEntries = new List(visibleCount); + var (start, visibleCount) = _listViewport.Slice(); + var visibleRows = new List(visibleCount); for (var i = 0; i < visibleCount; i++) { - visibleEntries.Add(entries[start + i]); + visibleRows.Add(rows[start + i]); } - var widths = MemoryJournalRowBadge.ComputeWidths(visibleEntries); - var lines = new List(interiorHeight); + var rowWidths = MemoryRowBadge.ComputeWidths(visibleRows, now); + MemoryRowBadge.AddHeaderLines(lines, headerLineCount, contentWidth, rowWidths); if (_listViewport.HiddenAbove > 0) { @@ -560,8 +325,8 @@ private IReadOnlyList RenderJournalListLines(int contentWidth, int inter for (var i = 0; i < visibleCount; i++) { - var selected = focused && start + i == _state.SelectedRow; - lines.Add(MemoryJournalRowBadge.Render(visibleEntries[i], selected, contentWidth, widths)); + var selected = start + i == _state.SelectedRow; + lines.Add(MemoryRowBadge.Render(visibleRows[i], now, selected, contentWidth, rowWidths)); } if (_listViewport.HiddenBelow > 0) @@ -569,63 +334,19 @@ private IReadOnlyList RenderJournalListLines(int contentWidth, int inter lines.Add(FormatIndicator(_listViewport.HiddenBelow, "below")); } - return PadLines(lines, interiorHeight); - } - - /// - /// Resolves the visible window into a list of - /// items for , reserving rows for "N more - /// above/below" indicators once the items no longer fit - /// . - /// - private (int Start, int Count) SliceViewport(int itemCount, int interiorHeight) - { - var reservedRows = 0; - - for (var pass = 0; pass < MaxIndicatorSettlePasses; pass++) - { - var windowHeight = Math.Max(0, interiorHeight - reservedRows); - _listViewport.Update(itemCount, windowHeight); - _listViewport.EnsureVisible(_state.SelectedRow); - - var needed = (_listViewport.HiddenAbove > 0 ? 1 : 0) + (_listViewport.HiddenBelow > 0 ? 1 : 0); - - if (needed == reservedRows) - { - break; - } - - reservedRows = needed; - } - - return _listViewport.Slice(); + PadTo(lines, interiorHeight); + return lines; } - private static IReadOnlyList PadLines(List lines, int interiorHeight) + private static void PadTo(List lines, int height) { - while (lines.Count < interiorHeight) + while (lines.Count < height) { lines.Add(string.Empty); } - - return lines; } private static string FormatIndicator(int hiddenCount, string direction) => $" {hiddenCount} more {direction}"; private void RefreshBlocking() => _state.RefreshAsync(CancellationToken.None).GetAwaiter().GetResult(); - - /// - /// Performs a pending refresh once after entering the tab. - /// - private void EnsureLoaded() - { - if (!_pendingRefresh) - { - return; - } - - _pendingRefresh = false; - RefreshBlocking(); - } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryPromoteForm.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryPromoteForm.cs deleted file mode 100644 index f73605f8be7..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryPromoteForm.cs +++ /dev/null @@ -1,104 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Memory; -using ChilliCream.Nitro.CommandLine.Tui.Input; -using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; -using Spectre.Console.Rendering; -using Form = ChilliCream.Nitro.CommandLine.Tui.Widgets.Form.Form; - -namespace ChilliCream.Nitro.CommandLine.Tui.Memory; - -/// -/// Collects a required type and optional tags for promoting a journal entry. -/// Repeated promotion returns the existing curated memory. -/// -internal sealed class MemoryPromoteForm -{ - public const string TypeFieldId = "type"; - public const string TagsFieldId = "tags"; - - public const string PromoteButtonId = "promote"; - public const string CancelButtonId = "cancel"; - - /// - /// The footer hints displayed while the promote form captures input. - /// - public static readonly IReadOnlyList Hints = - [ - new KeyHint("ctrl+s", "promote"), - new KeyHint("esc", "cancel") - ]; - - private readonly string _journalId; - private readonly Form _form; - private readonly TextField _typeField; - private readonly TextField _tagsField; - - public MemoryPromoteForm(MemoryJournalEntry entry) - { - ArgumentNullException.ThrowIfNull(entry); - - _journalId = entry.Id; - _typeField = new TextField(TypeFieldId, "Type", required: true, validator: RequireType); - _tagsField = new TextField(TagsFieldId, "Tags (comma separated)"); - - var buttons = new FormButtons( - [ - new FormButtonSpec(PromoteButtonId, "Promote", ButtonKind.Primary), - new FormButtonSpec(CancelButtonId, "Cancel", ButtonKind.Secondary) - ]); - - _form = new Form($"Promote: {entry.Id}", [_typeField, _tagsField], buttons); - } - - /// - /// Whether either field contains text, including whitespace. - /// - public bool IsDirty => Text(_typeField).Length != 0 || Text(_tagsField).Length != 0; - - public FormResult? HandleKey(ConsoleKeyInfo info) => _form.HandleKey(info); - - public IRenderable Render(int width, int height) => _form.Render(width, height); - - /// - /// Promotes the journal entry this form was built with from the - /// submitted through the memory store. - /// - public async Task SubmitAsync( - IMemoryStore store, IReadOnlyDictionary values, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(store); - ArgumentNullException.ThrowIfNull(values); - - var type = Text(values, TypeFieldId); - var tags = ParseTags(Text(values, TagsFieldId)); - - try - { - var outcome = await store.PromoteAsync(_journalId, type, tags, cancellationToken) - .ConfigureAwait(false); - - var toastText = outcome.AlreadyPromoted - ? $"Journal entry '{_journalId}' was already promoted as '{outcome.Record.Id}'." - : $"Promoted memory '{outcome.Record.Id}'."; - - return new MemoryPromoteOutcome.Succeeded(outcome.Record.Id, outcome.AlreadyPromoted, toastText); - } - catch (ExitException ex) - { - return new MemoryPromoteOutcome.Failed(ex.Message); - } - } - - private static string? RequireType(FormValue value) - => value is FormValue.Text { Value: var text } && text.Trim().Length == 0 - ? "Type is required." - : null; - - private static IReadOnlyList ParseTags(string value) - => value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - - private static string Text(FormField field) - => field.GetValue() is FormValue.Text { Value: var value } ? value : ""; - - private static string Text(IReadOnlyDictionary values, string id) - => values[id] is FormValue.Text { Value: var value } ? value : ""; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryPromoteOutcome.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryPromoteOutcome.cs deleted file mode 100644 index cdb19c3856f..00000000000 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryPromoteOutcome.cs +++ /dev/null @@ -1,35 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Tui.Input; - -namespace ChilliCream.Nitro.CommandLine.Tui.Memory; - -/// -/// The outcome of submitting a against the -/// memory store. -/// -internal abstract record MemoryPromoteOutcome -{ - private MemoryPromoteOutcome() - { - } - - /// - /// The curated memory id and whether the journal entry had already been promoted. - /// - public sealed record Succeeded(string CuratedId, bool AlreadyPromoted, string ToastText) : MemoryPromoteOutcome; - - /// - /// The store rejected the write with an message. - /// - public sealed record Failed(string ToastText) : MemoryPromoteOutcome; - - /// - /// The shell toast this outcome should show: success styled for - /// , error styled for . - /// - public TuiMessage.ShowToast ToShowToast() => this switch - { - Succeeded succeeded => new TuiMessage.ShowToast(succeeded.ToastText, ToastStyle.Success), - Failed failed => new TuiMessage.ShowToast(failed.ToastText, ToastStyle.Error), - _ => throw new NotSupportedException() - }; -} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRow.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRow.cs new file mode 100644 index 00000000000..cbc0fb7b4ce --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRow.cs @@ -0,0 +1,14 @@ +namespace ChilliCream.Nitro.CommandLine.Tui.Memory; + +/// +/// One row of the Memory tab's table: a curated memory or a journal entry tagged by +/// . is null for a journal row, and is +/// the curated updated_at or the journal created_at. +/// +internal readonly record struct MemoryRow( + MemoryCollectionFilter Kind, + string Id, + string? Type, + IReadOnlyList Tags, + string Body, + DateTimeOffset Time); diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRowBadge.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRowBadge.cs index 22494fc99b8..7c4c45c22d2 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRowBadge.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryRowBadge.cs @@ -1,46 +1,88 @@ -using ChilliCream.Nitro.CommandLine.Services.Memory; +using System.Globalization; using ChilliCream.Nitro.CommandLine.Tui.Mail; using ChilliCream.Nitro.CommandLine.Tui.Theming; +using ChilliCream.Nitro.CommandLine.Tui.Widgets; namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// Renders a curated-memory row with a selection prefix, type, tags, and -/// relative modification time. +/// Renders the Memory table's header row and each row: kind, type, tags, and age columns. +/// Kind is never dropped; narrow widths drop Type first, then Age, identically for the header +/// and the rows so the two always agree. Tags has no drop priority; it is sized to whatever +/// width Kind, Type, and Age leave and truncated with an ellipsis once its text does not fit. +/// The full body is shown only in the row's popover. Built on the shared +/// and table widget. /// internal static class MemoryRowBadge { private const string SelectedPrefix = "> "; private const string UnselectedPrefix = " "; + private const string NoType = "-"; private const string NoTags = "-"; + private const string CuratedKindText = "curated"; + private const string JournalKindText = "journal"; - public readonly record struct Widths(int Type, int Age); + private const string KindHeader = "KIND"; + private const string TypeHeader = "TYPE"; + private const string TagsHeader = "TAGS"; + private const string AgeHeader = "AGE"; + + private const int MinKindWidth = 8; + private const int MinTypeWidth = 10; + private const int MinAgeWidth = 10; + + private const string NowLabel = "now"; + private const string JustNowLabel = "just now"; + private const string AgoSuffix = " ago"; + private const string IsoDateFormat = "yyyy-MM-dd"; + + // Type drops first, then Age; Kind has no drop priority so it is never dropped. Tags is not + // part of this list at all: it is sized separately to whatever width Kind, Type, and Age + // leave, so it always shows, shrinking (and truncating with an ellipsis) instead of + // dropping. + private static readonly IReadOnlyList s_fixedColumns = + [ + new TableColumnSpec(KindHeader, MinKindWidth), + new TableColumnSpec(TypeHeader, MinTypeWidth, DropPriority: 0), + new TableColumnSpec(AgeHeader, MinAgeWidth, DropPriority: 1) + ]; + + private static readonly TableColumnSpec s_tagsColumn = new(TagsHeader, MinWidth: 0); /// - /// Computes across , the rows about to be rendered. + /// The column widths a set of rows agree on for Kind, Type, and Age: each padded to at + /// least its minimum width, and wider still when its header title or a row's value needs + /// more room. Tags has no fixed width; it is sized per call from the space these columns + /// leave. /// - public static Widths ComputeWidths(IReadOnlyList rows, DateTimeOffset now) + public readonly record struct Widths(int Kind, int Type, int Age); + + /// + /// Computes across , with each column no + /// narrower than its minimum width or its header title. + /// + public static Widths ComputeWidths(IReadOnlyList rows, DateTimeOffset now) { - var typeWidth = 0; - var ageWidth = 0; + var rowValues = new List>(rows.Count); - foreach (var record in rows) + foreach (var row in rows) { - typeWidth = Math.Max(typeWidth, DisplayWidth.Measure(record.Type)); - ageWidth = Math.Max(ageWidth, DisplayWidth.Measure(MailAges.Format(record.UpdatedAt, now))); + rowValues.Add([KindText(row), TypeText(row), FormatAge(row.Time, now)]); } - return new Widths(typeWidth, ageWidth); + var widths = TableLayout.ComputeWidths(s_fixedColumns, rowValues); + return new Widths(widths[0], widths[1], widths[2]); } /// - /// Builds the markup line for one curated memory row, padding - /// scope/type/age to and truncating the tags - /// column with an ellipsis so the whole line still fits within - /// display columns. A - /// of 0 or less produces an empty line. + /// Builds the markup line for one row. Columns are padded to . + /// When the full set of columns does not fit within display + /// columns, Type is dropped first, then Age; Kind always remains, and Tags shrinks (as a + /// last resort, to nothing) to absorb whatever the others leave, truncating its text with + /// an ellipsis once it no longer fits. A of 0 or less produces + /// an empty line. /// - public static string Render(MemoryRecord record, DateTimeOffset now, bool selected, int maxWidth, Widths widths) + public static string Render(MemoryRow row, DateTimeOffset now, bool selected, int maxWidth, Widths widths) { if (maxWidth <= 0) { @@ -48,83 +90,174 @@ public static string Render(MemoryRecord record, DateTimeOffset now, bool select } var prefix = selected ? SelectedPrefix : UnselectedPrefix; - var type = DisplayWidth.PadRight(record.Type, widths.Type); - var age = DisplayWidth.PadRight(MailAges.Format(record.UpdatedAt, now), widths.Age); - var tagsText = record.Tags.Count == 0 ? NoTags : string.Join(",", record.Tags); - - var fixedPlainWidth = DisplayWidth.Measure(prefix) - + DisplayWidth.Measure(type) + 1 - + DisplayWidth.Measure(age) + 1; - - var tagsBudget = Math.Max(0, maxWidth - fixedPlainWidth); - var truncatedTags = DisplayWidth.Truncate(tagsText, tagsBudget); - + var kindStyle = ThemeTokens.GetStyle("memory.list.kind").ToMarkup(); var typeStyle = ThemeTokens.GetStyle("memory.list.type").ToMarkup(); var tagsStyle = ThemeTokens.GetStyle("memory.list.tags").ToMarkup(); var ageStyle = ThemeTokens.GetStyle("memory.list.age").ToMarkup(); - var line = fixedPlainWidth > maxWidth - ? RenderNarrow(prefix, maxWidth, type, typeStyle, age, ageStyle) - : $"{Markup.Escape(prefix)}" - + $"{Stylize(typeStyle, Markup.Escape(type))} " - + $"{Stylize(tagsStyle, Markup.Escape(truncatedTags))} " - + $"{Stylize(ageStyle, Markup.Escape(age))}"; + var cells = new TableCellSpec[] + { + new(KindText(row), kindStyle), + new(TypeText(row), typeStyle), + new(TagsText(row), tagsStyle), + new(FormatAge(row.Time, now), ageStyle) + }; + + var budget = maxWidth - PrefixWidth(prefix); + var (columns, layout) = PlanColumns(budget, widths); + var line = TableRenderer.RenderRow(prefix, new TableCellSpec(string.Empty), cells, columns, layout); if (selected) { var highlightStyle = ThemeTokens.GetStyle("selection.highlight").ToMarkup(); - line = Stylize(highlightStyle, line); + line = TableRenderer.Stylize(highlightStyle, line); } return line; } - private static string Stylize(string styleMarkup, string content) => - styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; - - private static string RenderNarrow( - string prefix, - int maxWidth, - string type, - string typeStyle, - string age, - string ageStyle) + /// + /// Builds the header title line shown above the rows: KIND, TYPE, TAGS, AGE, aligned to + /// . Columns are dropped using the same thresholds as + /// , so the header always agrees with the rows below it. A + /// of 0 or less produces an empty line. + /// + public static string RenderHeader(int maxWidth, Widths widths) { - var prefixText = DisplayWidth.Slice(prefix, maxWidth); - var line = Markup.Escape(prefixText); - var remaining = maxWidth - DisplayWidth.Measure(prefixText); - var hasColumn = false; + if (maxWidth <= 0) + { + return string.Empty; + } - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, type, typeStyle); - AppendNarrowColumn(ref line, ref remaining, ref hasColumn, age, ageStyle); + var headerStyle = ThemeTokens.GetStyle("memory.list.header").ToMarkup(); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var (columns, layout) = PlanColumns(budget, widths); - return line; + return TableRenderer.RenderRow( + UnselectedPrefix, new TableCellSpec(string.Empty), BuildHeaderCells(columns, headerStyle), columns, layout); } - private static void AppendNarrowColumn( - ref string line, - ref int remaining, - ref bool hasColumn, - string value, - string styleMarkup) + /// + /// Builds the dashed rule line under the header, filling + /// display columns. A of 0 or less produces an empty line. + /// + public static string RenderRule(int maxWidth) { - var separatorWidth = hasColumn ? 1 : 0; - var valueBudget = remaining - separatorWidth; + var ruleStyle = ThemeTokens.GetStyle("memory.list.age").ToMarkup(); + return TableRenderer.RenderRule(maxWidth, ruleStyle); + } - if (valueBudget <= 0) + /// + /// Appends the Memory table's fixed top block to : a blank line, + /// the header row and the rule, keeping only the first of + /// the three. A of 0 or less appends nothing. + /// + public static void AddHeaderLines(List lines, int headerLineCount, int maxWidth, Widths widths) + { + if (maxWidth <= 0) { return; } - var truncatedValue = DisplayWidth.Truncate(value, valueBudget); + var headerStyle = ThemeTokens.GetStyle("memory.list.header").ToMarkup(); + var ruleStyle = ThemeTokens.GetStyle("memory.list.age").ToMarkup(); + var budget = maxWidth - PrefixWidth(UnselectedPrefix); + var (columns, layout) = PlanColumns(budget, widths); + + TableRenderer.RenderTopBlock( + lines, + headerLineCount, + maxWidth, + UnselectedPrefix, + new TableCellSpec(string.Empty), + columns, + layout, + headerStyle, + ruleStyle); + } + + /// + /// Plans the four-column layout for display columns, in the + /// display order Kind, Type, Tags, Age: Kind always shows, Type and then Age drop first + /// when they do not all fit, and Tags is sized to whatever width remains (zero when + /// nothing does). + /// + private static (IReadOnlyList Columns, IReadOnlyList Layout) PlanColumns( + int budget, Widths widths) + { + var fixedLayout = TableLayout.Plan(budget, s_fixedColumns, ToWidthList(widths)); + + var usedWidth = 0; + var visibleFixedCount = 0; + + foreach (var column in fixedLayout) + { + if (!column.Visible) + { + continue; + } + + usedWidth += column.Width; + visibleFixedCount++; + } + + if (visibleFixedCount > 0) + { + usedWidth += DisplayWidth.Measure(TableLayout.Gutter) * visibleFixedCount; + } + + var tagsWidth = Math.Max(0, budget - usedWidth); - if (truncatedValue.Length == 0) + var columns = new List { s_fixedColumns[0], s_fixedColumns[1], s_tagsColumn, s_fixedColumns[2] }; + var layout = new List { - return; + fixedLayout[0], fixedLayout[1], new ColumnLayout(true, tagsWidth), fixedLayout[2] + }; + + return (columns, layout); + } + + private static TableCellSpec[] BuildHeaderCells(IReadOnlyList columns, string headerStyle) + { + var cells = new TableCellSpec[columns.Count]; + + for (var i = 0; i < columns.Count; i++) + { + cells[i] = new TableCellSpec(columns[i].Title, headerStyle); + } + + return cells; + } + + private static int PrefixWidth(string prefix) => DisplayWidth.Measure(prefix) + 1; + + private static IReadOnlyList ToWidthList(Widths widths) => [widths.Kind, widths.Type, widths.Age]; + + private static string KindText(MemoryRow row) => + row.Kind == MemoryCollectionFilter.Curated ? CuratedKindText : JournalKindText; + + private static string TypeText(MemoryRow row) => row.Type ?? NoType; + + private static string TagsText(MemoryRow row) => row.Tags.Count == 0 ? NoTags : string.Join(",", row.Tags); + + /// + /// Formats the elapsed time between and : + /// "just now" under a minute, a relative duration ("26m", "3h", "2d") with an " ago" + /// suffix, or an absolute date once the row is a week or older. + /// + private static string FormatAge(DateTimeOffset value, DateTimeOffset now) + { + var formatted = MailAges.Format(value, now); + + if (formatted == NowLabel) + { + return JustNowLabel; } - line += (hasColumn ? " " : string.Empty) + Stylize(styleMarkup, Markup.Escape(truncatedValue)); - remaining -= separatorWidth + DisplayWidth.Measure(truncatedValue); - hasColumn = true; + return IsAbsoluteDate(formatted) ? formatted : formatted + AgoSuffix; } + + private static bool IsAbsoluteDate(string formatted) => + DateTime.TryParseExact( + formatted, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out _); } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryState.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryState.cs index d69980e212b..1060dcddd5d 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryState.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Memory/MemoryState.cs @@ -3,123 +3,82 @@ namespace ChilliCream.Nitro.CommandLine.Tui.Memory; /// -/// The selected collection, search text, loaded memory items, selection, and focus. +/// The loaded curated-memory and journal rows, kind filter, search text, and selection for +/// the Memory tab. /// internal sealed class MemoryState(MemoryDataLoader loader) { /// - /// The active collection, initially curated memories. + /// The active kind filter, initially every entry. /// - public MemoryCollectionFilter Collection { get; private set; } = MemoryCollectionFilter.Curated; + public MemoryCollectionFilter Filter { get; private set; } = MemoryCollectionFilter.All; /// - /// The search box text last applied to the loaded list, parsed by - /// . + /// The search box text last applied to the loaded rows, parsed by + /// . Its tag: and type: terms narrow curated + /// rows only; free text narrows both. /// - public string SearchText { get; private set; } = ""; + public string SearchText { get; private set; } = string.Empty; /// - /// The curated memories currently loaded, populated when - /// is . + /// Every row matching and , curated and + /// journal entries merged, sorted by descending then id. /// - public IReadOnlyList CuratedRecords { get; private set; } = []; + public IReadOnlyList Rows { get; private set; } = []; /// - /// The journal entries currently loaded, populated when - /// is . - /// - public IReadOnlyList JournalEntries { get; private set; } = []; - - /// - /// The index of the selected row within whichever list - /// currently shows. + /// The index of the selected row within . /// public int SelectedRow { get; set; } /// - /// Which pane currently holds focus. - /// - public MemoryFocus Focus { get; set; } = MemoryFocus.List; - - /// - /// The number of rows in whichever list - /// currently shows. - /// - public int ItemCount => Collection == MemoryCollectionFilter.Curated ? CuratedRecords.Count : JournalEntries.Count; - - /// - /// A diagnostic message from the last when the store - /// rejected the read with an , or null otherwise. + /// A diagnostic message from the last when the store rejected + /// the read with an , or null otherwise. /// public string? LoadError { get; private set; } /// - /// The curated memory at , or null when - /// is not - /// or the row is out of range. + /// The row at , or null when there is no such row. /// - public MemoryRecord? SelectedCuratedRecord - => Collection == MemoryCollectionFilter.Curated && SelectedRow >= 0 && SelectedRow < CuratedRecords.Count - ? CuratedRecords[SelectedRow] - : null; + public MemoryRow? SelectedItem + => SelectedRow >= 0 && SelectedRow < Rows.Count ? Rows[SelectedRow] : null; /// - /// The journal entry at , or null when - /// is not - /// or the row is out of range. - /// - public MemoryJournalEntry? SelectedJournalEntry - => Collection == MemoryCollectionFilter.Journal && SelectedRow >= 0 && SelectedRow < JournalEntries.Count - ? JournalEntries[SelectedRow] - : null; - - /// - /// Reloads whichever list currently shows for - /// . The selected item - /// stays selected when it is still present in the reloaded list; - /// otherwise the selected row is clamped to the new list's bounds. + /// Reloads every row matching and . The + /// selected row stays selected by id when it is still present; otherwise the selection is + /// clamped to the new list's bounds. /// public async Task RefreshAsync(CancellationToken cancellationToken) { - var query = MemoryQueryParser.Parse(SearchText); - var selectedId = Collection == MemoryCollectionFilter.Curated - ? SelectedCuratedRecord?.Id - : SelectedJournalEntry?.Id; + var selectedId = SelectedItem?.Id; try { - if (Collection == MemoryCollectionFilter.Curated) - { - CuratedRecords = await loader.LoadCuratedAsync(query, cancellationToken).ConfigureAwait(false); - } - else - { - JournalEntries = await loader.LoadJournalAsync(query, cancellationToken).ConfigureAwait(false); - } - + Rows = await LoadRowsAsync(cancellationToken).ConfigureAwait(false); LoadError = null; } catch (ExitException exception) { LoadError = exception.Message; - ClearActiveCollection(); + Rows = []; } var preservedIndex = selectedId is null ? -1 : IndexOf(selectedId); - SelectedRow = preservedIndex >= 0 ? preservedIndex : Math.Clamp(SelectedRow, 0, Math.Max(0, ItemCount - 1)); + SelectedRow = preservedIndex >= 0 ? preservedIndex : Math.Clamp(SelectedRow, 0, Math.Max(0, Rows.Count - 1)); } /// - /// Toggles the collection when is nonzero. - /// Reloads the active collection even when the delta is zero. + /// Cycles through All, Curated, and Journal when + /// is nonzero, reloads, and selects the first row. /// - public async Task CycleCollectionAsync(int delta, CancellationToken cancellationToken) + public async Task CycleFilterAsync(int delta, CancellationToken cancellationToken) { if (delta != 0) { - Collection = Collection == MemoryCollectionFilter.Curated - ? MemoryCollectionFilter.Journal - : MemoryCollectionFilter.Curated; + var values = Enum.GetValues(); + var currentIndex = Array.IndexOf(values, Filter); + var nextIndex = ((currentIndex + delta) % values.Length + values.Length) % values.Length; + Filter = values[nextIndex]; } SelectedRow = 0; @@ -131,43 +90,44 @@ public async Task CycleCollectionAsync(int delta, CancellationToken cancellation /// public async Task ApplySearchAsync(string text, CancellationToken cancellationToken) { - SearchText = text; + SearchText = text.Trim(); SelectedRow = 0; await RefreshAsync(cancellationToken).ConfigureAwait(false); } - private void ClearActiveCollection() + private async Task> LoadRowsAsync(CancellationToken cancellationToken) { - if (Collection == MemoryCollectionFilter.Curated) + var query = MemoryQueryParser.Parse(SearchText); + var rows = new List(); + + if (Filter != MemoryCollectionFilter.Journal) { - CuratedRecords = []; + var curated = await loader.LoadCuratedAsync(query, cancellationToken).ConfigureAwait(false); + rows.AddRange(curated.Select(ToRow)); } - else + + if (Filter != MemoryCollectionFilter.Curated) { - JournalEntries = []; + var journal = await loader.LoadJournalAsync(query, cancellationToken).ConfigureAwait(false); + rows.AddRange(journal.Select(ToRow)); } + + return rows.OrderByDescending(r => r.Time).ThenBy(r => r.Id, StringComparer.Ordinal).ToList(); } + private static MemoryRow ToRow(MemoryRecord record) => + new(MemoryCollectionFilter.Curated, record.Id, record.Type, record.Tags, record.Body, record.UpdatedAt); + + private static MemoryRow ToRow(MemoryJournalEntry entry) => + new(MemoryCollectionFilter.Journal, entry.Id, Type: null, Tags: [], entry.Body, entry.CreatedAt); + private int IndexOf(string id) { - if (Collection == MemoryCollectionFilter.Curated) - { - for (var i = 0; i < CuratedRecords.Count; i++) - { - if (CuratedRecords[i].Id == id) - { - return i; - } - } - } - else + for (var i = 0; i < Rows.Count; i++) { - for (var i = 0; i < JournalEntries.Count; i++) + if (Rows[i].Id == id) { - if (JournalEntries[i].Id == id) - { - return i; - } + return i; } } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/IPopover.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/IPopover.cs new file mode 100644 index 00000000000..7b0d02e66be --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/IPopover.cs @@ -0,0 +1,41 @@ +using ChilliCream.Nitro.CommandLine.Tui.Input; +using Spectre.Console.Rendering; + +namespace ChilliCream.Nitro.CommandLine.Tui.Shell; + +/// +/// A detail overlay opened from a mode's currently selected row through +/// and hosted by in its single +/// popover slot: one render-chain position, one raw-key route, reloaded on every data-changed +/// event, and ticked every frame. +/// +internal interface IPopover +{ + /// + /// The current footer hints, shown in place of the active mode's own hints while the + /// popover is open. + /// + IReadOnlyList Hints { get; } + + /// + /// Loads (or reloads) the popover's content, blocking the caller. + /// + void Load(CancellationToken cancellationToken); + + /// + /// Recomputes any time-dependent content as of now. Returns whether anything the render + /// depends on changed since the last call. + /// + bool Tick(); + + /// + /// Renders the popover into the given content area. + /// + IRenderable Render(int width, int height); + + /// + /// Handles one raw key, returning the terminal the hosting + /// shell is expected to act on, or null when the key was consumed without effect. + /// + PopoverResult? HandleKey(ConsoleKeyInfo info); +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/ITuiMode.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/ITuiMode.cs index f31c04b3259..2c32a4b56f0 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/ITuiMode.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/ITuiMode.cs @@ -54,4 +54,17 @@ void SelectTask(string id) /// equality. The default suppresses no hints. /// IReadOnlyCollection SuppressedGlobalHints => []; + + /// + /// Creates a popover for the currently selected row, or null when nothing is selected or + /// the mode hosts no popover. The default implementation hosts none. + /// + IPopover? TryCreatePopover() => null; + + /// + /// Handles a tab-specific request from this mode's own open popover, returning zero or + /// more follow-up messages for the shell to dispatch in turn. The default implementation + /// handles nothing. + /// + IReadOnlyList HandlePopoverRequest(PopoverResult.Request request) => []; } diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/PopoverResult.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/PopoverResult.cs new file mode 100644 index 00000000000..55f5f7411d9 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/PopoverResult.cs @@ -0,0 +1,25 @@ +namespace ChilliCream.Nitro.CommandLine.Tui.Shell; + +/// +/// A terminal outcome of that the hosting +/// is expected to act on. A null return from means the key was +/// consumed without any shell-level effect. +/// +internal abstract record PopoverResult +{ + private PopoverResult() + { + } + + /// + /// The popover should be dismissed. + /// + public sealed record Closed : PopoverResult; + + /// + /// A tab-specific request, carried opaquely by the shell, that the popover's owning + /// is expected to interpret through its own + /// . + /// + public sealed record Request(object Payload) : PopoverResult; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/TuiShell.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/TuiShell.cs index d293ad3de7f..b90aa5fcf7f 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/TuiShell.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Shell/TuiShell.cs @@ -1,6 +1,8 @@ using System.Globalization; using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tui.Agents; using ChilliCream.Nitro.CommandLine.Tui.Board; using ChilliCream.Nitro.CommandLine.Tui.Editing; using ChilliCream.Nitro.CommandLine.Tui.Input; @@ -35,6 +37,7 @@ internal sealed class TuiShell private readonly SearchMode? _searchMode; private readonly DependencyTreeView? _treeView; private readonly ITaskStore? _store; + private readonly IAgentStore _agentStore; private readonly string? _actor; private readonly Func? _mailWakeDaemonState; @@ -55,6 +58,10 @@ internal sealed class TuiShell private TaskCreateForm? _createForm; private EditingConfirmDialog? _discardDialog; private DiscardTarget _discardTarget; + private EditingConfirmDialog? _agentDeleteDialog; + private string? _agentDeleteTarget; + private EditingConfirmDialog? _agentDeleteOfflineDialog; + private IPopover? _popover; private int _width; private int _height; @@ -63,6 +70,7 @@ public TuiShell( ITuiMode activeMode, int initialWidth, int initialHeight, + IAgentStore agentStore, SearchMode? searchMode = null, DependencyTreeView? treeView = null, ITaskStore? store = null, @@ -78,6 +86,7 @@ [new TuiTab( dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)))], initialWidth, initialHeight, + agentStore, tasksTabIndex: 0, searchMode, treeView, @@ -96,6 +105,7 @@ [new TuiTab( /// The non-empty list of hosted tabs in display order. /// The initial frame width. /// The initial frame height. + /// The agent store backing the Agents tab's delete actions. /// The task search mode, or null to disable shell search entry. /// The dependency tree mode, or null to disable shell tree entry. /// The task store, or null to disable shell task writes and detail entry. @@ -116,6 +126,7 @@ public TuiShell( IReadOnlyList tabs, int initialWidth, int initialHeight, + IAgentStore agentStore, int tasksTabIndex = 0, SearchMode? searchMode = null, DependencyTreeView? treeView = null, @@ -126,6 +137,7 @@ public TuiShell( TimeSpan? quitGateDrainBound = null) { ArgumentNullException.ThrowIfNull(tabs); + ArgumentNullException.ThrowIfNull(agentStore); if (tabs.Count == 0) { @@ -144,6 +156,7 @@ public TuiShell( _searchMode = searchMode; _treeView = treeView; _store = store; + _agentStore = agentStore; _actor = actor; _mailWakeDaemonState = mailWakeDaemonState; _quitGates = quitGates ?? []; @@ -217,11 +230,17 @@ public IRenderable Render() ? form.Render(_width, contentHeight) : _lifecycleDialog is { } lifecycleDialog ? lifecycleDialog.Render(_width, contentHeight) - : _picker is { } picker - ? picker.Render(_width, contentHeight) - : _createForm is { } createForm - ? createForm.Render(_width, contentHeight) - : ActiveMode.Render(_width, contentHeight); + : _agentDeleteDialog is { } agentDeleteDialog + ? agentDeleteDialog.Render(_width, contentHeight) + : _agentDeleteOfflineDialog is { } agentDeleteOfflineDialog + ? agentDeleteOfflineDialog.Render(_width, contentHeight) + : _picker is { } picker + ? picker.Render(_width, contentHeight) + : _popover is { } popover + ? popover.Render(_width, contentHeight) + : _createForm is { } createForm + ? createForm.Render(_width, contentHeight) + : ActiveMode.Render(_width, contentHeight); var toastRow = _toaster.Render() ?? new Markup(FormatFooter(BuildFooterHints(), _width, _actor, _mailWakeDaemonState?.Invoke())); @@ -294,15 +313,22 @@ private bool HandleTick(DateTimeOffset now) var searchDirty = _searchMode is { } search && ReferenceEquals(ActiveMode, search) && search.TickAsync(now, CancellationToken.None).GetAwaiter().GetResult(); + var agentsDirty = ActiveMode is AgentsMode agents && agents.Tick(); + var popoverDirty = _popover?.Tick() ?? false; - return toastDirty || searchDirty; + return toastDirty || searchDirty || agentsDirty || popoverDirty; } /// - /// Refreshes every hosted tab's currently active mode, not only the - /// active tab's. + /// Refreshes every hosted tab's currently active mode, not only the active tab's, and + /// reloads the open popover, if any. /// - private bool HandleDataChanged() => BroadcastToTabs(new TuiMessage.RefreshRequested()); + private bool HandleDataChanged() + { + var tabsChanged = BroadcastToTabs(new TuiMessage.RefreshRequested()); + _popover?.Load(CancellationToken.None); + return tabsChanged; + } /// /// Sends an effect-completion message to every tab's current mode to drain @@ -357,11 +383,26 @@ private bool HandleKey(ConsoleKeyInfo info) return HandleLifecycleDialogKey(info); } + if (_agentDeleteDialog is not null) + { + return HandleAgentDeleteDialogKey(info); + } + + if (_agentDeleteOfflineDialog is not null) + { + return HandleAgentDeleteOfflineDialogKey(info); + } + if (_picker is not null) { return HandlePickerKey(info); } + if (_popover is not null) + { + return HandlePopoverKey(info); + } + if (_createForm is not null) { return HandleCreateFormKey(info); @@ -536,6 +577,80 @@ private bool SubmitLifecycleAction(string reason) return true; } + private bool HandleAgentDeleteDialogKey(ConsoleKeyInfo info) + { + var result = _agentDeleteDialog!.HandleKey(info); + + switch (result) + { + case null: + return true; + + case ConfirmDialogResult.Cancelled: + _agentDeleteDialog = null; + _agentDeleteTarget = null; + return true; + + case ConfirmDialogResult.Confirmed: + return SubmitAgentDelete(); + + default: + return true; + } + } + + private bool SubmitAgentDelete() + { + var name = _agentDeleteTarget!; + _agentDeleteDialog = null; + _agentDeleteTarget = null; + + // A confirmed delete from the popover closes it back to the table; the table + // shows the same effect through its own refresh below. + _popover = null; + + var deleted = _agentStore.DeleteAsync(name, CancellationToken.None).GetAwaiter().GetResult(); + + HandleMessage(new TuiMessage.ShowToast( + deleted ? $"Deleted agent '{name}'." : $"Agent '{name}' was not found.", + deleted ? ToastStyle.Info : ToastStyle.Warn)); + HandleMessage(new TuiMessage.RefreshRequested()); + return true; + } + + private bool HandleAgentDeleteOfflineDialogKey(ConsoleKeyInfo info) + { + var result = _agentDeleteOfflineDialog!.HandleKey(info); + + switch (result) + { + case null: + return true; + + case ConfirmDialogResult.Cancelled: + _agentDeleteOfflineDialog = null; + return true; + + case ConfirmDialogResult.Confirmed: + return SubmitAgentDeleteOffline(); + + default: + return true; + } + } + + private bool SubmitAgentDeleteOffline() + { + _agentDeleteOfflineDialog = null; + + var deletedCount = _agentStore.DeleteInactiveAsync(CancellationToken.None).GetAwaiter().GetResult(); + + HandleMessage( + new TuiMessage.ShowToast($"Deleted {deletedCount} offline or idle agents.", ToastStyle.Info)); + HandleMessage(new TuiMessage.RefreshRequested()); + return true; + } + private bool HandleDiscardDialogKey(ConsoleKeyInfo info) { var result = _discardDialog!.HandleKey(info); @@ -598,6 +713,37 @@ private bool HandlePickerKey(ConsoleKeyInfo info) } } + /// + /// Routes one raw key to the open popover: a close dismisses it, and any other request is + /// handed to the active mode's own , which is + /// how the agent delete and copy gestures keep working. + /// + private bool HandlePopoverKey(ConsoleKeyInfo info) + { + var result = _popover!.HandleKey(info); + + switch (result) + { + case null: + return true; + + case PopoverResult.Closed: + _popover = null; + return true; + + case PopoverResult.Request request: + foreach (var followUp in ActiveMode.HandlePopoverRequest(request)) + { + HandleMessage(followUp); + } + + return true; + + default: + return true; + } + } + private bool SubmitPicker(string selectedId) { var task = _pickerTask!; @@ -715,6 +861,9 @@ private bool HandleMessage(TuiMessage message) case TuiMessage.OpenSelected when ActiveMode is BoardMode: return TryOpenDetail(); + case TuiMessage.OpenSelected: + return TryOpenPopover(); + case TuiMessage.FocusSearchRequested: if (!IsTasksTabActive || _searchMode is not { } search) { @@ -737,6 +886,12 @@ private bool HandleMessage(TuiMessage message) case TuiMessage.DeleteRequested: return TryOpenDeleteDialog(); + case TuiMessage.DeleteAgentRequested deleteAgent: + return TryOpenAgentDeleteDialog(deleteAgent.Name); + + case TuiMessage.DeleteOfflineAgentsRequested: + return TryOpenAgentDeleteOfflineDialog(); + case TuiMessage.StatusPickerRequested: return TryOpenPicker(PickerKind.Status); @@ -852,6 +1007,30 @@ private bool TryOpenDetail() return true; } + /// + /// Opens the popover the active mode returns for its currently selected row, hosted as a + /// shell overlay rather than switched to on the active tab's navigation stack. Falls back + /// to dispatching to the active mode itself when it + /// hosts no popover for the current selection, which is how search's open-on-Tab and the + /// dependency tree's follow key keep working. + /// + private bool TryOpenPopover() + { + if (ActiveMode.TryCreatePopover() is { } popover) + { + popover.Load(CancellationToken.None); + _popover = popover; + return true; + } + + foreach (var followUp in ActiveMode.Handle(new TuiMessage.OpenSelected())) + { + HandleMessage(followUp); + } + + return true; + } + private bool TryOpenTree() { if (_treeView is not { } tree) @@ -954,6 +1133,55 @@ private bool TryOpenDeleteDialog() return true; } + /// + /// Opens the delete confirmation for the named agent. Does nothing outside the Agents + /// tab, and shows a toast instead of a dialog when no agent is selected. + /// + private bool TryOpenAgentDeleteDialog(string name) + { + if (ActiveMode is not AgentsMode) + { + return false; + } + + if (name.Length == 0) + { + return ShowToastNow("No agent selected.", ToastStyle.Warn); + } + + _agentDeleteTarget = name; + _agentDeleteDialog = new EditingConfirmDialog( + $"Delete agent '{name}'? Its mail and tasks keep the name; this cannot be undone.", + "Delete", + ButtonKind.Danger); + return true; + } + + /// + /// Opens the delete-all-offline-or-idle confirmation. Does nothing outside the Agents tab, + /// and shows a toast instead of a dialog when there are no offline or idle agents. + /// + private bool TryOpenAgentDeleteOfflineDialog() + { + if (ActiveMode is not AgentsMode agentsMode) + { + return false; + } + + var inactiveCount = agentsMode.CountInactiveAgents(); + + if (inactiveCount == 0) + { + return ShowToastNow("No offline or idle agents to delete.", ToastStyle.Warn); + } + + _agentDeleteOfflineDialog = new EditingConfirmDialog( + $"Delete {inactiveCount} offline or idle agents? This cannot be undone.", + "Delete", + ButtonKind.Danger); + return true; + } + private bool TryOpenPicker(PickerKind kind) { if (!IsTasksTabActive || _store is null) @@ -1059,11 +1287,21 @@ private IReadOnlyList BuildFooterHints() return EditingConfirmDialog.Hints; } + if (_agentDeleteDialog is not null || _agentDeleteOfflineDialog is not null) + { + return EditingConfirmDialog.Hints; + } + if (_picker is not null) { return QuickPicker.Hints; } + if (_popover is { } popover) + { + return popover.Hints; + } + if (_createForm is not null) { return TaskCreateForm.Hints; diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Theming/DefaultTheme.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Theming/DefaultTheme.cs index 270926d2bbe..f3cdba3fdf9 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Theming/DefaultTheme.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Theming/DefaultTheme.cs @@ -18,8 +18,10 @@ internal static class DefaultTheme ["board.column.status.ready.focused"] = new Style(Color.Green, decoration: Decoration.Bold), ["board.column.status.inprogress"] = new Style(Color.Blue), ["board.column.status.inprogress.focused"] = new Style(Color.Blue, decoration: Decoration.Bold), - ["board.column.status.closed"] = new Style(Color.Grey, decoration: Decoration.Dim), - ["board.column.status.closed.focused"] = new Style(Color.Grey, decoration: Decoration.Bold), + ["board.column.status.closed"] = new Style(Color.MediumPurple), + ["board.column.status.closed.focused"] = new Style(Color.MediumPurple, decoration: Decoration.Bold), + + ["board.column.header"] = new Style(Color.Grey70, decoration: Decoration.Bold), ["badge.priority.p0"] = new Style(Color.Red), ["badge.priority.p1"] = new Style(Color.Orange1), @@ -43,8 +45,8 @@ internal static class DefaultTheme ["selection.highlight"] = new Style(Color.Default, Color.Grey35), + ["agents.list.header"] = new Style(decoration: Decoration.Bold | Decoration.Dim), ["agents.list.name"] = new Style(Color.Aqua), - ["agents.list.client"] = new Style(Color.SkyBlue1, decoration: Decoration.Dim), ["agents.list.harness"] = new Style(Color.SkyBlue1, decoration: Decoration.Dim), ["agents.list.role"] = new Style(Color.Grey70), ["agents.list.role.orchestrator"] = new Style(Color.MediumPurple1), @@ -53,41 +55,30 @@ internal static class DefaultTheme ["agents.list.role.reviewer"] = new Style(Color.Orange1), ["agents.list.role.researcher"] = new Style(Color.Blue), ["agents.list.age"] = new Style(Color.Grey58, decoration: Decoration.Dim), - ["agents.list.implicit"] = new Style(decoration: Decoration.Dim), ["agents.list.presence"] = new Style(Color.Grey70), ["agents.list.presence.online"] = new Style(Color.Green), + ["agents.list.presence.idle"] = new Style(Color.Orange1), ["agents.list.presence.unreachable"] = new Style(Color.Yellow), - ["agents.list.presence.unobservable"] = new Style(Color.SlateBlue1), - ["agents.list.presence.remote"] = new Style(Color.SkyBlue1), ["agents.list.presence.offline"] = new Style(Color.Grey50, decoration: Decoration.Dim), - ["agents.list.presence.conflict"] = new Style(Color.Red, decoration: Decoration.Bold), - - ["mail.message.unread"] = new Style(Color.White, decoration: Decoration.Bold), - - ["mail.row.glyph.from-me"] = new Style(Color.SkyBlue1), - ["mail.row.glyph.direct"] = new Style(Color.Green), - ["mail.row.glyph.broadcast"] = new Style(Color.Orange1), - ["mail.row.age"] = new Style(Color.Grey58, decoration: Decoration.Dim), - - ["mail.row.heading"] = new Style(Color.Grey70, decoration: Decoration.Bold), - ["mail.row.from"] = new Style(Color.White), - ["mail.row.from.me"] = new Style(Color.SkyBlue1), - ["mail.row.to"] = new Style(Color.Grey70), - ["mail.row.preview"] = new Style(Color.Grey58, decoration: Decoration.Dim), - ["mail.row.unread-to-me"] = new Style(Color.Black, Color.Yellow, decoration: Decoration.Bold), - ["mail.row.thread.fold"] = new Style(Color.Grey70), - ["mail.row.thread.count"] = new Style(Color.Grey58, decoration: Decoration.Dim), - ["mail.row.thread.membership"] = new Style(Color.Grey50), - - ["mail.detail.recipient.unread"] = new Style(Color.Yellow, decoration: Decoration.Bold), - ["mail.detail.recipient.read"] = new Style(Color.Grey70), - - ["mail.mailbox.workspace.border"] = new Style(Color.Purple), - ["mail.mailbox.workspace.border.focused"] = new Style(Color.MediumOrchid1, decoration: Decoration.Bold), + ["agents.popover.label"] = new Style(Color.Grey58, decoration: Decoration.Dim), + ["agents.popover.section.title"] = new Style(decoration: Decoration.Bold), + ["agents.popover.row.empty"] = new Style(Color.Grey58, decoration: Decoration.Dim), + ["agents.popover.row.unread"] = new Style(Color.White, decoration: Decoration.Bold), + ["agents.popover.row.dimmed"] = new Style(Color.Grey, decoration: Decoration.Dim), + ["agents.popover.show-more"] = new Style(Color.Grey58, decoration: Decoration.Dim), + + ["mail.list.header"] = new Style(Color.Grey70, decoration: Decoration.Bold), + ["mail.list.subject"] = new Style(Color.White), + ["mail.list.from"] = new Style(Color.Grey70), + ["mail.list.to"] = new Style(Color.Grey70), + ["mail.list.messages"] = new Style(Color.Grey58, decoration: Decoration.Dim), + ["mail.list.age"] = new Style(Color.Grey58, decoration: Decoration.Dim), + + ["memory.list.header"] = new Style(Color.Grey70, decoration: Decoration.Bold), + ["memory.list.kind"] = new Style(Color.MediumPurple1), ["memory.list.type"] = new Style(Color.SkyBlue1), ["memory.list.tags"] = new Style(Color.Grey70), - ["memory.list.scope"] = new Style(Color.Grey50), ["memory.list.age"] = new Style(Color.Grey58, decoration: Decoration.Dim), ["detail.section.header"] = new Style(decoration: Decoration.Bold), diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/ColumnPane.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/ColumnPane.cs index 46529775825..e923d48331e 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/ColumnPane.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/ColumnPane.cs @@ -14,6 +14,13 @@ internal static class ColumnPane /// strings, one per visible row, in top-to-bottom order. /// public static Panel Render(string name, int count, IReadOnlyList lines, bool focused) + => RenderWithHeader($"{name} ({count})", lines, focused); + + /// + /// Builds the panel for one column with a caller-supplied header, for a title + /// that does not fit the default "name (count)" format. + /// + public static Panel RenderWithHeader(string header, IReadOnlyList lines, bool focused) { IRenderable content = lines.Count == 0 ? new Markup(string.Empty) @@ -23,7 +30,7 @@ public static Panel Render(string name, int count, IReadOnlyList lines, return new Panel(content) { - Header = new PanelHeader($"{name} ({count})"), + Header = new PanelHeader(header), Border = BoxBorder.Rounded, BorderStyle = ThemeTokens.GetStyle(borderToken) }; diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TableLayout.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TableLayout.cs new file mode 100644 index 00000000000..357dbc26974 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TableLayout.cs @@ -0,0 +1,192 @@ +namespace ChilliCream.Nitro.CommandLine.Tui.Widgets; + +/// +/// How a 's cell text is justified within its computed width. +/// +internal enum ColumnAlignment +{ + Left, + Right +} + +/// +/// Describes one column of a table rendered with and +/// : its title, minimum width, and how it is dropped or sized once +/// the table is narrower than every column needs. A column with no +/// is never dropped; among droppable columns, the lowest priority value drops first. +/// +internal sealed record TableColumnSpec( + string Title, + int MinWidth, + int? DropPriority = null, + ColumnAlignment Alignment = ColumnAlignment.Left, + int? FixedWidth = null); + +/// +/// Whether and how wide one column renders once has fit the +/// table to the available width. +/// +internal readonly record struct ColumnLayout(bool Visible, int Width); + +/// +/// Computes column widths from a table's columns and rows, and decides which columns fit a +/// given width: a gutter of four spaces separates columns, and one space of left padding +/// precedes the first one. +/// +internal static class TableLayout +{ + public const string Gutter = " "; + + /// + /// Returns each column's width, in order: its fixed width when + /// it has one, otherwise at least its minimum width or its title's width, and wider still + /// when a row's value in that column needs more room. + /// + public static IReadOnlyList ComputeWidths( + IReadOnlyList columns, IReadOnlyList> rowValues) + { + var widths = new int[columns.Count]; + + for (var i = 0; i < columns.Count; i++) + { + widths[i] = columns[i].FixedWidth + ?? Math.Max(columns[i].MinWidth, DisplayWidth.Measure(columns[i].Title)); + } + + foreach (var row in rowValues) + { + for (var i = 0; i < columns.Count; i++) + { + if (columns[i].FixedWidth is null) + { + widths[i] = Math.Max(widths[i], DisplayWidth.Measure(row[i])); + } + } + } + + return widths; + } + + /// + /// Decides which columns fit display columns given their + /// : droppable columns are removed lowest priority first until + /// the rest fit, and when even the never-dropped columns do not fit, the first remaining + /// column is truncated to what space is left. + /// + public static IReadOnlyList Plan( + int budget, IReadOnlyList columns, IReadOnlyList widths) + { + var visible = new bool[columns.Count]; + + for (var i = 0; i < columns.Count; i++) + { + visible[i] = true; + } + + while (!Fits(budget, widths, visible) && DropLowestPriority(columns, visible)) + { + } + + var layouts = new ColumnLayout[columns.Count]; + + for (var i = 0; i < columns.Count; i++) + { + layouts[i] = new ColumnLayout(visible[i], widths[i]); + } + + TruncateFirstVisibleIfNeeded(budget, widths, visible, layouts); + + return layouts; + } + + private static bool Fits(int budget, IReadOnlyList widths, bool[] visible) + { + var required = 0; + var visibleCount = 0; + + for (var i = 0; i < widths.Count; i++) + { + if (!visible[i]) + { + continue; + } + + required += widths[i]; + visibleCount++; + } + + if (visibleCount > 1) + { + required += DisplayWidth.Measure(Gutter) * (visibleCount - 1); + } + + return required <= budget; + } + + private static bool DropLowestPriority(IReadOnlyList columns, bool[] visible) + { + var dropIndex = -1; + var lowestPriority = int.MaxValue; + + for (var i = 0; i < columns.Count; i++) + { + if (!visible[i] || columns[i].DropPriority is not { } priority) + { + continue; + } + + if (priority < lowestPriority) + { + lowestPriority = priority; + dropIndex = i; + } + } + + if (dropIndex < 0) + { + return false; + } + + visible[dropIndex] = false; + return true; + } + + private static void TruncateFirstVisibleIfNeeded( + int budget, IReadOnlyList widths, bool[] visible, ColumnLayout[] layouts) + { + if (Fits(budget, widths, visible)) + { + return; + } + + var firstVisible = Array.IndexOf(visible, true); + + if (firstVisible < 0) + { + return; + } + + var otherWidth = 0; + var visibleCount = 0; + + for (var i = 0; i < widths.Count; i++) + { + if (!visible[i]) + { + continue; + } + + visibleCount++; + + if (i != firstVisible) + { + otherWidth += widths[i]; + } + } + + var gutterWidth = visibleCount > 1 ? DisplayWidth.Measure(Gutter) * (visibleCount - 1) : 0; + var truncatedWidth = Math.Max(0, budget - otherWidth - gutterWidth); + + layouts[firstVisible] = new ColumnLayout(true, truncatedWidth); + } +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TableRenderer.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TableRenderer.cs new file mode 100644 index 00000000000..1671b783645 --- /dev/null +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TableRenderer.cs @@ -0,0 +1,119 @@ +namespace ChilliCream.Nitro.CommandLine.Tui.Widgets; + +/// +/// One cell's already-styled content: the plain text measured and padded for layout, and the +/// Spectre style markup (without brackets) it renders with. An empty style renders unstyled. +/// +internal readonly record struct TableCellSpec(string Text, string StyleMarkup = ""); + +/// +/// Renders a table's fixed top block and rows from a layout: a +/// leading cursor cell and glyph cell followed by the column cells, each column separated by +/// and padded or truncated to its planned width. The top block +/// is a blank line, the header row and the rule. +/// +internal static class TableRenderer +{ + private const char RuleGlyph = 'โ”€'; + private const string BlankLine = " "; + + /// + /// The number of lines spends on the blank line, header row, + /// and rule, before any table row is drawn. + /// + public const int TopBlockLineCount = 3; + + /// + /// Builds the markup line for one row: and + /// unconditionally, one space, then every column whose entry is + /// visible, padded (or, for the first column when nothing else fits, truncated) to its + /// planned width and separated by a gutter. + /// + public static string RenderRow( + string prefix, + TableCellSpec glyph, + IReadOnlyList cells, + IReadOnlyList columns, + IReadOnlyList layout) + { + var line = Markup.Escape(prefix) + Stylize(glyph.StyleMarkup, Markup.Escape(glyph.Text)) + " "; + var needsGutter = false; + + for (var i = 0; i < columns.Count; i++) + { + if (!layout[i].Visible) + { + continue; + } + + if (needsGutter) + { + line += TableLayout.Gutter; + } + + needsGutter = true; + + var width = layout[i].Width; + var truncated = DisplayWidth.Truncate(cells[i].Text, width); + var cellText = columns[i].Alignment == ColumnAlignment.Right + ? DisplayWidth.PadLeft(truncated, width) + : DisplayWidth.PadRight(truncated, width); + + line += Stylize(cells[i].StyleMarkup, Markup.Escape(cellText)); + } + + return line; + } + + /// + /// Builds the dashed rule line under the header, filling display + /// columns. A non-positive width produces an empty line. + /// + public static string RenderRule(int width, string styleMarkup) => + width <= 0 ? string.Empty : Stylize(styleMarkup, new string(RuleGlyph, width)); + + /// + /// Appends the table's fixed top block to : a blank line, the header + /// row built from each column's in + /// , and the dashed rule, keeping only the first + /// of the (later lines are + /// dropped first). + /// + public static void RenderTopBlock( + List lines, + int lineCount, + int width, + string prefix, + TableCellSpec glyph, + IReadOnlyList columns, + IReadOnlyList layout, + string headerStyle, + string ruleStyle) + { + var headerCells = new TableCellSpec[columns.Count]; + + for (var i = 0; i < columns.Count; i++) + { + headerCells[i] = new TableCellSpec(columns[i].Title, headerStyle); + } + + string[] block = + [ + BlankLine, + RenderRow(prefix, glyph, headerCells, columns, layout), + RenderRule(width, ruleStyle) + ]; + + for (var i = 0; i < lineCount && i < block.Length; i++) + { + lines.Add(block[i]); + } + } + + /// + /// Wraps in Spectre markup for , + /// or returns it unchanged when the style is empty. + /// + public static string Stylize(string styleMarkup, string content) => + styleMarkup.Length == 0 ? content : $"[{styleMarkup}]{content}[/]"; +} diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskBadge.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskBadge.cs index 7c74e39011a..0a3ca4018fb 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskBadge.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskBadge.cs @@ -37,7 +37,7 @@ public static string Render( var glyph = TaskGlyphs.Status(status); var typeCode = TaskGlyphs.TypeCode(type); var priorityText = TaskPriorities.Format(priority); - var priorityStyle = ThemeTokens.GetStyle($"badge.priority.p{priority}").ToMarkup(); + var priorityStyle = PriorityStyle(priority); // Terminal-cell width of everything but the title. var fixedPlainWidth = DisplayWidth.Measure(prefix) + DisplayWidth.Measure(glyph) + 1 @@ -65,6 +65,12 @@ public static string Render( return line; } + /// + /// The Spectre style markup for 's badge, per the + /// badge.priority.p<priority> theme token. + /// + public static string PriorityStyle(int priority) => ThemeTokens.GetStyle($"badge.priority.p{priority}").ToMarkup(); + private static string RenderNarrow( string prefix, string glyph, diff --git a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskGlyphs.cs b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskGlyphs.cs index 653ba2e4621..d474d53ed40 100644 --- a/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskGlyphs.cs +++ b/src/Nitro/CommandLine/src/CommandLine/Tui/Widgets/TaskGlyphs.cs @@ -46,6 +46,12 @@ public static string StatusMarkup(string status) _ => type.Length > 0 ? type[..1].ToUpperInvariant() : "?" }; + /// + /// Returns the full type name, exactly as stored: lower case for the well-known types, + /// unchanged for a custom type. + /// + public static string TypeName(string type) => type; + /// /// The bracketed type code as a Spectre markup fragment, styled per the /// badge.type.* theme token for . diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTestBase.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTestBase.cs index 25699500e17..12f6817b955 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTestBase.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTestBase.cs @@ -33,158 +33,72 @@ protected string DatabasePath => AgentWorkspace.GetDatabasePath(WorkspaceDirectory); protected async Task SeedAgentAsync(string actor, string role = "") - => await new AgentRegistry(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase()) - .RegisterAsync(actor, role, client: "", TestContext.Current.CancellationToken); - - protected async Task InsertSessionIdentityAsync( - string actor, - string sessionId, - string harness = AgentSessionHarness.ClaudeCode, - string role = "") { - await SeedAgentAsync(actor, role); - await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); await connection.OpenAsync(TestContext.Current.CancellationToken); + await using var command = connection.CreateCommand(); command.CommandText = - "INSERT INTO agent_session_identities " - + "(harness, session_id, actor, role, actor_revision, created_at, last_seen_at) " - + "VALUES ($harness, $sessionId, $actor, $role, 1, $now, $now)"; - command.Parameters.AddWithValue("$harness", harness); - command.Parameters.AddWithValue("$sessionId", sessionId); - command.Parameters.AddWithValue("$actor", actor); + """ + INSERT INTO agents (name, role, registered_at, started_at, last_seen_at) + VALUES ($name, $role, $now, $now, $now) + ON CONFLICT (name) DO UPDATE SET role = excluded.role, last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("$name", actor); command.Parameters.AddWithValue("$role", role); command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); - await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - } - protected async Task InitWorkspaceAsync() - { - var result = await ExecuteCommandAsync("agent", "init"); - Assert.Equal(0, result.ExitCode); + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } /// - /// Inserts a session on with fresh start and heartbeat timestamps - /// and the supplied endpoint and ping state. A null - /// leaves the session without an associated agent. + /// Seeds the named agent and binds it to a Claude Code session directly on + /// the unified agents row, mirroring what StartSessionAsync + /// would write. /// - protected async Task InsertAliveSessionRowAsync( - string host, + protected async Task BindAgentSessionAsync( + string actor, string sessionId, - string? agentName, - string bindingKind = "explicit", - string harness = "claude-code", - string endpointKind = "none", - string endpointAddr = "", - string role = "", - string harnessVersion = "", - string? lastPingResult = null, - string? lastPingDetail = null) + string harness = AgentSessionHarness.ClaudeCode) { - await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); - await connection.OpenAsync(TestContext.Current.CancellationToken); + await SeedAgentAsync(actor); - if (agentName is not null) - { - await using var agentCommand = connection.CreateCommand(); - agentCommand.CommandText = - "INSERT OR IGNORE INTO agents (name, registered_at, last_seen_at) " - + "VALUES ($name, $now, $now);"; - agentCommand.Parameters.AddWithValue("$name", agentName); - agentCommand.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow); - await agentCommand.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - } + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(cancellationToken); await using var command = connection.CreateCommand(); command.CommandText = - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - role, harness_version, last_ping_result, last_ping_detail - ) VALUES ( - $harness, $sessionId, $agentName, $bindingKind, $host, - '/work', '/work/.nitro/agents', $endpointKind, $endpointAddr, $now, $now, - $role, $harnessVersion, $lastPingResult, $lastPingDetail - ); - """; + "UPDATE agents SET harness = $harness, session_id = $sessionId, " + + "started_at = $now, last_seen_at = $now WHERE name = $name"; command.Parameters.AddWithValue("$harness", harness); command.Parameters.AddWithValue("$sessionId", sessionId); - command.Parameters.AddWithValue("$agentName", (object?)agentName ?? DBNull.Value); - command.Parameters.AddWithValue("$bindingKind", bindingKind); - command.Parameters.AddWithValue("$host", host); - command.Parameters.AddWithValue("$endpointKind", endpointKind); - command.Parameters.AddWithValue("$endpointAddr", endpointAddr); - command.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow); - command.Parameters.AddWithValue("$role", role); - command.Parameters.AddWithValue("$harnessVersion", harnessVersion); - command.Parameters.AddWithValue("$lastPingResult", (object?)lastPingResult ?? DBNull.Value); - command.Parameters.AddWithValue("$lastPingDetail", (object?)lastPingDetail ?? DBNull.Value); - - await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); + command.Parameters.AddWithValue("$name", actor); + await command.ExecuteNonQueryAsync(cancellationToken); } - /// - /// Updates the role on all session rows matching - /// and . - /// - protected async Task UpdateSessionRoleAsync(string host, string sessionId, string role) + protected async Task InitWorkspaceAsync() { - await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); - await connection.OpenAsync(TestContext.Current.CancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET role = $role WHERE host = $host AND session_id = $sessionId"; - command.Parameters.AddWithValue("$role", role); - command.Parameters.AddWithValue("$host", host); - command.Parameters.AddWithValue("$sessionId", sessionId); - - await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + var result = await ExecuteCommandAsync("agent", "init"); + Assert.Equal(0, result.ExitCode); } /// - /// Inserts an agent_sessions row on whose - /// heartbeat is far outside the registry's stale window, so it is reaped - /// on the next read when is the workspace's - /// current instance id (a remote host's row is never reaped, however - /// stale). + /// Soft-deletes the named agent directly, bypassing the store, since delete mechanics + /// are a separate ticket. /// - protected async Task InsertStaleSessionRowAsync(string host, string sessionId, string? agentName = null) + protected async Task MarkAgentDeletedAsync(string name) { - await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); - await connection.OpenAsync(TestContext.Current.CancellationToken); - - if (agentName is not null) - { - await using var agentCommand = connection.CreateCommand(); - agentCommand.CommandText = - "INSERT OR IGNORE INTO agents (name, registered_at, last_seen_at) " - + "VALUES ($name, $now, $now);"; - agentCommand.Parameters.AddWithValue("$name", agentName); - agentCommand.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow); - await agentCommand.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - } + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', $sessionId, $agentName, $bindingKind, $host, - '/work', '/work/.nitro/agents', 'none', '', $stale, $stale - ); - """; - command.Parameters.AddWithValue("$sessionId", sessionId); - command.Parameters.AddWithValue("$agentName", (object?)agentName ?? DBNull.Value); - command.Parameters.AddWithValue("$bindingKind", agentName is null ? "none" : "explicit"); - command.Parameters.AddWithValue("$host", host); - command.Parameters.AddWithValue("$stale", FakeTime.GetUtcNow().AddDays(-30)); - - await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + command.CommandText = "UPDATE agents SET deleted_at = $now WHERE name = $name"; + command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); + command.Parameters.AddWithValue("$name", name); + await command.ExecuteNonQueryAsync(cancellationToken); } /// diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTests.cs index 5ad3d2f184f..46c505198d8 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentCommandTests.cs @@ -35,7 +35,7 @@ mail Send and receive mail between coding agents. memory Save and recall durable agent memory. login Allocate an actor name for a harness without a session-start hook. register Set the role of an actor allocated by `agent login` or a session-start hook. - list List the actors this workspace knows, with their session when they have one. + list Lists the agents in the workspace. takeover Take over another actor's mail and tasks. hooks Install, inspect, and remove Nitro's turn-boundary hook entries per harness. """); @@ -67,7 +67,7 @@ mail Send and receive mail between coding agents. memory Save and recall durable agent memory. login Allocate an actor name for a harness without a session-start hook. register Set the role of an actor allocated by `agent login` or a session-start hook. - list List the actors this workspace knows, with their session when they have one. + list Lists the agents in the workspace. takeover Take over another actor's mail and tasks. hooks Install, inspect, and remove Nitro's turn-boundary hook entries per harness. """); @@ -102,7 +102,7 @@ mail Send and receive mail between coding agents. memory Save and recall durable agent memory. login Allocate an actor name for a harness without a session-start hook. register Set the role of an actor allocated by `agent login` or a session-start hook. - list List the actors this workspace knows, with their session when they have one. + list Lists the agents in the workspace. takeover Take over another actor's mail and tasks. hooks Install, inspect, and remove Nitro's turn-boundary hook entries per harness. """); @@ -137,7 +137,7 @@ mail Send and receive mail between coding agents. memory Save and recall durable agent memory. login Allocate an actor name for a harness without a session-start hook. register Set the role of an actor allocated by `agent login` or a session-start hook. - list List the actors this workspace knows, with their session when they have one. + list Lists the agents in the workspace. takeover Take over another actor's mail and tasks. hooks Install, inspect, and remove Nitro's turn-boundary hook entries per harness. """); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentTuiLauncherTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentTuiLauncherTests.cs index 9b153f58338..9c8c8f03dce 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentTuiLauncherTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/AgentTuiLauncherTests.cs @@ -34,29 +34,14 @@ private static string RenderToText(TuiShell shell, int width = 80) } [Fact] - public void BuildMailTab_Should_OpenWithoutAnActor() - { - var store = new FakeMailStore(); - - var mailTab = AgentTuiLauncher.BuildMailTab( - store, - new Tui.Agents.FakeAgentRegistry(), - new FakeTimeProvider(s_now), TestContext.Current.CancellationToken); - - var mailMode = Assert.IsType(mailTab.RootMode); - Assert.Null(mailMode.State.Actor); - } - - [Fact] - public void BuildMailTab_Should_HostAWorkingMailMode() + public void BuildMailTab_Should_HostAWorkingMailMode_When_MailStoreIsGiven() { // arrange var store = new FakeMailStore(); // act var mailTab = AgentTuiLauncher.BuildMailTab( - store, new Tui.Agents.FakeAgentRegistry(), new FakeTimeProvider(s_now), - TestContext.Current.CancellationToken); + store, new Tui.Agents.FakeAgentStore(new FakeTimeProvider(s_now)), new FakeTimeProvider(s_now)); // assert Assert.IsType(mailTab.RootMode); @@ -64,12 +49,11 @@ public void BuildMailTab_Should_HostAWorkingMailMode() } [Fact] - public void BuildTabs_Should_RegisterTabsInOrder_TasksMailAgentsMemory() + public void BuildTabs_Should_RegisterTabsInOrderTasksMailAgentsMemory_When_AllStoresAreGiven() { // arrange var taskStore = new FakeTaskStore(); var mailStore = new FakeMailStore(); - var agentRegistry = new Tui.Agents.FakeAgentRegistry(); var timeProvider = new FakeTimeProvider(s_now); var tempRoot = Directory.CreateTempSubdirectory("nitro-agent-tui-launcher-tests"); @@ -83,24 +67,24 @@ public void BuildTabs_Should_RegisterTabsInOrder_TasksMailAgentsMemory() timeProvider, new AgentDatabase()); + var agentStore = new Tui.Agents.FakeAgentStore(timeProvider); + var tabs = AgentTuiLauncher.BuildTabs( taskStore, mailStore, memoryStore, - agentRegistry, - new Tui.Agents.FakeAgentSessionRegistry(), - new Tui.Agents.FakeClaudeSessionActivityReader(), - timeProvider, - TestContext.Current.CancellationToken); + agentStore, + timeProvider); var shell = new TuiShell( tabs, 80, 24, + agentStore: agentStore, tasksTabIndex: 0, - new SearchMode(taskStore), - new DependencyTreeView(taskStore, rootId: ""), - taskStore, + searchMode: new SearchMode(taskStore), + treeView: new DependencyTreeView(taskStore, rootId: ""), + store: taskStore, actor: "tasks-actor"); // act @@ -134,11 +118,13 @@ public void Render_Should_ShowTheMailWakeDaemonBadge_When_AStateProviderIsGiven( var taskStore = new FakeTaskStore(); var loader = new BoardDataLoader(taskStore, new FakeTimeProvider(s_now)); var boardMode = new BoardMode(loader); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( new KeyDispatcher(KeyMap.CreateDefaultGlobal()), boardMode, width, 24, + agentStore: new Tui.Agents.FakeAgentStore(time), actor: "tasks-actor", mailWakeDaemonState: () => state); @@ -150,7 +136,7 @@ public void Render_Should_ShowTheMailWakeDaemonBadge_When_AStateProviderIsGiven( } [Fact] - public async Task RunAsync_Should_StartAndStopTheMailWakeDaemonCoordinator_AroundTheApplicationLoop() + public async Task RunAsync_Should_StartAndStopTheMailWakeDaemonCoordinator_When_TheApplicationLoopIsCancelled() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -191,9 +177,7 @@ public async Task RunAsync_Should_StartAndStopTheMailWakeDaemonCoordinator_Aroun new FakeTaskStore(), new FakeMailStore(), memoryStore, - new Tui.Agents.FakeAgentRegistry(), - new Tui.Agents.FakeAgentSessionRegistry(), - new Tui.Agents.FakeClaudeSessionActivityReader(), + new Tui.Agents.FakeAgentStore(new FakeTimeProvider(s_now)), new FakeTimeProvider(s_now), workspaceDirectory, coordinator.Object, @@ -258,9 +242,7 @@ public async Task RunAsync_Should_StillStopTheMailWakeDaemonCoordinator_When_Can new FakeTaskStore(), new FakeMailStore(), memoryStore, - new Tui.Agents.FakeAgentRegistry(), - new Tui.Agents.FakeAgentSessionRegistry(), - new Tui.Agents.FakeClaudeSessionActivityReader(), + new Tui.Agents.FakeAgentStore(new FakeTimeProvider(s_now)), new FakeTimeProvider(s_now), workspaceDirectory, coordinator.Object, diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ClaudeHookCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ClaudeHookCommandTests.cs index 278d341b2f7..95aa2b695b6 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ClaudeHookCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ClaudeHookCommandTests.cs @@ -13,12 +13,12 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; public sealed class ClaudeHookCommandTests(NitroCommandFixture fixture) : AgentCommandTestBase(fixture) { [Fact] - public async Task SessionStart_Should_WriteTheActorContext_ToStdout() + public async Task SessionStart_Should_WriteTheActorContext_When_TheSessionIsBound() { - // arrange: an identity already bound to this session id, so the - // announced actor is the seeded name rather than an allocated one. + // arrange + // an agent already bound to this session id, so the announced actor is the seeded name await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -53,7 +53,7 @@ public async Task UserPromptSubmit_Should_WriteNeutralResponse_When_NoMailIsUnre { // arrange await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -68,10 +68,10 @@ public async Task UserPromptSubmit_Should_WriteNeutralResponse_When_NoMailIsUnre [Fact] public async Task UserPromptSubmit_Should_AppendTheMailDigest_When_TheActorHasUnreadMail() { - // arrange: one unread message addressed to the actor this session - // is bound to, sent by a second allocated actor. + // arrange + // one unread message addressed to the actor this session is bound to await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); var message = await SeedMailAsync(); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -90,14 +90,16 @@ public async Task UserPromptSubmit_Should_AppendTheMailDigest_When_TheActorHasUn [Fact] public async Task Stop_Should_WriteNeutralResponse_When_NoUnreadMailIsUndelivered() { - // arrange: a presence row bound to the actor, with an empty inbox, - // so the gate has nothing to block the turn for. + // arrange + // an empty inbox, so the gate has nothing to block the turn for await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); await ExecuteCommandAsync("agent", "hook", "claude", "session-start"); - Assert.Equal("maya", await QueryScalarAsync("SELECT agent_name FROM agent_sessions")); + Assert.Equal( + "maya", + await QueryScalarAsync("SELECT name FROM agents WHERE harness = 'claude-code' AND session_id = 'session-1'")); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -112,10 +114,10 @@ public async Task Stop_Should_WriteNeutralResponse_When_NoUnreadMailIsUndelivere [Fact] public async Task Stop_Should_BlockTheTurn_When_UnreadMailIsUndelivered() { - // arrange: a presence row bound to the actor, and one unread - // message never yet delivered on the gate channel. + // arrange + // one unread message never yet delivered on the gate channel await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); var message = await SeedMailAsync(); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -135,15 +137,16 @@ public async Task Stop_Should_BlockTheTurn_When_UnreadMailIsUndelivered() } [Fact] - public async Task SessionEnd_Should_RemoveThePresenceRow() + public async Task SessionEnd_Should_StampEndedAtAndKeepTheRow_When_TheSessionIsBound() { - // arrange: a presence row this session started. + // arrange + // a session this session-start bound to the agent row await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); await ExecuteCommandAsync("agent", "hook", "claude", "session-start"); - Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Null(await QueryScalarAsync("SELECT ended_at FROM agents WHERE name = 'maya'")); SetupStandardInput( $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -152,20 +155,62 @@ public async Task SessionEnd_Should_RemoveThePresenceRow() // assert Assert.Equal(0, result.ExitCode); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.NotNull(await QueryScalarAsync("SELECT ended_at FROM agents WHERE name = 'maya'")); + Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agents WHERE name = 'maya'")); + result.StdOut.Trim().MatchInlineSnapshot("{}"); + } + + [Fact] + public async Task Notification_Should_WriteNeutralResponse_When_TheNotificationTypeIsNotIdlePrompt() + { + // arrange + await InitWorkspaceAsync(); + await BindAgentSessionAsync("maya", "session-1"); + SetupStandardInput( + $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}},"notification_type":"permission_request"}"""); + + // act + var result = await ExecuteCommandAsync("agent", "hook", "claude", "notification"); + + // assert + Assert.Equal(0, result.ExitCode); + result.StdOut.Trim().MatchInlineSnapshot("{}"); + } + + [Fact] + public async Task Notification_Should_TouchTheSession_When_TheNotificationTypeIsIdlePrompt() + { + // arrange + await InitWorkspaceAsync(); + await BindAgentSessionAsync("maya", "session-1"); + SetupStandardInput( + $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); + await ExecuteCommandAsync("agent", "hook", "claude", "session-start"); + var lastSeenBefore = await QueryScalarAsync("SELECT last_seen_at FROM agents WHERE name = 'maya'"); + FakeTime.Advance(TimeSpan.FromMinutes(5)); + SetupStandardInput( + $$"""{"session_id":"session-1","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}},"notification_type":"idle_prompt"}"""); + + // act + var result = await ExecuteCommandAsync("agent", "hook", "claude", "notification"); + + // assert + Assert.Equal(0, result.ExitCode); result.StdOut.Trim().MatchInlineSnapshot("{}"); + Assert.NotEqual(lastSeenBefore, await QueryScalarAsync("SELECT last_seen_at FROM agents WHERE name = 'maya'")); } [Theory] [InlineData("user-prompt-submit")] [InlineData("stop")] + [InlineData("notification")] [InlineData("session-end")] public async Task Event_Should_WriteNeutralResponse_When_ThePayloadNamesNoSession(string eventName) { - // arrange: a payload with no session id, so nothing identifies which - // session the event speaks for. + // arrange + // a payload with no session id, so nothing identifies which session the event speaks for await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1"); + await BindAgentSessionAsync("maya", "session-1"); SetupStandardInput( $$"""{"cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -188,9 +233,10 @@ public async Task HookHelp_ShouldBeInvisible() } [Fact] - public async Task ClaudeHelp_ReturnsSuccess() + public async Task ClaudeHelp_Should_ListTheHookEvents_When_HelpIsRequested() { - // arrange & act + // arrange + // act var result = await ExecuteCommandAsync("agent", "hook", "claude", "--help"); // assert @@ -209,7 +255,8 @@ nitro agent hook claude [command] [options] session-start Adapt Claude Code's SessionStart hook: upsert this session's presence row. user-prompt-submit Adapt Claude Code's UserPromptSubmit hook: reset the block budget and inject the unread-mail digest. stop Adapt Claude Code's Stop hook: block the turn while unread mail is undelivered. - session-end Adapt Claude Code's SessionEnd hook: delete this session's presence row. + notification Adapt Claude Code's Notification hook: touch last-seen on an idle-prompt notification. + session-end Adapt Claude Code's SessionEnd hook: mark this session's agent row as ended. """); } @@ -223,12 +270,16 @@ nitro agent hook claude [command] [options] [InlineData( "stop", "Adapt Claude Code's Stop hook: block the turn while unread mail is undelivered.")] + [InlineData( + "notification", + "Adapt Claude Code's Notification hook: touch last-seen on an idle-prompt notification.")] [InlineData( "session-end", - "Adapt Claude Code's SessionEnd hook: delete this session's presence row.")] - public async Task EventHelp_ReturnsSuccess(string eventName, string description) + "Adapt Claude Code's SessionEnd hook: mark this session's agent row as ended.")] + public async Task EventHelp_Should_PrintTheEventDescription_When_HelpIsRequested(string eventName, string description) { - // arrange & act + // arrange + // act var result = await ExecuteCommandAsync("agent", "hook", "claude", eventName, "--help"); // assert @@ -253,7 +304,7 @@ private async Task SeedMailAsync() new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase(), - new AgentRegistry(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase())); + new AgentStore(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase())); return await store.SendMessageAsync( new MailMessageCreation diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/CodexHookCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/CodexHookCommandTests.cs index 0c11e0b2970..8dcee685016 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/CodexHookCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/CodexHookCommandTests.cs @@ -79,9 +79,10 @@ public async Task UserPromptSubmit_Should_WriteNeutralResponse_When_NoSessionRes } [Fact] - public async Task SessionEnd_Should_DeleteThePresenceRow_And_WriteNeutralResponse() + public async Task SessionEnd_Should_StampEndedAtAndKeepTheRow_When_ThePayloadNamesASession() { - // arrange: a presence row this same generation created on SessionStart. + // arrange + // A presence row this same generation created on SessionStart. await InitWorkspaceAsync(); await SeedCodexIdentityAsync(); SetupHookPayload(); @@ -93,12 +94,13 @@ public async Task SessionEnd_Should_DeleteThePresenceRow_And_WriteNeutralRespons // assert Assert.Equal(0, result.ExitCode); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.NotNull(await QueryScalarAsync("SELECT ended_at FROM agents WHERE name = 'maya'")); + Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agents WHERE name = 'maya'")); result.StdOut.Trim().MatchInlineSnapshot("{}"); } [Fact] - public async Task SessionEnd_Should_KeepThePresenceRow_When_ThePayloadNamesNoSession() + public async Task SessionEnd_Should_LeaveTheRowUnaffected_When_ThePayloadNamesNoSession() { // arrange // Start the session, then submit an event without a session id. @@ -113,7 +115,8 @@ public async Task SessionEnd_Should_KeepThePresenceRow_When_ThePayloadNamesNoSes // assert Assert.Equal(0, result.ExitCode); - Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Null(await QueryScalarAsync("SELECT ended_at FROM agents WHERE name = 'maya'")); + Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agents WHERE name = 'maya'")); result.StdOut.Trim().MatchInlineSnapshot("{}"); } @@ -200,9 +203,10 @@ public async Task HookHelp_StaysHidden() } [Fact] - public async Task CodexHelp_ReturnsSuccess() + public async Task CodexHelp_Should_ListTheHookEvents_When_HelpIsRequested() { - // arrange & act + // arrange + // act var result = await ExecuteCommandAsync("agent", "hook", "codex", "--help"); // assert @@ -220,7 +224,7 @@ nitro agent hook codex [command] [options] Commands: session-start Adapt Codex CLI's SessionStart hook: upsert this session's presence row. user-prompt-submit Adapt Codex CLI's UserPromptSubmit hook: inject the unread-mail digest. - session-end Adapt Codex CLI's SessionEnd hook: delete this session's presence row. + session-end Adapt Codex CLI's SessionEnd hook: mark this session's agent row as ended. notify Adapt Codex CLI's notify program: queue the unread-mail digest into the thread's next turn, then exec any wrapped foreign notify program. """); } @@ -228,10 +232,11 @@ nitro agent hook codex [command] [options] [Theory] [InlineData("session-start", "Adapt Codex CLI's SessionStart hook: upsert this session's presence row.")] [InlineData("user-prompt-submit", "Adapt Codex CLI's UserPromptSubmit hook: inject the unread-mail digest.")] - [InlineData("session-end", "Adapt Codex CLI's SessionEnd hook: delete this session's presence row.")] - public async Task EventHelp_ReturnsSuccess(string eventName, string description) + [InlineData("session-end", "Adapt Codex CLI's SessionEnd hook: mark this session's agent row as ended.")] + public async Task EventHelp_Should_PrintTheEventDescription_When_HelpIsRequested(string eventName, string description) { - // arrange & act + // arrange + // act var result = await ExecuteCommandAsync("agent", "hook", "codex", eventName, "--help"); // assert @@ -260,7 +265,7 @@ public async Task NotifyHelp_ReturnsSuccess() } private Task SeedCodexIdentityAsync() - => InsertSessionIdentityAsync("maya", SessionId, AgentSessionHarness.Codex); + => BindAgentSessionAsync("maya", SessionId, AgentSessionHarness.Codex); /// /// Redirects notify sidecar lookup to the test directory, which has no sidecar. @@ -299,7 +304,7 @@ private async Task SeedMailAsync() new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase(), - new AgentRegistry(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase())); + new AgentStore(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase())); return await store.SendMessageAsync( new MailMessageCreation diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ListAgentCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ListAgentCommandTests.cs index 3bfa5227c0b..6d77060e8c2 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ListAgentCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/ListAgentCommandTests.cs @@ -1,25 +1,25 @@ using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; namespace ChilliCream.Nitro.CommandLine.Tests.Agents; -public sealed class ListAgentCommandTests : AgentCommandTestBase +/// +/// Covers agent list against the unified agents table: role filtering, board-style +/// ordering, and the Name/Role/Harness/Started/Last Seen/Online columns. +/// +public sealed class ListAgentCommandTests(NitroCommandFixture fixture) : AgentCommandTestBase(fixture) { - private const string FixedHost = "host-list-agent-tests"; - - public ListAgentCommandTests(NitroCommandFixture fixture) : base(fixture) - { - SetupInstanceId(FixedHost); - } - [Fact] public async Task Help_ReturnsSuccess() { + // arrange & act var result = await ExecuteCommandAsync("agent", "list", "--help"); + // assert result.AssertHelpOutput( """ Description: - List the actors this workspace knows, with their session when they have one. + Lists the agents in the workspace. Usage: nitro agent list [options] @@ -36,146 +36,320 @@ nitro agent list --role "orchestrator" } [Fact] - public async Task Execute_Should_PrintNoActors_When_NoIdentitiesExist() + public async Task Execute_Should_PrintNoActors_When_NoAgentsExist() { + // arrange await InitWorkspaceAsync(); + // act var result = await ExecuteCommandAsync("agent", "list"); + // assert result.AssertSuccess("No actors."); } [Fact] - public async Task Execute_Should_ListTheActor_When_ItHasNoSession() + public async Task Execute_Should_FilterByRole_When_RoleIsGiven() { + // arrange await InitWorkspaceAsync(); - await SeedAgentAsync("alpha"); + await SeedAgentAsync("maya", "orchestrator"); + await SeedAgentAsync("nova", "planner"); - var result = await ExecuteCommandAsync("agent", "list"); + // act + var result = await ExecuteCommandAsync("agent", "list", "--role", "orchestrator"); - result.AssertSuccess("alpha offline no session last heard 2026-01-01 00:00"); + // assert + var line = Assert.Single(result.StdOut.Trim().Split('\n')); + Assert.StartsWith("maya", line); } [Fact] - public async Task Execute_Should_ListIdentityAsOffline_When_NoConnectionExists() + public async Task Execute_Should_PrintTheBoardColumns_When_AgentsAreInEveryState() { + // arrange + // Online, login-only, ended and deleted agents; the deleted one must not appear. await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1", role: "planner"); + await SeedBoardScenarioAsync(); + // act var result = await ExecuteCommandAsync("agent", "list"); - var line = Assert.Single(result.StdOut.Split('\n')); - Assert.StartsWith("maya offline claude-code role planner", line); + // assert + // Online first, then unreachable, then offline; the deleted agent is absent. + result.AssertSuccess( + """ + maya orchestrator Claude Code 30m 10m yes + nova - - 30m 10m no + ada researcher Codex 30m 10m no + """); } [Fact] - public async Task Execute_Should_IgnoreConnection_When_ItHasNoIdentity() + public async Task JsonOutput_Should_PrintTheBoardColumns_When_AgentsAreInEveryState() { + // arrange + // Same board scenario as the human-readable rendering. await InitWorkspaceAsync(); - await InsertAliveSessionRowAsync(FixedHost, "session-1", agentName: null, bindingKind: "none"); + await SeedBoardScenarioAsync(); + SetupInteractionMode(InteractionMode.JsonOutput); + // act var result = await ExecuteCommandAsync("agent", "list"); - result.AssertSuccess("No actors."); + // assert + result.AssertSuccess( + """ + { + "items": [ + { + "name": "maya", + "role": "orchestrator", + "harness": "claude-code", + "startedAt": "2026-01-01T00:00:00+00:00", + "lastSeenAt": "2026-01-01T00:20:00+00:00", + "online": true + }, + { + "name": "nova", + "role": "", + "harness": null, + "startedAt": "2026-01-01T00:00:00+00:00", + "lastSeenAt": "2026-01-01T00:20:00+00:00", + "online": false + }, + { + "name": "ada", + "role": "researcher", + "harness": "codex", + "startedAt": "2026-01-01T00:00:00+00:00", + "lastSeenAt": "2026-01-01T00:20:00+00:00", + "online": false + } + ] + } + """); } [Fact] - public async Task Execute_Should_ShowOnlineStateAndVersion_When_LiveConnectionExists() + public async Task Execute_Should_OrderByName_When_TwoOnlineAgentsLastSeenFallInTheSameFiveMinuteWindow() { + // arrange + // 10:01 and 10:04 share the 10:00 window await InitWorkspaceAsync(); - await InsertAliveSessionRowAsync( - FixedHost, - "session-1", - "maya", - endpointKind: AgentSessionEndpointKind.ClaudePeer, - endpointAddr: "maya-peer", - harnessVersion: "2.1.241"); - await InsertSessionIdentityAsync("maya", "session-1"); + var windowStart = FakeTime.GetUtcNow(); + await InsertOnlineAgentSeenAtAsync("zed", windowStart.AddMinutes(4)); + await InsertOnlineAgentSeenAtAsync("ann", windowStart.AddMinutes(1)); + FakeTime.Advance(TimeSpan.FromMinutes(6)); + // act var result = await ExecuteCommandAsync("agent", "list"); - var line = Assert.Single(result.StdOut.Split('\n')); - Assert.StartsWith("maya online claude-code 2.1.241", line); + // assert + var lines = result.StdOut.Trim().Split('\n'); + Assert.StartsWith("ann", lines[0]); + Assert.StartsWith("zed", lines[1]); } [Fact] - public async Task Execute_Should_ShowRemoteState_When_ConnectionBelongsToAnotherHost() + public async Task Execute_Should_SortTheLaterWindowFirst_When_OneAgentsLastSeenCrossedTheNextFiveMinuteBoundary() { + // arrange + // 10:06 falls in the 10:05 window, 10:01 and 10:04 in the 10:00 window await InitWorkspaceAsync(); - await InsertAliveSessionRowAsync("other-host", "session-1", "maya"); - await InsertSessionIdentityAsync("maya", "session-1"); + var windowStart = FakeTime.GetUtcNow(); + await InsertOnlineAgentSeenAtAsync("zzz", windowStart.AddMinutes(1)); + await InsertOnlineAgentSeenAtAsync("yyy", windowStart.AddMinutes(4)); + await InsertOnlineAgentSeenAtAsync("aaa", windowStart.AddMinutes(6)); + FakeTime.Advance(TimeSpan.FromMinutes(7)); + // act var result = await ExecuteCommandAsync("agent", "list"); - Assert.Contains("maya remote", result.StdOut); + // assert + var lines = result.StdOut.Trim().Split('\n'); + Assert.StartsWith("aaa", lines[0]); } [Fact] - public async Task Execute_Should_KeepIdentityOffline_When_StaleConnectionIsReaped() + public async Task Execute_Should_PlaceTwoLastSeenTimesInDifferentWindows_When_OneLandsRightBeforeAndOneRightAtTheBoundary() { + // arrange + // 10:04:59 is in the 10:00 window, 10:05:00 starts the 10:05 window await InitWorkspaceAsync(); - await InsertStaleSessionRowAsync(FixedHost, "session-1", "maya"); - await InsertSessionIdentityAsync("maya", "session-1"); + var boundary = FakeTime.GetUtcNow().AddMinutes(5); + await InsertOnlineAgentSeenAtAsync("b", boundary); + await InsertOnlineAgentSeenAtAsync("a", boundary - TimeSpan.FromSeconds(1)); + FakeTime.Advance(TimeSpan.FromMinutes(6)); + // act var result = await ExecuteCommandAsync("agent", "list"); - Assert.Contains("maya offline", result.StdOut); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); - Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agent_session_identities")); + // assert + var lines = result.StdOut.Trim().Split('\n'); + Assert.StartsWith("b", lines[0]); + Assert.StartsWith("a", lines[1]); } [Fact] - public async Task Execute_Should_FilterByIdentityRole_When_IdentityIsOffline() + public async Task Execute_Should_KeepOnlineBeforeOffline_When_TheOfflineAgentsWindowIsLaterThanTheOnlineAgents() { + // arrange + // The offline agent's window is later than the online agent's await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-1", role: "orchestrator"); - await InsertSessionIdentityAsync( - "nova", "session-2", harness: AgentSessionHarness.Codex, role: "planner"); + var windowStart = FakeTime.GetUtcNow(); + await InsertOnlineAgentSeenAtAsync("zzz", windowStart); + await InsertAgentRowAsync( + "aaa", + harness: AgentSessionHarness.ClaudeCode, + sessionId: "session-aaa", + endpointKind: AgentSessionEndpointKind.ClaudePeer, + startedAt: windowStart, + lastSeenAt: windowStart.AddMinutes(15), + endedAt: windowStart.AddMinutes(15)); + FakeTime.Advance(TimeSpan.FromMinutes(20)); - var result = await ExecuteCommandAsync("agent", "list", "--role", "orchestrator"); + // act + var result = await ExecuteCommandAsync("agent", "list"); - var line = Assert.Single(result.StdOut.Split('\n')); - Assert.StartsWith("maya offline", line); + // assert + var lines = result.StdOut.Trim().Split('\n'); + Assert.StartsWith("zzz", lines[0]); + Assert.StartsWith("aaa", lines[1]); } [Fact] - public async Task Execute_Should_OmitConnectionDiagnostics_When_IdentityIsOffline() + public async Task Execute_Should_OrderIdleBetweenOnlineAndUnreachable_When_AgentsAreInEveryState() { + // arrange await InitWorkspaceAsync(); - await InsertSessionIdentityAsync("maya", "session-offline", role: "planner"); - SetupInteractionMode(InteractionMode.JsonOutput); + var startedAt = FakeTime.GetUtcNow(); + await InsertOnlineAgentSeenAtAsync("idle", startedAt); + await InsertAgentRowAsync("unreachable", startedAt: startedAt, lastSeenAt: startedAt); + await InsertAgentRowAsync( + "offline", + harness: AgentSessionHarness.ClaudeCode, + sessionId: "session-offline", + endpointKind: AgentSessionEndpointKind.ClaudePeer, + startedAt: startedAt, + lastSeenAt: startedAt, + endedAt: startedAt); + FakeTime.Advance(AgentStateResolver.OnlineWindow + TimeSpan.FromMinutes(1)); + await InsertOnlineAgentSeenAtAsync("online", FakeTime.GetUtcNow()); + // act var result = await ExecuteCommandAsync("agent", "list"); - using var document = System.Text.Json.JsonDocument.Parse(result.StdOut); - var item = Assert.Single(document.RootElement.GetProperty("items").EnumerateArray()); - Assert.Equal("maya", item.GetProperty("actor").GetString()); - Assert.Equal("session-offline", item.GetProperty("sessionId").GetString()); - Assert.False(item.GetProperty("online").GetBoolean()); - Assert.Equal("offline", item.GetProperty("state").GetString()); - Assert.Equal(System.Text.Json.JsonValueKind.Null, item.GetProperty("host").ValueKind); - Assert.Equal(System.Text.Json.JsonValueKind.Null, item.GetProperty("endpointKind").ValueKind); + // assert + var lines = result.StdOut.Trim().Split('\n'); + Assert.Collection( + lines, + line => Assert.StartsWith("online", line), + line => Assert.StartsWith("idle", line), + line => Assert.StartsWith("unreachable", line), + line => Assert.StartsWith("offline", line)); } - [Fact] - public async Task Execute_Should_IncludeConnectionDiagnostics_When_IdentityIsOnline() + /// + /// Inserts an online Claude Code agent last seen at exactly . + /// + private Task InsertOnlineAgentSeenAtAsync(string name, DateTimeOffset lastSeenAt) + => InsertAgentRowAsync( + name, + harness: AgentSessionHarness.ClaudeCode, + sessionId: $"session-{name}", + endpointKind: AgentSessionEndpointKind.ClaudePeer, + startedAt: lastSeenAt, + lastSeenAt: lastSeenAt); + + /// + /// Seeds one online Claude Code hook agent ("maya"), one login-only agent with no + /// harness or session ("nova", unreachable since it has no endpoint), one Codex agent + /// whose session already ended ("ada", offline regardless of its endpoint), and one + /// deleted agent ("zoe") that agent list must never show. All four start at the + /// same time and are last seen 20 minutes later; the command runs 30 minutes after they + /// started, so "started" reads 30m and "last seen" reads 10m for every visible row. + /// + private async Task SeedBoardScenarioAsync() { - await InitWorkspaceAsync(); - await InsertAliveSessionRowAsync( - FixedHost, - "session-online", + var startedAt = FakeTime.GetUtcNow(); + var lastSeenAt = startedAt.AddMinutes(20); + + await InsertAgentRowAsync( "maya", + role: "orchestrator", + harness: AgentSessionHarness.ClaudeCode, + sessionId: "session-maya", endpointKind: AgentSessionEndpointKind.ClaudePeer, - endpointAddr: "maya-peer"); - await InsertSessionIdentityAsync("maya", "session-online"); - SetupInteractionMode(InteractionMode.JsonOutput); + startedAt: startedAt, + lastSeenAt: lastSeenAt); + + await InsertAgentRowAsync( + "nova", + startedAt: startedAt, + lastSeenAt: lastSeenAt); + + await InsertAgentRowAsync( + "ada", + role: "researcher", + harness: AgentSessionHarness.Codex, + sessionId: "session-ada", + endpointKind: AgentSessionEndpointKind.CodexThread, + startedAt: startedAt, + lastSeenAt: lastSeenAt, + endedAt: lastSeenAt); + + await InsertAgentRowAsync( + "zoe", + startedAt: startedAt, + lastSeenAt: lastSeenAt, + deletedAt: lastSeenAt); + + FakeTime.Advance(TimeSpan.FromMinutes(30)); + } - var result = await ExecuteCommandAsync("agent", "list"); + /// + /// Inserts one row directly into the unified agents table, bypassing + /// so the row's name, timestamps, and state are fully + /// controlled by the caller instead of coming from the actor name pool. + /// + private async Task InsertAgentRowAsync( + string name, + string role = "", + string? harness = null, + string? sessionId = null, + string endpointKind = AgentSessionEndpointKind.None, + DateTimeOffset? startedAt = null, + DateTimeOffset? lastSeenAt = null, + DateTimeOffset? endedAt = null, + DateTimeOffset? deletedAt = null) + { + var now = FakeTime.GetUtcNow(); - using var document = System.Text.Json.JsonDocument.Parse(result.StdOut); - var item = Assert.Single(document.RootElement.GetProperty("items").EnumerateArray()); - Assert.True(item.GetProperty("online").GetBoolean()); - Assert.Equal(FixedHost, item.GetProperty("host").GetString()); - Assert.Equal("maya-peer", item.GetProperty("endpointAddr").GetString()); + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents ( + name, role, harness, session_id, endpoint_kind, + registered_at, started_at, last_seen_at, ended_at, deleted_at + ) VALUES ( + $name, $role, $harness, $sessionId, $endpointKind, + $now, $startedAt, $lastSeenAt, $endedAt, $deletedAt + ); + """; + command.Parameters.AddWithValue("$name", name); + command.Parameters.AddWithValue("$role", role); + command.Parameters.AddWithValue("$harness", (object?)harness ?? DBNull.Value); + command.Parameters.AddWithValue("$sessionId", (object?)sessionId ?? DBNull.Value); + command.Parameters.AddWithValue("$endpointKind", endpointKind); + command.Parameters.AddWithValue("$now", now); + command.Parameters.AddWithValue("$startedAt", startedAt ?? now); + command.Parameters.AddWithValue("$lastSeenAt", lastSeenAt ?? now); + command.Parameters.AddWithValue("$endedAt", (object?)endedAt ?? DBNull.Value); + command.Parameters.AddWithValue("$deletedAt", (object?)deletedAt ?? DBNull.Value); + + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/LoginAgentCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/LoginAgentCommandTests.cs index a46fa8392a1..48872cf4bb4 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/LoginAgentCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/LoginAgentCommandTests.cs @@ -1,3 +1,5 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// @@ -54,7 +56,7 @@ nitro agent register --actor {actor} } [Fact] - public async Task Login_Should_BindNoSession() + public async Task Login_Should_AllocateAMoviePoolName_When_HarnessIsNull() { // arrange await InitWorkspaceAsync(); @@ -62,11 +64,28 @@ public async Task Login_Should_BindNoSession() // act var result = await ExecuteCommandAsync("agent", "login"); - // assert: the name exists but belongs to nobody until register binds it. + // assert + Assert.Equal(0, result.ExitCode); + var actor = await QueryScalarAsync("SELECT name FROM agents"); + Assert.NotNull(actor); + Assert.Contains(actor, AgentNamePool.Names); + Assert.Null(await QueryScalarAsync($"SELECT harness FROM agents WHERE name = '{actor}'")); + } + + [Fact] + public async Task Login_Should_BindNoSession_When_OnlyLoginHasRun() + { + // arrange + await InitWorkspaceAsync(); + + // act + var result = await ExecuteCommandAsync("agent", "login"); + + // assert + // The name exists but belongs to nobody until register binds it. Assert.Equal(0, result.ExitCode); Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agents")); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_session_identities")); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agents WHERE harness IS NOT NULL")); } [Fact] @@ -102,7 +121,7 @@ public async Task JsonOutput_Should_ReturnTheActor() } [Fact] - public async Task Login_Should_AllocateAnActor_ThatRegisterAccepts() + public async Task Login_Should_AllocateAnActor_ThatRegisterAccepts_When_TheActorWasOnlyAllocated() { // arrange await InitWorkspaceAsync(); @@ -112,17 +131,18 @@ public async Task Login_Should_AllocateAnActor_ThatRegisterAccepts() // act var result = await ExecuteCommandAsync("agent", "register", "--actor", actor!); - // assert: registering the allocated name needs no session of any kind. + // assert + // Registering the allocated name needs no session of any kind. Assert.Equal(0, result.ExitCode); Assert.Equal($"โœ“ Actor '{actor}'.", result.StdOut.Trim()); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_session_identities")); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Null(await QueryScalarAsync($"SELECT harness FROM agents WHERE name = '{actor}'")); } [Fact] - public async Task Login_Should_AllocateAnActor_ThatActsWithoutASession() + public async Task Login_Should_AllocateAnActor_ThatActsWithoutASession_When_TheActorWasOnlyAllocated() { - // arrange: no harness session at all, only the allocated name. + // arrange + // No harness session at all, only the allocated name. await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "login"); var actor = await QueryScalarAsync("SELECT name FROM agents"); @@ -131,12 +151,13 @@ public async Task Login_Should_AllocateAnActor_ThatActsWithoutASession() var result = await ExecuteCommandAsync( "agent", "tasks", "create", "Fix the parser", "--actor", actor!); - // assert: a session is only ever needed to push mail, never to act. + // assert + // A session is only ever needed to push mail, never to act. Assert.Equal(0, result.ExitCode); Assert.Equal( actor, await QueryScalarAsync("SELECT actor FROM events WHERE event_type = 'created'")); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Null(await QueryScalarAsync($"SELECT harness FROM agents WHERE name = '{actor}'")); } [Fact] diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/BroadcastMailCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/BroadcastMailCommandTests.cs index 54c41296a31..bc096a83a8e 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/BroadcastMailCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/BroadcastMailCommandTests.cs @@ -1,4 +1,3 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Workspace; using ChilliCream.Nitro.CommandLine.Tests.Hook; @@ -38,14 +37,15 @@ nitro agent mail broadcast --role "backend" --subject "Heads up" --body "Deployi } [Fact] - public async Task ExcludesSender_SendsToOthersOrderedByName() + public async Task Broadcast_Should_ExcludeSenderAndOrderOthersByName_When_MultipleAgentsAreRegistered() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); await ExecuteCommandAsync("agent", "register", "--actor", "alpha"); - await SetupSuccessfulWakeAsync("host-broadcast-order-test", "alpha", "zeta"); + await SetupSuccessfulWakeAsync("alpha", "zeta"); // act var result = await ExecuteCommandAsync( @@ -78,14 +78,15 @@ No other registered agent to broadcast to. } [Fact] - public async Task ExcludesImplicitRows_SendsOnlyToRegistered() + public async Task Broadcast_Should_SendToEveryNonDeletedAgent_When_AgentWasNeverExplicitlyRegistered() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); - await CreateRegistry().EnsureImplicitAsync("implicit-agent", TestContext.Current.CancellationToken); - await SetupSuccessfulWakeAsync("host-broadcast-implicit-row-test", "zeta"); + await SeedAgentAsync("implicit-agent"); + await SetupSuccessfulWakeAsync("zeta"); // act var result = await ExecuteCommandAsync( @@ -96,32 +97,29 @@ public async Task ExcludesImplicitRows_SendsOnlyToRegistered() "SELECT id FROM messages WHERE subject = 'Heads up'"); result.AssertSuccess( $""" - โœ“ Sent '{id}' to zeta. + โœ“ Sent '{id}' to implicit-agent, zeta. """); } [Fact] - public async Task RoleFilter_SendsOnlyToLiveAgentsWithThatRole() + public async Task Broadcast_Should_ExcludeDeletedAgent_When_SendingToAll() { // arrange await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-role-test"); - SetupCodexQueueClient(new FakeCodexQueueClient()); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); - await ExecuteCommandAsync("agent", "register", "--actor", "alpha"); - await SeedAliveSessionAsync( - "session-zeta", "zeta", "backend", "host-broadcast-role-test", - endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-zeta"); - await SeedAliveSessionAsync("session-alpha", "alpha", "frontend", "host-broadcast-role-test"); + await SeedAgentAsync("gone"); + await MarkAgentDeletedAsync("gone"); + await SetupSuccessfulWakeAsync("zeta"); // act var result = await ExecuteCommandAsync( - "agent", "mail", "broadcast", "--role", "backend", - "--subject", "Heads up", "--body", "Deploying."); + "agent", "mail", "broadcast", "--subject", "Heads up", "--body", "Deploying."); // assert - var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'Heads up'"); + var id = await QueryScalarAsync( + "SELECT id FROM messages WHERE subject = 'Heads up'"); result.AssertSuccess( $""" โœ“ Sent '{id}' to zeta. @@ -129,62 +127,55 @@ await SeedAliveSessionAsync( } [Fact] - public async Task RoleFilter_NoMatchingAgent_ReturnsError() + public async Task RoleFilter_Should_SendOnlyToMatchingAgents_When_RoleIsSpecified() { // arrange await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-role-test"); - await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); - await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); - await SeedAliveSessionAsync("session-zeta", "zeta", "frontend", "host-broadcast-role-test"); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("zeta", "backend"); + await SeedAgentAsync("alpha", "frontend"); // act var result = await ExecuteCommandAsync( "agent", "mail", "broadcast", "--role", "backend", - "--subject", "hi", "--body", "hello"); + "--subject", "Heads up", "--body", "Deploying."); // assert - result.AssertError( - """ - No live agent with role 'backend' to broadcast to (older sessions must re-register). + var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'Heads up'"); + result.AssertSuccess( + $""" + โœ“ Sent '{id}' to zeta. """); } [Fact] - public async Task RoleFilter_ExcludesClosedHistoricalIdentity_ReturnsNoLiveRecipientError() + public async Task RoleFilter_NoMatchingAgent_ReturnsError() { // arrange - // Seed a registered orchestrator identity without a session. await InitWorkspaceAsync(); await SeedAgentAsync("test-agent"); - await SeedAgentAsync("zeta", "orchestrator"); + await SeedAgentAsync("zeta", "frontend"); // act var result = await ExecuteCommandAsync( - "agent", "mail", "broadcast", "--role", "orchestrator", + "agent", "mail", "broadcast", "--role", "backend", "--subject", "hi", "--body", "hello"); // assert result.AssertError( """ - No live agent with role 'orchestrator' to broadcast to (older sessions must re-register). + No agent with role 'backend' to broadcast to. """); } [Fact] - public async Task RoleFilter_FallsBackToTheDurableRole_When_TheLiveSessionsOwnRoleIsBlank() + public async Task RoleFilter_Should_IncludeAgent_When_NoLiveSessionExists() { // arrange - // Only zeta has a live session, with a blank role and an orchestrator identity. + // Role now comes solely from the durable agents row; no session is required. await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-fallback-test"); - SetupCodexQueueClient(new FakeCodexQueueClient()); await SeedAgentAsync("test-agent"); await SeedAgentAsync("zeta", "orchestrator"); - await SeedAliveSessionAsync( - "session-zeta", "zeta", role: "", host: "host-broadcast-fallback-test", - endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-zeta"); - await SeedAgentAsync("closed-orchestrator", "orchestrator"); // act var result = await ExecuteCommandAsync( @@ -200,16 +191,14 @@ await SeedAliveSessionAsync( } [Fact] - public async Task RoleFilter_ExcludesAnImplicitIdentity_EvenWhenItsLiveSessionHasTheRole() + public async Task RoleFilter_Should_ExcludeDeletedAgent_When_ItsRoleMatches() { // arrange - // Seed an implicit identity with a live backend session. - var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-implicit-test"); - await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); - await CreateRegistry().EnsureImplicitAsync("ghost", cancellationToken); - await SeedAliveSessionAsync("session-ghost", "ghost", "backend", "host-broadcast-implicit-test"); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("ghost", "backend"); + await MarkAgentDeletedAsync("ghost"); + await SeedAgentAsync("zeta", "backend"); // act var result = await ExecuteCommandAsync( @@ -217,58 +206,22 @@ public async Task RoleFilter_ExcludesAnImplicitIdentity_EvenWhenItsLiveSessionHa "--subject", "hi", "--body", "hello"); // assert - result.AssertError( - """ - No live agent with role 'backend' to broadcast to (older sessions must re-register). - """); - } - - [Fact] - public async Task RoleFilter_DedupesMultipleLiveSessionsForTheSameActor() - { - // arrange - await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-dedup-test"); - SetupCodexQueueClient(new FakeCodexQueueClient()); - await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); - await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); - await SeedAliveSessionAsync( - "session-zeta-1", "zeta", "orchestrator", "host-broadcast-dedup-test", - endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-zeta-1"); - await SeedAliveSessionAsync( - "session-zeta-2", "zeta", "orchestrator", "host-broadcast-dedup-test", - endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-zeta-2"); - - // act - var result = await ExecuteCommandAsync( - "agent", "mail", "broadcast", "--role", "orchestrator", - "--subject", "Heads up", "--body", "Deploying."); - - // assert - var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'Heads up'"); + // Only the live agent with the matching role receives the mail. + var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'hi'"); result.AssertSuccess( $""" โœ“ Sent '{id}' to zeta. """); - Assert.Equal( - "1", - await QueryScalarAsync($"SELECT COUNT(*) FROM message_recipients WHERE message_id = '{id}'")); } [Fact] - public async Task RoleFilter_ReflectsTheCurrentRole_AfterTheLiveSessionsRoleChanges() + public async Task RoleFilter_Should_ReflectCurrentRole_When_RoleChangesAfterRegistration() { // arrange - // Change the session role from backend to orchestrator before discovery. await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-rolechange-test"); - SetupCodexQueueClient(new FakeCodexQueueClient()); - await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); - await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); - await SeedAliveSessionAsync( - "session-zeta", "zeta", "backend", "host-broadcast-rolechange-test", - endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-zeta"); - await ExecuteAsync("UPDATE agent_sessions SET role = 'orchestrator' WHERE session_id = 'session-zeta'"); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("zeta", "backend"); + await ExecuteAsync("UPDATE agents SET role = 'orchestrator' WHERE name = 'zeta'"); // act var backendResult = await ExecuteCommandAsync( @@ -281,7 +234,7 @@ await SeedAliveSessionAsync( // assert backendResult.AssertError( """ - No live agent with role 'backend' to broadcast to (older sessions must re-register). + No agent with role 'backend' to broadcast to. """); var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'orchestrator broadcast'"); orchestratorResult.AssertSuccess( @@ -291,71 +244,16 @@ await SeedAliveSessionAsync( } [Fact] - public async Task RoleFilter_ExcludesAnUnboundSession() + public async Task RoleFilter_Should_WakeLiveSession_When_RoleMatches() { // arrange - // Seed a session with an orchestrator role and no bound agent. await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-unbound-test"); - await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); - await SeedAliveSessionAsync( - "session-unbound", agentName: null, role: "orchestrator", host: "host-broadcast-unbound-test"); - - // act - var result = await ExecuteCommandAsync( - "agent", "mail", "broadcast", "--role", "orchestrator", - "--subject", "hi", "--body", "hello"); - - // assert - result.AssertError( - """ - No live agent with role 'orchestrator' to broadcast to (older sessions must re-register). - """); - } - - [Fact] - public async Task MailRoleRecipients_ResolvedRecipient_StillDeliversDurably_When_TheSessionEndsBeforeSend() - { - // arrange - // Resolve the recipient before deleting its session and sending through the mail store. - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(); - await SeedAgentAsync("test-agent"); - await SeedAgentAsync("zeta"); - await SeedAliveSessionAsync("session-zeta", "zeta", "orchestrator", "host-broadcast-race-test"); - - var to = await MailRoleRecipients.ResolveAsync( - CreateSessions("host-broadcast-race-test"), "orchestrator", "test-agent", cancellationToken); - - // act - await ExecuteAsync("DELETE FROM agent_sessions WHERE session_id = 'session-zeta'"); - var message = await CreateStore().SendMessageAsync( - new MailMessageCreation - { - Sender = "test-agent", - Subject = "Heads up", - Body = "Deploying.", - To = to - }, - cancellationToken); - - // assert - Assert.Equal(["zeta"], to); - Assert.Equal(["zeta"], message.Recipients.Select(recipient => recipient.Name)); - } - - [Fact] - public async Task RoleFilter_Should_WakeResolvedLiveSession_When_RoleMatches() - { - // arrange - await InitWorkspaceAsync(); - SetupInstanceId("host-broadcast-role-ping-test"); var queueClient = new FakeCodexQueueClient(); SetupCodexQueueClient(queueClient); - await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); - await ExecuteCommandAsync("agent", "register", "--actor", "zeta"); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("zeta", "orchestrator"); await SeedAliveSessionAsync( - "session-zeta", "zeta", "orchestrator", "host-broadcast-role-ping-test", + "session-zeta", "zeta", "orchestrator", endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-zeta"); // act @@ -391,13 +289,14 @@ No other registered agent to broadcast to. } [Fact] - public async Task JsonOutput_ReturnsMessageResult() + public async Task Broadcast_Should_ReturnMessageResult_When_JsonOutputIsRequested() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - await SetupSuccessfulWakeAsync("host-broadcast-json-test", "bob"); + await SetupSuccessfulWakeAsync("bob"); SetupInteractionMode(InteractionMode.JsonOutput); // act diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/MailCommandTestBase.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/MailCommandTestBase.cs index df9bc5ccb99..3e97c47df16 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/MailCommandTestBase.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/MailCommandTestBase.cs @@ -47,47 +47,42 @@ protected async Task InitWorkspaceAsync() /// clock, for seeding data without going through the CLI. /// internal MailStore CreateStore() - => new(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase(), CreateRegistry()); + => new(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase(), CreateAgentStore()); /// - /// Creates an like , - /// additionally wired with the instance id and global config directory - /// providers requires, pinned to - /// so a directly-enqueued generation lines - /// up with a command run under the matching . + /// Creates an bound to this test's workspace and clock. /// - internal MailStore CreateWakeStore(string instanceId) - => new( - new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase(), CreateRegistry(), - new FixedInstanceIdProvider(instanceId), new FixedGlobalConfigDirectoryProvider(WorkingDirectory)); - - /// - /// Creates an bound to this test's workspace - /// and clock, for seeding agents without going through the CLI. - /// - internal AgentRegistry CreateRegistry() + internal AgentStore CreateAgentStore() => new(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase()); /// - /// Creates an bound to this test's - /// workspace, clock, and instance id, for resolving live participants - /// directly without going through the CLI: every row it acts on must - /// already exist, seeded directly against the database. + /// Registers an agent directly against the unified agents table, bypassing + /// the store's allocated-name contract so tests can seed a deterministic name. /// - internal AgentSessionRegistry CreateSessions(string host) - => new( - new TestFileSystem(WorkingDirectory), - FakeTime, - new AgentDatabase(), - CreateRegistry(), - new FixedInstanceIdProvider(host), - new FixedGlobalConfigDirectoryProvider(WorkingDirectory)); + internal async Task SeedAgentAsync(string name, string role = "") + { + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, role, registered_at, started_at, last_seen_at) + VALUES ($name, $role, $now, $now, $now) + ON CONFLICT (name) DO UPDATE SET role = excluded.role, last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("$name", name); + command.Parameters.AddWithValue("$role", role); + command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); + + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } /// - /// Registers an agent directly against the registry. + /// Marks the named agent as deleted. /// - internal Task SeedAgentAsync(string name, string role = "") - => CreateRegistry().RegisterAsync(name, role, client: "", TestContext.Current.CancellationToken); + internal Task MarkAgentDeletedAsync(string name) + => ExecuteAsync($"UPDATE agents SET deleted_at = '{FakeTime.GetUtcNow():O}' WHERE name = '{name}'"); /// /// Sends a message directly against the store, starting a new thread. @@ -110,31 +105,19 @@ internal Task SeedMessageAsync( }, TestContext.Current.CancellationToken); - /// - /// Seeds a fresh codex-thread session explicitly bound to - /// on . Configure - /// with the same host when the command must discover this session. - /// - private protected Task SeedAliveCodexThreadSessionAsync(string agentName, string threadId, string host) - => SeedAliveSessionAsync( - "session-1", agentName, role: "", host, - endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: threadId); - /// /// Configures successful foreground wake delivery for each named agent. /// private protected async Task SetupSuccessfulWakeAsync( - string host, params string[] agentNames) { - SetupInstanceId(host); var queueClient = new FakeCodexQueueClient(); SetupCodexQueueClient(queueClient); foreach (var agentName in agentNames) { await SeedAliveSessionAsync( - $"session-{agentName}", agentName, role: "", host, + $"session-{agentName}", agentName, role: "", endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: $"thread-{agentName}"); } @@ -142,15 +125,15 @@ await SeedAliveSessionAsync( return queueClient; } - private protected MailNudge CreateMailNudge(string host, FakeCodexQueueClient queueClient) + private protected MailNudge CreateMailNudge(FakeCodexQueueClient queueClient) { var fileSystem = new TestFileSystem(WorkingDirectory); var database = new AgentDatabase(); return new MailNudge( - CreateSessions(host), + CreateAgentStore(), CreateStore(), - new SessionDeliveryLedger(fileSystem, database), + new AgentDeliveryLedger(fileSystem, database), new FakeClaudePeerClient(), queueClient, FakeTime); @@ -178,50 +161,38 @@ private protected static bool ReadDigestReadFlag((string ThreadId, string Messag } /// - /// Seeds a fresh session on , explicitly bound to - /// or unbound when it is . - /// Configure with the same host - /// when the command must discover this session. + /// Seeds a fresh codex session directly on the unified agents row for + /// , mirroring what StartSessionAsync would write. /// private protected async Task SeedAliveSessionAsync( string sessionId, - string? agentName, + string agentName, string role, - string host, string endpointKind = AgentSessionEndpointKind.None, string endpointAddr = "") { await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); await connection.OpenAsync(TestContext.Current.CancellationToken); - if (agentName is not null) - { - await using var agentCommand = connection.CreateCommand(); - agentCommand.CommandText = - "INSERT OR IGNORE INTO agents (name, registered_at, last_seen_at) " - + "VALUES ($name, $now, $now);"; - agentCommand.Parameters.AddWithValue("$name", agentName); - agentCommand.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow); - await agentCommand.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); - } - await using var command = connection.CreateCommand(); command.CommandText = """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, role, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'codex', $sessionId, $agentName, $bindingKind, $role, $host, - '/work', '/work/.nitro/agents', $endpointKind, $endpointAddr, $now, $now - ); + INSERT INTO agents ( + name, role, harness, session_id, endpoint_kind, endpoint_addr, + registered_at, started_at, last_seen_at + ) + VALUES ($name, $role, 'codex', $sessionId, $endpointKind, $endpointAddr, $now, $now, $now) + ON CONFLICT (name) DO UPDATE SET + role = excluded.role, + harness = excluded.harness, + session_id = excluded.session_id, + endpoint_kind = excluded.endpoint_kind, + endpoint_addr = excluded.endpoint_addr, + last_seen_at = excluded.last_seen_at; """; - command.Parameters.AddWithValue("$sessionId", sessionId); - command.Parameters.AddWithValue("$agentName", (object?)agentName ?? DBNull.Value); - command.Parameters.AddWithValue( - "$bindingKind", agentName is null ? AgentSessionBindingKind.None : AgentSessionBindingKind.Explicit); + command.Parameters.AddWithValue("$name", agentName); command.Parameters.AddWithValue("$role", role); - command.Parameters.AddWithValue("$host", host); + command.Parameters.AddWithValue("$sessionId", sessionId); command.Parameters.AddWithValue("$endpointKind", endpointKind); command.Parameters.AddWithValue("$endpointAddr", endpointAddr); command.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/ReplyMailCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/ReplyMailCommandTests.cs index 12793a4691b..97ed7d6a986 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/ReplyMailCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/ReplyMailCommandTests.cs @@ -39,15 +39,15 @@ private async Task SendOriginalMessageAsync(string sender, string subjec } [Fact] - public async Task ReplyAll_ExcludesSelf_IncludesSenderAndOtherRecipients() + public async Task ReplyAll_Should_ExcludeSelf_AndIncludeSenderAndOtherRecipients_When_ReplyingToAll() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync("agent", "register", "--actor", "alice"); - await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - await ExecuteCommandAsync("agent", "register", "--actor", "carol"); + await SeedAgentAsync("alice"); + await SeedAgentAsync("bob"); + await SeedAgentAsync("carol"); var originalId = await SendOriginalMessageAsync("alice", "Status", "bob", "carol"); - await SetupSuccessfulWakeAsync("host-reply-all-test", "alice", "carol"); + await SetupSuccessfulWakeAsync("alice", "carol"); // act var result = await ExecuteCommandAsync( @@ -62,12 +62,56 @@ public async Task ReplyAll_ExcludesSelf_IncludesSenderAndOtherRecipients() """); } + [Fact] + public async Task ReplyAll_Should_DropDeletedParticipant_AndPrintSkipLine_When_OneParticipantIsDeleted() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("alice"); + await SeedAgentAsync("bob"); + await SeedAgentAsync("carol"); + var originalId = await SendOriginalMessageAsync("alice", "Status", "bob", "carol"); + await MarkAgentDeletedAsync("carol"); + await SetupSuccessfulWakeAsync("alice"); + + // act + var result = await ExecuteCommandAsync( + "agent", "mail", "reply", "--message", originalId, "--body", "Thanks!", "--actor", "bob"); + + // assert + var replyId = await QueryScalarAsync( + "SELECT id FROM messages WHERE in_reply_to = '" + originalId + "'"); + result.AssertSuccess( + $""" + โœ“ Sent '{replyId}' to alice. + Skipped deleted or unknown agents: carol. + """); + } + + [Fact] + public async Task DirectReply_Should_ReturnError_When_LoneRecipientIsDeleted() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("alice"); + await SeedAgentAsync("bob"); + var originalId = await SendOriginalMessageAsync("alice", "Status", "bob"); + await MarkAgentDeletedAsync("alice"); + + // act + var result = await ExecuteCommandAsync( + "agent", "mail", "reply", "--message", originalId, "--body", "x", "--actor", "bob"); + + // assert + result.AssertError("Agent 'alice' was deleted. Look the name up with 'nitro agent list'."); + } + [Fact] public async Task SelfOnlyReply_ReturnsError() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync("agent", "register", "--actor", "alice"); + await SeedAgentAsync("alice"); var originalId = await SendOriginalMessageAsync("alice", "Note to self", "alice"); // act @@ -84,9 +128,9 @@ public async Task NonParticipant_ReturnsError() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync("agent", "register", "--actor", "alice"); - await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - await ExecuteCommandAsync("agent", "register", "--actor", "carol"); + await SeedAgentAsync("alice"); + await SeedAgentAsync("bob"); + await SeedAgentAsync("carol"); var originalId = await SendOriginalMessageAsync("alice", "Status", "bob"); // act @@ -116,14 +160,14 @@ public async Task NonexistentMessage_ReturnsError() } [Fact] - public async Task Reply_ThreadsUnderOriginalMessage_AndInheritsRootSubject() + public async Task Reply_Should_ThreadUnderOriginalMessage_AndInheritRootSubject_When_JsonOutputIsRequested() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync("agent", "register", "--actor", "alice"); - await ExecuteCommandAsync("agent", "register", "--actor", "bob"); + await SeedAgentAsync("alice"); + await SeedAgentAsync("bob"); var originalId = await SendOriginalMessageAsync("alice", "Root subject", "bob"); - await SetupSuccessfulWakeAsync("host-reply-thread-test", "alice"); + await SetupSuccessfulWakeAsync("alice"); SetupInteractionMode(InteractionMode.JsonOutput); // act @@ -131,27 +175,30 @@ public async Task Reply_ThreadsUnderOriginalMessage_AndInheritsRootSubject() "agent", "mail", "reply", "--message", originalId, "--body", "Thanks!", "--actor", "bob"); // assert + Assert.Empty(result.StdErr); + Assert.Equal(0, result.ExitCode); + using var document = System.Text.Json.JsonDocument.Parse(result.StdOut); var root = document.RootElement; - Assert.Empty(result.StdErr); - Assert.Equal(0, result.ExitCode); - Assert.Equal(originalId, root.GetProperty("threadId").GetString()); - Assert.Equal(originalId, root.GetProperty("inReplyTo").GetString()); - Assert.Equal("Root subject", root.GetProperty("subject").GetString()); - Assert.Equal(["alice"], root.GetProperty("to").EnumerateArray().Select(e => e.GetString()!).ToArray()); - Assert.True(root.GetProperty("messageStored").GetBoolean()); + Snapshot.Create() + .Add(root.GetProperty("threadId").GetString() == originalId, "ThreadIdMatchesOriginal") + .Add(root.GetProperty("inReplyTo").GetString() == originalId, "InReplyToMatchesOriginal") + .Add(root.GetProperty("subject").GetString(), "Subject") + .Add(root.GetProperty("to").EnumerateArray().Select(e => e.GetString()!).ToArray(), "To") + .Add(root.GetProperty("messageStored").GetBoolean(), "MessageStored") + .MatchMarkdownSnapshot(); } [Fact] - public async Task Reply_Should_NudgeRecipientWithExactMessageIdAndBody() + public async Task Reply_Should_NudgeRecipientWithExactMessageIdAndBody_When_ReplyIsSent() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync("agent", "register", "--actor", "alice"); - await ExecuteCommandAsync("agent", "register", "--actor", "bob"); + await SeedAgentAsync("alice"); + await SeedAgentAsync("bob"); var originalId = await SendOriginalMessageAsync("alice", "Status", "bob"); - var queueClient = await SetupSuccessfulWakeAsync("host-reply-nudge-test", "alice"); + var queueClient = await SetupSuccessfulWakeAsync("alice"); // act await ExecuteCommandAsync( @@ -170,7 +217,7 @@ public async Task BodyAndBodyFileBothMissing_ReturnsParseError() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync("agent", "register", "--actor", "alice"); + await SeedAgentAsync("alice"); var originalId = await SendOriginalMessageAsync("alice", "Status", "alice"); // act diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/SendMailCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/SendMailCommandTests.cs index 8904d8f2cdc..813f8b72f8a 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/SendMailCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/SendMailCommandTests.cs @@ -2,6 +2,7 @@ using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Agents; using ChilliCream.Nitro.CommandLine.Tests.Hook; using Moq; @@ -11,17 +12,17 @@ public sealed class SendMailCommandTests(NitroCommandFixture fixture) : MailCommandTestBase(fixture) { [Fact] - public async Task NudgeAsync_Should_ReturnNormally_When_ParticipantDiscoveryThrows() + public async Task NudgeAsync_Should_ReturnNormally_When_AgentLookupThrows() { // arrange - var sessions = new Mock(); - sessions - .Setup(registry => registry.ListParticipantsAsync(It.IsAny())) - .ThrowsAsync(new InvalidOperationException("participant discovery failed")); + var agentStore = new Mock(); + agentStore + .Setup(store => store.FindAsync("bob", It.IsAny())) + .ThrowsAsync(new InvalidOperationException("agent lookup failed")); var nudge = new MailNudge( - sessions.Object, + agentStore.Object, Mock.Of(), - Mock.Of(), + Mock.Of(), Mock.Of(), Mock.Of(), TimeProvider.System); @@ -30,9 +31,7 @@ public async Task NudgeAsync_Should_ReturnNormally_When_ParticipantDiscoveryThro await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); // assert - sessions.Verify( - registry => registry.ListParticipantsAsync(It.IsAny()), - Times.Once); + agentStore.Verify(store => store.FindAsync("bob", It.IsAny()), Times.Once); } [Fact] @@ -67,12 +66,13 @@ nitro agent mail send --body-file notes.txt --to "agent-a" --to "agent-b" --cc " } [Fact] - public async Task SingleRecipient_SendsMessage() + public async Task Send_Should_DeliverMessage_When_ThereIsASingleRecipient() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - var queueClient = await SetupSuccessfulWakeAsync("host-send-single-test", "bob"); + var queueClient = await SetupSuccessfulWakeAsync("bob"); // act var result = await ExecuteCommandAsync( @@ -96,10 +96,10 @@ public async Task NudgeAsync_Should_SendPointer_When_TheSameMessageIsPushedTwice await InitWorkspaceAsync(); await SeedAgentAsync("test-agent"); await SeedAgentAsync("bob"); - var queueClient = await SetupSuccessfulWakeAsync("host-send-repeat-test", "bob"); + var queueClient = await SetupSuccessfulWakeAsync("bob"); var message = await SeedMessageAsync( "test-agent", "Status", ["bob"], body: "All good."); - var nudge = CreateMailNudge("host-send-repeat-test", queueClient); + var nudge = CreateMailNudge(queueClient); // act await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); @@ -118,22 +118,23 @@ public async Task NudgeAsync_Should_SendPointer_When_TheSameMessageIsPushedTwice [Fact] public async Task NudgeAsync_Should_LeaveTheMessageUnread_When_ItPushesTheBody() { - // arrange: pushing the body to the session never means it was read. + // arrange + // Pushing the body to the session never means it was read. await InitWorkspaceAsync(); await SeedAgentAsync("test-agent"); await SeedAgentAsync("bob"); - var queueClient = await SetupSuccessfulWakeAsync("host-send-unread-test", "bob"); + var queueClient = await SetupSuccessfulWakeAsync("bob"); var message = await SeedMessageAsync("test-agent", "Status", ["bob"], body: "All good."); var store = CreateStore(); var cancellationToken = TestContext.Current.CancellationToken; var unreadBefore = await store.CountUnreadAsync("bob", cancellationToken); - var nudge = CreateMailNudge("host-send-unread-test", queueClient); + var nudge = CreateMailNudge(queueClient); // act await nudge.NudgeAsync(["bob"], cancellationToken); - // assert: the pushed payload says unread, the message is still in the - // unread inbox, and the unread count is unchanged. + // assert + // The pushed payload says unread and the unread inbox and count are unchanged. var call = Assert.Single(queueClient.Calls); Assert.False(ReadDigestReadFlag(call)); var unread = await store.QueryInboxAsync( @@ -143,19 +144,191 @@ public async Task NudgeAsync_Should_LeaveTheMessageUnread_When_ItPushesTheBody() } [Fact] - public async Task SingleRecipient_Should_SendBodyToEachLiveSession_When_ActorHasTwoSessions() + public async Task NudgeAsync_Should_ReserveNoDelivery_When_TheSessionIdIsMissingOnAClaudePeerEndpoint() + { + // arrange + await InitWorkspaceAsync(); + await SeedAliveSessionAsync( + "session-alice", "alice", role: "", + endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-alice"); + await SeedAliveSessionAsync( + "session-bob", "bob", role: "", + endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-bob"); + await ExecuteAsync( + "UPDATE agents SET endpoint_kind = 'claude-peer', endpoint_addr = 'peer-addr', " + + "session_id = NULL WHERE name = 'bob'"); + await SeedMessageAsync("alice", "Status", ["bob"], body: "All good."); + var peerClient = new FakeClaudePeerClient(); + var nudge = new MailNudge( + CreateAgentStore(), + CreateStore(), + new AgentDeliveryLedger( + new ChilliCream.Nitro.CommandLine.Tests.Hook.TestFileSystem(WorkingDirectory), new AgentDatabase()), + peerClient, + new FakeCodexQueueClient(), + FakeTime); + + // act + await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); + + // assert + Assert.Empty(peerClient.Calls); + Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries WHERE agent = 'bob'")); + } + + [Fact] + public async Task NudgeAsync_Should_ReserveNoDelivery_When_TheEndpointKindIsOpencodeServerWithASession() + { + // arrange + // SendAsync has no transport for opencode-server, even with a session. + await InitWorkspaceAsync(); + await SeedAliveSessionAsync( + "session-alice", "alice", role: "", + endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-alice"); + await SeedAliveSessionAsync( + "session-bob", "bob", role: "", + endpointKind: AgentSessionEndpointKind.OpencodeServer, endpointAddr: "opencode-bob"); + await SeedMessageAsync("alice", "Status", ["bob"], body: "All good."); + var codexQueueClient = new FakeCodexQueueClient(); + var nudge = new MailNudge( + CreateAgentStore(), + CreateStore(), + new AgentDeliveryLedger( + new ChilliCream.Nitro.CommandLine.Tests.Hook.TestFileSystem(WorkingDirectory), new AgentDatabase()), + new FakeClaudePeerClient(), + codexQueueClient, + FakeTime); + + // act + await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); + + // assert + // No reservation was written, so a later nudge could still deliver it. + Assert.Empty(codexQueueClient.Calls); + Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries WHERE agent = 'bob'")); + var unread = await CreateStore().QueryInboxAsync( + new MailInboxFilter { Actor = "bob", UnreadOnly = true }, TestContext.Current.CancellationToken); + Assert.Single(unread); + } + + [Fact] + public async Task NudgeAsync_Should_ReserveADelivery_When_TheEndpointKindIsClaudePeerWithASession() + { + // arrange + // A claude-peer endpoint with a session is a transport SendAsync can reach. + await InitWorkspaceAsync(); + await SeedAliveSessionAsync( + "session-alice", "alice", role: "", + endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-alice"); + await SeedAliveSessionAsync( + "session-bob", "bob", role: "", + endpointKind: AgentSessionEndpointKind.ClaudePeer, endpointAddr: "peer-bob"); + var message = await SeedMessageAsync("alice", "Status", ["bob"], body: "All good."); + var peerClient = new FakeClaudePeerClient(); + var nudge = new MailNudge( + CreateAgentStore(), + CreateStore(), + new AgentDeliveryLedger( + new ChilliCream.Nitro.CommandLine.Tests.Hook.TestFileSystem(WorkingDirectory), new AgentDatabase()), + peerClient, + new FakeCodexQueueClient(), + FakeTime); + + // act + await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); + + // assert + var call = Assert.Single(peerClient.Calls); + Assert.Equal( + ("session-bob", message.Id, "All good."), + ReadDigestCall((call.SessionId, call.Message))); + Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries WHERE agent = 'bob'")); + } + + [Fact] + public async Task NudgeAsync_Should_ReserveADelivery_When_TheAgentIsIdle() + { + // arrange + // An agent quiet past the online window resolves Idle, which the wake dispatcher still targets. + await InitWorkspaceAsync(); + await SeedAliveSessionAsync( + "session-alice", "alice", role: "", + endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-alice"); + await SeedAliveSessionAsync( + "session-bob", "bob", role: "", + endpointKind: AgentSessionEndpointKind.ClaudePeer, endpointAddr: "peer-bob"); + await ExecuteAsync($"UPDATE agents SET last_seen_at = '{FakeTime.GetUtcNow():O}' WHERE name = 'bob'"); + FakeTime.Advance(AgentStateResolver.OnlineWindow + TimeSpan.FromMinutes(1)); + var message = await SeedMessageAsync("alice", "Status", ["bob"], body: "All good."); + var peerClient = new FakeClaudePeerClient(); + var nudge = new MailNudge( + CreateAgentStore(), + CreateStore(), + new AgentDeliveryLedger( + new ChilliCream.Nitro.CommandLine.Tests.Hook.TestFileSystem(WorkingDirectory), new AgentDatabase()), + peerClient, + new FakeCodexQueueClient(), + FakeTime); + + // act + await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); + + // assert + var call = Assert.Single(peerClient.Calls); + Assert.Equal( + ("session-bob", message.Id, "All good."), + ReadDigestCall((call.SessionId, call.Message))); + Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries WHERE agent = 'bob'")); + } + + [Fact] + public async Task NudgeAsync_Should_ReserveNoDelivery_When_TheAgentHasEnded() + { + // arrange + // An ended session resolves Offline, which the nudge guard must still skip. + await InitWorkspaceAsync(); + await SeedAliveSessionAsync( + "session-alice", "alice", role: "", + endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-alice"); + await SeedAliveSessionAsync( + "session-bob", "bob", role: "", + endpointKind: AgentSessionEndpointKind.ClaudePeer, endpointAddr: "peer-bob"); + await CreateAgentStore().EndSessionAsync( + AgentSessionHarness.Codex, "session-bob", TestContext.Current.CancellationToken); + await SeedMessageAsync("alice", "Status", ["bob"], body: "All good."); + var peerClient = new FakeClaudePeerClient(); + var nudge = new MailNudge( + CreateAgentStore(), + CreateStore(), + new AgentDeliveryLedger( + new ChilliCream.Nitro.CommandLine.Tests.Hook.TestFileSystem(WorkingDirectory), new AgentDatabase()), + peerClient, + new FakeCodexQueueClient(), + FakeTime); + + // act + await nudge.NudgeAsync(["bob"], TestContext.Current.CancellationToken); + + // assert + Assert.Empty(peerClient.Calls); + Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries WHERE agent = 'bob'")); + } + + [Fact] + public async Task SingleRecipient_Should_SendBodyToItsCurrentSession_When_AnEarlierSessionWasSuperseded() { // arrange + // One agent row per actor, so a later session supersedes an earlier one. await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - SetupInstanceId("host-send-two-sessions-test"); var queueClient = new FakeCodexQueueClient(); SetupCodexQueueClient(queueClient); await SeedAliveSessionAsync( - "session-bob-1", "bob", role: "", host: "host-send-two-sessions-test", + "session-bob-1", "bob", role: "", endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-bob-1"); await SeedAliveSessionAsync( - "session-bob-2", "bob", role: "", host: "host-send-two-sessions-test", + "session-bob-2", "bob", role: "", endpointKind: AgentSessionEndpointKind.CodexThread, endpointAddr: "thread-bob-2"); // act @@ -164,23 +337,19 @@ await ExecuteCommandAsync( // assert var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'Status'"); - Assert.Equal( - new[] - { - ("thread-bob-1", id!, "All good."), - ("thread-bob-2", id!, "All good.") - }, - queueClient.Calls.Select(ReadDigestCall).OrderBy(call => call.ThreadId).ToArray()); + var call = Assert.Single(queueClient.Calls); + Assert.Equal(("thread-bob-2", id!, "All good."), ReadDigestCall(call)); } [Fact] - public async Task NameInBothToAndCc_CollapsesWithToWinning() + public async Task Send_Should_CollapseNameInBothToAndCc_WithToWinning_When_RecipientsOverlap() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "bob"); await ExecuteCommandAsync("agent", "register", "--actor", "carol"); - await SetupSuccessfulWakeAsync("host-send-dedupe-test", "bob", "carol"); + await SetupSuccessfulWakeAsync("bob", "carol"); SetupInteractionMode(InteractionMode.JsonOutput); // act @@ -201,143 +370,133 @@ public async Task NameInBothToAndCc_CollapsesWithToWinning() } [Fact] - public async Task UnknownRecipients_SendsAndWarnsInFirstOccurrenceOrder() + public async Task Send_Should_ReturnUnknownAgentError_When_ToRecipientUnknown() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); // act var result = await ExecuteCommandAsync( "agent", "mail", "send", "--to", "dave", "--to", "eve", "--subject", "hi", "--body", "yo"); // assert - var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'hi'"); - result.AssertSuccess( - $""" - โœ“ Sent '{id}' to dave, eve. - note: 'dave' has never registered. - note: 'eve' has never registered. + // The first offending name, in to-then-cc order, is reported. + result.AssertError( + """ + Unknown agent 'dave'. Look the name up with 'nitro agent list'. """); - Assert.Equal( - "1", - await QueryScalarAsync("SELECT implicit FROM agents WHERE name = 'dave'")); - Assert.Equal( - "1", - await QueryScalarAsync("SELECT implicit FROM agents WHERE name = 'eve'")); + Assert.Null(await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'hi'")); } [Fact] - public async Task MixOfKnownAndUnknownRecipients_WarnsOnlyOnUnknown() + public async Task Send_Should_ReturnUnknownAgentErrorAndWriteNothing_When_RecipientsMixKnownAndUnknown() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - await SetupSuccessfulWakeAsync("host-send-known-unknown-test", "bob"); + await SetupSuccessfulWakeAsync("bob"); // act var result = await ExecuteCommandAsync( "agent", "mail", "send", "--to", "bob", "--to", "dave", "--subject", "hi", "--body", "yo"); // assert - var id = await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'hi'"); - result.AssertSuccess( - $""" - โœ“ Sent '{id}' to bob, dave. - note: 'dave' has never registered. + result.AssertError( + """ + Unknown agent 'dave'. Look the name up with 'nitro agent list'. """); + Assert.Null(await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'hi'")); } [Fact] - public async Task InvalidRecipientName_StillHardFails() + public async Task Send_Should_ReturnDeletedAgentError_When_ToRecipientDeleted() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("dave"); + await MarkAgentDeletedAsync("dave"); // act var result = await ExecuteCommandAsync( - "agent", "mail", "send", "--to", "Dave!", "--subject", "hi", "--body", "yo"); + "agent", "mail", "send", "--to", "dave", "--subject", "hi", "--body", "yo"); // assert result.AssertError( """ - Invalid agent name 'Dave!'. Agent names may only contain lowercase letters, digits, hyphens, and underscores. + Agent 'dave' was deleted. Look the name up with 'nitro agent list'. """); } [Fact] - public async Task ImplicitRecipient_CanReadInbox_AndCanRegister() + public async Task InvalidRecipientName_StillHardFails() { // arrange await InitWorkspaceAsync(); - await ExecuteCommandAsync( - "agent", "mail", "send", "--to", "dave", "--subject", "hi", "--body", "yo"); - - // act - var beforeRegister = await ExecuteCommandAsync("agent", "mail", "inbox", "--actor", "dave"); - - // assert - Assert.Equal(0, beforeRegister.ExitCode); - Assert.Contains("hi", beforeRegister.StdOut); // act - var registerResult = await ExecuteCommandAsync("agent", "register", "--actor", "dave"); - var afterRegister = await ExecuteCommandAsync("agent", "mail", "inbox", "--actor", "dave"); + var result = await ExecuteCommandAsync( + "agent", "mail", "send", "--to", "Dave!", "--subject", "hi", "--body", "yo"); // assert - Assert.Equal(0, registerResult.ExitCode); - Assert.Equal(0, afterRegister.ExitCode); - Assert.Contains("hi", afterRegister.StdOut); + result.AssertError( + """ + Invalid agent name 'Dave!'. Agent names may only contain lowercase letters, digits, hyphens, and underscores. + """); } [Fact] - public async Task JsonOutput_ReturnsSendResult() + public async Task Send_Should_AllowRecipientToReadInbox_When_RecipientIsRegistered() { // arrange await InitWorkspaceAsync(); - await SeedAgentAsync("bob"); - await SetupSuccessfulWakeAsync("host-send-json-test", "bob"); - SetupInteractionMode(InteractionMode.JsonOutput); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("dave"); // act - var result = await ExecuteCommandAsync( - "agent", "mail", "send", "--to", "bob", "--subject", "Status", "--body", "All good."); + var sendResult = await ExecuteCommandAsync( + "agent", "mail", "send", "--to", "dave", "--subject", "hi", "--body", "yo"); + var inbox = await ExecuteCommandAsync("agent", "mail", "inbox", "--actor", "dave"); // assert - using var document = System.Text.Json.JsonDocument.Parse(result.StdOut); - var root = document.RootElement; - - Assert.Empty(result.StdErr); - Assert.Equal(0, result.ExitCode); - Assert.StartsWith("m-", root.GetProperty("id").GetString()); - Assert.Equal(root.GetProperty("id").GetString(), root.GetProperty("threadId").GetString()); - Assert.Equal(System.Text.Json.JsonValueKind.Null, root.GetProperty("inReplyTo").ValueKind); - Assert.Equal("test-agent", root.GetProperty("from").GetString()); - Assert.Equal(["bob"], root.GetProperty("to").EnumerateArray().Select(e => e.GetString()!).ToArray()); - Assert.Equal("Status", root.GetProperty("subject").GetString()); - Assert.True(root.TryGetProperty("createdAt", out _)); - Assert.Empty(root.GetProperty("unregistered").EnumerateArray()); - Assert.True(root.GetProperty("messageStored").GetBoolean()); + Assert.Equal(0, sendResult.ExitCode); + Assert.Equal(0, inbox.ExitCode); + Assert.Contains("hi", inbox.StdOut); } [Fact] - public async Task JsonOutput_ReturnsUnregisteredRecipients() + public async Task Send_Should_ReturnSendResult_When_JsonOutputIsRequested() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); + await SeedAgentAsync("bob"); + await SetupSuccessfulWakeAsync("bob"); SetupInteractionMode(InteractionMode.JsonOutput); // act var result = await ExecuteCommandAsync( - "agent", "mail", "send", "--to", "dave", "--subject", "Status", "--body", "All good."); + "agent", "mail", "send", "--to", "bob", "--subject", "Status", "--body", "All good."); // assert + Assert.Empty(result.StdErr); + Assert.Equal(0, result.ExitCode); + using var document = System.Text.Json.JsonDocument.Parse(result.StdOut); var root = document.RootElement; - Assert.Empty(result.StdErr); - Assert.Equal(0, result.ExitCode); - Assert.Equal( - ["dave"], root.GetProperty("unregistered").EnumerateArray().Select(e => e.GetString()!).ToArray()); + Snapshot.Create() + .Add(root.GetProperty("id").GetString(), "Id") + .Add(root.GetProperty("threadId").GetString(), "ThreadId") + .Add(root.GetProperty("inReplyTo").ValueKind, "InReplyTo") + .Add(root.GetProperty("from").GetString(), "From") + .Add(root.GetProperty("to").EnumerateArray().Select(e => e.GetString()!).ToArray(), "To") + .Add(root.GetProperty("subject").GetString(), "Subject") + .Add(root.GetProperty("createdAt").GetString(), "CreatedAt") + .Add(root.GetProperty("messageStored").GetBoolean(), "MessageStored") + .MatchMarkdownSnapshot(); } [Fact] @@ -394,12 +553,13 @@ public async Task EmptyBody_ReturnsError() } [Fact] - public async Task BodyFile_ReadsContentVerbatim_PreservingLineEndings() + public async Task Send_Should_ReadBodyFileContentVerbatim_PreservingLineEndings_When_BodyFileIsGiven() { // arrange await InitWorkspaceAsync(); + await SeedAgentAsync("test-agent"); await ExecuteCommandAsync("agent", "register", "--actor", "bob"); - await SetupSuccessfulWakeAsync("host-send-body-file-test", "bob"); + await SetupSuccessfulWakeAsync("bob"); var bodyFilePath = Path.Combine(WorkingDirectory, "body.txt"); await File.WriteAllTextAsync( bodyFilePath, "Line one\r\nLine two\r\n", TestContext.Current.CancellationToken); @@ -453,12 +613,12 @@ The file 'missing.txt' does not exist. } [Fact] - public async Task SendingToSelf_IsAllowed() + public async Task Send_Should_BeAllowed_When_RecipientIsSelf() { // arrange await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "register"); - await SetupSuccessfulWakeAsync("host-send-self-test", "test-agent"); + await SetupSuccessfulWakeAsync("test-agent"); // act var result = await ExecuteCommandAsync( diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/__snapshots__/ReplyMailCommandTests.Reply_Should_ThreadUnderOriginalMessage_AndInheritRootSubject_When_JsonOutputIsRequested.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/__snapshots__/ReplyMailCommandTests.Reply_Should_ThreadUnderOriginalMessage_AndInheritRootSubject_When_JsonOutputIsRequested.md new file mode 100644 index 00000000000..b05fb1c88f0 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/__snapshots__/ReplyMailCommandTests.Reply_Should_ThreadUnderOriginalMessage_AndInheritRootSubject_When_JsonOutputIsRequested.md @@ -0,0 +1,33 @@ +# Reply_Should_ThreadUnderOriginalMessage_AndInheritRootSubject_When_JsonOutputIsRequested + +## ThreadIdMatchesOriginal + +```json +true +``` + +## InReplyToMatchesOriginal + +```json +true +``` + +## Subject + +```text +Root subject +``` + +## To + +```json +[ + "alice" +] +``` + +## MessageStored + +```json +true +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/__snapshots__/SendMailCommandTests.Send_Should_ReturnSendResult_When_JsonOutputIsRequested.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/__snapshots__/SendMailCommandTests.Send_Should_ReturnSendResult_When_JsonOutputIsRequested.md new file mode 100644 index 00000000000..37e646d6e2e --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Mail/__snapshots__/SendMailCommandTests.Send_Should_ReturnSendResult_When_JsonOutputIsRequested.md @@ -0,0 +1,51 @@ +# Send_Should_ReturnSendResult_When_JsonOutputIsRequested + +## Id + +```text +m-bstpkf +``` + +## ThreadId + +```text +m-bstpkf +``` + +## InReplyTo + +```json +"Null" +``` + +## From + +```text +test-agent +``` + +## To + +```json +[ + "bob" +] +``` + +## Subject + +```text +Status +``` + +## CreatedAt + +```text +2026-01-01T00:00:00+00:00 +``` + +## MessageStored + +```json +true +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHookCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHookCommandTests.cs index 28ff17e3945..5dbad07cd1d 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHookCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHookCommandTests.cs @@ -16,12 +16,12 @@ public sealed class OpencodeHookCommandTests(NitroCommandFixture fixture) : Agen private const string ServerUrl = "http://127.0.0.1:4096"; [Fact] - public async Task SessionCreated_Should_RegisterThePresenceRow_And_WriteNeutralResponse() + public async Task SessionCreated_Should_BindTheAgentRowToTheSession_When_TheIdentityIsAlreadySeeded() { - // arrange: an identity already bound to this session id, so the - // registered row binds to the seeded name rather than an allocated one. + // arrange + // an agent already bound to this session id, so the started row binds to the seeded name await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupHookPayload(); // act @@ -29,17 +29,17 @@ public async Task SessionCreated_Should_RegisterThePresenceRow_And_WriteNeutralR // assert Assert.Equal(0, result.ExitCode); - Assert.Equal("maya", await QueryScalarAsync("SELECT agent_name FROM agent_sessions")); + Assert.Equal("maya", await QueryScalarAsync("SELECT name FROM agents WHERE session_id = 'session-1'")); result.StdOut.Trim().MatchInlineSnapshot("{}"); } [Fact] public async Task SessionCreated_Should_WriteNeutralResponse_When_ThePayloadNamesNoServerUrl() { - // arrange: a payload with no server URL, so nothing identifies the - // session's opencode server endpoint. + // arrange + // a payload with no server URL, so nothing identifies the session's opencode server endpoint await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupStandardInput( $$"""{"sessionId":"{{SessionId}}","cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}}}"""); @@ -48,17 +48,17 @@ public async Task SessionCreated_Should_WriteNeutralResponse_When_ThePayloadName // assert Assert.Equal(0, result.ExitCode); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Equal("none", await QueryScalarAsync("SELECT endpoint_kind FROM agents WHERE name = 'maya'")); result.StdOut.Trim().MatchInlineSnapshot("{}"); } [Fact] public async Task ChatMessage_Should_AppendTheActorAnnouncement_When_ItIsTheFirstMessage() { - // arrange: session-created armed the first-message announcement, so - // the first chat-message event claims it. + // arrange + // session-created armed the first-message announcement, so the first chat-message event claims it await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); SetupHookPayload(); @@ -76,10 +76,10 @@ public async Task ChatMessage_Should_AppendTheActorAnnouncement_When_ItIsTheFirs [Fact] public async Task ChatMessage_Should_AppendTheMailDigest_When_TheActorHasUnreadMail() { - // arrange: the announcement already claimed on session-created, and - // one unread message sent to the bound actor afterward. + // arrange + // the announcement already claimed on session-created, and one unread message sent afterward await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); await SeedAgentAsync("ada"); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); @@ -102,10 +102,10 @@ await ExecuteCommandAsync( [Fact] public async Task ChatMessage_Should_WriteNeutralResponse_When_NoMailIsUnread_And_AnnouncementAlreadyClaimed() { - // arrange: the announcement already claimed and no mail waiting, so - // this event has nothing left to say. + // arrange + // the announcement already claimed and no mail waiting, so this event has nothing left to say await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); SetupHookPayload(); @@ -123,10 +123,10 @@ public async Task ChatMessage_Should_WriteNeutralResponse_When_NoMailIsUnread_An [Fact] public async Task ChatMessage_Should_WriteNeutralResponse_When_ThePayloadIsMarkedNitroPushed() { - // arrange: a marked, Nitro-pushed turn never receives the - // announcement or digest this event exists to add. + // arrange + // a marked, Nitro-pushed turn never receives the announcement or digest this event exists to add await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); SetupStandardInput( @@ -145,9 +145,10 @@ public async Task ChatMessage_Should_WriteNeutralResponse_When_ThePayloadIsMarke [Fact] public async Task SessionIdle_Should_WriteNeutralResponse_When_NoMailIsUnread() { - // arrange: a presence row bound to the actor, with an empty inbox. + // arrange + // a presence row bound to the actor, with an empty inbox await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); SetupHookPayload(); @@ -161,41 +162,39 @@ public async Task SessionIdle_Should_WriteNeutralResponse_When_NoMailIsUnread() } [Fact] - public async Task SessionIdle_Should_NotReserveTheUnreadMail_And_WriteNeutralResponse() + public async Task SessionIdle_Should_WriteNeutralResponseWithoutReservingMail_When_TheActorHasUnreadMail() { // arrange // Start the session and send unread mail before invoking session-idle. await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); await SeedAgentAsync("ada"); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); await ExecuteCommandAsync( "agent", "mail", "send", "--body", "All good.", "--to", "maya", "--subject", "Status", "--actor", "ada"); SetupHookPayload(); - - // Capture the delivery count after the send and before session-idle. - var deliveriesBefore = await QueryScalarAsync("SELECT COUNT(*) FROM session_deliveries"); + var deliveriesBefore = await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries"); // act var result = await ExecuteCommandAsync("agent", "hook", "opencode", "session-idle"); // assert Assert.Equal(0, result.ExitCode); - Assert.Equal( - deliveriesBefore, await QueryScalarAsync("SELECT COUNT(*) FROM session_deliveries")); + Assert.Equal(deliveriesBefore, await QueryScalarAsync("SELECT COUNT(*) FROM agent_deliveries")); result.StdOut.Trim().MatchInlineSnapshot("{}"); } [Fact] - public async Task SessionDeleted_Should_RemoveThePresenceRow() + public async Task SessionDeleted_Should_StampEndedAtAndKeepTheRow_When_TheSessionIsActive() { - // arrange: a presence row this session started. + // arrange + // a presence row this session started await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupHookPayload(); await ExecuteCommandAsync("agent", "hook", "opencode", "session-created"); - Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.Null(await QueryScalarAsync("SELECT ended_at FROM agents WHERE name = 'maya'")); SetupHookPayload(); // act @@ -203,7 +202,8 @@ public async Task SessionDeleted_Should_RemoveThePresenceRow() // assert Assert.Equal(0, result.ExitCode); - Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agent_sessions")); + Assert.NotNull(await QueryScalarAsync("SELECT ended_at FROM agents WHERE name = 'maya'")); + Assert.Equal("1", await QueryScalarAsync("SELECT COUNT(*) FROM agents WHERE name = 'maya'")); result.StdOut.Trim().MatchInlineSnapshot("{}"); } @@ -213,10 +213,10 @@ public async Task SessionDeleted_Should_RemoveThePresenceRow() [InlineData("session-deleted")] public async Task Event_Should_WriteNeutralResponse_When_ThePayloadNamesNoSession(string eventName) { - // arrange: a payload with no session id, so nothing identifies which - // session the event speaks for. + // arrange + // a payload with no session id, so nothing identifies which session the event speaks for await InitWorkspaceAsync(); - await InsertOpencodeIdentityAsync("maya"); + await SeedOpencodeIdentityAsync(); SetupStandardInput( $$"""{"cwd":{{System.Text.Json.JsonSerializer.Serialize(WorkingDirectory)}},"serverUrl":"{{ServerUrl}}"}"""); @@ -229,9 +229,11 @@ public async Task Event_Should_WriteNeutralResponse_When_ThePayloadNamesNoSessio } [Fact] - public async Task HookHelp_ShouldBeInvisible() + public async Task HookHelp_Should_BeInvisible_When_HelpIsRequested() { - // arrange & act + // arrange + + // act var result = await ExecuteCommandAsync("agent", "hook", "--help"); // assert @@ -239,9 +241,11 @@ public async Task HookHelp_ShouldBeInvisible() } [Fact] - public async Task OpencodeHelp_ReturnsSuccess() + public async Task OpencodeHelp_Should_ListTheEventCommands_When_HelpIsRequested() { - // arrange & act + // arrange + + // act var result = await ExecuteCommandAsync("agent", "hook", "opencode", "--help"); // assert @@ -277,9 +281,11 @@ nitro agent hook opencode [command] [options] [InlineData( "session-deleted", "Adapt opencode's session.deleted event: remove this session's presence row.")] - public async Task EventHelp_ReturnsSuccess(string eventName, string description) + public async Task EventHelp_Should_PrintTheEventDescription_When_HelpIsRequested(string eventName, string description) { - // arrange & act + // arrange + + // act var result = await ExecuteCommandAsync("agent", "hook", "opencode", eventName, "--help"); // assert @@ -296,8 +302,8 @@ nitro agent hook opencode {eventName} [options] """); } - private Task InsertOpencodeIdentityAsync(string actor) - => InsertSessionIdentityAsync(actor, SessionId, AgentSessionHarness.Opencode); + private Task SeedOpencodeIdentityAsync() + => BindAgentSessionAsync("maya", SessionId, AgentSessionHarness.Opencode); /// /// Feeds one shim event payload to stdin. Every command run consumes diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHooksCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHooksCommandTests.cs index 2839cef0043..458b33c74b1 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHooksCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/OpencodeHooksCommandTests.cs @@ -1,17 +1,11 @@ using ChilliCream.Nitro.CommandLine.Commands.Agent.Hooks.Opencode; using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; namespace ChilliCream.Nitro.CommandLine.Tests.Agents; -public sealed class OpencodeHooksCommandTests : AgentCommandTestBase +public sealed class OpencodeHooksCommandTests(NitroCommandFixture fixture) : AgentCommandTestBase(fixture) { - private const string FixedHost = "host-opencode-hooks-tests"; - - public OpencodeHooksCommandTests(NitroCommandFixture fixture) : base(fixture) - { - SetupInstanceId(FixedHost); - } - [Fact] public async Task ExecuteCommandAsync_Should_ExplainFailOpenLocalOnlySetup_When_OpencodeHelpIsRequested() { @@ -109,11 +103,9 @@ public async Task ExecuteCommandAsync_Should_ReportSessionAsReachable_When_LastP SetupGlobalConfigDirectory(Path.Combine(WorkingDirectory, "..", "app-data")); await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "hooks", "opencode", "install", "--scope", "project"); - await InsertAliveSessionRowAsync( - FixedHost, - "session-reachable", + await InsertAgentRowAsync( "maya", - harness: AgentSessionHarness.Opencode, + "session-reachable", endpointKind: AgentSessionEndpointKind.OpencodeServer, endpointAddr: "http://127.0.0.1:51000", lastPingResult: AgentPingResult.Ok); @@ -136,11 +128,9 @@ public async Task ExecuteCommandAsync_Should_NotNameRemedy_When_BoundEndpointLas SetupGlobalConfigDirectory(Path.Combine(WorkingDirectory, "..", "app-data")); await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "hooks", "opencode", "install", "--scope", "project"); - await InsertAliveSessionRowAsync( - FixedHost, - "session-bound-ping-failed", + await InsertAgentRowAsync( "maya", - harness: AgentSessionHarness.Opencode, + "session-bound-ping-failed", endpointKind: AgentSessionEndpointKind.OpencodeServer, endpointAddr: "http://127.0.0.1:51000", lastPingResult: AgentPingResult.Error, @@ -163,12 +153,7 @@ public async Task ExecuteCommandAsync_Should_NameRemedy_When_EndpointIsUnreachab SetupGlobalConfigDirectory(Path.Combine(WorkingDirectory, "..", "app-data")); await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "hooks", "opencode", "install", "--scope", "project"); - await InsertAliveSessionRowAsync( - FixedHost, - "session-unreachable", - "maya", - harness: AgentSessionHarness.Opencode, - endpointKind: AgentSessionEndpointKind.None); + await InsertAgentRowAsync("maya", "session-unreachable"); // act var result = await ExecuteCommandAsync("agent", "hooks", "opencode", "status", "--scope", "project"); @@ -193,11 +178,9 @@ public async Task ExecuteCommandAsync_Should_NameEndpointGoneWithoutClaimingUnre SetupGlobalConfigDirectory(Path.Combine(WorkingDirectory, "..", "app-data")); await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "hooks", "opencode", "install", "--scope", "project"); - await InsertAliveSessionRowAsync( - FixedHost, - "session-endpoint-gone", + await InsertAgentRowAsync( "maya", - harness: AgentSessionHarness.Opencode, + "session-endpoint-gone", endpointKind: AgentSessionEndpointKind.OpencodeServer, endpointAddr: "http://127.0.0.1:51000", lastPingResult: AgentPingResult.EndpointGone); @@ -251,11 +234,9 @@ public async Task ExecuteCommandAsync_Should_IncludeSessionFields_When_StatusJso SetupGlobalConfigDirectory(Path.Combine(WorkingDirectory, "..", "app-data")); await InitWorkspaceAsync(); await ExecuteCommandAsync("agent", "hooks", "opencode", "install", "--scope", "project"); - await InsertAliveSessionRowAsync( - FixedHost, - "session-json", + await InsertAgentRowAsync( "maya", - harness: AgentSessionHarness.Opencode, + "session-json", endpointKind: AgentSessionEndpointKind.OpencodeServer, endpointAddr: "http://127.0.0.1:51000", lastPingResult: AgentPingResult.Ok, @@ -273,4 +254,69 @@ await InsertAliveSessionRowAsync( Assert.Equal(AgentPingResult.Ok, session.GetProperty("lastPingResult").GetString()); Assert.Equal("healthy", session.GetProperty("lastPingDetail").GetString()); } + + [Fact] + public async Task ExecuteCommandAsync_Should_OmitTheSession_When_TheSessionHasEnded() + { + // arrange + SetupGlobalConfigDirectory(Path.Combine(WorkingDirectory, "..", "app-data")); + await InitWorkspaceAsync(); + await ExecuteCommandAsync("agent", "hooks", "opencode", "install", "--scope", "project"); + await InsertAgentRowAsync( + "maya", + "session-ended", + endpointKind: AgentSessionEndpointKind.OpencodeServer, + endpointAddr: "http://127.0.0.1:51000", + lastPingResult: AgentPingResult.Ok, + endedAt: FakeTime.GetUtcNow()); + SetupInteractionMode(InteractionMode.JsonOutput); + + // act + var result = await ExecuteCommandAsync("agent", "hooks", "opencode", "status", "--scope", "project"); + + // assert + using var document = System.Text.Json.JsonDocument.Parse(result.StdOut); + document.RootElement.GetProperty("sessions").GetRawText().MatchInlineSnapshot("[]"); + } + + /// + /// Inserts one opencode agent row directly into the unified agents table with + /// fresh timestamps and the supplied endpoint and ping state. + /// + private async Task InsertAgentRowAsync( + string name, + string sessionId, + string endpointKind = AgentSessionEndpointKind.None, + string endpointAddr = "", + string? lastPingResult = null, + string? lastPingDetail = null, + DateTimeOffset? endedAt = null) + { + var now = FakeTime.GetUtcNow(); + + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents ( + name, harness, session_id, endpoint_kind, endpoint_addr, + last_ping_result, last_ping_detail, registered_at, started_at, last_seen_at, ended_at + ) VALUES ( + $name, $harness, $sessionId, $endpointKind, $endpointAddr, + $lastPingResult, $lastPingDetail, $now, $now, $now, $endedAt + ); + """; + command.Parameters.AddWithValue("$name", name); + command.Parameters.AddWithValue("$harness", AgentSessionHarness.Opencode); + command.Parameters.AddWithValue("$sessionId", sessionId); + command.Parameters.AddWithValue("$endpointKind", endpointKind); + command.Parameters.AddWithValue("$endpointAddr", endpointAddr); + command.Parameters.AddWithValue("$lastPingResult", (object?)lastPingResult ?? DBNull.Value); + command.Parameters.AddWithValue("$lastPingDetail", (object?)lastPingDetail ?? DBNull.Value); + command.Parameters.AddWithValue("$now", now); + command.Parameters.AddWithValue("$endedAt", (object?)endedAt ?? DBNull.Value); + + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/RegisterAgentCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/RegisterAgentCommandTests.cs index 9130ca17e5b..3d2a063f019 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/RegisterAgentCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/RegisterAgentCommandTests.cs @@ -62,6 +62,39 @@ public async Task Register_Should_ReportTheActorAlone_When_NoRoleIsGiven() Assert.Equal("", await QueryScalarAsync("SELECT role FROM agents WHERE name = 'maya'")); } + [Fact] + public async Task Register_Should_KeepTheRole_When_NoRoleIsGiven() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("maya", "planner"); + + // act + var result = await ExecuteCommandAsync("agent", "register", "--actor", "maya"); + + // assert + // Omitting --role touches the beat only, the stored role survives. + result.AssertSuccess("โœ“ Actor 'maya', role 'planner'."); + Assert.Equal("planner", await QueryScalarAsync("SELECT role FROM agents WHERE name = 'maya'")); + } + + [Fact] + public async Task Register_Should_BumpLastSeenAt_When_NoRoleIsGiven() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("maya"); + var before = await QueryScalarAsync("SELECT last_seen_at FROM agents WHERE name = 'maya'"); + FakeTime.Advance(TimeSpan.FromMinutes(5)); + + // act + await ExecuteCommandAsync("agent", "register", "--actor", "maya"); + + // assert + var after = await QueryScalarAsync("SELECT last_seen_at FROM agents WHERE name = 'maya'"); + Assert.NotEqual(before, after); + } + [Fact] public async Task Register_Should_ClearTheRole_When_TheRoleIsExplicitlyEmpty() { @@ -94,6 +127,21 @@ public async Task Register_Should_Fail_When_TheActorWasNeverAllocated() Assert.Equal("0", await QueryScalarAsync("SELECT COUNT(*) FROM agents")); } + [Fact] + public async Task Register_Should_Fail_When_TheActorWasDeleted() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("maya"); + await MarkAgentDeletedAsync("maya"); + + // act + var result = await ExecuteCommandAsync("agent", "register", "--actor", "maya"); + + // assert + result.AssertError("Agent 'maya' was deleted."); + } + [Fact] public async Task Register_Should_Fail_When_ActorIsOmitted() { diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/TakeoverAgentCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/TakeoverAgentCommandTests.cs index 3ebe0f0a09c..ee88dd8a67b 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/TakeoverAgentCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/TakeoverAgentCommandTests.cs @@ -1,3 +1,6 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; + namespace ChilliCream.Nitro.CommandLine.Tests.Agents; public sealed class TakeoverAgentCommandTests(NitroCommandFixture fixture) @@ -53,7 +56,7 @@ public async Task Takeover_Should_MoveMailAndTasks_InheritRole_AndWriteHumanOutp // assert result.AssertSuccess( - $"โœ“ 'nora' took over from 'maya': role 'planner', 2 messages, 1 tasks ({taskId})."); + $"โœ“ 'nora' took over from 'maya': role 'planner', 1 messages, 1 tasks ({taskId})."); var state = string.Join( "|", await QueryScalarAsync("SELECT role FROM agents WHERE name = 'nora'"), @@ -85,7 +88,6 @@ public async Task Takeover_Should_ReturnExactJsonShape() "to": "nora", "role": "planner", "recipientsMoved": 0, - "sendersMoved": 0, "tasks": [] } """); @@ -93,14 +95,13 @@ public async Task Takeover_Should_ReturnExactJsonShape() } [Fact] - public async Task Takeover_Should_RefuseLiveSourceSession_UnlessForced() + public async Task Takeover_Should_RefuseOnlineSource_When_ForceIsOmitted() { // arrange - SetupInstanceId("local-instance"); await InitWorkspaceAsync(); await SeedAgentAsync("maya"); await SeedAgentAsync("nora"); - await InsertAliveSessionRowAsync("local-instance", "session-1", "maya"); + await MarkAgentOnlineAsync("maya"); // act var refused = await ExecuteCommandAsync( @@ -109,12 +110,132 @@ public async Task Takeover_Should_RefuseLiveSourceSession_UnlessForced() "agent", "takeover", "--from", "maya", "--actor", "nora", "--force"); // assert - refused.AssertError( - "Actor 'maya' still has a live session; pass --force to take over anyway."); + refused.AssertError("Actor 'maya' is Online; pass --force to take over anyway."); forced.AssertSuccess("โœ“ 'nora' took over from 'maya': role '', 0 messages, no tasks."); Assert.Equal("1", await QueryScalarAsync("SELECT forced FROM agent_takeovers")); } + [Fact] + public async Task Takeover_Should_AcceptEndedSource_When_ForceIsOmitted() + { + // arrange + // An ended session is Offline, so no --force is needed. + await InitWorkspaceAsync(); + await SeedAgentAsync("maya"); + await SeedAgentAsync("nora"); + await MarkAgentOnlineAsync("maya"); + await MarkAgentEndedAsync("maya"); + + // act + var result = await ExecuteCommandAsync( + "agent", "takeover", "--from", "maya", "--actor", "nora"); + + // assert + result.AssertSuccess("โœ“ 'nora' took over from 'maya': role '', 0 messages, no tasks."); + } + + [Fact] + public async Task Takeover_Should_AcceptDeletedSource_When_ForceIsOmitted() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("maya"); + await SeedAgentAsync("nora"); + await MarkAgentDeletedAsync("maya"); + + // act + var result = await ExecuteCommandAsync( + "agent", "takeover", "--from", "maya", "--actor", "nora"); + + // assert + result.AssertSuccess("โœ“ 'nora' took over from 'maya': role '', 0 messages, no tasks."); + } + + [Fact] + public async Task Takeover_Should_Refuse_When_TargetWasDeleted() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("maya"); + await SeedAgentAsync("nora"); + await MarkAgentDeletedAsync("nora"); + + // act + var result = await ExecuteCommandAsync( + "agent", "takeover", "--from", "maya", "--actor", "nora"); + + // assert + result.AssertError("Agent 'nora' was deleted."); + } + + [Fact] + public async Task Takeover_Should_MoveUnreadMailOnly_When_SourceHasReadAndUnreadMail() + { + // arrange + await InitWorkspaceAsync(); + await SeedAgentAsync("maya", "planner"); + await SeedAgentAsync("nora"); + await SeedAgentAsync("sender"); + await SendMailAsync("sender", "maya", "unread"); + await SendMailAsync("sender", "maya", "read"); + var readId = (await QueryScalarAsync("SELECT id FROM messages WHERE subject = 'read'"))!; + var readResult = await ExecuteCommandAsync( + "agent", "mail", "read", "--message", readId, "--actor", "maya"); + Assert.Equal(0, readResult.ExitCode); + var taskId = await CreateTaskAsync("maya"); + + // act + var result = await ExecuteCommandAsync( + "agent", "takeover", "--from", "maya", "--actor", "nora"); + + // assert + result.AssertSuccess( + $"โœ“ 'nora' took over from 'maya': role 'planner', 1 messages, 1 tasks ({taskId})."); + var state = string.Join( + "|", + await QueryScalarAsync($"SELECT recipient FROM message_recipients WHERE message_id = '{readId}'"), + await QueryScalarAsync( + "SELECT recipient FROM message_recipients WHERE message_id = " + + "(SELECT id FROM messages WHERE subject = 'unread')"), + await QueryScalarAsync($"SELECT assignee FROM tasks WHERE id = '{taskId}'")); + state.MatchInlineSnapshot("maya|nora|nora"); + } + + /// + /// Gives the named agent a live-looking harness session and a fresh beat, so it + /// resolves as . + /// + private async Task MarkAgentOnlineAsync(string name) + { + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + "UPDATE agents SET harness = $harness, session_id = $sessionId, " + + "endpoint_kind = $endpointKind, last_seen_at = $now WHERE name = $name"; + command.Parameters.AddWithValue("$harness", AgentSessionHarness.ClaudeCode); + command.Parameters.AddWithValue("$sessionId", $"session-{name}"); + command.Parameters.AddWithValue("$endpointKind", AgentSessionEndpointKind.ClaudePeer); + command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); + command.Parameters.AddWithValue("$name", name); + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } + + /// + /// Stamps the named agent's session as ended, so it resolves as + /// regardless of its endpoint. + /// + private async Task MarkAgentEndedAsync(string name) + { + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET ended_at = $now WHERE name = $name"; + command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); + command.Parameters.AddWithValue("$name", name); + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } + [Theory] [InlineData("maya", "maya", "The source and target actors must be different.")] [InlineData("unknown", "nora", "Unknown actor 'unknown'. Run `nitro agent list` to see the actors this workspace knows.")] @@ -194,7 +315,7 @@ await QueryScalarAsync( "SELECT from_actor || ':' || to_actor || ':' || actor || ':' || role || ':' || reason " + "FROM agent_takeovers WHERE reason IS NOT NULL")); ledger.MatchInlineSnapshot( - "2|3|message_recipient:1,message_sender:1,task:1|0|maya:nora:nora:planner:handoff"); + "2|2|message_recipient:1,task:1|0|maya:nora:nora:planner:handoff"); } [Fact] diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/InitAgentCommandTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/InitAgentCommandTests.cs index 0a0eb2119c2..c4211d79a93 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/InitAgentCommandTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/InitAgentCommandTests.cs @@ -203,20 +203,14 @@ No agent workspace found. Run `nitro agent init` first. } [Fact] - public async Task Migrate_RewritesSessionWorkspacePaths() + public async Task Migrate_Should_RewriteAgentsWorkspacePath_When_WorkspaceMoves() { // arrange - // Seed a session with the workspace path that will be migrated. + // Seed an agent with the workspace path that will be migrated. await InitWorkspaceAsync(); + await SeedAgentAsync("maya"); await QueryScalarAsync( - $""" - INSERT INTO agent_sessions ( - harness, session_id, host, cwd, workspace_path, - endpoint_kind, endpoint_addr, started_at, last_beat_at) - VALUES ( - 'claude-code', 's1', 'host', '{WorkingDirectory}', '{WorkspaceDirectory}', - 'none', '', '2026-01-01T00:00:00+00:00', '2026-01-01T00:00:00+00:00'); - """); + $"UPDATE agents SET workspace_path = '{WorkspaceDirectory}' WHERE name = 'maya';"); Directory.CreateDirectory(Path.Combine(WorkingDirectory, ".git")); // act @@ -225,7 +219,7 @@ INSERT INTO agent_sessions ( // assert Assert.Equal(0, result.ExitCode); Assert.Equal("1", await QueryScalarAsync( - $"SELECT COUNT(*) FROM agent_sessions WHERE workspace_path = '{GitWorkspaceDirectory}'", + $"SELECT COUNT(*) FROM agents WHERE name = 'maya' AND workspace_path = '{GitWorkspaceDirectory}'", GitDatabasePath)); } @@ -702,7 +696,7 @@ Already initialized at '.nitro/agents'. Use --force to reinitialize. /// prefix and gitignore content. /// [Fact] - public async Task PlainInit_UpgradesSchemaOnly_When_ExistingVersionIsUpgradable() + public async Task Init_Should_UpgradeSchemaOnly_When_ExistingVersionIsUpgradable() { // arrange await SeedV3WorkspaceAsync("legacy3"); @@ -720,7 +714,7 @@ public async Task PlainInit_UpgradesSchemaOnly_When_ExistingVersionIsUpgradable( Assert.Equal( AgentDatabase.CurrentVersion.ToString(), await QueryScalarAsync("PRAGMA user_version;")); Assert.Equal("1", await QueryScalarAsync( - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_sessions'")); + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agents'")); Assert.Equal("legacy3", await QueryScalarAsync("SELECT value FROM config WHERE key = 'prefix'")); Assert.Equal( "sentinel\n", @@ -794,14 +788,14 @@ public async Task AlreadyInitialized_Force_PreservesSeededTaskAndMailRows() } [Fact] - public async Task TasksAndMail_ShareTheSameUnifiedWorkspace() + public async Task Init_Should_ShareTasksAndMailInTheSameUnifiedWorkspace_When_BothAreUsed() { // arrange await InitWorkspaceAsync(); var taskId = await CreateTaskAsync("Ship the unified workspace"); - SetupInstanceId("host-unified-workspace-test"); // act + await SeedAgentAsync("test-agent"); await SeedAgentAsync("bob"); var sendResult = await ExecuteCommandAsync( "agent", "mail", "send", "--to", "bob", "--subject", "Status", "--body", "Merged."); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TaskStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TaskStoreTests.cs index 144868abafd..d0c11b88253 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TaskStoreTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TaskStoreTests.cs @@ -726,6 +726,82 @@ public async Task DeleteTaskAsync_TombstonesAndRecordsEvent() Assert.Equal([TaskEventTypes.Deleted], await QueryEventTypesAsync(connection, "acme-1")); } + [Fact] + public async Task ReleaseAssigneeAsync_Should_ReleaseInProgressTasksAndAppearInReady() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync( + connection, "acme-1", status: TaskStates.InProgress, priority: 2, assignee: "felix"); + await InsertTaskAsync( + connection, "acme-2", status: TaskStates.InProgress, priority: 2, assignee: "felix"); + await InsertTaskAsync( + connection, "acme-3", status: TaskStates.InProgress, priority: 2, assignee: "oscar"); + + // act + var count = await _store.ReleaseAssigneeAsync("felix", "agent deleted", cancellationToken); + var ready = await _store.QueryTasksAsync( + new TaskFilter { Statuses = [TaskStates.Open], ExcludeBlocked = true }, cancellationToken); + var untouched = await _store.GetRequiredTaskAsync("acme-3", cancellationToken); + + // assert + Snapshot.Create() + .Add(count, "Released Count") + .Add( + ready + .OrderBy(task => task.Id, StringComparer.Ordinal) + .Select(task => new { task.Id, task.Status, task.Assignee }), + "Released Tasks") + .Add( + new { untouched.Id, untouched.Status, untouched.Assignee }, + "Untouched Task") + .MatchMarkdownSnapshot(); + } + + [Fact] + public async Task ReleaseAssigneeAsync_Should_LeaveOpenTaskAssignedToAgentAlone() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync( + connection, "acme-1", status: TaskStates.Open, priority: 2, assignee: "felix"); + + // act + var count = await _store.ReleaseAssigneeAsync("felix", "agent deleted", cancellationToken); + var task = await _store.GetRequiredTaskAsync("acme-1", cancellationToken); + + // assert + Assert.Equal(0, count); + Assert.Equal(TaskStates.Open, task.Status); + Assert.Equal("felix", task.Assignee); + } + + [Fact] + public async Task ReleaseAssigneeAsync_Should_RecordEventsWithReasonAndEmptyActor() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync( + connection, "acme-1", status: TaskStates.InProgress, priority: 2, assignee: "felix"); + + // act + await _store.ReleaseAssigneeAsync("felix", "agent deleted", cancellationToken); + + // assert + Assert.Equal( + [TaskEventTypes.AssigneeChanged, TaskEventTypes.StatusChanged], + await QueryEventTypesAsync(connection, "acme-1")); + Assert.Equal( + [ + "assignee_changed||felix||agent deleted", + "status_changed||in_progress|open|agent deleted" + ], + await QueryEventDetailsAsync(connection, "acme-1", cancellationToken)); + } + [Fact] public async Task CloseEligibleEpicsAsync_ClosesOnlyEpicsWithAllChildrenClosed() { @@ -1176,6 +1252,122 @@ public async Task RemoveDependencyAsync_RemovesAndRecordsEvent() [TaskEventTypes.DependencyRemoved], await QueryEventTypesAsync(connection, "acme-1")); } + [Fact] + public async Task QueryParticipationAsync_Should_IncludeTask_When_AgentOnlyCommented() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync(connection, "acme-1", status: TaskStates.Open, priority: 2); + await _store.AddCommentAsync("acme-1", "Taking a look.", "felix", cancellationToken); + + // act + var tasks = await _store.QueryParticipationAsync("felix", null, cancellationToken); + + // assert + var task = Assert.Single(tasks); + Assert.Equal("acme-1", task.Id); + } + + [Fact] + public async Task QueryParticipationAsync_Should_ExcludeTask_When_AgentHasNoParticipation() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync(connection, "acme-1", status: TaskStates.Open, priority: 2); + await _store.AddCommentAsync("acme-1", "Taking a look.", "someone-else", cancellationToken); + + // act + var tasks = await _store.QueryParticipationAsync("felix", null, cancellationToken); + + // assert + Assert.Empty(tasks); + } + + [Fact] + public async Task QueryParticipationAsync_Should_IncludeTask_When_TaskIsClosed() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync(connection, "acme-1", status: TaskStates.Open, priority: 2); + await _store.CloseTaskAsync(["acme-1"], "Done.", "felix", cancellationToken); + + // act + var tasks = await _store.QueryParticipationAsync("felix", null, cancellationToken); + + // assert + var task = Assert.Single(tasks); + Assert.Equal(TaskStates.Closed, task.Status); + } + + [Fact] + public async Task QueryParticipationAsync_Should_ExcludeTask_When_TaskIsTombstone() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync(connection, "acme-1", status: TaskStates.Open, priority: 2); + await _store.AddCommentAsync("acme-1", "Taking a look.", "felix", cancellationToken); + await _store.DeleteTaskAsync("acme-1", "No longer needed.", "felix", cancellationToken); + + // act + var tasks = await _store.QueryParticipationAsync("felix", null, cancellationToken); + + // assert + Assert.Empty(tasks); + } + + [Fact] + public async Task QueryParticipationAsync_Should_RankByUpdatedAt_When_TaskIsAssignedOnly() + { + // arrange: acme-1 is assigned to felix by oscar, without felix ever acting on it. + // acme-2 carries an older comment by felix, so it must rank behind acme-1's + // more recent assignment (its updated_at). + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync(connection, "acme-2", status: TaskStates.Open, priority: 2); + await _store.AddCommentAsync("acme-2", "Early look.", "felix", cancellationToken); + + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + await InsertTaskAsync(connection, "acme-1", status: TaskStates.Open, priority: 2); + await _store.UpdateTaskAsync( + "acme-1", + new TaskUpdate { Actor = "oscar", Assignee = "felix", AssigneeGiven = true }, + cancellationToken); + + // act + var tasks = await _store.QueryParticipationAsync("felix", null, cancellationToken); + + // assert + Assert.Equal(["acme-1", "acme-2"], tasks.Select(t => t.Id)); + } + + [Fact] + public async Task QueryParticipationAsync_Should_RankByAgentsOwnLatestEvent_When_OthersActOnTaskLater() + { + // arrange: felix comments on acme-1 first; oscar comments on it again later, which + // bumps acme-1's updated_at past acme-2's assignment without felix acting again. + // Ranking must follow felix's own latest event on acme-1, not the task's updated_at. + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await SeedAsync(cancellationToken); + await InsertTaskAsync(connection, "acme-1", status: TaskStates.Open, priority: 2); + await _store.AddCommentAsync("acme-1", "Felix's take.", "felix", cancellationToken); + + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + await InsertTaskAsync(connection, "acme-2", status: TaskStates.Open, priority: 2, assignee: "felix"); + + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + await _store.AddCommentAsync("acme-1", "Oscar's take.", "oscar", cancellationToken); + + // act + var tasks = await _store.QueryParticipationAsync("felix", null, cancellationToken); + + // assert + Assert.Equal(["acme-2", "acme-1"], tasks.Select(t => t.Id)); + } + [Fact] public async Task SetConfigAsync_UpsertsValue() { @@ -1273,6 +1465,36 @@ private static async Task> QueryEventActorsAsync( return events; } + /// + /// Returns a task's events, in event-id order, formatted as + /// "type|actor|old_value|new_value|comment" with null values as empty strings. + /// + private static async Task> QueryEventDetailsAsync( + SqliteConnection connection, + string taskId, + CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.CommandText = + "SELECT event_type, actor, old_value, new_value, comment FROM events " + + "WHERE task_id = @taskId ORDER BY id"; + command.Parameters.AddWithValue("@taskId", taskId); + + var events = new List(); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + events.Add( + $"{reader.GetString(0)}|{reader.GetString(1)}|" + + $"{(reader.IsDBNull(2) ? "" : reader.GetString(2))}|" + + $"{(reader.IsDBNull(3) ? "" : reader.GetString(3))}|" + + $"{(reader.IsDBNull(4) ? "" : reader.GetString(4))}"); + } + + return events; + } + private async Task SeedAsync(CancellationToken cancellationToken) { var workspaceDirectory = AgentWorkspace.GetDirectory(_workingDirectory); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TasksCommandTestBase.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TasksCommandTestBase.cs index c525c8613f2..c85b9b0e6b8 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TasksCommandTestBase.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/TasksCommandTestBase.cs @@ -31,8 +31,23 @@ protected string DatabasePath => AgentWorkspace.GetDatabasePath(WorkspaceDirectory); protected async Task SeedAgentAsync(string actor, string role = "") - => await new AgentRegistry(new TestFileSystem(WorkingDirectory), FakeTime, new AgentDatabase()) - .RegisterAsync(actor, role, client: "", TestContext.Current.CancellationToken); + { + await using var connection = new SqliteConnection($"Data Source={DatabasePath};Pooling=False"); + await connection.OpenAsync(TestContext.Current.CancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, role, registered_at, started_at, last_seen_at) + VALUES ($name, $role, $now, $now, $now) + ON CONFLICT (name) DO UPDATE SET role = excluded.role, last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("$name", actor); + command.Parameters.AddWithValue("$role", role); + command.Parameters.AddWithValue("$now", FakeTime.GetUtcNow()); + + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } protected async Task InitWorkspaceAsync() { diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/__snapshots__/TaskStoreTests.ReleaseAssigneeAsync_Should_ReleaseInProgressTasksAndAppearInReady.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/__snapshots__/TaskStoreTests.ReleaseAssigneeAsync_Should_ReleaseInProgressTasksAndAppearInReady.md new file mode 100644 index 00000000000..35aab53eb02 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/Agent/Tasks/__snapshots__/TaskStoreTests.ReleaseAssigneeAsync_Should_ReleaseInProgressTasksAndAppearInReady.md @@ -0,0 +1,34 @@ +# ReleaseAssigneeAsync_Should_ReleaseInProgressTasksAndAppearInReady + +## Released Count + +```json +2 +``` + +## Released Tasks + +```json +[ + { + "Id": "acme-1", + "Status": "open", + "Assignee": null + }, + { + "Id": "acme-2", + "Status": "open", + "Assignee": null + } +] +``` + +## Untouched Task + +```json +{ + "Id": "acme-3", + "Status": "in_progress", + "Assignee": "oscar" +} +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/CommandTestBase.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/CommandTestBase.cs index 1e91b50743c..fcd359ef909 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/CommandTestBase.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Commands/CommandTestBase.cs @@ -38,7 +38,6 @@ public abstract class CommandTestBase private readonly List _files = []; private readonly Mock _fileSystemMock = new(); private IFileSystem? _fileSystemOverride; - private INitroInstanceIdProvider? _instanceIdProviderOverride; private IStandardInputReader? _standardInputOverride; private IGlobalConfigDirectoryProvider? _globalConfigDirectoryProviderOverride; private Services.Hook.IClaudeSettingsPathResolver? _claudeSettingsPathResolverOverride; @@ -90,14 +89,6 @@ private protected void SetupFileSystem(IFileSystem fileSystem) _fileSystemOverride = fileSystem; } - /// - /// Configures Nitro instance id resolution to return . - /// - private protected void SetupInstanceId(string id) - { - _instanceIdProviderOverride = new FixedInstanceIdProvider(id); - } - /// /// Configures global configuration lookup to use . /// @@ -377,11 +368,6 @@ private ServiceProvider BuildServices(INitroConsole console) services.Replace(ServiceDescriptor.Singleton(_fileSystemOverride ?? _fileSystemMock.Object)); - if (_instanceIdProviderOverride is not null) - { - services.Replace(ServiceDescriptor.Singleton(_instanceIdProviderOverride)); - } - if (_globalConfigDirectoryProviderOverride is not null) { services.Replace(ServiceDescriptor.Singleton(_globalConfigDirectoryProviderOverride)); @@ -634,12 +620,6 @@ public sealed record CommandResult( string StdOut, string StdErr, string ExecutableName); -internal sealed class FixedInstanceIdProvider(string id) : INitroInstanceIdProvider -{ - public Task GetIdAsync(string globalConfigDirectory, CancellationToken cancellationToken) - => Task.FromResult(id); -} - internal sealed class FixedGlobalConfigDirectoryProvider(string directory) : IGlobalConfigDirectoryProvider { public string GetDirectory() => directory; diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/DapperCommandDefinitionUsageTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/DapperCommandDefinitionUsageTests.cs new file mode 100644 index 00000000000..b8640b59412 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/DapperCommandDefinitionUsageTests.cs @@ -0,0 +1,44 @@ +using System.Runtime.CompilerServices; + +namespace ChilliCream.Nitro.CommandLine.Tests; + +public sealed class DapperCommandDefinitionUsageTests +{ + [Fact] + public void SourceFiles_Should_NotContainCommandDefinitionOrDynamicParameters_When_UnderServicesOrCommands() + { + // arrange + // Dapper.AOT does not intercept CommandDefinition or DynamicParameters calls. + var sourceRoot = GetCommandLineSourceRoot(); + var scannedDirectories = new[] { "Services", "Commands" }; + var bannedTokens = new[] { "new CommandDefinition(", "DynamicParameters" }; + + // act + var offenders = new List(); + + foreach (var directory in scannedDirectories) + { + var root = Path.Combine(sourceRoot, directory); + + foreach (var file in Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories)) + { + var content = File.ReadAllText(file); + + if (bannedTokens.Any(token => content.Contains(token, StringComparison.Ordinal))) + { + offenders.Add(Path.GetRelativePath(sourceRoot, file)); + } + } + } + + // assert + Assert.Equal([], offenders); + } + + private static string GetCommandLineSourceRoot([CallerFilePath] string sourceFile = "") + { + var directory = Path.GetDirectoryName(sourceFile)!; + + return Path.GetFullPath(Path.Combine(directory, "..", "..", "src", "CommandLine")); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/AgentEffectiveRoleTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/AgentEffectiveRoleTests.cs deleted file mode 100644 index 931cd54634e..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/AgentEffectiveRoleTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Hook; -using ChilliCream.Nitro.CommandLine.Services.Workspace; -using Moq; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -public sealed class AgentEffectiveRoleTests -{ - [Fact] - public async Task ResolveAsync_Should_ReturnSessionRole_When_SessionRoleIsNonEmpty() - { - // arrange - var agentRegistry = new Mock(MockBehavior.Strict); - - // act - var role = await AgentEffectiveRole.ResolveAsync( - "planner", "maya", agentRegistry.Object, TestContext.Current.CancellationToken); - - // assert - Assert.Equal("planner", role); - } - - [Fact] - public async Task ResolveAsync_Should_PropagateCancellation_When_LookupIsCanceled() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var agentRegistry = new Mock(MockBehavior.Strict); - agentRegistry - .Setup(registry => registry.GetAsync("maya", cancellationToken)) - .ThrowsAsync(new TaskCanceledException()); - - // act - var exception = await Record.ExceptionAsync( - () => AgentEffectiveRole.ResolveAsync( - string.Empty, "maya", agentRegistry.Object, cancellationToken)); - - // assert - Assert.IsAssignableFrom(exception); - } - - [Fact] - public async Task ResolveAsync_Should_PropagateSchemaMismatch_When_LookupFindsIncompatibleSchema() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var agentRegistry = new Mock(MockBehavior.Strict); - agentRegistry - .Setup(registry => registry.GetAsync("maya", cancellationToken)) - .ThrowsAsync(new AgentWorkspaceSchemaMismatchException("schema mismatch")); - - // act - var exception = await Record.ExceptionAsync( - () => AgentEffectiveRole.ResolveAsync( - string.Empty, "maya", agentRegistry.Object, cancellationToken)); - - // assert - Assert.IsType(exception); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CancellingAnnouncementAgentStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CancellingAnnouncementAgentStore.cs new file mode 100644 index 00000000000..77c60ed8ee8 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CancellingAnnouncementAgentStore.cs @@ -0,0 +1,91 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Hook; + +/// +/// Delegates to except for +/// , which cancels +/// and throws . +/// +internal sealed class CancellingAnnouncementAgentStore( + IAgentStore inner, CancellationTokenSource cancellationTokenSource) : IAgentStore +{ + public Task LoginAsync(CancellationToken cancellationToken) + => inner.LoginAsync(cancellationToken); + + public Task StartSessionAsync( + AgentSessionStartRequest request, CancellationToken cancellationToken) + => inner.StartSessionAsync(request, cancellationToken); + + public Task TouchSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.TouchSessionAsync(harness, sessionId, cancellationToken); + + public Task TouchAsync(string name, CancellationToken cancellationToken) + => inner.TouchAsync(name, cancellationToken); + + public Task EndSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.EndSessionAsync(harness, sessionId, cancellationToken); + + public Task SetRoleAsync(string name, string role, CancellationToken cancellationToken) + => inner.SetRoleAsync(name, role, cancellationToken); + + public Task FindAsync(string name, CancellationToken cancellationToken) + => inner.FindAsync(name, cancellationToken); + + public Task FindBySessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.FindBySessionAsync(harness, sessionId, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken) + => inner.ListAsync(cancellationToken); + + public Task SetEndpointAsync( + string name, + string endpointKind, + string endpointAddr, + string? endpointSecret, + CancellationToken cancellationToken) + => inner.SetEndpointAsync(name, endpointKind, endpointAddr, endpointSecret, cancellationToken); + + public Task ResetBlockBudgetAsync(string name, CancellationToken cancellationToken) + => inner.ResetBlockBudgetAsync(name, cancellationToken); + + public Task IncrementBlockBudgetAsync(string name, CancellationToken cancellationToken) + => inner.IncrementBlockBudgetAsync(name, cancellationToken); + + public Task TryClaimPingCooldownAsync( + string name, TimeSpan cooldown, string attemptId, CancellationToken cancellationToken) + => inner.TryClaimPingCooldownAsync(name, cooldown, attemptId, cancellationToken); + + public Task WritePingResultAsync( + string name, string attemptId, string result, string? detail, CancellationToken cancellationToken) + => inner.WritePingResultAsync(name, attemptId, result, detail, cancellationToken); + + public Task ArmAnnouncementAsync(string name, CancellationToken cancellationToken) + => inner.ArmAnnouncementAsync(name, cancellationToken); + + public Task ClaimAnnouncementAsync(string name, CancellationToken cancellationToken) + { + cancellationTokenSource.Cancel(); + + throw new InvalidOperationException("Simulated announcement-claim failure."); + } + + public Task IsAnnouncementPendingAsync(string name, CancellationToken cancellationToken) + => inner.IsAnnouncementPendingAsync(name, cancellationToken); + + public Task RearmIdlePushAsync(string name, CancellationToken cancellationToken) + => inner.RearmIdlePushAsync(name, cancellationToken); + + public Task ClaimIdlePushAsync(string name, CancellationToken cancellationToken) + => inner.ClaimIdlePushAsync(name, cancellationToken); + + public Task RecordHarnessVersionAsync( + string name, string harnessVersion, CancellationToken cancellationToken) + => inner.RecordHarnessVersionAsync(name, harnessVersion, cancellationToken); + + public Task DeleteAsync(string name, CancellationToken cancellationToken) + => inner.DeleteAsync(name, cancellationToken); + + public Task DeleteInactiveAsync(CancellationToken cancellationToken) + => inner.DeleteInactiveAsync(cancellationToken); +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CancellingAnnouncementSessionRegistry.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CancellingAnnouncementSessionRegistry.cs deleted file mode 100644 index c5ec16230d9..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CancellingAnnouncementSessionRegistry.cs +++ /dev/null @@ -1,108 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -/// -/// Delegates to except for -/// , which cancels -/// and throws . -/// -internal sealed class CancellingAnnouncementSessionRegistry( - IAgentSessionRegistry inner, CancellationTokenSource cancellationTokenSource) : IAgentSessionRegistry -{ - public Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? envActor, - CancellationToken cancellationToken) - => inner.StartAsync(generation, cwd, workspacePath, endpointKind, endpointAddr, envActor, cancellationToken); - - public Task ClaimAsync( - AgentSessionGeneration generation, string actor, bool forceRebind, CancellationToken cancellationToken) - => inner.ClaimAsync(generation, actor, forceRebind, cancellationToken); - - public Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.EndAsync(generation, cancellationToken); - - public Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.FindByGenerationAsync(generation, cancellationToken); - - public Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ResetBlockBudgetAsync(generation, cancellationToken); - - public Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.IncrementBlockBudgetAsync(generation, cancellationToken); - - public Task> ReapAsync(CancellationToken cancellationToken) - => inner.ReapAsync(cancellationToken); - - public Task> ListAsync(CancellationToken cancellationToken) - => inner.ListAsync(cancellationToken); - - public Task> ListParticipantsAsync(CancellationToken cancellationToken) - => inner.ListParticipantsAsync(cancellationToken); - - public Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.TouchAsync(generation, cancellationToken); - - public Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - => inner.RecordHarnessVersionAsync(generation, harnessVersion, cancellationToken); - - public Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - => inner.SetRoleAsync(generation, role, cancellationToken); - - public Task RegisterAsync( - AgentSessionGeneration generation, - string actor, - string role, - string client, - bool forceRebind, - CancellationToken cancellationToken) - => inner.RegisterAsync(generation, actor, role, client, forceRebind, cancellationToken); - - public Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - => inner.FindBySessionIdAsync(harness, host, sessionId, cancellationToken); - - public Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - => inner.FindLiveClaimedByAgentNameAsync(agentName, cancellationToken); - - public Task TryClaimPingCooldownAsync( - AgentSessionRecord session, - string attemptId, - DateTimeOffset now, - TimeSpan cooldown, - CancellationToken cancellationToken) - => inner.TryClaimPingCooldownAsync(session, attemptId, now, cooldown, cancellationToken); - - public Task WritePingResultAsync( - string harness, - string sessionId, - string attemptId, - string result, - string? detail, - CancellationToken cancellationToken) - => inner.WritePingResultAsync(harness, sessionId, attemptId, result, detail, cancellationToken); - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ArmAnnouncementAsync(generation, cancellationToken); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - { - cancellationTokenSource.Cancel(); - - throw new InvalidOperationException("Simulated announcement-claim failure."); - } - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.RearmIdlePushAsync(generation, cancellationToken); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimIdlePushAsync(generation, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookExecutorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookExecutorTests.cs index e0063977cc2..626929c084b 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookExecutorTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookExecutorTests.cs @@ -1,7 +1,6 @@ using ChilliCream.Nitro.CommandLine.Services.Hook; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using ChilliCream.Nitro.CommandLine.Tests.Agents; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Time.Testing; @@ -170,26 +169,16 @@ public async Task RunAsync_Should_WriteNeutral_When_TheDatabaseIsContended() var fileSystem = new TestFileSystem(workspaceRoot); var timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); var database = new AgentDatabase(); - var agentRegistry = new AgentRegistry(fileSystem, timeProvider, database); - var sessions = new AgentSessionRegistry( - fileSystem, - timeProvider, - database, - agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); - var ledger = new SessionDeliveryLedger(fileSystem, database); - var mail = new MailStore(fileSystem, timeProvider, database, agentRegistry); + var agentStore = new AgentStore(fileSystem, timeProvider, database); + var ledger = new AgentDeliveryLedger(fileSystem, database); + var mail = new MailStore(fileSystem, timeProvider, database, agentStore); var handler = new ClaudeHookHandler( fileSystem, timeProvider, - sessions, - agentRegistry, + agentStore, ledger, mail, - new FixedClaudeSessionFileReader(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); + new FixedClaudeSessionFileReader()); await using (await database.InitializeAsync(workspaceDirectory, cancellationToken)) { @@ -197,6 +186,8 @@ public async Task RunAsync_Should_WriteNeutral_When_TheDatabaseIsContended() var payload = new ClaudeHookPayload { SessionId = "session-1", Cwd = workspaceRoot }; await handler.HandleSessionStartAsync(payload, skipSessionFileLookup: true, cancellationToken); + await SeedAgentAsync(database, workspaceDirectory, timeProvider, "alice", cancellationToken); + await SeedAgentAsync(database, workspaceDirectory, timeProvider, "bob", cancellationToken); await mail.SendMessageAsync( new MailMessageCreation { Sender = "bob", Subject = "status", Body = "check", To = ["alice"] }, cancellationToken); @@ -208,7 +199,7 @@ await mail.SendMessageAsync( await using (var lockCommand = lockConnection.CreateCommand()) { lockCommand.Transaction = lockTransaction; - lockCommand.CommandText = "UPDATE agent_sessions SET last_beat_at = last_beat_at;"; + lockCommand.CommandText = "UPDATE agents SET last_seen_at = last_seen_at;"; await lockCommand.ExecuteNonQueryAsync(cancellationToken); } @@ -254,26 +245,16 @@ public async Task RunAsync_Should_WriteNeutral_When_SchemaVersionMismatches() var fileSystem = new TestFileSystem(workspaceRoot); var timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); var database = new AgentDatabase(); - var agentRegistry = new AgentRegistry(fileSystem, timeProvider, database); - var sessions = new AgentSessionRegistry( - fileSystem, - timeProvider, - database, - agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); - var ledger = new SessionDeliveryLedger(fileSystem, database); - var mail = new MailStore(fileSystem, timeProvider, database, agentRegistry); + var agentStore = new AgentStore(fileSystem, timeProvider, database); + var ledger = new AgentDeliveryLedger(fileSystem, database); + var mail = new MailStore(fileSystem, timeProvider, database, agentStore); var handler = new ClaudeHookHandler( fileSystem, timeProvider, - sessions, - agentRegistry, + agentStore, ledger, mail, - new FixedClaudeSessionFileReader(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); + new FixedClaudeSessionFileReader()); await using (await database.InitializeAsync(workspaceDirectory, cancellationToken)) { @@ -425,4 +406,28 @@ await ClaudeHookExecutor.RunAsync( Assert.Equal(expectedCwd, captured.Cwd); Assert.Equal(expectedStopHookActive, captured.StopHookActive); } + + /// + /// Registers the named agent directly against the unified agents table. + /// + private static async Task SeedAgentAsync( + AgentDatabase database, + string workspaceDirectory, + TimeProvider timeProvider, + string name, + CancellationToken cancellationToken) + { + await using var connection = await database.ConnectAsync(workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookHandlerTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookHandlerTests.cs index 67ef556b518..766f55febf8 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookHandlerTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHookHandlerTests.cs @@ -1,11 +1,11 @@ +using System.Text.Json; using ChilliCream.Nitro.CommandLine.Services.Hook; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using ChilliCream.Nitro.CommandLine.Tests.Agents; +using Microsoft.Data.Sqlite; using Microsoft.Extensions.Time.Testing; -using Moq; namespace ChilliCream.Nitro.CommandLine.Tests.Hook; @@ -23,9 +23,8 @@ public sealed class ClaudeHookHandlerTests : IDisposable private readonly TestFileSystem _fileSystem; private readonly FakeTimeProvider _timeProvider; private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; - private readonly SessionDeliveryLedger _ledger; + private readonly AgentStore _agentStore; + private readonly AgentDeliveryLedger _ledger; private readonly MailStore _mail; private readonly ClaudeHookHandler _handler; @@ -38,39 +37,27 @@ public ClaudeHookHandlerTests() _fileSystem = new TestFileSystem(_workspaceRoot); _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, _timeProvider, _database); - _sessions = new AgentSessionRegistry( - _fileSystem, - _timeProvider, - _database, - _agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); - _ledger = new SessionDeliveryLedger(_fileSystem, _database); - _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentRegistry); + _agentStore = new AgentStore(_fileSystem, _timeProvider, _database); + _ledger = new AgentDeliveryLedger(_fileSystem, _database); + _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentStore); _handler = CreateHandler(); } public void Dispose() => _tempRoot.Delete(recursive: true); - private ClaudeHookHandler CreateHandler() => CreateHandler(_agentRegistry); - - private ClaudeHookHandler CreateHandler(IAgentRegistry agentRegistry) => new( + private ClaudeHookHandler CreateHandler(IClaudeSessionFileReader? sessionFileReader = null) => new( _fileSystem, _timeProvider, - _sessions, - agentRegistry, + _agentStore, _ledger, _mail, - new FixedClaudeSessionFileReader(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); + sessionFileReader ?? new FixedClaudeSessionFileReader()); // ---------- SessionStart ---------- [Fact] - public async Task HandleSessionStartAsync_Should_BindTheRowToAGeneratedActor_When_NoEnvActorIsSet() + public async Task HandleSessionStartAsync_Should_MintAnAgentAndAnnounceTheNameOnly_When_TheSessionIsUnknown() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -82,15 +69,15 @@ public async Task HandleSessionStartAsync_Should_BindTheRowToAGeneratedActor_Whe // assert var row = await FindRowAsync(cancellationToken); Assert.NotNull(row); - Assert.Contains($"Your Nitro actor name is \"{row.AgentName}\".", outcome.AdditionalContext); - Assert.DoesNotContain(SessionId, row.AgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, row.BindingKind); Assert.Equal("", row.Role); - Assert.NotNull(await _agentRegistry.GetAsync(row.AgentName!, cancellationToken)); + outcome.AdditionalContext!.Replace(row.Name, "").MatchInlineSnapshot( + """ + Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. + """); } [Fact] - public async Task HandleSessionStartAsync_Should_BindTheSameGeneratedActor_When_CalledAgainForTheSameSession() + public async Task HandleSessionStartAsync_Should_ReuseTheSameAgent_When_CalledAgainForTheSameSession() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -101,29 +88,29 @@ public async Task HandleSessionStartAsync_Should_BindTheSameGeneratedActor_When_ var second = await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // assert - var row = await FindRowAsync(cancellationToken); - Assert.NotNull(row); Assert.Equal(first.AdditionalContext, second.AdditionalContext); - Assert.Contains($"Your Nitro actor name is \"{row.AgentName}\".", second.AdditionalContext); - Assert.Equal(AgentSessionBindingKind.Explicit, row.BindingKind); + var row = await FindRowAsync(cancellationToken); + Assert.Contains($"\"{row!.Name}\"", second.AdditionalContext); } [Fact] - public async Task HandleSessionStartAsync_Should_UseDurableAgentRole_When_SessionRoleIsEmpty() + public async Task HandleSessionStartAsync_Should_ReuseAnEndedRowAndAnnounceNameAndRole_When_TheSessionResumes() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var actor = await StartAndGetActorAsync(cancellationToken); - await _sessions.RegisterAsync( - CurrentGeneration(), actor: null, actorGiven: false, role: "researcher", roleGiven: true, - cancellationToken: cancellationToken); - await _sessions.SetRoleAsync(CurrentGeneration(), string.Empty, cancellationToken); + await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + var actor = (await FindRowAsync(cancellationToken))!.Name; + await _agentStore.SetRoleAsync(actor, "researcher", cancellationToken); + await _handler.HandleSessionEndAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // act var outcome = await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // assert + var row = await FindRowAsync(cancellationToken); + Assert.Equal(actor, row!.Name); + Assert.Null(row.EndedAt); outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( """ Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. @@ -132,72 +119,25 @@ Your Nitro role is "researcher". } [Fact] - public async Task HandleSessionStartAsync_Should_UseSessionRole_When_DurableAgentRoleAlsoExists() + public async Task HandleSessionStartAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); - await _sessions.RegisterAsync( - CurrentGeneration(), actor: null, actorGiven: false, role: "researcher", roleGiven: true, - cancellationToken: cancellationToken); - await _sessions.SetRoleAsync(CurrentGeneration(), "planner", cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); // act var outcome = await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // assert - outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( - """ - Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. - Your Nitro role is "planner". - """); - } - - [Fact] - public async Task HandleSessionStartAsync_Should_OmitRole_When_SessionRoleIsEmptyAndAgentIsMissing() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var agentRegistry = new Mock(MockBehavior.Strict); - agentRegistry - .Setup(registry => registry.GetAsync(It.IsAny(), cancellationToken)) - .ReturnsAsync((AgentRecord?)null); - var handler = CreateHandler(agentRegistry.Object); - - // act - var outcome = await handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); - var actor = (await FindRowAsync(cancellationToken))!.AgentName!; - - // assert - outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( - """ - Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. - """); - } - - [Fact] - public async Task HandleSessionStartAsync_Should_PreserveActorContext_When_DurableRoleLookupFails() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var agentRegistry = new Mock(MockBehavior.Strict); - agentRegistry - .Setup(registry => registry.GetAsync(It.IsAny(), cancellationToken)) - .ThrowsAsync(new InvalidOperationException("lookup failed")); - var handler = CreateHandler(agentRegistry.Object); - - // act - var outcome = await handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); - var actor = (await FindRowAsync(cancellationToken))!.AgentName!; - - // assert - outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( - """ - Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. - """); + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); } [Fact] @@ -244,6 +184,7 @@ public async Task HandleSessionStartAsync_Should_ReturnNeutral_When_CwdIsMissing [Fact] public async Task HandleSessionStartAsync_Should_NotCreateAProvisionalIdentity_When_SessionIdIsMissing() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var payload = new ClaudeHookPayload { SessionId = null, Cwd = _workspaceRoot }; @@ -255,7 +196,7 @@ public async Task HandleSessionStartAsync_Should_NotCreateAProvisionalIdentity_W // assert Assert.Equal(ClaudeHookOutcome.Neutral, first); Assert.Equal(ClaudeHookOutcome.Neutral, second); - Assert.Equal(0L, await CountAllSessionRowsAsync(cancellationToken)); + Assert.Equal(0L, await CountAllAgentRowsAsync(cancellationToken)); } [Fact] @@ -264,16 +205,7 @@ public async Task HandleSessionStartAsync_Should_RecordHarnessVersion_When_TheSe // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var handler = new ClaudeHookHandler( - _fileSystem, - _timeProvider, - _sessions, - _agentRegistry, - _ledger, - _mail, - new FixedClaudeSessionFileReader(new ClaudeSessionFile(SessionId, "", "", "2.1.241")), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); + var handler = CreateHandler(new FixedClaudeSessionFileReader(new ClaudeSessionFile(SessionId, "", "", "2.1.241"))); // act // skipSessionFileLookup: false enables the session-file lookup. @@ -303,23 +235,89 @@ public async Task HandleSessionStartAsync_Should_LeaveHarnessVersionBlank_When_S // ---------- UserPromptSubmit ---------- [Fact] - public async Task HandleUserPromptSubmitAsync_Should_AdvanceLastBeatAt_When_GenerationResolves() + public async Task HandleUserPromptSubmitAsync_Should_AdvanceLastSeenAt_When_TheSessionResolves() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); - var before = (await FindRowAsync(cancellationToken))!.LastBeatAt; + var before = (await FindRowAsync(cancellationToken))!.LastSeenAt; _timeProvider.Advance(TimeSpan.FromMinutes(5)); // act await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // assert - var after = (await FindRowAsync(cancellationToken))!.LastBeatAt; + var after = (await FindRowAsync(cancellationToken))!.LastSeenAt; Assert.True(after > before); } + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_AnnounceTheName_When_TheSessionIsUnknown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + outcome.AdditionalContext!.Replace(row.Name, "").MatchInlineSnapshot( + """ + Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. + """); + } + + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_AnnounceTheNameThenTheDigest_When_TheSessionIsUnknownAndMailIsPending() + { + // arrange + // A free pool name is reserved for mail, then freed so the mint below has to draw it. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var freeName = AgentActorAllocator.BaseActors[0]; + await SeedAgentAsync(freeName, cancellationToken); + var message = await SendMailAsync("bob", freeName, cancellationToken); + await DeleteAgentRowAsync(freeName, cancellationToken); + await TombstoneOtherPoolNamesAsync(freeName, cancellationToken); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.Equal(freeName, row!.Name); + outcome.AdditionalContext!.Replace(message.Id, "").MatchInlineSnapshot( + $$""" + Your Nitro actor name is "{{freeName}}". Pass this name to the `--actor` option to act under this actor explicitly. + + You have 1 unread nitro message; 1 shown below as `nitro agent mail read --thread --output json` prints them. Reply with `nitro agent mail reply --message --actor {{freeName}} --body "..."` or ack with `nitro agent mail ack --message --actor {{freeName}}`; anything not shown is in `nitro agent mail inbox --unread --actor {{freeName}}`. + { + "items": [ + { + "id": "", + "threadId": "", + "inReplyTo": null, + "from": "bob", + "to": [ + "{{freeName}}" + ], + "cc": [], + "subject": "status", + "body": "please check", + "createdAt": "2026-01-10T12:00:00+00:00", + "read": false, + "archived": false, + "takeovers": [] + } + ] + } + """); + } + [Fact] public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutral_When_NoMailIsAddressedToTheActor() { @@ -436,7 +434,7 @@ public async Task HandleUserPromptSubmitAsync_Should_NotRedeliver_When_AMessageI } [Fact] - public async Task HandleUserPromptSubmitAsync_Should_ResetTheBlockBudget() + public async Task HandleUserPromptSubmitAsync_Should_ResetTheBlockBudget_When_ItIsCalled() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -460,23 +458,45 @@ public async Task HandleUserPromptSubmitAsync_Should_ResetTheBlockBudget() Assert.Equal(0, resetRow!.BlockBudgetUsed); } + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + // ---------- Stop ---------- [Fact] - public async Task HandleStopAsync_Should_AdvanceLastBeatAt_When_GenerationResolves() + public async Task HandleStopAsync_Should_AdvanceLastSeenAt_When_TheSessionResolves() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); - var before = (await FindRowAsync(cancellationToken))!.LastBeatAt; + var before = (await FindRowAsync(cancellationToken))!.LastSeenAt; _timeProvider.Advance(TimeSpan.FromMinutes(5)); // act await _handler.HandleStopAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // assert - var after = (await FindRowAsync(cancellationToken))!.LastBeatAt; + var after = (await FindRowAsync(cancellationToken))!.LastSeenAt; Assert.True(after > before); } @@ -551,14 +571,8 @@ public async Task HandleStopAsync_Should_KeepTheBlockReason_When_AFreshStopDiges Assert.Contains(firstMessage.Id, first.BlockReason); var pingSeenMessage = await SendMailAsync("carol", actor, cancellationToken); - var generation = CurrentGeneration(); await _ledger.ReserveAsync( - generation.Harness, - generation.SessionId, - [pingSeenMessage.Id], - AgentSessionChannel.Ping, - _timeProvider.GetUtcNow(), - cancellationToken); + actor, [pingSeenMessage.Id], AgentSessionChannel.Ping, _timeProvider.GetUtcNow(), cancellationToken); // act var outcome = await _handler.HandleStopAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); @@ -642,7 +656,7 @@ public async Task HandleStopAsync_Should_LeaveTheMessageEligibleForAFutureBudget } [Fact] - public async Task HandleStopAsync_Should_ReturnNeutral_When_TheRowIsDeletedBetweenResolveAndIncrement() + public async Task HandleStopAsync_Should_ReturnNeutral_When_TheBudgetIncrementNoLongerMatchesTheRow() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -653,13 +667,10 @@ public async Task HandleStopAsync_Should_ReturnNeutral_When_TheRowIsDeletedBetwe var handler = new ClaudeHookHandler( _fileSystem, _timeProvider, - new IncrementNeverMatchesAgentSessionRegistry(_sessions), - _agentRegistry, + new IncrementNeverMatchesAgentStore(_agentStore), _ledger, _mail, - new FixedClaudeSessionFileReader(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); + new FixedClaudeSessionFileReader()); // act var outcome = await handler.HandleStopAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); @@ -681,17 +692,14 @@ public async Task HandleStopAsync_Should_ReserveAtMostMaxDigestMessages_When_Man await SendMailAsync($"bob-{i}", actor, cancellationToken); } - var spyLedger = new ReserveCapturingSessionDeliveryLedger(_ledger); + var spyLedger = new ReserveCapturingAgentDeliveryLedger(_ledger); var handler = new ClaudeHookHandler( _fileSystem, _timeProvider, - _sessions, - _agentRegistry, + _agentStore, spyLedger, _mail, - new FixedClaudeSessionFileReader(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); + new FixedClaudeSessionFileReader()); // act var outcome = await handler.HandleStopAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); @@ -703,15 +711,15 @@ public async Task HandleStopAsync_Should_ReserveAtMostMaxDigestMessages_When_Man } [Fact] - public async Task HandleStopAsync_Should_ResolveTheSameGeneration_When_ReplayedFromADifferentHandlerInstance() + public async Task HandleStopAsync_Should_ResolveTheSameAgent_When_ReplayedFromADifferentHandlerInstance() { // arrange - // Both handlers use the same session id and fixed Nitro instance id. + // Both handlers resolve the same harness session id against the same database. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var sessionStartHandler = CreateHandler(); await sessionStartHandler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); - var actor = (await FindRowAsync(cancellationToken))!.AgentName!; + var actor = (await FindRowAsync(cancellationToken))!.Name; await SendMailAsync("bob", actor, cancellationToken); // act @@ -723,23 +731,129 @@ public async Task HandleStopAsync_Should_ResolveTheSameGeneration_When_ReplayedF Assert.NotNull(outcome.BlockReason); } + [Fact] + public async Task HandleStopAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleStopAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + + // ---------- Notification ---------- + + [Fact] + public async Task HandleNotificationAsync_Should_ReturnNeutralWithoutTouching_When_TheNotificationTypeIsNotIdlePrompt() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + var before = (await FindRowAsync(cancellationToken))!.LastSeenAt; + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleNotificationAsync( + Payload(SessionId, notificationType: "permission_request"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = (await FindRowAsync(cancellationToken))!.LastSeenAt; + Assert.Equal(before, after); + } + + [Fact] + public async Task HandleNotificationAsync_Should_AdvanceLastSeenAt_When_TheNotificationTypeIsIdlePromptAndTheSessionResolves() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + var before = (await FindRowAsync(cancellationToken))!.LastSeenAt; + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleNotificationAsync( + Payload(SessionId, notificationType: "idle_prompt"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = (await FindRowAsync(cancellationToken))!.LastSeenAt; + Assert.True(after > before); + } + + [Fact] + public async Task HandleNotificationAsync_Should_AnnounceTheName_When_TheSessionIsUnknownAndTheNotificationTypeIsIdlePrompt() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleNotificationAsync( + Payload(SessionId, notificationType: "idle_prompt"), skipSessionFileLookup: true, cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + outcome.AdditionalContext!.Replace(row.Name, "").MatchInlineSnapshot( + """ + Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. + """); + } + + [Fact] + public async Task HandleNotificationAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleNotificationAsync( + Payload(SessionId, notificationType: "idle_prompt"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + } + // ---------- SessionEnd ---------- [Fact] - public async Task HandleSessionEndAsync_Should_DeleteTheRow() + public async Task HandleSessionEndAsync_Should_StampEndedAtAndKeepTheRow_When_TheSessionIsActive() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); - Assert.NotNull(await FindRowAsync(cancellationToken)); // act var outcome = await _handler.HandleSessionEndAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); // assert Assert.Equal(ClaudeHookOutcome.Neutral, outcome); - Assert.Null(await FindRowAsync(cancellationToken)); + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + Assert.NotNull(row.EndedAt); } [Fact] @@ -756,14 +870,158 @@ public async Task HandleSessionEndAsync_Should_ReturnNeutral_When_NoRowExists() Assert.Equal(ClaudeHookOutcome.Neutral, outcome); } - // ---------- helpers ---------- + [Fact] + public async Task HandleSessionEndAsync_Should_ReturnNeutralWithoutClearingDeletedAt_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + + // act + var outcome = await _handler.HandleSessionEndAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var row = await FindRowAsync(cancellationToken); + Assert.Null(row!.EndedAt); + } - private ClaudeHookPayload Payload(string sessionId, bool stopHookActive = false) => new() + // ---------- Subagent sessions ---------- + + [Fact] + public async Task HandleSessionStartAsync_Should_ReturnNeutralWithoutMintingOrAnnouncing_When_AgentIdIsSet() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleSessionStartAsync( + Payload(SessionId, agentId: "agent-1"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + Assert.Null(await FindRowAsync(cancellationToken)); + } + + [Fact] + public async Task HandleSessionStartAsync_Should_MintAndAnnounce_When_OnlyAgentTypeIsSet() + { + // arrange + // agent_type alone (a top-level `claude --agent ` session) is not a subagent marker. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var json = $$"""{"session_id":"{{SessionId}}","cwd":{{JsonSerializer.Serialize(_workspaceRoot)}},"agent_type":"general-purpose"}"""; + var payload = JsonSerializer.Deserialize(json, ClaudeHookJsonContext.Default.ClaudeHookPayload)!; + + // act + var outcome = await _handler.HandleSessionStartAsync(payload, skipSessionFileLookup: true, cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + outcome.AdditionalContext!.Replace(row.Name, "").MatchInlineSnapshot( + """ + Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. + """); + } + + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutralWithoutMintingOrDigest_When_AgentIdIsSet() { - SessionId = sessionId, - Cwd = _workspaceRoot, - StopHookActive = stopHookActive - }; + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync( + Payload(SessionId, agentId: "agent-1"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + + [Fact] + public async Task HandleStopAsync_Should_ReturnNeutralWithoutBlockingOrDigest_When_AgentIdIsSet() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleStopAsync( + Payload(SessionId, agentId: "agent-1"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.False(outcome.Block); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Equal(before.BlockBudgetUsed, after!.BlockBudgetUsed); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + + [Fact] + public async Task HandleNotificationAsync_Should_ReturnNeutralWithoutMinting_When_AgentIdIsSetAndNotificationTypeIsIdlePrompt() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleNotificationAsync( + Payload(SessionId, notificationType: "idle_prompt", agentId: "agent-1"), + skipSessionFileLookup: true, + cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + Assert.Null(await FindRowAsync(cancellationToken)); + } + + [Fact] + public async Task HandleSessionEndAsync_Should_ReturnNeutralWithoutStampingEndedAt_When_AgentIdIsSet() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + await StartAndGetActorAsync(cancellationToken); + + // act + var outcome = await _handler.HandleSessionEndAsync( + Payload(SessionId, agentId: "agent-1"), skipSessionFileLookup: true, cancellationToken); + + // assert + Assert.Equal(ClaudeHookOutcome.Neutral, outcome); + Assert.Null((await FindRowAsync(cancellationToken))!.EndedAt); + } + + // ---------- helpers ---------- + + private ClaudeHookPayload Payload( + string sessionId, + bool stopHookActive = false, + string? notificationType = null, + string? agentId = null) => new() + { + SessionId = sessionId, + Cwd = _workspaceRoot, + StopHookActive = stopHookActive, + NotificationType = notificationType, + AgentId = agentId + }; private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) { @@ -773,16 +1031,21 @@ private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) } private async Task SendMailAsync(string sender, string recipient, CancellationToken cancellationToken) - => await _mail.SendMessageAsync( + { + // Registers the mail sender behind the store's sender-usability check. + await SeedAgentAsync(sender, cancellationToken); + + return await _mail.SendMessageAsync( new MailMessageCreation { Sender = sender, Subject = "status", Body = "please check", To = [recipient] }, cancellationToken); + } private async Task StartAndGetActorAsync(CancellationToken cancellationToken) { await _handler.HandleSessionStartAsync(Payload(SessionId), skipSessionFileLookup: true, cancellationToken); var row = await FindRowAsync(cancellationToken); - return row!.AgentName!; + return row!.Name; } private async Task AssertStillUnreadAsync( @@ -794,18 +1057,83 @@ private async Task AssertStillUnreadAsync( Assert.Equal(unreadBefore, await _mail.CountUnreadAsync(actor, cancellationToken)); } - private async Task FindRowAsync(CancellationToken cancellationToken) - => await _sessions.FindByGenerationAsync(CurrentGeneration(), cancellationToken); + private Task FindRowAsync(CancellationToken cancellationToken) + => _agentStore.FindBySessionAsync(AgentSessionHarness.ClaudeCode, SessionId, cancellationToken); - private async Task CountAllSessionRowsAsync(CancellationToken cancellationToken) + private async Task CountAllAgentRowsAsync(CancellationToken cancellationToken) { await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT COUNT(*) FROM agent_sessions;"; + command.CommandText = "SELECT COUNT(*) FROM agents;"; return Convert.ToInt64(await command.ExecuteScalarAsync(cancellationToken)); } - private static AgentSessionGeneration CurrentGeneration() - => new(AgentSessionHarness.ClaudeCode, SessionId, "host-1"); + /// + /// Registers the named agent directly against the unified agents table. + /// + private async Task SeedAgentAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Marks the named agent as soft-deleted. + /// + private async Task MarkDeletedAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET deleted_at = @now WHERE name = @name"; + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Hard-deletes the named agent's row, freeing it for the actor allocator to draw again. + /// + private async Task DeleteAgentRowAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM agents WHERE name = @name"; + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Tombstones every pool name except , forcing the actor + /// allocator to draw that one name for the next mint. + /// + private async Task TombstoneOtherPoolNamesAsync(string keep, CancellationToken cancellationToken) + { + var now = _timeProvider.GetUtcNow(); + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + "INSERT INTO agents (name, registered_at, started_at, last_seen_at, deleted_at) " + + "VALUES (@name, @now, @now, @now, @now)"; + var nameParameter = command.Parameters.Add("@name", SqliteType.Text); + command.Parameters.AddWithValue("@now", now); + + foreach (var name in AgentActorAllocator.BaseActors.Where(name => name != keep)) + { + nameParameter.Value = name; + await command.ExecuteNonQueryAsync(cancellationToken); + } + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHooksEditorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHooksEditorTests.cs index 9a6df593051..d34eddba7e6 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHooksEditorTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ClaudeHooksEditorTests.cs @@ -13,12 +13,38 @@ public sealed class ClaudeHooksEditorTests new("/home/agent/.dotnet/tools/nitro", []); [Fact] - public void Install_MissingFile_CreatesAllFourEventsAsInstalled() + public void Install_Should_CreateAllFiveEventsAsInstalled_When_TheSettingsFileIsMissing() { + // arrange + // act var result = ClaudeHooksEditor.Install(null, s_descriptor, DateTimeOffset.UnixEpoch); - Assert.All(result.Outcomes, o => Assert.Equal(HookInstallOutcome.Installed, o.Outcome)); - Assert.Equal(ClaudeHooksTemplate.Events, result.Outcomes.Select(o => o.Event)); + // assert + result.Outcomes.MatchInlineSnapshot( + """ + [ + { + "Event": "SessionStart", + "Outcome": "Installed" + }, + { + "Event": "UserPromptSubmit", + "Outcome": "Installed" + }, + { + "Event": "Stop", + "Outcome": "Installed" + }, + { + "Event": "Notification", + "Outcome": "Installed" + }, + { + "Event": "SessionEnd", + "Outcome": "Installed" + } + ] + """); var root = Parse(result.SettingsJson); var hooks = (JsonObject)root["hooks"]!; @@ -29,7 +55,7 @@ public void Install_MissingFile_CreatesAllFourEventsAsInstalled() AssertCommand(group, ClaudeHooksTemplate.BuildCommand(s_descriptor, claudeEvent), 10); } - Assert.Equal(4, result.Sidecar.Count); + Assert.Equal(5, result.Sidecar.Count); Assert.All(result.Sidecar.Values, e => Assert.Equal(DateTimeOffset.UnixEpoch, e.InstalledAt)); } @@ -147,6 +173,115 @@ public void Install_Twice_IsIdempotent() Assert.Equal(once, twice); } + [Fact] + public void Status_Should_ReportNotificationMissing_When_TheInstallHasFourEntries() + { + // arrange + var before = ClaudeHooksInstallFixtures.Read("install", "four-events.json"); + + // act + var result = ClaudeHooksEditor.Status(before, s_descriptor); + + // assert + result.MatchInlineSnapshot( + """ + [ + { + "Event": "SessionStart", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude session-start" + }, + { + "Event": "UserPromptSubmit", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude user-prompt-submit" + }, + { + "Event": "Stop", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude stop" + }, + { + "Event": "Notification", + "Outcome": "Missing", + "InstalledCommand": null + }, + { + "Event": "SessionEnd", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude session-end" + } + ] + """); + } + + [Fact] + public void Install_Should_AddNotificationAndLeaveTheOtherFourUnchanged_When_TheInstallHasFourEntries() + { + // arrange + var before = ClaudeHooksInstallFixtures.Read("install", "four-events.json"); + + // act + var result = ClaudeHooksEditor.Install(before, s_descriptor, DateTimeOffset.UnixEpoch); + + // assert + result.Outcomes.MatchInlineSnapshot( + """ + [ + { + "Event": "SessionStart", + "Outcome": "Unchanged" + }, + { + "Event": "UserPromptSubmit", + "Outcome": "Unchanged" + }, + { + "Event": "Stop", + "Outcome": "Unchanged" + }, + { + "Event": "Notification", + "Outcome": "Installed" + }, + { + "Event": "SessionEnd", + "Outcome": "Unchanged" + } + ] + """); + ClaudeHooksEditor.Status(result.SettingsJson, s_descriptor).MatchInlineSnapshot( + """ + [ + { + "Event": "SessionStart", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude session-start" + }, + { + "Event": "UserPromptSubmit", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude user-prompt-submit" + }, + { + "Event": "Stop", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude stop" + }, + { + "Event": "Notification", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude notification" + }, + { + "Event": "SessionEnd", + "Outcome": "Installed", + "InstalledCommand": "/home/agent/.dotnet/tools/nitro agent hook claude session-end" + } + ] + """); + } + [Fact] public void Status_ReportsMissingInstalledAndOutdated() { diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CodexHookHandlerTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CodexHookHandlerTests.cs index e42aa518415..f5018ae7204 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CodexHookHandlerTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/CodexHookHandlerTests.cs @@ -1,9 +1,8 @@ using ChilliCream.Nitro.CommandLine.Services.Hook; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; +using Microsoft.Data.Sqlite; using Microsoft.Extensions.Time.Testing; -using Moq; namespace ChilliCream.Nitro.CommandLine.Tests.Hook; @@ -21,11 +20,9 @@ public sealed class CodexHookHandlerTests : IDisposable private readonly TestFileSystem _fileSystem; private readonly FakeTimeProvider _timeProvider; private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; - private readonly SessionDeliveryLedger _ledger; + private readonly AgentStore _agentStore; + private readonly AgentDeliveryLedger _ledger; private readonly MailStore _mail; - private readonly FixedEnvironmentVariableProvider _environmentVariables; private readonly FakeCodexQueueClient _queueClient; private readonly CodexHookHandler _handler; @@ -38,17 +35,9 @@ public CodexHookHandlerTests() _fileSystem = new TestFileSystem(_workspaceRoot); _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, _timeProvider, _database); - _sessions = new AgentSessionRegistry( - _fileSystem, - _timeProvider, - _database, - _agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); - _ledger = new SessionDeliveryLedger(_fileSystem, _database); - _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentRegistry); - _environmentVariables = new FixedEnvironmentVariableProvider(); + _agentStore = new AgentStore(_fileSystem, _timeProvider, _database); + _ledger = new AgentDeliveryLedger(_fileSystem, _database); + _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentStore); _queueClient = new FakeCodexQueueClient(); _handler = CreateHandler(); @@ -56,73 +45,72 @@ public CodexHookHandlerTests() public void Dispose() => _tempRoot.Delete(recursive: true); - private CodexHookHandler CreateHandler() => CreateHandler(_agentRegistry); - - private CodexHookHandler CreateHandler(IAgentRegistry agentRegistry) => new( + private CodexHookHandler CreateHandler(ICodexHarnessVersionResolver? harnessVersionResolver = null) => new( _fileSystem, _timeProvider, - _sessions, - agentRegistry, + _agentStore, _ledger, _mail, - _environmentVariables, - new FixedCodexHarnessVersionResolver(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot), + harnessVersionResolver ?? new FixedCodexHarnessVersionResolver(), _queueClient); // ---------- SessionStart ---------- [Fact] - public async Task HandleSessionStartAsync_Should_BindTheRowToAGeneratedActor_When_NoEnvActorIsSet() + public async Task HandleSessionStartAsync_Should_MintAnAgentAndAnnounceTheNameOnly_When_TheSessionIsUnknown() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + // act var outcome = await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); // assert var row = await FindRowAsync(cancellationToken); Assert.NotNull(row); - Assert.Contains($"Your Nitro actor name is \"{row.AgentName}\".", outcome.AdditionalContext); - Assert.DoesNotContain(SessionId, row.AgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, row.BindingKind); Assert.Equal("", row.Role); - Assert.NotNull(await _agentRegistry.GetAsync(row.AgentName!, cancellationToken)); + outcome.AdditionalContext!.Replace(row.Name, "").MatchInlineSnapshot( + """ + Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. + """); } [Fact] - public async Task HandleSessionStartAsync_Should_BindTheSameGeneratedActor_When_CalledAgainForTheSameSession() + public async Task HandleSessionStartAsync_Should_ReuseTheSameAgent_When_CalledAgainForTheSameSession() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var first = await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); - var outcome = await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // act + var second = await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // assert + Assert.Equal(first.AdditionalContext, second.AdditionalContext); var row = await FindRowAsync(cancellationToken); - Assert.NotNull(row); - Assert.Equal(first.AdditionalContext, outcome.AdditionalContext); - Assert.Contains($"Your Nitro actor name is \"{row.AgentName}\".", outcome.AdditionalContext); - Assert.Equal(AgentSessionBindingKind.Explicit, row.BindingKind); + Assert.Contains($"\"{row!.Name}\"", second.AdditionalContext); } [Fact] - public async Task HandleSessionStartAsync_Should_UseDurableAgentRole_When_SessionRoleIsEmpty() + public async Task HandleSessionStartAsync_Should_ReuseAnEndedRowAndAnnounceNameAndRole_When_TheSessionResumes() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var actor = await StartAndGetActorAsync(cancellationToken); - await _sessions.RegisterAsync( - CurrentGeneration(), actor: null, actorGiven: false, role: "researcher", roleGiven: true, - cancellationToken: cancellationToken); - await _sessions.SetRoleAsync(CurrentGeneration(), string.Empty, cancellationToken); + await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + var actor = (await FindRowAsync(cancellationToken))!.Name; + await _agentStore.SetRoleAsync(actor, "researcher", cancellationToken); + await _handler.HandleSessionEndAsync(Payload(SessionId), cancellationToken); // act var outcome = await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); // assert + var row = await FindRowAsync(cancellationToken); + Assert.Equal(actor, row!.Name); + Assert.Null(row.EndedAt); outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( """ Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. @@ -131,82 +119,38 @@ Your Nitro role is "researcher". } [Fact] - public async Task HandleSessionStartAsync_Should_UseSessionRole_When_DurableAgentRoleAlsoExists() + public async Task HandleSessionStartAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); - await _sessions.RegisterAsync( - CurrentGeneration(), actor: null, actorGiven: false, role: "researcher", roleGiven: true, - cancellationToken: cancellationToken); - await _sessions.SetRoleAsync(CurrentGeneration(), "planner", cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); // act var outcome = await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); // assert - outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( - """ - Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. - Your Nitro role is "planner". - """); - } - - [Fact] - public async Task HandleSessionStartAsync_Should_OmitRole_When_SessionRoleIsEmptyAndAgentIsMissing() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var agentRegistry = new Mock(MockBehavior.Strict); - agentRegistry - .Setup(registry => registry.GetAsync(It.IsAny(), cancellationToken)) - .ReturnsAsync((AgentRecord?)null); - var handler = CreateHandler(agentRegistry.Object); - - // act - var outcome = await handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); - var actor = (await FindRowAsync(cancellationToken))!.AgentName!; - - // assert - outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( - """ - Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. - """); + Assert.Equal(CodexHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); } [Fact] - public async Task HandleSessionStartAsync_Should_PreserveActorContext_When_DurableRoleLookupFails() + public async Task HandleSessionStartAsync_Should_SetTheCodexThreadEndpointToTheSessionId_When_TheSessionIdIsAValidAddress() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var agentRegistry = new Mock(MockBehavior.Strict); - agentRegistry - .Setup(registry => registry.GetAsync(It.IsAny(), cancellationToken)) - .ThrowsAsync(new InvalidOperationException("lookup failed")); - var handler = CreateHandler(agentRegistry.Object); // act - var outcome = await handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); - var actor = (await FindRowAsync(cancellationToken))!.AgentName!; - - // assert - outcome.AdditionalContext!.Replace(actor, "").MatchInlineSnapshot( - """ - Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. - """); - } - - [Fact] - public async Task HandleSessionStartAsync_Should_SetTheCodexThreadEndpoint_ToTheSessionId() - { - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // assert var row = await FindRowAsync(cancellationToken); Assert.NotNull(row); Assert.Equal(AgentSessionEndpointKind.CodexThread, row.EndpointKind); @@ -216,6 +160,7 @@ public async Task HandleSessionStartAsync_Should_SetTheCodexThreadEndpoint_ToThe [Fact] public async Task HandleSessionStartAsync_Should_ReturnNeutralWithoutCreatingARow_When_CwdHasNoWorkspace() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var noWorkspaceRoot = Directory.CreateTempSubdirectory("nitro-codex-hook-no-workspace-tests"); @@ -224,8 +169,10 @@ public async Task HandleSessionStartAsync_Should_ReturnNeutralWithoutCreatingARo { var payload = new CodexHookPayload { SessionId = SessionId, Cwd = noWorkspaceRoot.FullName }; + // act var outcome = await _handler.HandleSessionStartAsync(payload, cancellationToken); + // assert Assert.Equal(CodexHookOutcome.Neutral, outcome); Assert.Null(await FindRowAsync(cancellationToken)); } @@ -243,14 +190,17 @@ public async Task HandleSessionStartAsync_Should_ReturnNeutral_When_CwdIsMissing await InitializeWorkspaceAsync(cancellationToken); var payload = new CodexHookPayload { SessionId = SessionId, Cwd = null }; + // act var outcome = await _handler.HandleSessionStartAsync(payload, cancellationToken); + // assert Assert.Equal(CodexHookOutcome.Neutral, outcome); } [Fact] public async Task HandleSessionStartAsync_Should_NotCreateAProvisionalIdentity_When_SessionIdIsMissing() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var payload = new CodexHookPayload { SessionId = null, Cwd = _workspaceRoot }; @@ -262,29 +212,21 @@ public async Task HandleSessionStartAsync_Should_NotCreateAProvisionalIdentity_W // assert Assert.Equal(CodexHookOutcome.Neutral, first); Assert.Equal(CodexHookOutcome.Neutral, second); - Assert.Equal(0L, await CountAllSessionRowsAsync(cancellationToken)); + Assert.Equal(0L, await CountAllAgentRowsAsync(cancellationToken)); } [Fact] public async Task HandleSessionStartAsync_Should_RecordHarnessVersion_When_TheResolverReturnsOne() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var handler = new CodexHookHandler( - _fileSystem, - _timeProvider, - _sessions, - _agentRegistry, - _ledger, - _mail, - _environmentVariables, - new FixedCodexHarnessVersionResolver("0.101.0"), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot), - _queueClient); + var handler = CreateHandler(new FixedCodexHarnessVersionResolver("0.101.0")); + // act await handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // assert var row = await FindRowAsync(cancellationToken); Assert.Equal("0.101.0", row!.HarnessVersion); } @@ -292,11 +234,14 @@ public async Task HandleSessionStartAsync_Should_RecordHarnessVersion_When_TheRe [Fact] public async Task HandleSessionStartAsync_Should_LeaveHarnessVersionBlank_When_TheResolverReturnsNone() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + // act await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // assert var row = await FindRowAsync(cancellationToken); Assert.Equal("", row!.HarnessVersion); } @@ -304,42 +249,117 @@ public async Task HandleSessionStartAsync_Should_LeaveHarnessVersionBlank_When_T // ---------- UserPromptSubmit ---------- [Fact] - public async Task HandleUserPromptSubmitAsync_Should_AdvanceLastBeatAt_When_GenerationResolves() + public async Task HandleUserPromptSubmitAsync_Should_AdvanceLastSeenAt_When_TheSessionResolves() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); - var before = (await FindRowAsync(cancellationToken))!.LastBeatAt; + var before = (await FindRowAsync(cancellationToken))!.LastSeenAt; _timeProvider.Advance(TimeSpan.FromMinutes(5)); + // act await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); - var after = (await FindRowAsync(cancellationToken))!.LastBeatAt; + // assert + var after = (await FindRowAsync(cancellationToken))!.LastSeenAt; Assert.True(after > before); } + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_AnnounceTheName_When_TheSessionIsUnknown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + outcome.AdditionalContext!.Replace(row.Name, "").MatchInlineSnapshot( + """ + Your Nitro actor name is "". Pass this name to the `--actor` option to act under this actor explicitly. + """); + } + + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_AnnounceTheNameThenTheDigest_When_TheSessionIsUnknownAndMailIsPending() + { + // arrange + // A free pool name is reserved for mail, then freed so the mint below has to draw it. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var freeName = AgentActorAllocator.BaseActors[0]; + await SeedAgentAsync(freeName, cancellationToken); + var message = await SendMailAsync("bob", freeName, cancellationToken); + await DeleteAgentRowAsync(freeName, cancellationToken); + await TombstoneOtherPoolNamesAsync(freeName, cancellationToken); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.Equal(freeName, row!.Name); + outcome.AdditionalContext!.Replace(message.Id, "").MatchInlineSnapshot( + $$""" + Your Nitro actor name is "{{freeName}}". Pass this name to the `--actor` option to act under this actor explicitly. + + You have 1 unread nitro message; 1 shown below as `nitro agent mail read --thread --output json` prints them. Reply with `nitro agent mail reply --message --actor {{freeName}} --body "..."` or ack with `nitro agent mail ack --message --actor {{freeName}}`; anything not shown is in `nitro agent mail inbox --unread --actor {{freeName}}`. + { + "items": [ + { + "id": "", + "threadId": "", + "inReplyTo": null, + "from": "bob", + "to": [ + "{{freeName}}" + ], + "cc": [], + "subject": "status", + "body": "please check", + "createdAt": "2026-01-10T12:00:00+00:00", + "read": false, + "archived": false, + "takeovers": [] + } + ] + } + """); + } + [Fact] public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutral_When_NoMailIsAddressedToTheActor() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // act var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); + // assert Assert.Equal(CodexHookOutcome.Neutral, outcome); } [Fact] public async Task HandleUserPromptSubmitAsync_Should_ReturnDigest_When_UnreadMailExistsForTheClaimedActor() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); var message = await SendMailAsync("bob", actor, cancellationToken); + // act var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); + // assert outcome.AdditionalContext! .Replace(actor, "") .Replace(message.Id, "") @@ -372,6 +392,7 @@ public async Task HandleUserPromptSubmitAsync_Should_ReturnDigest_When_UnreadMai [Fact] public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutral_When_CalledAgainWithNoNewMail() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); @@ -379,66 +400,121 @@ public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutral_When_CalledAg var first = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); Assert.NotNull(first.AdditionalContext); + // act var second = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); + // assert Assert.Equal(CodexHookOutcome.Neutral, second); } + [Fact] + public async Task HandleUserPromptSubmitAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleUserPromptSubmitAsync(Payload(SessionId), cancellationToken); + + // assert + Assert.Equal(CodexHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + // ---------- SessionEnd ---------- [Fact] - public async Task HandleSessionEndAsync_Should_DeleteTheRow() + public async Task HandleSessionEndAsync_Should_StampEndedAtAndKeepTheRow_When_TheSessionIsActive() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); - Assert.NotNull(await FindRowAsync(cancellationToken)); + // act var outcome = await _handler.HandleSessionEndAsync(Payload(SessionId), cancellationToken); + // assert Assert.Equal(CodexHookOutcome.Neutral, outcome); - Assert.Null(await FindRowAsync(cancellationToken)); + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + Assert.NotNull(row.EndedAt); } [Fact] public async Task HandleSessionEndAsync_Should_ReturnNeutral_When_NoRowExists() { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleSessionEndAsync(Payload(SessionId), cancellationToken); + + // assert + Assert.Equal(CodexHookOutcome.Neutral, outcome); + } + + [Fact] + public async Task HandleSessionEndAsync_Should_ReturnNeutralWithoutClearingDeletedAt_When_TheSessionBelongsToADeletedAgent() + { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + // act var outcome = await _handler.HandleSessionEndAsync(Payload(SessionId), cancellationToken); + // assert Assert.Equal(CodexHookOutcome.Neutral, outcome); + var row = await FindRowAsync(cancellationToken); + Assert.Null(row!.EndedAt); } // ---------- Notify (the idle-turn gate) ---------- [Fact] - public async Task HandleNotifyAsync_Should_AdvanceLastBeatAt_When_GenerationResolves() + public async Task HandleNotifyAsync_Should_AdvanceLastSeenAt_When_TheThreadResolves() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); - var before = (await FindRowAsync(cancellationToken))!.LastBeatAt; + var before = (await FindRowAsync(cancellationToken))!.LastSeenAt; _timeProvider.Advance(TimeSpan.FromMinutes(5)); + // act await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); - var after = (await FindRowAsync(cancellationToken))!.LastBeatAt; + // assert + var after = (await FindRowAsync(cancellationToken))!.LastSeenAt; Assert.True(after > before); } [Fact] public async Task HandleNotifyAsync_Should_ReturnNeutral_When_TypeIsNotAgentTurnComplete() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); + // act var outcome = await _handler.HandleNotifyAsync( NotifyPayload(SessionId, type: "something-else"), cancellationToken); + // assert Assert.Equal(CodexNotifyOutcome.Neutral, outcome); Assert.Empty(_queueClient.Calls); } @@ -446,12 +522,15 @@ public async Task HandleNotifyAsync_Should_ReturnNeutral_When_TypeIsNotAgentTurn [Fact] public async Task HandleNotifyAsync_Should_ReturnNeutral_When_NoMailIsAddressedToTheGeneratedActor() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); + // act var outcome = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); + // assert Assert.Equal(CodexNotifyOutcome.Neutral, outcome); Assert.Empty(_queueClient.Calls); } @@ -459,13 +538,16 @@ public async Task HandleNotifyAsync_Should_ReturnNeutral_When_NoMailIsAddressedT [Fact] public async Task HandleNotifyAsync_Should_QueueTheDigestJson_When_UnreadMailExistsForTheClaimedActor() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); var message = await SendMailAsync("bob", actor, cancellationToken); + // act var outcome = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); + // assert Assert.True(outcome.Queued); var call = Assert.Single(_queueClient.Calls); Assert.Equal(SessionId, call.ThreadId); @@ -505,14 +587,8 @@ public async Task HandleNotifyAsync_Should_QueueTheInboxPointer_When_MailWasSeen await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); var message = await SendMailAsync("bob", actor, cancellationToken); - var generation = CurrentGeneration(); await _ledger.ReserveAsync( - generation.Harness, - generation.SessionId, - [message.Id], - AgentSessionChannel.Ping, - _timeProvider.GetUtcNow(), - cancellationToken); + actor, [message.Id], AgentSessionChannel.Ping, _timeProvider.GetUtcNow(), cancellationToken); // act var outcome = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); @@ -534,7 +610,6 @@ public async Task HandleNotifyAsync_Should_NotReQueue_When_TheQueuedDigestsOwnDe await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); - var first = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); Assert.True(first.Queued); @@ -549,16 +624,19 @@ public async Task HandleNotifyAsync_Should_NotReQueue_When_TheQueuedDigestsOwnDe [Fact] public async Task HandleNotifyAsync_Should_QueueAgain_When_NewMailArrivesAfterAnEarlierQueue() { + // arrange // A new message remains eligible after an earlier message was queued. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); - await SendMailAsync("carol", actor, cancellationToken); + + // act var outcome = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); + // assert Assert.True(outcome.Queued); Assert.Equal(2, _queueClient.Calls.Count); } @@ -566,22 +644,47 @@ public async Task HandleNotifyAsync_Should_QueueAgain_When_NewMailArrivesAfterAn [Fact] public async Task HandleNotifyAsync_Should_ReturnNeutral_When_QueueClientFails() { + // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); _queueClient.NextResult = CodexQueueResult.Error; - var outcome = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); - Assert.False(outcome.Queued); + // act // Retry the same message after the failed queue attempt. var retried = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); + + // assert Assert.Equal(CodexNotifyOutcome.Neutral, retried); Assert.Single(_queueClient.Calls); } + [Fact] + public async Task HandleNotifyAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleNotifyAsync(NotifyPayload(SessionId), cancellationToken); + + // assert + Assert.Equal(CodexNotifyOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(_queueClient.Calls); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + // ---------- helpers ---------- private CodexHookPayload Payload(string sessionId) => new() { SessionId = sessionId, Cwd = _workspaceRoot }; @@ -597,34 +700,102 @@ private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) } private async Task SendMailAsync(string sender, string recipient, CancellationToken cancellationToken) - => await _mail.SendMessageAsync( + { + // Registers the mail sender behind the store's sender-usability check. + await SeedAgentAsync(sender, cancellationToken); + + return await _mail.SendMessageAsync( new MailMessageCreation { Sender = sender, Subject = "status", Body = "please check", To = [recipient] }, cancellationToken); + } private async Task StartAndGetActorAsync(CancellationToken cancellationToken) { await _handler.HandleSessionStartAsync(Payload(SessionId), cancellationToken); var row = await FindRowAsync(cancellationToken); - return row!.AgentName!; + return row!.Name; } - private async Task FindRowAsync(CancellationToken cancellationToken) - => await _sessions.FindByGenerationAsync(CurrentGeneration(), cancellationToken); + private Task FindRowAsync(CancellationToken cancellationToken) + => _agentStore.FindBySessionAsync(AgentSessionHarness.Codex, SessionId, cancellationToken); - private async Task CountAllSessionRowsAsync(CancellationToken cancellationToken) + private async Task CountAllAgentRowsAsync(CancellationToken cancellationToken) { await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT COUNT(*) FROM agent_sessions;"; + command.CommandText = "SELECT COUNT(*) FROM agents;"; return Convert.ToInt64(await command.ExecuteScalarAsync(cancellationToken)); } - private static AgentSessionGeneration CurrentGeneration() => new( - AgentSessionHarness.Codex, - SessionId, - "host-1"); + /// + /// Registers the named agent directly against the unified agents table. + /// + private async Task SeedAgentAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Marks the named agent as soft-deleted. + /// + private async Task MarkDeletedAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET deleted_at = @now WHERE name = @name"; + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Hard-deletes the named agent's row, freeing it for the actor allocator to draw again. + /// + private async Task DeleteAgentRowAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM agents WHERE name = @name"; + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Tombstones every pool name except , forcing the actor + /// allocator to draw that one name for the next mint. + /// + private async Task TombstoneOtherPoolNamesAsync(string keep, CancellationToken cancellationToken) + { + var now = _timeProvider.GetUtcNow(); + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + "INSERT INTO agents (name, registered_at, started_at, last_seen_at, deleted_at) " + + "VALUES (@name, @now, @now, @now, @now)"; + var nameParameter = command.Parameters.Add("@name", SqliteType.Text); + command.Parameters.AddWithValue("@now", now); + + foreach (var name in AgentActorAllocator.BaseActors.Where(name => name != keep)) + { + nameParameter.Value = name; + await command.ExecuteNonQueryAsync(cancellationToken); + } + } } internal sealed class FakeCodexQueueClient : ICodexQueueClient diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/IncrementNeverMatchesAgentSessionRegistry.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/IncrementNeverMatchesAgentSessionRegistry.cs deleted file mode 100644 index 1ef1fd70b88..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/IncrementNeverMatchesAgentSessionRegistry.cs +++ /dev/null @@ -1,102 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -/// -/// Delegates to except for -/// , which returns null without updating the session. -/// -internal sealed class IncrementNeverMatchesAgentSessionRegistry(IAgentSessionRegistry inner) : IAgentSessionRegistry -{ - public Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? envActor, - CancellationToken cancellationToken) - => inner.StartAsync(generation, cwd, workspacePath, endpointKind, endpointAddr, envActor, cancellationToken); - - public Task ClaimAsync( - AgentSessionGeneration generation, string actor, bool forceRebind, CancellationToken cancellationToken) - => inner.ClaimAsync(generation, actor, forceRebind, cancellationToken); - - public Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.EndAsync(generation, cancellationToken); - - public Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.FindByGenerationAsync(generation, cancellationToken); - - public Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ResetBlockBudgetAsync(generation, cancellationToken); - - public Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => Task.FromResult(null); - - public Task> ReapAsync(CancellationToken cancellationToken) - => inner.ReapAsync(cancellationToken); - - public Task> ListAsync(CancellationToken cancellationToken) - => inner.ListAsync(cancellationToken); - - public Task> ListParticipantsAsync(CancellationToken cancellationToken) - => inner.ListParticipantsAsync(cancellationToken); - - public Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.TouchAsync(generation, cancellationToken); - - public Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - => inner.RecordHarnessVersionAsync(generation, harnessVersion, cancellationToken); - - public Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - => inner.SetRoleAsync(generation, role, cancellationToken); - - public Task RegisterAsync( - AgentSessionGeneration generation, - string actor, - string role, - string client, - bool forceRebind, - CancellationToken cancellationToken) - => inner.RegisterAsync(generation, actor, role, client, forceRebind, cancellationToken); - - public Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - => inner.FindBySessionIdAsync(harness, host, sessionId, cancellationToken); - - public Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - => inner.FindLiveClaimedByAgentNameAsync(agentName, cancellationToken); - - public Task TryClaimPingCooldownAsync( - AgentSessionRecord session, - string attemptId, - DateTimeOffset now, - TimeSpan cooldown, - CancellationToken cancellationToken) - => inner.TryClaimPingCooldownAsync(session, attemptId, now, cooldown, cancellationToken); - - public Task WritePingResultAsync( - string harness, - string sessionId, - string attemptId, - string result, - string? detail, - CancellationToken cancellationToken) - => inner.WritePingResultAsync(harness, sessionId, attemptId, result, detail, cancellationToken); - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ArmAnnouncementAsync(generation, cancellationToken); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimAnnouncementAsync(generation, cancellationToken); - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.RearmIdlePushAsync(generation, cancellationToken); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimIdlePushAsync(generation, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/IncrementNeverMatchesAgentStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/IncrementNeverMatchesAgentStore.cs new file mode 100644 index 00000000000..d521b9761cc --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/IncrementNeverMatchesAgentStore.cs @@ -0,0 +1,85 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Hook; + +/// +/// Delegates to except for +/// , which returns 0 without updating the row. +/// +internal sealed class IncrementNeverMatchesAgentStore(IAgentStore inner) : IAgentStore +{ + public Task LoginAsync(CancellationToken cancellationToken) + => inner.LoginAsync(cancellationToken); + + public Task StartSessionAsync( + AgentSessionStartRequest request, CancellationToken cancellationToken) + => inner.StartSessionAsync(request, cancellationToken); + + public Task TouchSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.TouchSessionAsync(harness, sessionId, cancellationToken); + + public Task TouchAsync(string name, CancellationToken cancellationToken) + => inner.TouchAsync(name, cancellationToken); + + public Task EndSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.EndSessionAsync(harness, sessionId, cancellationToken); + + public Task SetRoleAsync(string name, string role, CancellationToken cancellationToken) + => inner.SetRoleAsync(name, role, cancellationToken); + + public Task FindAsync(string name, CancellationToken cancellationToken) + => inner.FindAsync(name, cancellationToken); + + public Task FindBySessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.FindBySessionAsync(harness, sessionId, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken) + => inner.ListAsync(cancellationToken); + + public Task SetEndpointAsync( + string name, + string endpointKind, + string endpointAddr, + string? endpointSecret, + CancellationToken cancellationToken) + => inner.SetEndpointAsync(name, endpointKind, endpointAddr, endpointSecret, cancellationToken); + + public Task ResetBlockBudgetAsync(string name, CancellationToken cancellationToken) + => inner.ResetBlockBudgetAsync(name, cancellationToken); + + public Task IncrementBlockBudgetAsync(string name, CancellationToken cancellationToken) + => Task.FromResult(0); + + public Task TryClaimPingCooldownAsync( + string name, TimeSpan cooldown, string attemptId, CancellationToken cancellationToken) + => inner.TryClaimPingCooldownAsync(name, cooldown, attemptId, cancellationToken); + + public Task WritePingResultAsync( + string name, string attemptId, string result, string? detail, CancellationToken cancellationToken) + => inner.WritePingResultAsync(name, attemptId, result, detail, cancellationToken); + + public Task ArmAnnouncementAsync(string name, CancellationToken cancellationToken) + => inner.ArmAnnouncementAsync(name, cancellationToken); + + public Task ClaimAnnouncementAsync(string name, CancellationToken cancellationToken) + => inner.ClaimAnnouncementAsync(name, cancellationToken); + + public Task IsAnnouncementPendingAsync(string name, CancellationToken cancellationToken) + => inner.IsAnnouncementPendingAsync(name, cancellationToken); + + public Task RearmIdlePushAsync(string name, CancellationToken cancellationToken) + => inner.RearmIdlePushAsync(name, cancellationToken); + + public Task ClaimIdlePushAsync(string name, CancellationToken cancellationToken) + => inner.ClaimIdlePushAsync(name, cancellationToken); + + public Task RecordHarnessVersionAsync( + string name, string harnessVersion, CancellationToken cancellationToken) + => inner.RecordHarnessVersionAsync(name, harnessVersion, cancellationToken); + + public Task DeleteAsync(string name, CancellationToken cancellationToken) + => inner.DeleteAsync(name, cancellationToken); + + public Task DeleteInactiveAsync(CancellationToken cancellationToken) + => inner.DeleteInactiveAsync(cancellationToken); +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookExecutorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookExecutorTests.cs index 9270bc35e0b..3486e294f3f 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookExecutorTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookExecutorTests.cs @@ -1,7 +1,6 @@ using ChilliCream.Nitro.CommandLine.Services.Hook; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Time.Testing; @@ -190,26 +189,12 @@ public async Task RunAsync_Should_WriteNeutral_When_TheDatabaseIsContended() var fileSystem = new TestFileSystem(workspaceRoot); var timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); var database = new AgentDatabase(); - var agentRegistry = new AgentRegistry(fileSystem, timeProvider, database); - var sessions = new AgentSessionRegistry( - fileSystem, - timeProvider, - database, - agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); - var ledger = new SessionDeliveryLedger(fileSystem, database); - var mail = new MailStore(fileSystem, timeProvider, database, agentRegistry); + var agentStore = new AgentStore(fileSystem, timeProvider, database); + var ledger = new AgentDeliveryLedger(fileSystem, database); + var mail = new MailStore(fileSystem, timeProvider, database, agentStore); var environmentVariables = new FixedEnvironmentVariableProvider(); var handler = new OpencodeHookHandler( - fileSystem, - timeProvider, - sessions, - ledger, - mail, - environmentVariables, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); + fileSystem, timeProvider, agentStore, ledger, mail, environmentVariables); await using (await database.InitializeAsync(workspaceDirectory, cancellationToken)) { @@ -230,7 +215,7 @@ public async Task RunAsync_Should_WriteNeutral_When_TheDatabaseIsContended() await using (var lockCommand = lockConnection.CreateCommand()) { lockCommand.Transaction = lockTransaction; - lockCommand.CommandText = "UPDATE agent_sessions SET last_beat_at = last_beat_at;"; + lockCommand.CommandText = "UPDATE agents SET last_seen_at = last_seen_at;"; await lockCommand.ExecuteNonQueryAsync(cancellationToken); } @@ -277,25 +262,11 @@ public async Task RunAsync_Should_WriteNeutral_When_SchemaVersionIsNewerThanSupp var fileSystem = new TestFileSystem(workspaceRoot); var timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); var database = new AgentDatabase(); - var agentRegistry = new AgentRegistry(fileSystem, timeProvider, database); - var sessions = new AgentSessionRegistry( - fileSystem, - timeProvider, - database, - agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); - var ledger = new SessionDeliveryLedger(fileSystem, database); - var mail = new MailStore(fileSystem, timeProvider, database, agentRegistry); + var agentStore = new AgentStore(fileSystem, timeProvider, database); + var ledger = new AgentDeliveryLedger(fileSystem, database); + var mail = new MailStore(fileSystem, timeProvider, database, agentStore); var handler = new OpencodeHookHandler( - fileSystem, - timeProvider, - sessions, - ledger, - mail, - new FixedEnvironmentVariableProvider(), - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(workspaceRoot)); + fileSystem, timeProvider, agentStore, ledger, mail, new FixedEnvironmentVariableProvider()); await using (await database.InitializeAsync(workspaceDirectory, cancellationToken)) { diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookHandlerTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookHandlerTests.cs index c0ae6cb91d8..1c1ec5d26e2 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookHandlerTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/OpencodeHookHandlerTests.cs @@ -2,7 +2,6 @@ using ChilliCream.Nitro.CommandLine.Services.Hook; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using Microsoft.Extensions.Time.Testing; namespace ChilliCream.Nitro.CommandLine.Tests.Hook; @@ -20,9 +19,8 @@ public sealed class OpencodeHookHandlerTests : IDisposable private readonly TestFileSystem _fileSystem; private readonly FakeTimeProvider _timeProvider; private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; - private readonly SessionDeliveryLedger _ledger; + private readonly AgentStore _agentStore; + private readonly AgentDeliveryLedger _ledger; private readonly MailStore _mail; private readonly FixedEnvironmentVariableProvider _environmentVariables; private readonly OpencodeHookHandler _handler; @@ -36,30 +34,29 @@ public OpencodeHookHandlerTests() _fileSystem = new TestFileSystem(_workspaceRoot); _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, _timeProvider, _database); - _sessions = new AgentSessionRegistry( - _fileSystem, - _timeProvider, - _database, - _agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); - _ledger = new SessionDeliveryLedger(_fileSystem, _database); - _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentRegistry); + _agentStore = new AgentStore(_fileSystem, _timeProvider, _database); + _ledger = new AgentDeliveryLedger(_fileSystem, _database); + _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentStore); _environmentVariables = new FixedEnvironmentVariableProvider(); - _handler = new OpencodeHookHandler( - _fileSystem, - _timeProvider, - _sessions, - _ledger, - _mail, - _environmentVariables, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); + _handler = CreateHandler(); } public void Dispose() => _tempRoot.Delete(recursive: true); + private OpencodeHookHandler CreateHandler() => new( + _fileSystem, _timeProvider, _agentStore, _ledger, _mail, _environmentVariables); + + private OpencodeHookHandler CreateHandler(IAgentDeliveryLedger ledger) => new( + _fileSystem, _timeProvider, _agentStore, ledger, _mail, _environmentVariables); + + private OpencodeHookHandler CreateHandler(IAgentStore agentStore) => new( + _fileSystem, _timeProvider, agentStore, _ledger, _mail, _environmentVariables); + + private OpencodeHookHandler CreateHandler(IAgentStore agentStore, IAgentDeliveryLedger ledger) => new( + _fileSystem, _timeProvider, agentStore, ledger, _mail, _environmentVariables); + + // ---------- SessionCreated ---------- + [Fact] public async Task HandleSessionCreatedAsync_Should_StoreTheOpencodeEndpointVersionAndPassword() { @@ -79,6 +76,24 @@ public async Task HandleSessionCreatedAsync_Should_StoreTheOpencodeEndpointVersi Assert.Equal("1.18.25", row.HarnessVersion); } + [Fact] + public async Task HandleSessionCreatedAsync_Should_ReuseTheSameAgent_When_CalledAgainForTheSameSession() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); + var actor = (await FindRowAsync(cancellationToken))!.Name; + + // act + await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert + var row = await FindRowAsync(cancellationToken); + Assert.Equal(actor, row!.Name); + Assert.Equal(1L, await CountAllAgentRowsAsync(cancellationToken)); + } + /// /// A session reporting serverBound: false registers no push endpoint /// and leaves the idle-push gate unarmed. @@ -101,19 +116,51 @@ public async Task HandleSessionCreatedAsync_Should_RejectThePlaceholderServerUrl Assert.NotNull(row); Assert.Equal(AgentSessionEndpointKind.None, row.EndpointKind); Assert.Equal(string.Empty, row.EndpointAddr); - Assert.Null(row.EndpointSecret); + Assert.False(await _agentStore.ClaimIdlePushAsync(row.Name, cancellationToken)); + Assert.True(await _agentStore.IsAnnouncementPendingAsync(row.Name, cancellationToken)); + } + + [Fact] + public async Task HandleSessionCreatedAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var outcome = await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert - Assert.False(await _sessions.ClaimIdlePushAsync(CurrentGeneration(), cancellationToken)); + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + + [Fact] + public async Task HandleSessionCreatedAsync_Should_ReturnNeutralWithoutCreatingARow_When_TheServerUrlIsMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var payload = Payload(SessionId); + payload.ServerUrl = null; + + // act + var outcome = await _handler.HandleSessionCreatedAsync(payload, dryRun: true, cancellationToken); // assert - Assert.True(await _sessions.IsAnnouncementPendingAsync(CurrentGeneration(), cancellationToken)); + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + Assert.Equal(0L, await CountAllAgentRowsAsync(cancellationToken)); } - /// - /// A session demoted to endpoint_kind = 'none' at session.created must stay unarmed for the - /// idle-push gate even after a genuine chat message. - /// + // ---------- ChatMessage ---------- + [Fact] public async Task HandleChatMessageAsync_Should_NotArmIdlePush_When_EndpointIsUntrusted() { @@ -124,12 +171,13 @@ public async Task HandleChatMessageAsync_Should_NotArmIdlePush_When_EndpointIsUn untrustedPayload.ServerUrl = "http://localhost:4096/"; untrustedPayload.ServerBound = false; await _handler.HandleSessionCreatedAsync(untrustedPayload, dryRun: true, cancellationToken); + var actor = (await FindRowAsync(cancellationToken))!.Name; // act await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert - Assert.False(await _sessions.ClaimIdlePushAsync(CurrentGeneration(), cancellationToken)); + Assert.False(await _agentStore.ClaimIdlePushAsync(actor, cancellationToken)); } [Fact] @@ -169,13 +217,14 @@ public async Task HandleChatMessageAsync_Should_AppendTheUnreadMailDigest() } [Fact] - public async Task HandleChatMessageAsync_Should_ResetThePerTurnBudget() + public async Task HandleChatMessageAsync_Should_ResetThePerTurnBudget_When_AGenuineChatMessageArrives() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); - await _sessions.IncrementBlockBudgetAsync(CurrentGeneration(), cancellationToken); + var actor = (await FindRowAsync(cancellationToken))!.Name; + await _agentStore.IncrementBlockBudgetAsync(actor, cancellationToken); // act await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); @@ -185,25 +234,6 @@ public async Task HandleChatMessageAsync_Should_ResetThePerTurnBudget() Assert.Equal(0, row!.BlockBudgetUsed); } - [Fact] - public async Task HandleSessionIdleAsync_Should_NotSpendTheIdlePushArmedFlag_When_ItArrivesBeforeTheDaemon() - { - // arrange - // Session creation arms the idle-push gate before the idle event. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var actor = await StartAndGetActorAsync(cancellationToken); - await SendMailAsync("bob", actor, cancellationToken); - - // act - // Handle the idle event before claiming the push gate. - var outcome = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); - - // assert - Assert.Equal(OpencodeHookOutcome.Neutral, outcome); - Assert.True(await _sessions.ClaimIdlePushAsync(CurrentGeneration(), cancellationToken)); - } - [Fact] public async Task HandleChatMessageAsync_Should_NotRearmOrAppendParts_When_TheMessageWasPushedByNitro() { @@ -213,13 +243,12 @@ public async Task HandleChatMessageAsync_Should_NotRearmOrAppendParts_When_TheMe var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); - await _sessions.IncrementBlockBudgetAsync(CurrentGeneration(), cancellationToken); + await _agentStore.IncrementBlockBudgetAsync(actor, cancellationToken); var pushedPayload = Payload(SessionId); pushedPayload.NitroPushed = true; // act - var pushed = await _handler.HandleChatMessageAsync( - pushedPayload, dryRun: true, cancellationToken); + var pushed = await _handler.HandleChatMessageAsync(pushedPayload, dryRun: true, cancellationToken); await SendMailAsync("carol", actor, cancellationToken); var idle = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); @@ -230,98 +259,107 @@ public async Task HandleChatMessageAsync_Should_NotRearmOrAppendParts_When_TheMe } [Fact] - public async Task HandleSessionIdleAsync_Should_SkipTheHeartbeatTouch_When_HooksAreSuppressed() + public async Task HandleChatMessageAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await StartAndGetActorAsync(cancellationToken); - var beforeSuppressed = (await FindRowAsync(cancellationToken))!.LastBeatAt; - _environmentVariables.Set("NITRO_HOOK_SUPPRESS", "1"); - _timeProvider.Advance(TimeSpan.FromMinutes(1)); + var actor = await StartAndGetActorAsync(cancellationToken); + var message = await SendMailAsync("bob", actor, cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); // act - var suppressed = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); + var outcome = await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert - Assert.Equal(OpencodeHookOutcome.Neutral, suppressed); - Assert.Equal(beforeSuppressed, (await FindRowAsync(cancellationToken))!.LastBeatAt); + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); + Assert.Empty(await _ledger.FindDeliveredAsync(actor, [message.Id], cancellationToken)); + } + + [Fact] + public async Task HandleChatMessageAsync_Should_ReturnNeutralWithoutMinting_When_TheSessionIsUnknown() + { + // arrange + // Today's OpenCode behavior, unchanged: chat-message never mints a fresh agent. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); // act - _environmentVariables.Set("NITRO_HOOK_SUPPRESS", "0"); - var resumed = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); + var outcome = await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert - Assert.Equal(OpencodeHookOutcome.Neutral, resumed); - Assert.Equal(_timeProvider.GetUtcNow(), (await FindRowAsync(cancellationToken))!.LastBeatAt); + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + Assert.Null(await FindRowAsync(cancellationToken)); } [Fact] - public async Task HandleChatMessageAsync_Should_RemainNeutral_When_TheSessionIsDeletedBeforeReservation() + public async Task HandleSessionIdleAsync_Should_NotSpendTheIdlePushArmedFlag_When_ItArrivesBeforeTheDaemon() { // arrange - // Claim the announcement before injecting deletion during digest reservation. + // Session creation arms the idle-push gate before the idle event. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); - await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); await SendMailAsync("bob", actor, cancellationToken); - var handler = CreateHandler(new SessionDeletingDeliveryLedger(_ledger, _sessions, CurrentGeneration())); // act - var outcome = await handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); + // Handle the idle event before claiming the push gate. + var outcome = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert Assert.Equal(OpencodeHookOutcome.Neutral, outcome); - Assert.Null(await FindRowAsync(cancellationToken)); + Assert.True(await _agentStore.ClaimIdlePushAsync(actor, cancellationToken)); } [Fact] - public async Task HandleChatMessageAsync_Should_RemainNeutral_When_TheSessionWasReplacedBeforeTouch() + public async Task HandleSessionIdleAsync_Should_SkipTheHeartbeatTouch_When_HooksAreSuppressed() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); - await _sessions.StartAsync( - new AgentSessionGeneration(AgentSessionHarness.Opencode, SessionId, "host-2"), - _workspaceRoot, - _workspaceDirectory, - AgentSessionEndpointKind.OpencodeServer, - "http://127.0.0.1:4096", - endpointSecret: null, - envActor: null, - cancellationToken); + await StartAndGetActorAsync(cancellationToken); + var beforeSuppressed = (await FindRowAsync(cancellationToken))!.LastSeenAt; + _environmentVariables.Set("NITRO_HOOK_SUPPRESS", "1"); + _timeProvider.Advance(TimeSpan.FromMinutes(1)); // act - var outcome = await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); + var suppressed = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert - Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + Assert.Equal(OpencodeHookOutcome.Neutral, suppressed); + Assert.Equal(beforeSuppressed, (await FindRowAsync(cancellationToken))!.LastSeenAt); + + // act + _environmentVariables.Set("NITRO_HOOK_SUPPRESS", "0"); + var resumed = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert + Assert.Equal(OpencodeHookOutcome.Neutral, resumed); + Assert.Equal(_timeProvider.GetUtcNow(), (await FindRowAsync(cancellationToken))!.LastSeenAt); } [Fact] - public async Task HandleSessionIdleAsync_Should_RemainNeutral_When_TheSessionWasReplacedBeforeTouch() + public async Task HandleSessionIdleAsync_Should_ReturnNeutralWithoutWriting_When_TheSessionBelongsToADeletedAgent() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); - await _sessions.StartAsync( - new AgentSessionGeneration(AgentSessionHarness.Opencode, SessionId, "host-2"), - _workspaceRoot, - _workspaceDirectory, - AgentSessionEndpointKind.OpencodeServer, - "http://127.0.0.1:4096", - endpointSecret: null, - envActor: null, - cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + var before = await FindRowAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); // act var outcome = await _handler.HandleSessionIdleAsync(Payload(SessionId), dryRun: true, cancellationToken); // assert Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + var after = await FindRowAsync(cancellationToken); + Assert.Equal(before!.LastSeenAt, after!.LastSeenAt); } [Fact] @@ -340,12 +378,18 @@ await Assert.ThrowsAsync( () => handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken)); // assert - Assert.True(await _sessions.IsAnnouncementPendingAsync(CurrentGeneration(), cancellationToken)); + Assert.True(await _agentStore.IsAnnouncementPendingAsync(actor, cancellationToken)); - // assert + // act var retry = await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert Assert.Contains("Your Nitro actor name is", retry.Parts[0]); + + // act var again = await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert Assert.Equal(OpencodeHookOutcome.Neutral, again); } @@ -358,7 +402,7 @@ public async Task HandleChatMessageAsync_Should_RestoreTheDigestReservation_When await InitializeWorkspaceAsync(cancellationToken); var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); - var handler = CreateHandler(new ThrowingAnnouncementSessionRegistry(_sessions)); + var handler = CreateHandler(new ThrowingAnnouncementAgentStore(_agentStore)); // act await Assert.ThrowsAsync( @@ -383,8 +427,8 @@ public async Task HandleChatMessageAsync_Should_ReleaseOnlyThisTurnsReservations var b = await SendMailAsync("bob", actor, cancellationToken); var c = await SendMailAsync("bob", actor, cancellationToken); await _ledger.ReserveAsync( - CurrentGeneration(), [c.Id], AgentSessionChannel.Digest, _timeProvider.GetUtcNow(), cancellationToken); - var handler = CreateHandler(new ThrowingAnnouncementSessionRegistry(_sessions)); + actor, [c.Id], AgentSessionChannel.Digest, _timeProvider.GetUtcNow(), cancellationToken); + var handler = CreateHandler(new ThrowingAnnouncementAgentStore(_agentStore)); // act await Assert.ThrowsAsync( @@ -393,17 +437,13 @@ await Assert.ThrowsAsync( // assert // This turn's reservations can be acquired again. var reReservedAb = await _ledger.ReserveAsync( - CurrentGeneration(), - [a.Id, b.Id], - AgentSessionChannel.Digest, - _timeProvider.GetUtcNow(), - cancellationToken); + actor, [a.Id, b.Id], AgentSessionChannel.Digest, _timeProvider.GetUtcNow(), cancellationToken); Assert.Equal(2, reReservedAb.Count); // assert // The earlier reservation remains held. var reReservedC = await _ledger.ReserveAsync( - CurrentGeneration(), [c.Id], AgentSessionChannel.Digest, _timeProvider.GetUtcNow(), cancellationToken); + actor, [c.Id], AgentSessionChannel.Digest, _timeProvider.GetUtcNow(), cancellationToken); Assert.Empty(reReservedC); } @@ -417,7 +457,7 @@ public async Task HandleChatMessageAsync_Should_StillReleaseTheDigestReservation var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var handler = CreateHandler(new CancellingAnnouncementSessionRegistry(_sessions, cts)); + var handler = CreateHandler(new CancellingAnnouncementAgentStore(_agentStore, cts)); // act await Assert.ThrowsAnyAsync( @@ -441,7 +481,7 @@ public async Task HandleChatMessageAsync_Should_PropagateTheOriginalException_Wh var actor = await StartAndGetActorAsync(cancellationToken); await SendMailAsync("bob", actor, cancellationToken); var handler = CreateHandler( - new ThrowingAnnouncementSessionRegistry(_sessions), new ReleaseThrowingDeliveryLedger(_ledger)); + new ThrowingAnnouncementAgentStore(_agentStore), new ReleaseThrowingDeliveryLedger(_ledger)); // act var exception = await Assert.ThrowsAsync( @@ -512,7 +552,7 @@ public async Task HandleChatMessageAsync_Should_NotAnnounceAgain_When_ADelivered // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await StartAndGetActorAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); await _handler.HandleChatMessageAsync(Payload(SessionId), dryRun: true, cancellationToken); var deliveredPayload = Payload(SessionId); deliveredPayload.Delivered = true; @@ -531,7 +571,7 @@ public async Task HandleChatMessageAsync_Should_NotAnnounceAgain_When_ADelivered // assert Assert.Equal(OpencodeHookOutcome.Neutral, again); - Assert.False(await _sessions.IsAnnouncementPendingAsync(CurrentGeneration(), cancellationToken)); + Assert.False(await _agentStore.IsAnnouncementPendingAsync(actor, cancellationToken)); } [Fact] @@ -558,7 +598,7 @@ public async Task HandleChatMessageAsync_Should_ReleaseTheDigestReservation_When } [Fact] - public async Task HandleChatMessageAsync_Should_AnnounceAgain_When_TheSessionIsCreatedAfterDeletion() + public async Task HandleChatMessageAsync_Should_AnnounceAgain_When_TheSessionIsCreatedAfterEnding() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -576,6 +616,58 @@ public async Task HandleChatMessageAsync_Should_AnnounceAgain_When_TheSessionIsC Assert.Contains("Your Nitro actor name is", announcement); } + // ---------- SessionDeleted ---------- + + [Fact] + public async Task HandleSessionDeletedAsync_Should_StampEndedAtAndKeepTheRow_When_TheSessionIsActive() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // act + var outcome = await _handler.HandleSessionDeletedAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + var row = await FindRowAsync(cancellationToken); + Assert.NotNull(row); + Assert.NotNull(row.EndedAt); + } + + [Fact] + public async Task HandleSessionDeletedAsync_Should_ReturnNeutral_When_NoRowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + + // act + var outcome = await _handler.HandleSessionDeletedAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + } + + [Fact] + public async Task HandleSessionDeletedAsync_Should_ReturnNeutralWithoutClearingDeletedAt_When_TheSessionBelongsToADeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await StartAndGetActorAsync(cancellationToken); + await MarkDeletedAsync(actor, cancellationToken); + + // act + var outcome = await _handler.HandleSessionDeletedAsync(Payload(SessionId), dryRun: true, cancellationToken); + + // assert + Assert.Equal(OpencodeHookOutcome.Neutral, outcome); + var row = await FindRowAsync(cancellationToken); + Assert.Null(row!.EndedAt); + } + [Fact] public void OpencodeHookPayload_Should_ReadTheShimFieldNames() { @@ -593,6 +685,8 @@ public void OpencodeHookPayload_Should_ReadTheShimFieldNames() Assert.Equal("1.18.25", payload.HarnessVersion); } + // ---------- helpers ---------- + private OpencodeHookPayload Payload(string sessionId) => new() { SessionId = sessionId, @@ -603,37 +697,6 @@ public void OpencodeHookPayload_Should_ReadTheShimFieldNames() ServerBound = true }; - private OpencodeHookHandler CreateHandler(ISessionDeliveryLedger ledger) => new( - _fileSystem, - _timeProvider, - _sessions, - ledger, - _mail, - _environmentVariables, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); - - private OpencodeHookHandler CreateHandler(IAgentSessionRegistry sessionRegistry) => new( - _fileSystem, - _timeProvider, - sessionRegistry, - _ledger, - _mail, - _environmentVariables, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); - - private OpencodeHookHandler CreateHandler( - IAgentSessionRegistry sessionRegistry, ISessionDeliveryLedger ledger) => new( - _fileSystem, - _timeProvider, - sessionRegistry, - ledger, - _mail, - _environmentVariables, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workspaceRoot)); - private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) { await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) @@ -646,19 +709,61 @@ private async Task StartAndGetActorAsync(CancellationToken cancellationT await _handler.HandleSessionCreatedAsync(Payload(SessionId), dryRun: true, cancellationToken); var row = await FindRowAsync(cancellationToken); - return row!.AgentName!; + return row!.Name; } - private Task SendMailAsync(string sender, string recipient, CancellationToken cancellationToken) - => _mail.SendMessageAsync( + private async Task SendMailAsync(string sender, string recipient, CancellationToken cancellationToken) + { + // Registers the mail sender behind the store's sender-usability check. + await SeedAgentAsync(sender, cancellationToken); + + return await _mail.SendMessageAsync( new MailMessageCreation { Sender = sender, Subject = "status", Body = "please check", To = [recipient] }, cancellationToken); + } + + private Task FindRowAsync(CancellationToken cancellationToken) + => _agentStore.FindBySessionAsync(AgentSessionHarness.Opencode, SessionId, cancellationToken); + + private async Task CountAllAgentRowsAsync(CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM agents;"; - private Task FindRowAsync(CancellationToken cancellationToken) - => _sessions.FindByGenerationAsync(CurrentGeneration(), cancellationToken); + return Convert.ToInt64(await command.ExecuteScalarAsync(cancellationToken)); + } + + /// + /// Registers the named agent directly against the unified agents table. + /// + private async Task SeedAgentAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } - private static AgentSessionGeneration CurrentGeneration() => new( - AgentSessionHarness.Opencode, - SessionId, - "host-1"); + /// + /// Marks the named agent as soft-deleted. + /// + private async Task MarkDeletedAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET deleted_at = @now WHERE name = @name"; + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReleaseThrowingDeliveryLedger.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReleaseThrowingDeliveryLedger.cs index e73d705646e..d4e202e9c90 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReleaseThrowingDeliveryLedger.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReleaseThrowingDeliveryLedger.cs @@ -3,32 +3,24 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Hook; /// -/// Delegates both reservation overloads to . -/// throws . +/// Delegates and to +/// . throws . /// -internal sealed class ReleaseThrowingDeliveryLedger(ISessionDeliveryLedger inner) : ISessionDeliveryLedger +internal sealed class ReleaseThrowingDeliveryLedger(IAgentDeliveryLedger inner) : IAgentDeliveryLedger { - public Task> ReserveAsync( - string harness, - string sessionId, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - => inner.ReserveAsync(harness, sessionId, messageIds, channel, deliveredAt, cancellationToken); + public Task> FindDeliveredAsync( + string agent, IReadOnlyList messageIds, CancellationToken cancellationToken) + => inner.FindDeliveredAsync(agent, messageIds, cancellationToken); public Task> ReserveAsync( - AgentSessionGeneration generation, + string agent, IReadOnlyList messageIds, string channel, DateTimeOffset deliveredAt, CancellationToken cancellationToken) - => inner.ReserveAsync(generation, messageIds, channel, deliveredAt, cancellationToken); + => inner.ReserveAsync(agent, messageIds, channel, deliveredAt, cancellationToken); public Task ReleaseAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - CancellationToken cancellationToken) + string agent, IReadOnlyList messageIds, string channel, CancellationToken cancellationToken) => throw new NotSupportedException("Simulated compensating-release failure."); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReserveCapturingAgentDeliveryLedger.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReserveCapturingAgentDeliveryLedger.cs new file mode 100644 index 00000000000..10e9d950bc8 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReserveCapturingAgentDeliveryLedger.cs @@ -0,0 +1,31 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Hook; + +/// +/// Wraps a real , delegating every call while +/// capturing the messageIds argument of the most recent ReserveAsync call. +/// +internal sealed class ReserveCapturingAgentDeliveryLedger(IAgentDeliveryLedger inner) : IAgentDeliveryLedger +{ + public IReadOnlyList? LastMessageIds { get; private set; } + + public Task> FindDeliveredAsync( + string agent, IReadOnlyList messageIds, CancellationToken cancellationToken) + => inner.FindDeliveredAsync(agent, messageIds, cancellationToken); + + public Task> ReserveAsync( + string agent, + IReadOnlyList messageIds, + string channel, + DateTimeOffset deliveredAt, + CancellationToken cancellationToken) + { + LastMessageIds = messageIds; + return inner.ReserveAsync(agent, messageIds, channel, deliveredAt, cancellationToken); + } + + public Task ReleaseAsync( + string agent, IReadOnlyList messageIds, string channel, CancellationToken cancellationToken) + => inner.ReleaseAsync(agent, messageIds, channel, cancellationToken); +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReserveCapturingSessionDeliveryLedger.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReserveCapturingSessionDeliveryLedger.cs deleted file mode 100644 index d06f8ca6068..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ReserveCapturingSessionDeliveryLedger.cs +++ /dev/null @@ -1,49 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -/// -/// Wraps a real , delegating every call -/// while capturing the messageIds argument of the most recent -/// ReserveAsync call. -/// -internal sealed class ReserveCapturingSessionDeliveryLedger(ISessionDeliveryLedger inner) : ISessionDeliveryLedger -{ - public IReadOnlyList? LastMessageIds { get; private set; } - - public Task> FindDeliveredAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - CancellationToken cancellationToken) - => inner.FindDeliveredAsync(generation, messageIds, cancellationToken); - - public Task> ReserveAsync( - string harness, - string sessionId, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - { - LastMessageIds = messageIds; - return inner.ReserveAsync(harness, sessionId, messageIds, channel, deliveredAt, cancellationToken); - } - - public Task> ReserveAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - { - LastMessageIds = messageIds; - return inner.ReserveAsync(generation, messageIds, channel, deliveredAt, cancellationToken); - } - - public Task ReleaseAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - CancellationToken cancellationToken) - => inner.ReleaseAsync(generation, messageIds, channel, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/SessionDeletingDeliveryLedger.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/SessionDeletingDeliveryLedger.cs deleted file mode 100644 index edc68f136a5..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/SessionDeletingDeliveryLedger.cs +++ /dev/null @@ -1,48 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -internal sealed class SessionDeletingDeliveryLedger( - ISessionDeliveryLedger inner, - IAgentSessionRegistry sessionRegistry, - AgentSessionGeneration generation) : ISessionDeliveryLedger -{ - private bool _deleted; - - public Task> ReserveAsync( - string harness, - string sessionId, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - => inner.ReserveAsync(harness, sessionId, messageIds, channel, deliveredAt, cancellationToken); - - public async Task> ReserveAsync( - AgentSessionGeneration reserveGeneration, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) - { - if (!_deleted) - { - _deleted = true; - await sessionRegistry.EndAsync(generation, cancellationToken); - } - - return await inner.ReserveAsync( - reserveGeneration, - messageIds, - channel, - deliveredAt, - cancellationToken); - } - - public Task ReleaseAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - CancellationToken cancellationToken) - => inner.ReleaseAsync(generation, messageIds, channel, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/SessionDeliveryLedgerTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/SessionDeliveryLedgerTests.cs deleted file mode 100644 index bd15b04b2aa..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/SessionDeliveryLedgerTests.cs +++ /dev/null @@ -1,224 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -/// -/// Tests reservation uniqueness, channel -/// independence, delivery lookup, and session ownership against a real workspace database. -/// -public sealed class SessionDeliveryLedgerTests : IDisposable -{ - private const string Harness = "claude-code"; - private const string SessionId = "session-1"; - private static readonly AgentSessionGeneration s_generation = new(Harness, SessionId, "host-1"); - - private readonly DirectoryInfo _tempRoot; - private readonly string _workspaceDirectory; - private readonly TestFileSystem _fileSystem; - private readonly AgentDatabase _database; - private readonly SessionDeliveryLedger _ledger; - - public SessionDeliveryLedgerTests() - { - _tempRoot = Directory.CreateTempSubdirectory("nitro-session-delivery-ledger-tests"); - _workspaceDirectory = AgentWorkspace.GetDirectory(_tempRoot.FullName); - Directory.CreateDirectory(_workspaceDirectory); - _fileSystem = new TestFileSystem(_tempRoot.FullName); - _database = new AgentDatabase(); - _ledger = new SessionDeliveryLedger(_fileSystem, _database); - } - - public void Dispose() => _tempRoot.Delete(recursive: true); - - [Fact] - public async Task ReserveAsync_Should_ReturnEmpty_When_MessageIdsIsEmpty() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - - // act - // The workspace directory has no initialized database. - var reserved = await _ledger.ReserveAsync( - s_generation, [], "digest", DateTimeOffset.UtcNow, cancellationToken); - - // assert - Assert.Empty(reserved); - } - - [Fact] - public async Task FindDeliveredAsync_Should_ReturnEmpty_When_MessageIdsIsEmpty() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var generation = new AgentSessionGeneration(Harness, SessionId, "host-1"); - - // act - var delivered = await _ledger.FindDeliveredAsync(generation, [], cancellationToken); - - // assert - Assert.Empty(delivered); - } - - [Fact] - public async Task FindDeliveredAsync_Should_ReturnDeliveredMessageIdsInInputOrder_When_DeliveredAcrossChannels() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var generation = new AgentSessionGeneration(Harness, SessionId, "host-1"); - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - await _ledger.ReserveAsync( - Harness, SessionId, ["m-1"], AgentSessionChannel.Digest, DateTimeOffset.UtcNow, cancellationToken); - await _ledger.ReserveAsync( - Harness, SessionId, ["m-2"], AgentSessionChannel.Gate, DateTimeOffset.UtcNow, cancellationToken); - await _ledger.ReserveAsync( - Harness, SessionId, ["m-3"], AgentSessionChannel.Ping, DateTimeOffset.UtcNow, cancellationToken); - - // act - var delivered = await _ledger.FindDeliveredAsync( - generation, ["m-3", "m-missing", "m-1", "m-2"], cancellationToken); - - // assert - Assert.Equal(["m-3", "m-1", "m-2"], delivered); - } - - [Fact] - public async Task FindDeliveredAsync_Should_IgnoreRowsFromDifferentSession() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var generation = new AgentSessionGeneration(Harness, SessionId, "host-1"); - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - await InitializeWorkspaceAndSessionAsync(cancellationToken, "session-2"); - await _ledger.ReserveAsync( - Harness, "session-2", ["m-1"], AgentSessionChannel.Digest, DateTimeOffset.UtcNow, cancellationToken); - - // act - var delivered = await _ledger.FindDeliveredAsync(generation, ["m-1"], cancellationToken); - - // assert - Assert.Empty(delivered); - } - - [Fact] - public async Task ReserveAsync_Should_ReserveEveryNewMessageId() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - - // act - var reserved = await _ledger.ReserveAsync( - s_generation, ["m-1", "m-2", "m-3"], "digest", DateTimeOffset.UtcNow, cancellationToken); - - // assert - Assert.Equal(["m-1", "m-2", "m-3"], reserved); - } - - [Fact] - public async Task ReserveAsync_Should_ExcludeAlreadyReservedMessageId_When_CalledAgain() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - await _ledger.ReserveAsync( - s_generation, ["m-1", "m-2"], "digest", DateTimeOffset.UtcNow, cancellationToken); - - // act - var reserved = await _ledger.ReserveAsync( - s_generation, ["m-1", "m-2", "m-3"], "digest", DateTimeOffset.UtcNow, cancellationToken); - - // assert - Assert.Equal(["m-3"], reserved); - } - - [Fact] - public async Task ReserveAsync_Should_ReserveIndependently_When_ChannelDiffers() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - await _ledger.ReserveAsync( - s_generation, ["m-1"], "digest", DateTimeOffset.UtcNow, cancellationToken); - - // act - var reservedGate = await _ledger.ReserveAsync( - s_generation, ["m-1"], "gate", DateTimeOffset.UtcNow, cancellationToken); - var reservedPing = await _ledger.ReserveAsync( - s_generation, ["m-1"], "ping", DateTimeOffset.UtcNow, cancellationToken); - - // assert - Assert.Equal(["m-1"], reservedGate); - Assert.Equal(["m-1"], reservedPing); - } - - [Fact] - public async Task ReserveAsync_Should_SplitReservationExactlyOnce_When_TwoSimultaneousHandlersRaceTheSameMessage() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - - // act - var results = await ConcurrentTestHarness.RunAsync( - 2, - _ => new SessionDeliveryLedger(_fileSystem, _database) - .ReserveAsync(s_generation, ["m-1"], "gate", DateTimeOffset.UtcNow, cancellationToken)); - - // assert - var totalReserved = results.Sum(r => r.Count); - Assert.Equal(1, totalReserved); - } - - [Fact] - public async Task ReserveAsync_Should_ExcludeAStaleGeneration_When_TheSessionHostWasReplaced() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var replacement = new AgentSessionGeneration(Harness, SessionId, "host-2"); - await InitializeWorkspaceAndSessionAsync(cancellationToken, SessionId); - await ReplaceSessionHostAsync(replacement.Host, cancellationToken); - - // act - var staleReserved = await _ledger.ReserveAsync( - s_generation, ["m-1"], "gate", DateTimeOffset.UtcNow, cancellationToken); - var replacementReserved = await _ledger.ReserveAsync( - replacement, ["m-1"], "gate", DateTimeOffset.UtcNow, cancellationToken); - - // assert - Assert.Empty(staleReserved); - Assert.Equal(["m-1"], replacementReserved); - } - - private async Task InitializeWorkspaceAndSessionAsync(CancellationToken cancellationToken, string sessionId) - { - await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', @sessionId, NULL, 'none', 'host-1', - '/work', '/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00Z', '2026-01-10T12:00:00Z' - ); - """; - - command.Parameters.AddWithValue("@sessionId", sessionId); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - private async Task ReplaceSessionHostAsync(string host, CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET host = @host WHERE harness = @harness AND session_id = @sessionId"; - command.Parameters.AddWithValue("@host", host); - command.Parameters.AddWithValue("@harness", Harness); - command.Parameters.AddWithValue("@sessionId", SessionId); - - await command.ExecuteNonQueryAsync(cancellationToken); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingAnnouncementAgentStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingAnnouncementAgentStore.cs new file mode 100644 index 00000000000..0461b24ad69 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingAnnouncementAgentStore.cs @@ -0,0 +1,85 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Hook; + +/// +/// Delegates to except for +/// , which throws . +/// +internal sealed class ThrowingAnnouncementAgentStore(IAgentStore inner) : IAgentStore +{ + public Task LoginAsync(CancellationToken cancellationToken) + => inner.LoginAsync(cancellationToken); + + public Task StartSessionAsync( + AgentSessionStartRequest request, CancellationToken cancellationToken) + => inner.StartSessionAsync(request, cancellationToken); + + public Task TouchSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.TouchSessionAsync(harness, sessionId, cancellationToken); + + public Task TouchAsync(string name, CancellationToken cancellationToken) + => inner.TouchAsync(name, cancellationToken); + + public Task EndSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.EndSessionAsync(harness, sessionId, cancellationToken); + + public Task SetRoleAsync(string name, string role, CancellationToken cancellationToken) + => inner.SetRoleAsync(name, role, cancellationToken); + + public Task FindAsync(string name, CancellationToken cancellationToken) + => inner.FindAsync(name, cancellationToken); + + public Task FindBySessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + => inner.FindBySessionAsync(harness, sessionId, cancellationToken); + + public Task> ListAsync(CancellationToken cancellationToken) + => inner.ListAsync(cancellationToken); + + public Task SetEndpointAsync( + string name, + string endpointKind, + string endpointAddr, + string? endpointSecret, + CancellationToken cancellationToken) + => inner.SetEndpointAsync(name, endpointKind, endpointAddr, endpointSecret, cancellationToken); + + public Task ResetBlockBudgetAsync(string name, CancellationToken cancellationToken) + => inner.ResetBlockBudgetAsync(name, cancellationToken); + + public Task IncrementBlockBudgetAsync(string name, CancellationToken cancellationToken) + => inner.IncrementBlockBudgetAsync(name, cancellationToken); + + public Task TryClaimPingCooldownAsync( + string name, TimeSpan cooldown, string attemptId, CancellationToken cancellationToken) + => inner.TryClaimPingCooldownAsync(name, cooldown, attemptId, cancellationToken); + + public Task WritePingResultAsync( + string name, string attemptId, string result, string? detail, CancellationToken cancellationToken) + => inner.WritePingResultAsync(name, attemptId, result, detail, cancellationToken); + + public Task ArmAnnouncementAsync(string name, CancellationToken cancellationToken) + => inner.ArmAnnouncementAsync(name, cancellationToken); + + public Task ClaimAnnouncementAsync(string name, CancellationToken cancellationToken) + => throw new InvalidOperationException("Simulated announcement-claim failure."); + + public Task IsAnnouncementPendingAsync(string name, CancellationToken cancellationToken) + => inner.IsAnnouncementPendingAsync(name, cancellationToken); + + public Task RearmIdlePushAsync(string name, CancellationToken cancellationToken) + => inner.RearmIdlePushAsync(name, cancellationToken); + + public Task ClaimIdlePushAsync(string name, CancellationToken cancellationToken) + => inner.ClaimIdlePushAsync(name, cancellationToken); + + public Task RecordHarnessVersionAsync( + string name, string harnessVersion, CancellationToken cancellationToken) + => inner.RecordHarnessVersionAsync(name, harnessVersion, cancellationToken); + + public Task DeleteAsync(string name, CancellationToken cancellationToken) + => inner.DeleteAsync(name, cancellationToken); + + public Task DeleteInactiveAsync(CancellationToken cancellationToken) + => inner.DeleteInactiveAsync(cancellationToken); +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingAnnouncementSessionRegistry.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingAnnouncementSessionRegistry.cs deleted file mode 100644 index c99afaac654..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingAnnouncementSessionRegistry.cs +++ /dev/null @@ -1,102 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Hook; - -/// -/// Delegates to except for -/// , which throws . -/// -internal sealed class ThrowingAnnouncementSessionRegistry(IAgentSessionRegistry inner) : IAgentSessionRegistry -{ - public Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? envActor, - CancellationToken cancellationToken) - => inner.StartAsync(generation, cwd, workspacePath, endpointKind, endpointAddr, envActor, cancellationToken); - - public Task ClaimAsync( - AgentSessionGeneration generation, string actor, bool forceRebind, CancellationToken cancellationToken) - => inner.ClaimAsync(generation, actor, forceRebind, cancellationToken); - - public Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.EndAsync(generation, cancellationToken); - - public Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.FindByGenerationAsync(generation, cancellationToken); - - public Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ResetBlockBudgetAsync(generation, cancellationToken); - - public Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.IncrementBlockBudgetAsync(generation, cancellationToken); - - public Task> ReapAsync(CancellationToken cancellationToken) - => inner.ReapAsync(cancellationToken); - - public Task> ListAsync(CancellationToken cancellationToken) - => inner.ListAsync(cancellationToken); - - public Task> ListParticipantsAsync(CancellationToken cancellationToken) - => inner.ListParticipantsAsync(cancellationToken); - - public Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.TouchAsync(generation, cancellationToken); - - public Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - => inner.RecordHarnessVersionAsync(generation, harnessVersion, cancellationToken); - - public Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - => inner.SetRoleAsync(generation, role, cancellationToken); - - public Task RegisterAsync( - AgentSessionGeneration generation, - string actor, - string role, - string client, - bool forceRebind, - CancellationToken cancellationToken) - => inner.RegisterAsync(generation, actor, role, client, forceRebind, cancellationToken); - - public Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - => inner.FindBySessionIdAsync(harness, host, sessionId, cancellationToken); - - public Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - => inner.FindLiveClaimedByAgentNameAsync(agentName, cancellationToken); - - public Task TryClaimPingCooldownAsync( - AgentSessionRecord session, - string attemptId, - DateTimeOffset now, - TimeSpan cooldown, - CancellationToken cancellationToken) - => inner.TryClaimPingCooldownAsync(session, attemptId, now, cooldown, cancellationToken); - - public Task WritePingResultAsync( - string harness, - string sessionId, - string attemptId, - string result, - string? detail, - CancellationToken cancellationToken) - => inner.WritePingResultAsync(harness, sessionId, attemptId, result, detail, cancellationToken); - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ArmAnnouncementAsync(generation, cancellationToken); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new InvalidOperationException("Simulated announcement-claim failure."); - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.RearmIdlePushAsync(generation, cancellationToken); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimIdlePushAsync(generation, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingDeliveryLedger.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingDeliveryLedger.cs index 72008731793..70e9fa5cef5 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingDeliveryLedger.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Hook/ThrowingDeliveryLedger.cs @@ -3,23 +3,18 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Hook; /// -/// An whose every member throws, used +/// An whose every member throws, used /// to stand in for a mail-store or ledger failure without touching a real /// workspace database. /// -internal sealed class ThrowingDeliveryLedger : ISessionDeliveryLedger +internal sealed class ThrowingDeliveryLedger : IAgentDeliveryLedger { - public Task> ReserveAsync( - string harness, - string sessionId, - IReadOnlyList messageIds, - string channel, - DateTimeOffset deliveredAt, - CancellationToken cancellationToken) + public Task> FindDeliveredAsync( + string agent, IReadOnlyList messageIds, CancellationToken cancellationToken) => throw new InvalidOperationException("Simulated delivery-ledger failure."); public Task> ReserveAsync( - AgentSessionGeneration generation, + string agent, IReadOnlyList messageIds, string channel, DateTimeOffset deliveredAt, @@ -27,9 +22,6 @@ public Task> ReserveAsync( => throw new InvalidOperationException("Simulated delivery-ledger failure."); public Task ReleaseAsync( - AgentSessionGeneration generation, - IReadOnlyList messageIds, - string channel, - CancellationToken cancellationToken) + string agent, IReadOnlyList messageIds, string channel, CancellationToken cancellationToken) => throw new InvalidOperationException("Simulated delivery-ledger failure."); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Mail/MailStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Mail/MailStoreTests.cs index 400d8322e44..2e74bde6885 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Mail/MailStoreTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Mail/MailStoreTests.cs @@ -1,6 +1,5 @@ using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Time.Testing; @@ -13,13 +12,11 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Mail; /// public sealed class MailStoreTests : IAsyncDisposable { - private const string InstanceId = "instance-a"; - private readonly DirectoryInfo _tempRoot; private readonly string _workingDirectory; private readonly string _workspaceDirectory; private readonly FakeTimeProvider _timeProvider; - private readonly AgentRegistry _registry; + private readonly AgentStore _agentStore; private readonly AgentDatabase _database; private readonly MailStore _store; @@ -34,24 +31,50 @@ public MailStoreTests() new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); _database = new AgentDatabase(); - _registry = new AgentRegistry(new TestFileSystem(_workingDirectory), _timeProvider, _database); + _agentStore = new AgentStore(new TestFileSystem(_workingDirectory), _timeProvider, _database); _store = CreateStore(); } /// /// Creates a new bound to this test's file - /// system, clock, database, and registry, with a fixed instance id and - /// global config directory. Concurrency tests create one of these per - /// racing caller. + /// system, clock, database, and agent store. Concurrency tests create + /// one of these per racing caller. /// private MailStore CreateStore() => new( new TestFileSystem(_workingDirectory), _timeProvider, _database, - _registry, - new FixedInstanceIdProvider(InstanceId), - new FixedGlobalConfigDirectoryProvider(_workingDirectory)); + _agentStore); + + /// + /// Marks the named agent as deleted. + /// + private async Task MarkDeletedAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET deleted_at = @now WHERE name = @name"; + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Hard-deletes the named agent's row, so it has no trace left to find. + /// + private async Task DeleteAgentRowAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "DELETE FROM agents WHERE name = @name"; + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } public async ValueTask DisposeAsync() { @@ -71,8 +94,22 @@ private async Task SeedAsync(CancellationToken cancellationTok return await _store.InitializeAsync(_workspaceDirectory, cancellationToken); } - private Task SeedAgentAsync(string name, CancellationToken cancellationToken) - => _registry.RegisterAsync(name, role: "", client: "", cancellationToken); + private async Task SeedAgentAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES ($name, $now, $now, $now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("$name", name); + command.Parameters.AddWithValue("$now", _timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } private Task SendAsync( string sender, @@ -98,8 +135,7 @@ private Task SendAsync( /// Reads one mail_wake_outbox row's generation and due columns /// directly, for asserting the transactional side effect /// has no public read surface for. - /// Returns null when no row exists for (, - /// ). + /// Returns null when no row exists for . /// private async Task<(long RequestedGeneration, long SettledGeneration, DateTimeOffset DueAt)?> ReadOutboxRowAsync( string actor, CancellationToken cancellationToken) @@ -110,9 +146,8 @@ private Task SendAsync( command.CommandText = """ SELECT requested_generation, settled_generation, due_at FROM mail_wake_outbox - WHERE nitro_instance_id = @instanceId AND actor = @actor + WHERE actor = @actor """; - command.Parameters.AddWithValue("@instanceId", InstanceId); command.Parameters.AddWithValue("@actor", actor); await using var reader = await command.ExecuteReaderAsync(cancellationToken); @@ -129,25 +164,23 @@ private Task SendAsync( } [Fact] - public async Task SendMessageAsync_Should_CreateImplicitRow_When_RecipientUnknown() + public async Task SendMessageAsync_Should_Throw_When_ToRecipientUnknown() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); // act - var message = await SendAsync("claude", "hello", ["bob", "alice"], null, cancellationToken); + var exception = await Assert.ThrowsAsync( + () => SendAsync("claude", "hello", ["bob"], null, cancellationToken)); // assert - Assert.Equal(["bob", "alice"], message.Unregistered); - var bob = await _registry.GetAsync("bob", cancellationToken); - var alice = await _registry.GetAsync("alice", cancellationToken); - Assert.True(bob?.Implicit); - Assert.True(alice?.Implicit); + Assert.Equal("Unknown agent 'bob'. Look the name up with 'nitro agent list'.", exception.Message); } [Fact] - public async Task SendMessageAsync_Should_ReportOnlyUnknownRecipients_When_Mixed() + public async Task SendMessageAsync_Should_Throw_When_SenderUnknown() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -155,69 +188,100 @@ public async Task SendMessageAsync_Should_ReportOnlyUnknownRecipients_When_Mixed await SeedAgentAsync("bob", cancellationToken); // act - var message = await SendAsync("claude", "hello", ["bob", "dave"], null, cancellationToken); + var exception = await Assert.ThrowsAsync( + () => SendAsync("claude", "hello", ["bob"], null, cancellationToken)); // assert - Assert.Equal(["dave"], message.Unregistered); + Assert.Equal("Unknown agent 'claude'. Look the name up with 'nitro agent list'.", exception.Message); + Assert.Equal(0L, await CountAsync("messages", "1 = 1", cancellationToken)); } [Fact] - public async Task SendMessageAsync_Should_ReportStillImplicitRecipient_When_AlreadyImplicit() + public async Task SendMessageAsync_Should_Throw_When_SenderDeleted() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); - await SendAsync("claude", "first", ["dave"], null, cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await MarkDeletedAsync("claude", cancellationToken); // act - var second = await SendAsync("claude", "second", ["dave"], null, cancellationToken); + var exception = await Assert.ThrowsAsync( + () => SendAsync("claude", "hello", ["bob"], null, cancellationToken)); // assert - Assert.Equal(["dave"], second.Unregistered); + Assert.Equal("Agent 'claude' was deleted. Look the name up with 'nitro agent list'.", exception.Message); + Assert.Equal(0L, await CountAsync("messages", "1 = 1", cancellationToken)); } [Fact] - public async Task SendMessageAsync_Should_NotReportRegisteredRecipient_When_ImplicitRegistersAfterwards() + public async Task SendMessageAsync_Should_Throw_When_CcRecipientDeleted() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); - await SendAsync("claude", "first", ["dave"], null, cancellationToken); - await _registry.RegisterAsync("dave", role: "", client: "", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("dave", cancellationToken); + await MarkDeletedAsync("dave", cancellationToken); // act - var second = await SendAsync("claude", "second", ["dave"], null, cancellationToken); + var exception = await Assert.ThrowsAsync( + () => SendAsync("claude", "hello", ["bob"], ["dave"], cancellationToken)); // assert - Assert.Empty(second.Unregistered); + Assert.Equal("Agent 'dave' was deleted. Look the name up with 'nitro agent list'.", exception.Message); } [Fact] - public async Task SendMessageAsync_Should_Throw_When_RecipientNameInvalid() + public async Task SendMessageAsync_Should_WriteNothing_When_ARecipientIsRejected() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); - // act & assert + // act await Assert.ThrowsAsync( - () => SendAsync("claude", "hello", ["Dave!"], null, cancellationToken)); + () => SendAsync("claude", "rejected", ["bob", "ghost"], null, cancellationToken)); + + // assert + Assert.Equal(0L, await CountAsync("messages", "subject = 'rejected'", cancellationToken)); + Assert.Equal(0L, await CountAsync("message_recipients", "recipient = 'bob'", cancellationToken)); } [Fact] - public async Task SendMessageAsync_Should_AutoRegisterSender_When_NotAlreadyRegistered() + public async Task SendMessageAsync_Should_CreateNoAgentsRow_When_SendingToKnownRecipients() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); + var before = await CountAsync("agents", "1 = 1", cancellationToken); // act await SendAsync("claude", "hello", ["bob"], null, cancellationToken); // assert - var sender = await _registry.GetAsync("claude", cancellationToken); - Assert.NotNull(sender); + // Sending between two already-registered agents mints no new agents row. + var after = await CountAsync("agents", "1 = 1", cancellationToken); + Assert.Equal(before, after); + } + + [Fact] + public async Task SendMessageAsync_Should_Throw_When_RecipientNameInvalid() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + + // act & assert + await Assert.ThrowsAsync( + () => SendAsync("claude", "hello", ["Dave!"], null, cancellationToken)); } [Fact] @@ -226,6 +290,7 @@ public async Task SendMessageAsync_Should_CollapseDuplicatesWithToWinning_AndPre // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("alice", cancellationToken); await SeedAgentAsync("carol", cancellationToken); @@ -248,6 +313,7 @@ public async Task SendMessageAsync_Should_Throw_When_NoRecipients() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); // act & assert await Assert.ThrowsAsync( @@ -260,6 +326,7 @@ public async Task SendMessageAsync_Should_Throw_When_SubjectEmpty() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); // act & assert @@ -273,6 +340,7 @@ public async Task ReplyMessageAsync_Should_ComputeRecipients_AsSenderAndRecipien // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); var original = await SendAsync("claude", "hello", ["bob"], ["carol"], cancellationToken); @@ -292,6 +360,7 @@ public async Task ReplyMessageAsync_Should_Throw_When_ActorNotParticipant() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var original = await SendAsync("claude", "hello", ["bob"], null, cancellationToken); @@ -306,6 +375,7 @@ public async Task ReplyMessageAsync_Should_Throw_When_OnlyParticipantIsActor() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var original = await SendAsync("claude", "note to self", ["claude"], null, cancellationToken); // act @@ -316,6 +386,86 @@ public async Task ReplyMessageAsync_Should_Throw_When_OnlyParticipantIsActor() Assert.Contains("claude", exception.Message); } + [Fact] + public async Task ReplyMessageAsync_Should_DropDeletedParticipant_AndReportSkip_When_ReplyingAllToMultipleParticipants() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + var original = await SendAsync("claude", "hello", ["bob"], ["carol"], cancellationToken); + await MarkDeletedAsync("carol", cancellationToken); + + // act + var reply = await _store.ReplyMessageAsync(original.Id, "bob", "reply body", cancellationToken); + + // assert + Assert.Equal(["claude"], reply.Recipients.Select(r => r.Name)); + Assert.Equal(["carol"], reply.Skipped); + } + + [Fact] + public async Task ReplyMessageAsync_Should_Throw_When_EveryReplyAllParticipantIsDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + var original = await SendAsync("claude", "hello", ["bob"], ["carol"], cancellationToken); + await MarkDeletedAsync("claude", cancellationToken); + await MarkDeletedAsync("carol", cancellationToken); + + // act + var exception = await Assert.ThrowsAsync( + () => _store.ReplyMessageAsync(original.Id, "bob", "reply body", cancellationToken)); + + // assert + Assert.Equal( + "No recipients left: 'claude' was deleted, 'carol' was deleted.", exception.Message); + } + + [Fact] + public async Task ReplyMessageAsync_Should_Throw_WithSendStyleText_When_DirectReplyRecipientIsDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("alice", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + var original = await SendAsync("alice", "hello", ["bob"], null, cancellationToken); + await MarkDeletedAsync("alice", cancellationToken); + + // act + var exception = await Assert.ThrowsAsync( + () => _store.ReplyMessageAsync(original.Id, "bob", "reply body", cancellationToken)); + + // assert + Assert.Equal("Agent 'alice' was deleted. Look the name up with 'nitro agent list'.", exception.Message); + } + + [Fact] + public async Task ReplyMessageAsync_Should_Throw_When_ActorHasNoAgentRow() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + var original = await SendAsync("claude", "hello", ["bob"], null, cancellationToken); + await DeleteAgentRowAsync("claude", cancellationToken); + + // act + var exception = await Assert.ThrowsAsync( + () => _store.ReplyMessageAsync(original.Id, "claude", "reply body", cancellationToken)); + + // assert + Assert.Equal("Unknown agent 'claude'. Look the name up with 'nitro agent list'.", exception.Message); + } + [Fact] public async Task ReplyMessageAsync_Should_InheritSubjectFromThreadRoot_ThroughMultipleReplies() { @@ -323,6 +473,7 @@ public async Task ReplyMessageAsync_Should_InheritSubjectFromThreadRoot_ThroughM var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var original = await SendAsync("claude", "root subject", ["bob"], null, cancellationToken); var firstReply = await _store.ReplyMessageAsync(original.Id, "bob", "reply 1", cancellationToken); @@ -341,6 +492,7 @@ public async Task SendMessageAsync_Should_ReturnWakeReceiptForEachRecipient_When // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); @@ -362,6 +514,7 @@ public async Task SendMessageAsync_Should_ReturnNoWakeReceiptsAndCreateNoOutboxR // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); // act @@ -378,6 +531,7 @@ public async Task SendMessageAsync_Should_AdvanceGenerationMonotonically_When_Se // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var first = await SendAsync( "claude", "first", ["bob"], null, cancellationToken, wakePolicy: MailWakePolicy.Enqueue); @@ -398,6 +552,7 @@ public async Task ReplyMessageAsync_Should_ReturnWakeReceipts_When_PolicyIsEnque var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var original = await SendAsync("claude", "hello", ["bob"], null, cancellationToken); // act @@ -416,6 +571,7 @@ public async Task SendMessageAsync_Should_PreserveEarliestDueAt_When_EnqueuedTwi // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "first", ["bob"], null, cancellationToken, wakePolicy: MailWakePolicy.Enqueue); var earliestDueAt = _timeProvider.GetUtcNow(); @@ -436,6 +592,7 @@ public async Task SendMessageAsync_Should_AdvanceGenerationsWithoutLoss_When_Con // arrange: separate MailStore instances race the same recipient, matching production's non-pooled connections. var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); const int concurrentSends = 5; @@ -481,6 +638,7 @@ BEFORE INSERT ON mail_wake_outbox } await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("boom", cancellationToken); // act & assert @@ -499,6 +657,7 @@ public async Task SendMessageAsync_Should_PersistNothing_When_CancelledBeforeAny // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); using var cancelled = new CancellationTokenSource(); await cancelled.CancelAsync(); @@ -518,6 +677,7 @@ public async Task SendMessageAsync_Should_BeReconcilableByItsReturnedId_When_Com // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); // act @@ -560,6 +720,7 @@ public async Task GetThreadMessagesAsync_Should_ReturnMessagesOrderedByCreatedAt var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var original = await SendAsync("claude", "root", ["bob"], null, cancellationToken); _timeProvider.Advance(TimeSpan.FromMinutes(1)); var reply = await _store.ReplyMessageAsync(original.Id, "bob", "reply", cancellationToken); @@ -577,6 +738,7 @@ public async Task QueryInboxAsync_Should_ReturnOnlyMessagesAddressedToActor() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); await SendAsync("claude", "for bob", ["bob"], null, cancellationToken); @@ -597,6 +759,7 @@ public async Task QueryInboxAsync_Should_FilterByUnreadOnly() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var first = await SendAsync("claude", "first", ["bob"], null, cancellationToken); await SendAsync("claude", "second", ["bob"], null, cancellationToken); @@ -617,6 +780,7 @@ public async Task QueryInboxAsync_Should_FilterByFrom() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("dave", cancellationToken); await SendAsync("claude", "from claude", ["bob"], null, cancellationToken); @@ -637,6 +801,7 @@ public async Task QueryInboxAsync_Should_ExcludeArchived_When_IncludeArchivedFal // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var message = await SendAsync("claude", "hello", ["bob"], null, cancellationToken); await _store.ArchiveAsync([message.Id], "bob", cancellationToken); @@ -655,6 +820,7 @@ public async Task QueryInboxAsync_Should_ApplyLimit() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "first", ["bob"], null, cancellationToken); await SendAsync("claude", "second", ["bob"], null, cancellationToken); @@ -692,6 +858,7 @@ public async Task QueryWorkspaceMessagesAsync_Should_OrderNewestFirst() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var first = await SendAsync("claude", "first", ["bob"], null, cancellationToken); _timeProvider.Advance(TimeSpan.FromMinutes(1)); @@ -772,6 +939,7 @@ public async Task QueryWorkspaceMessagesAsync_Should_FilterBySince() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "first", ["bob"], null, cancellationToken); _timeProvider.Advance(TimeSpan.FromSeconds(30)); @@ -794,6 +962,7 @@ public async Task QueryWorkspaceMessagesAsync_Should_ApplyLimit() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "first", ["bob"], null, cancellationToken); await SendAsync("claude", "second", ["bob"], null, cancellationToken); @@ -812,6 +981,7 @@ public async Task MarkReadAsync_Should_SetReadAt_OnlyForActorRecipientRow() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); var message = await SendAsync("claude", "hello", ["bob", "carol"], null, cancellationToken); @@ -833,6 +1003,7 @@ public async Task ArchiveAsync_Should_SetArchivedAt_OnlyForActorRecipientRow() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); var message = await SendAsync("claude", "hello", ["bob", "carol"], null, cancellationToken); @@ -849,41 +1020,52 @@ public async Task ArchiveAsync_Should_SetArchivedAt_OnlyForActorRecipientRow() } [Fact] - public async Task TransferParticipationAsync_Should_MoveRecipientAndPreserveReadState() + public async Task TransferParticipationAsync_Should_MoveRecipientRow_When_MessageIsUnread() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("old", cancellationToken); await SeedAgentAsync("target", cancellationToken); - var targetMessage = await SendAsync("claude", "target", ["target"], null, cancellationToken); - var unreadMessage = await SendAsync("claude", "unread", ["old"], null, cancellationToken); - var readMessage = await SendAsync("claude", "read", ["old"], null, cancellationToken); - await _store.MarkReadAsync([targetMessage.Id], "target", cancellationToken); - await _store.MarkReadAsync([readMessage.Id], "old", cancellationToken); + var message = await SendAsync("claude", "unread", ["old"], null, cancellationToken); // act var result = await _store.TransferParticipationAsync("OLD", "TARGET", cancellationToken); - var inbox = await _store.QueryInboxAsync(new MailInboxFilter { Actor = "target" }, cancellationToken); + var targetInbox = await _store.QueryInboxAsync(new MailInboxFilter { Actor = "target" }, cancellationToken); var sourceInbox = await _store.QueryInboxAsync(new MailInboxFilter { Actor = "old" }, cancellationToken); // assert - ($"{result.RecipientsMoved}|{result.SendersMoved}|{result.Dropped}|" - + $"{string.Join(",", result.SenderMessageIds)}|" - + string.Join(",", result.RecipientMessageIds)) - .MatchInlineSnapshot( - $"2|0|0||{string.Join(",", new[] { readMessage.Id, unreadMessage.Id }.Order())}"); - Assert.Equal( - new[] { readMessage.Id, targetMessage.Id, unreadMessage.Id }.Order(), - inbox.Select(t => t.Id).Order()); - Assert.Equal( - [true, true, false], - inbox.OrderBy(t => t.Subject).Select(t => t.Recipients.Single().ReadAt is not null)); - Assert.Empty(sourceInbox); + ($"{result.RecipientsMoved}|{result.Dropped}|{string.Join(",", result.RecipientMessageIds)}|{string.Join(",", targetInbox.Select(t => t.Id))}|{string.Join(",", sourceInbox.Select(t => t.Id))}") + .MatchInlineSnapshot($"1|0|{message.Id}|{message.Id}|"); + } + + [Fact] + public async Task TransferParticipationAsync_Should_KeepRecipientRowWithSource_When_MessageIsRead() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("old", cancellationToken); + await SeedAgentAsync("target", cancellationToken); + var message = await SendAsync("claude", "read", ["old"], null, cancellationToken); + await _store.MarkReadAsync([message.Id], "old", cancellationToken); + + // act + var result = await _store.TransferParticipationAsync("old", "target", cancellationToken); + var sourceInbox = await _store.QueryInboxAsync( + new MailInboxFilter { Actor = "old", UnreadOnly = false }, cancellationToken); + var targetInbox = await _store.QueryInboxAsync(new MailInboxFilter { Actor = "target" }, cancellationToken); + + // assert + Assert.Equal(new MailTransferResult(0, 0), result); + Assert.Equal(message.Id, Assert.Single(sourceInbox).Id); + Assert.Empty(targetInbox); } [Fact] - public async Task TransferParticipationAsync_Should_AllowThirdPartyReplyToTransferredSentMessage() + public async Task TransferParticipationAsync_Should_KeepSender_When_SourceSentMessage() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -892,18 +1074,16 @@ public async Task TransferParticipationAsync_Should_AllowThirdPartyReplyToTransf await SeedAgentAsync("target", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var message = await SendAsync("old", "sent", ["bob"], null, cancellationToken); - var transfer = await _store.TransferParticipationAsync("old", "target", cancellationToken); // act + var transfer = await _store.TransferParticipationAsync("old", "target", cancellationToken); + var reloaded = await _store.GetRequiredMessageAsync(message.Id, cancellationToken); var reply = await _store.ReplyMessageAsync(message.Id, "bob", "reply", cancellationToken); // assert - ($"{transfer.RecipientsMoved}|{transfer.SendersMoved}|{transfer.Dropped}|" - + $"{string.Join(",", transfer.SenderMessageIds)}|" - + string.Join(",", transfer.RecipientMessageIds)) - .MatchInlineSnapshot($"0|1|0|{message.Id}|"); - Assert.Equal("bob", reply.Sender); - Assert.Equal(["target"], reply.Recipients.Select(t => t.Name)); + Assert.Equal(new MailTransferResult(0, 0), transfer); + Assert.Equal("old", reloaded.Sender); + Assert.Equal(["old"], reply.Recipients.Select(t => t.Name)); Assert.Equal(message.ThreadId, reply.ThreadId); } @@ -915,6 +1095,7 @@ public async Task TransferParticipationAsync_Should_AllowTargetReplyToTransferre await InitWorkspaceAsync(cancellationToken); await SeedAgentAsync("old", cancellationToken); await SeedAgentAsync("target", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var message = await SendAsync("claude", "received", ["old"], null, cancellationToken); await _store.TransferParticipationAsync("old", "target", cancellationToken); @@ -933,6 +1114,7 @@ public async Task TransferParticipationAsync_Should_DropConflictingRecipientAndP // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("old", cancellationToken); await SeedAgentAsync("target", cancellationToken); var message = await SendAsync("claude", "shared", ["old", "target"], null, cancellationToken); @@ -943,10 +1125,7 @@ public async Task TransferParticipationAsync_Should_DropConflictingRecipientAndP var reloaded = await _store.GetRequiredMessageAsync(message.Id, cancellationToken); // assert - ($"{result.RecipientsMoved}|{result.SendersMoved}|{result.Dropped}|" - + $"{string.Join(",", result.SenderMessageIds)}|" - + string.Join(",", result.RecipientMessageIds)) - .MatchInlineSnapshot("0|0|1||"); + Assert.Equal(new MailTransferResult(0, 1), result); var recipient = Assert.Single(reloaded.Recipients); Assert.Equal("target", recipient.Name); Assert.NotNull(recipient.ReadAt); @@ -958,10 +1137,11 @@ public async Task TransferParticipationAsync_Should_IncludeTransferredParticipat // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("old", cancellationToken); await SeedAgentAsync("target", cancellationToken); await SeedAgentAsync("bob", cancellationToken); - var sent = await SendAsync("old", "sent", ["bob"], null, cancellationToken); + await SendAsync("old", "sent", ["bob"], null, cancellationToken); var received = await SendAsync("claude", "received", ["old"], null, cancellationToken); await _store.TransferParticipationAsync("old", "target", cancellationToken); @@ -969,9 +1149,8 @@ public async Task TransferParticipationAsync_Should_IncludeTransferredParticipat var threads = await _store.QueryThreadsAsync("target", cancellationToken); // assert - Assert.Equal(2, threads.Count); - Assert.Contains(threads, t => t.ThreadId == sent.ThreadId); - Assert.Contains(threads, t => t.ThreadId == received.ThreadId); + var thread = Assert.Single(threads); + Assert.Equal(received.ThreadId, thread.ThreadId); } [Fact] @@ -980,10 +1159,11 @@ public async Task TransferParticipationAsync_Should_IncludeTransferredParticipat // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("old", cancellationToken); await SeedAgentAsync("target", cancellationToken); await SeedAgentAsync("bob", cancellationToken); - var sent = await SendAsync("old", "matching", ["bob"], null, cancellationToken); + await SendAsync("old", "matching", ["bob"], null, cancellationToken); var received = await SendAsync("claude", "matching", ["old"], null, cancellationToken); await _store.TransferParticipationAsync("old", "target", cancellationToken); @@ -991,9 +1171,8 @@ public async Task TransferParticipationAsync_Should_IncludeTransferredParticipat var results = await _store.SearchAsync("target", "matching", cancellationToken); // assert - Assert.Equal(2, results.Count); - Assert.Contains(results, m => m.Id == sent.Id); - Assert.Contains(results, m => m.Id == received.Id); + var result = Assert.Single(results); + Assert.Equal(received.Id, result.Id); } [Fact] @@ -1002,6 +1181,7 @@ public async Task TransferParticipationAsync_Should_ReturnZeros_WhenRepeated() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("old", cancellationToken); await SeedAgentAsync("target", cancellationToken); await SeedAgentAsync("bob", cancellationToken); @@ -1013,7 +1193,7 @@ public async Task TransferParticipationAsync_Should_ReturnZeros_WhenRepeated() var result = await _store.TransferParticipationAsync("old", "target", cancellationToken); // assert - Assert.Equal(new MailTransferResult(0, 0, 0), result); + Assert.Equal(new MailTransferResult(0, 0), result); } [Fact] @@ -1048,6 +1228,7 @@ public async Task MarkReadAsync_Should_RollBackAll_When_AnyIdNotAddressedToActor // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var validMessage = await SendAsync("claude", "hello", ["bob"], null, cancellationToken); @@ -1067,6 +1248,7 @@ public async Task QueryThreadsAsync_Should_ReturnThreadsActorParticipatesIn_With // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); var thread = await SendAsync("claude", "shared thread", ["bob"], null, cancellationToken); @@ -1091,6 +1273,7 @@ public async Task QueryInboxThreadsAsync_Should_ReturnOnlyThreadsAddressedToActo // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); var addressedToBob = await SendAsync("claude", "for bob", ["bob"], null, cancellationToken); @@ -1114,6 +1297,7 @@ public async Task QueryInboxThreadsAsync_Should_ExcludeThread_When_OnlyMessageTo // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var message = await SendAsync("claude", "for bob", ["bob"], null, cancellationToken); await _store.ArchiveAsync([message.Id], "bob", cancellationToken); @@ -1131,6 +1315,7 @@ public async Task QueryInboxThreadsAsync_Should_IncludeArchivedThread_When_Inclu // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var message = await SendAsync("claude", "for bob", ["bob"], null, cancellationToken); await _store.ArchiveAsync([message.Id], "bob", cancellationToken); @@ -1152,6 +1337,7 @@ public async Task QueryInboxThreadsAsync_Should_IncludeThread_When_SomeButNotAll var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var first = await SendAsync("claude", "for bob", ["bob"], null, cancellationToken); var reply = await _store.ReplyMessageAsync(first.Id, "claude", "following up", cancellationToken); await _store.ArchiveAsync([first.Id], "bob", cancellationToken); @@ -1236,6 +1422,7 @@ public async Task QueryWorkspaceThreadsAsync_Should_NeverExposeActorUnreadState_ // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "for bob", ["bob"], null, cancellationToken); @@ -1247,12 +1434,201 @@ public async Task QueryWorkspaceThreadsAsync_Should_NeverExposeActorUnreadState_ Assert.Null(summary.UnreadCount); } + [Fact] + public async Task QueryParticipationThreadsAsync_Should_IncludeThread_When_AgentOnlyCcd() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + var thread = await SendAsync("claude", "cc carol", ["bob"], ["carol"], cancellationToken); + + // act + var threads = await _store.QueryParticipationThreadsAsync("carol", limit: null, cancellationToken); + + // assert + var summary = Assert.Single(threads); + Assert.Equal(thread.ThreadId, summary.ThreadId); + } + + [Fact] + public async Task QueryParticipationThreadsAsync_Should_RankByAgentsOwnMessage_When_OtherAgentRepliesLater() + { + // arrange + // A reply through the public API always keeps every thread participant on + // every later message, so a message that excludes bob is inserted directly. + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + await SeedAgentAsync("dave", cancellationToken); + var threadA = await SendAsync("bob", "thread a", ["carol"], null, cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(1)); + var threadB = await SendAsync("bob", "thread b", ["carol"], null, cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(1)); + + await using (var connection = await SeedAsync(cancellationToken)) + { + var laterCreatedAt = _timeProvider.GetUtcNow() + .ToString("yyyy-MM-dd HH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture); + + await ExecuteAsync( + connection, + """ + INSERT INTO messages (id, thread_id, in_reply_to, sender, subject, body, created_at) + VALUES (@id, @threadId, @inReplyTo, @sender, @subject, @body, @createdAt) + """, + ("@id", "m-later"), ("@threadId", threadA.ThreadId), ("@inReplyTo", threadA.Id), + ("@sender", "carol"), ("@subject", "thread a"), ("@body", "later reply"), + ("@createdAt", laterCreatedAt)); + + await ExecuteAsync( + connection, + """ + INSERT INTO message_recipients (message_id, recipient, kind, ordinal) + VALUES (@messageId, @recipient, 'to', 0) + """, + ("@messageId", "m-later"), ("@recipient", "dave")); + } + + // act + var threads = await _store.QueryParticipationThreadsAsync("bob", limit: null, cancellationToken); + + // assert + Assert.Equal([threadB.ThreadId, threadA.ThreadId], threads.Select(t => t.ThreadId)); + } + + [Fact] + public async Task QueryParticipationThreadsAsync_Should_ReturnTenNewestThreads_When_LimitIsTen() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + var threadIds = new List(); + + for (var i = 0; i < 12; i++) + { + var message = await SendAsync("bob", $"thread {i}", ["carol"], null, cancellationToken); + threadIds.Add(message.ThreadId); + _timeProvider.Advance(TimeSpan.FromMinutes(1)); + } + + // act + var threads = await _store.QueryParticipationThreadsAsync("bob", limit: 10, cancellationToken); + + // assert + var expectedNewestFirst = threadIds.Skip(2).Reverse(); + Assert.Equal(expectedNewestFirst, threads.Select(t => t.ThreadId)); + } + + [Fact] + public async Task QueryParticipationThreadsAsync_Should_ReturnOneRow_When_ThreadHasManyMessages() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + var first = await SendAsync("bob", "thread", ["carol"], null, cancellationToken); + var reply = await _store.ReplyMessageAsync(first.Id, "carol", "reply 1", cancellationToken); + await _store.ReplyMessageAsync(reply.Id, "bob", "reply 2", cancellationToken); + + // act + var threads = await _store.QueryParticipationThreadsAsync("bob", limit: null, cancellationToken); + + // assert + var summary = Assert.Single(threads); + Assert.Equal(first.ThreadId, summary.ThreadId); + Assert.Equal(3, summary.MessageCount); + } + + [Fact] + public async Task QueryParticipationThreadsAsync_Should_ScopeUnreadAndArchivedCounts_When_MultipleAgentsShareThread() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + var message = await SendAsync("claude", "for bob and carol", ["bob"], ["carol"], cancellationToken); + await _store.MarkReadAsync([message.Id], "bob", cancellationToken); + + // act + var bobThreads = await _store.QueryParticipationThreadsAsync("bob", limit: null, cancellationToken); + var carolThreads = await _store.QueryParticipationThreadsAsync("carol", limit: null, cancellationToken); + + // assert + Assert.Equal(0, Assert.Single(bobThreads).UnreadCount); + Assert.Equal(1, Assert.Single(carolThreads).UnreadCount); + } + + [Fact] + public async Task QueryParticipationThreadsAsync_Should_ReturnCompleteSummaries_When_ThreadsHaveRepliesCcReadAndArchived() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("carol", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); + var first = await SendAsync("claude", "thread one", ["bob"], ["carol"], cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(1)); + await _store.ReplyMessageAsync(first.Id, "carol", "reply body", cancellationToken); + await _store.MarkReadAsync([first.Id], "bob", cancellationToken); + await _store.ArchiveAsync([first.Id], "bob", cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(1)); + await SendAsync("bob", "thread two", ["carol"], null, cancellationToken); + + // act + var threads = await _store.QueryParticipationThreadsAsync("bob", limit: null, cancellationToken); + + // assert + threads.MatchInlineSnapshot( + """ + [ + { + "ThreadId": "m-9vcfyl", + "Subject": "thread two", + "MessageCount": 1, + "LastMessageAt": "2026-01-10T12:02:00+00:00", + "LastSender": "bob", + "LastRecipients": [ + "carol" + ], + "BodyPreview": "body", + "UnreadCount": 0, + "ArchivedCount": 0 + }, + { + "ThreadId": "m-4hjiuu", + "Subject": "thread one", + "MessageCount": 2, + "LastMessageAt": "2026-01-10T12:01:00+00:00", + "LastSender": "carol", + "LastRecipients": [ + "claude", + "bob" + ], + "BodyPreview": "reply body", + "UnreadCount": 1, + "ArchivedCount": 1 + } + ] + """); + } + [Fact] public async Task ThreadRollup_Should_CollapseWhitespaceAndTruncate_InBodyPreview() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var longBody = string.Concat(Enumerable.Repeat("word ", 40)) + "\n\ttrailing\r\nnewlines here"; await SendAsync("claude", "long body", ["bob"], null, cancellationToken, body: longBody); @@ -1275,6 +1651,7 @@ public async Task SearchAsync_Should_MatchSubjectOrBody_CaseInsensitive() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "Deploy the PARSER fix", ["bob"], null, cancellationToken); await SendAsync("claude", "unrelated", ["bob"], null, cancellationToken); @@ -1293,6 +1670,7 @@ public async Task SearchAsync_Should_MatchSender_CaseInsensitive() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "unrelated subject", ["bob"], null, cancellationToken); @@ -1310,6 +1688,7 @@ public async Task SearchAsync_Should_NotMatch_When_TextNotInSubjectBodyOrSender( // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "unrelated subject", ["bob"], null, cancellationToken); @@ -1326,6 +1705,7 @@ public async Task CountUnreadAsync_Should_CountOnlyUnreadAndNotArchived() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var first = await SendAsync("claude", "first", ["bob"], null, cancellationToken); await SendAsync("claude", "second", ["bob"], null, cancellationToken); @@ -1348,7 +1728,7 @@ public async Task Schema_Should_RejectSubjectOutOfLength_ViaCheckConstraint() await using var connection = await SeedAsync(cancellationToken); await ExecuteAsync( connection, - "INSERT INTO agents (name, registered_at, last_seen_at) VALUES (@n, @t, @t)", + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES (@n, @t, @t, @t)", ("@n", "claude"), ("@t", "2026-01-10T12:00:00+00:00")); // act & assert @@ -1362,22 +1742,31 @@ INSERT INTO messages (id, thread_id, sender, subject, body, created_at) ("@body", "body"), ("@createdAt", "2026-01-10T12:00:00+00:00"))); } + /// + /// The schema keeps sender and recipient as plain text with no foreign + /// key to agents, so an unknown or since-deleted name never + /// orphans a row when the agents table is dropped and recreated on a + /// schema upgrade. Recipient validity is enforced by the send path. + /// [Fact] - public async Task Schema_Should_RejectUnknownSender_ViaForeignKey() + public async Task Schema_Should_AcceptUnknownSender_When_NoForeignKeyToAgents() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await SeedAsync(cancellationToken); - // act & assert - await Assert.ThrowsAsync(() => ExecuteAsync( + // act + await ExecuteAsync( connection, """ INSERT INTO messages (id, thread_id, sender, subject, body, created_at) VALUES (@id, @id, @sender, @subject, @body, @createdAt) """, ("@id", "m-orphan"), ("@sender", "ghost"), ("@subject", "hi"), - ("@body", "body"), ("@createdAt", "2026-01-10T12:00:00+00:00"))); + ("@body", "body"), ("@createdAt", "2026-01-10T12:00:00+00:00")); + + // assert + Assert.Equal(1L, await CountAsync("messages", "id = 'm-orphan'", cancellationToken)); } [Fact] @@ -1401,6 +1790,7 @@ public async Task QuerySentAsync_Should_ReturnMessagesSentByAgent_NewestFirst() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SeedAgentAsync("carol", cancellationToken); var first = await SendAsync("claude", "first", ["bob"], null, cancellationToken); @@ -1421,6 +1811,7 @@ public async Task QuerySentAsync_Should_ApplyLimit() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "first", ["bob"], null, cancellationToken); await SendAsync("claude", "second", ["bob"], null, cancellationToken); @@ -1438,6 +1829,7 @@ public async Task QuerySentAsync_Should_NormalizeSenderName() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var message = await SendAsync("claude", "hello", ["bob"], null, cancellationToken); @@ -1455,6 +1847,7 @@ public async Task QuerySentAsync_Should_ReturnEmpty_When_AgentHasNoSentMail() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); await SendAsync("claude", "hello", ["bob"], null, cancellationToken); @@ -1471,6 +1864,7 @@ public async Task QuerySentAsync_Should_ReturnMessage_When_ActorHasNoOtherCorres // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("stranger", cancellationToken); var message = await SendAsync("claude", "hello", ["stranger"], null, cancellationToken); @@ -1489,6 +1883,7 @@ public async Task QuerySentAsync_Should_ExcludeMessages_When_ActorOnlyReceivedTh var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); await SeedAgentAsync("bob", cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var ownMessage = await SendAsync("claude", "mine", ["bob"], null, cancellationToken); await SendAsync("bob", "not mine", ["claude"], null, cancellationToken); @@ -1506,6 +1901,7 @@ public async Task QuerySentAsync_Should_ReturnSelfAddressedMessage_ExactlyOnce() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); var message = await SendAsync("claude", "note to self", ["claude"], null, cancellationToken); // act @@ -1522,6 +1918,7 @@ public async Task QuerySentAsync_Should_ReturnUnrepliedThreadRoot() // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitWorkspaceAsync(cancellationToken); + await SeedAgentAsync("claude", cancellationToken); await SeedAgentAsync("bob", cancellationToken); var root = await SendAsync("claude", "unanswered", ["bob"], null, cancellationToken); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Memory/MemoryStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Memory/MemoryStoreTests.cs index 84a35a36371..e47eea5d405 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Memory/MemoryStoreTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Memory/MemoryStoreTests.cs @@ -374,4 +374,81 @@ public async Task GetUnpromotedJournalEntriesAsync_Should_ExcludePromotedEntries // assert Assert.Equal([pending.Id], unpromoted.Select(entry => entry.Id)); } + + [Fact] + public async Task QueryParticipationAsync_Should_ShowAPromotedJournalEntryOnceAsCurated() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + var journal = await LogAsync("Investigated the flaky test."); + var outcome = await _store.PromoteAsync(journal.Id, "fact", [], cancellationToken); + + // act + var participation = await _store.QueryParticipationAsync( + "test-agent", limit: null, cancellationToken); + + // assert + var entry = Assert.Single(participation); + Assert.Equal(MemoryParticipationKind.Curated, entry.Kind); + Assert.Equal(outcome.Record.Id, entry.Id); + } + + [Fact] + public async Task QueryParticipationAsync_Should_SetNullTypeAndEmptyTags_When_TheEntryIsAJournalNote() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + var journal = await LogAsync("Raw note."); + + // act + var participation = await _store.QueryParticipationAsync( + "test-agent", limit: null, cancellationToken); + + // assert + var entry = Assert.Single(participation); + Assert.Equal(journal.Id, entry.Id); + Assert.Null(entry.Type); + Assert.Empty(entry.Tags); + } + + [Fact] + public async Task QueryParticipationAsync_Should_ExcludeAnotherAgentsEntries() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + var mine = await SaveAsync("Mine."); + await _store.SaveAsync( + new MemoryRecordCreation { Text = "Theirs.", Type = "fact", Tags = [], Actor = "other-agent" }, + cancellationToken); + await _store.LogAsync( + new MemoryJournalEntryCreation { Text = "Their note.", Actor = "other-agent" }, + cancellationToken); + + // act + var participation = await _store.QueryParticipationAsync( + "test-agent", limit: null, cancellationToken); + + // assert + Assert.Equal([mine.Id], participation.Select(entry => entry.Id)); + } + + [Fact] + public async Task QueryParticipationAsync_Should_OrderByCreatedAtDescendingAndRespectLimit() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + var oldest = await LogAsync("Oldest."); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + var middle = await SaveAsync("Middle."); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + var newest = await LogAsync("Newest."); + + // act + var all = await _store.QueryParticipationAsync("test-agent", limit: null, cancellationToken); + var limited = await _store.QueryParticipationAsync("test-agent", limit: 2, cancellationToken); + + // assert + Assert.Equal([newest.Id, middle.Id, oldest.Id], all.Select(entry => entry.Id)); + Assert.Equal([newest.Id, middle.Id], limited.Select(entry => entry.Id)); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ActorWakeDispatcherTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ActorWakeDispatcherTests.cs index 32ab3c77b16..70ef7b04b7a 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ActorWakeDispatcherTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ActorWakeDispatcherTests.cs @@ -1,10 +1,10 @@ using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using ChilliCream.Nitro.CommandLine.Tests.Hook; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Time.Testing; +using Moq; namespace ChilliCream.Nitro.CommandLine.Tests.Agents; @@ -12,33 +12,28 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// Exercises against a real workspace /// database, with a scriptable /// standing in for the real transports: the claim/no-outstanding-work -/// branch, the no-live-session and mail-already-read fast paths, per-target -/// failure mapping (session gone, no endpoint, unsupported, terminal -/// transport failure), the access-denied offer-and-retain-siblings -/// contract, more than four targets never exceeding four concurrent -/// transports, and losing the batch's own lease renewal mid-dispatch -/// (cancelling in-flight/not-yet-started targets without asserting their -/// outcome) followed by a clean reclaim on the next dispatch. +/// branch, the offline and mail-already-read fast paths, per-target failure +/// mapping (unsupported, terminal transport failure), the access-denied +/// offer-and-retain-siblings contract, and losing the batch's own lease +/// renewal mid-dispatch (cancelling an in-flight target without asserting +/// its outcome) followed by a clean reclaim on the next dispatch. /// public sealed class ActorWakeDispatcherTests : IDisposable { - private const string Actor = "codex-worker"; - private const string InstanceId = "host-1"; + private const string LeaderToken = "leader-token"; private readonly DirectoryInfo _tempRoot; private readonly string _workspaceDirectory; private readonly TestFileSystem _fileSystem; private readonly FakeTimeProvider _timeProvider; private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; + private readonly AgentStore _agentStore; private readonly MailStore _mail; private readonly MailWakeBatchStore _batches; - private readonly SessionPingGateStore _gates; + private readonly AgentPingGateStore _gates; private readonly PingLeaseStore _leases; private readonly SessionGateCoordinator _gateCoordinator; - private readonly FixedInstanceIdProvider _instanceIdProvider = new(InstanceId); - private readonly FixedGlobalConfigDirectoryProvider _globalConfigDirectoryProvider; + private readonly MailWakeDaemonLeaderStore _leaderStore; public ActorWakeDispatcherTests() { @@ -48,21 +43,13 @@ public ActorWakeDispatcherTests() _fileSystem = new TestFileSystem(_tempRoot.FullName); _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, _timeProvider, _database); - _sessions = new AgentSessionRegistry( - _fileSystem, - _timeProvider, - _database, - _agentRegistry, - _instanceIdProvider, - new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName)); - _globalConfigDirectoryProvider = new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName); - _mail = new MailStore( - _fileSystem, _timeProvider, _database, _agentRegistry, _instanceIdProvider, _globalConfigDirectoryProvider); + _agentStore = new AgentStore(_fileSystem, _timeProvider, _database); + _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentStore); _batches = new MailWakeBatchStore(_fileSystem, _database); - _gates = new SessionPingGateStore(_fileSystem, _database); + _gates = new AgentPingGateStore(_fileSystem, _database); _leases = new PingLeaseStore(_fileSystem, _database); _gateCoordinator = new SessionGateCoordinator(_gates, _leases); + _leaderStore = new MailWakeDaemonLeaderStore(_fileSystem, _database); } public void Dispose() => _tempRoot.Delete(recursive: true); @@ -70,212 +57,239 @@ public ActorWakeDispatcherTests() [Fact] public async Task DispatchAsync_Should_ReturnNull_When_NothingIsOutstanding() { - // arrange: no mail was ever sent with MailWakePolicy.Enqueue, so the - // actor has no mail_wake_outbox row at all. + // arrange + // No mail was ever sent, so the actor has no mail_wake_outbox row at all. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); var dispatcher = CreateDispatcher(new FakePingSessionExecutor()); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Null(receipt); } [Fact] - public async Task DispatchAsync_Should_CompleteAsSkipped_When_TheActorHasNoLiveSession() + public async Task DispatchAsync_Should_AttemptTransport_When_TheAgentIsIdle() { - // arrange: mail enqueued, but the actor never claimed a live - // session at all. + // arrange + // A session-bound agent, advanced well past the online window into idle. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); - var dispatcher = CreateDispatcher(new FakePingSessionExecutor()); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + _timeProvider.Advance(AgentStateResolver.OnlineWindow + TimeSpan.FromMinutes(1)); + await SendEnqueuedMailAsync(actor, cancellationToken); + var executor = new FakePingSessionExecutor(); + var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); - Assert.Equal(MailWakeTargetStatus.Skipped, receipt.Status); - Assert.Empty(receipt.Targets); - - // the generation settled (nothing durable is left behind): a fresh - // dispatch with still no live session finds nothing outstanding. - var again = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); - Assert.Null(again); + Assert.Equal(MailWakeTargetStatus.Delivered, receipt.Status); + var target = Assert.Single(receipt.Targets); + Assert.Equal(MailWakeTargetStatus.Delivered, target.Status); + Assert.Single(executor.Calls); } [Fact] - public async Task DispatchAsync_Should_SatisfyEveryTarget_When_TheMailWasAlreadyReadBeforeDispatch() + public async Task DispatchAsync_Should_SkipWithEndedReason_When_TheAgentHasEnded() { // arrange + // A session-bound agent whose harness session has ended. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - var message = await SendEnqueuedMailAsync(cancellationToken); - await _mail.MarkReadAsync([message.Id], Actor, cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await _agentStore.EndSessionAsync(AgentSessionHarness.Codex, "session-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); - // assert: satisfied, zero, no transport ever attempted, and no - // second message row was written. + // assert Assert.NotNull(receipt); - Assert.Equal(MailWakeTargetStatus.Satisfied, receipt.Status); var target = Assert.Single(receipt.Targets); - Assert.Equal(generation, target.Target); - Assert.Equal(MailWakeTargetStatus.Satisfied, target.Status); - Assert.Equal("mail-already-read", target.LastError); + Assert.Equal( + (MailWakeTargetStatus.Skipped, actor, MailWakeTargetStatus.Skipped, "ended"), + (receipt.Status, target.Target, target.Status, target.LastError)); Assert.Empty(executor.Calls); - var sent = await _mail.QuerySentAsync("pascal", null, cancellationToken); - Assert.Single(sent); + + // the batch completed instead of releasing for a retry. + _timeProvider.Advance(WakeDispatchPolicy.OfferedRetryDelay + TimeSpan.FromSeconds(1)); + Assert.Null(await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken)); } [Fact] - public async Task DispatchAsync_Should_DeliverAndSettleTheBatch_When_TheTransportSucceeds() + public async Task DispatchAsync_Should_SkipWithUnreachableReason_When_TheAgentIsLoginOnly() { // arrange + // A login-only agent, still within the online window but with no endpoint. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = (await _agentStore.LoginAsync(cancellationToken)).Name; + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); - Assert.Equal(MailWakeTargetStatus.Delivered, receipt.Status); var target = Assert.Single(receipt.Targets); - Assert.Equal(generation, target.Target); - Assert.Equal(MailWakeTargetStatus.Delivered, target.Status); - Assert.Single(executor.Calls); + Assert.Equal( + (MailWakeTargetStatus.Skipped, actor, MailWakeTargetStatus.Skipped, "unreachable"), + (receipt.Status, target.Target, target.Status, target.LastError)); + Assert.Empty(executor.Calls); - // the batch settled: nothing left outstanding for a fresh dispatch. - var again = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); - Assert.Null(again); + // the batch completed instead of releasing for a retry. + _timeProvider.Advance(WakeDispatchPolicy.OfferedRetryDelay + TimeSpan.FromSeconds(1)); + Assert.Null(await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken)); } [Fact] - public async Task DispatchAsync_Should_RecordFailed_When_TheEndpointIsNone() + public async Task DispatchAsync_Should_SkipWithUnreachableReason_When_TheSessionIdIsMissingOnAClaudePeerEndpoint() { // arrange + // A login-only agent with a claude-peer endpoint but no session id. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.None, "", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = (await _agentStore.LoginAsync(cancellationToken)).Name; + await _agentStore.SetEndpointAsync( + actor, AgentSessionEndpointKind.ClaudePeer, "peer-addr", null, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); - Assert.Equal(MailWakeTargetStatus.Failed, receipt.Status); var target = Assert.Single(receipt.Targets); - Assert.Equal(MailWakeTargetStatus.Failed, target.Status); - Assert.Equal("no-endpoint", target.LastError); + Assert.Equal( + (MailWakeTargetStatus.Skipped, actor, MailWakeTargetStatus.Skipped, "unreachable"), + (receipt.Status, target.Target, target.Status, target.LastError)); Assert.Empty(executor.Calls); + + // the batch completed instead of releasing for a retry. + _timeProvider.Advance(WakeDispatchPolicy.OfferedRetryDelay + TimeSpan.FromSeconds(1)); + Assert.Null(await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken)); } [Fact] - public async Task DispatchAsync_Should_RecordFailed_When_TheTransportEndsInAnUnacceptedTerminalFailure() + public async Task DispatchAsync_Should_SkipWithOfflineReason_When_TheAgentRowIsMissing() { // arrange + // The batch claims a target whose agent row no longer exists. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); - var executor = new FakePingSessionExecutor { NextReason = PingAttemptReason.Timeout }; - var dispatcher = CreateDispatcher(executor); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); + var executor = new FakePingSessionExecutor(); + var missingStore = new Mock(); + missingStore + .Setup(store => store.FindAsync(actor, It.IsAny())) + .ReturnsAsync((AgentRow?)null); + var dispatcher = new ActorWakeDispatcher( + _batches, missingStore.Object, _gateCoordinator, executor, _mail, _timeProvider); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); - Assert.Equal(MailWakeTargetStatus.Failed, receipt.Status); var target = Assert.Single(receipt.Targets); - Assert.Equal(MailWakeTargetStatus.Failed, target.Status); - Assert.Equal(PingAttemptReason.Timeout.ToString(), target.LastError); + Assert.Equal( + (MailWakeTargetStatus.Skipped, actor, MailWakeTargetStatus.Skipped, "offline"), + (receipt.Status, target.Target, target.Status, target.LastError)); + Assert.Empty(executor.Calls); + + // the batch completed instead of releasing for a retry. + _timeProvider.Advance(WakeDispatchPolicy.OfferedRetryDelay + TimeSpan.FromSeconds(1)); + Assert.Null(await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken)); } [Fact] - public async Task DispatchAsync_Should_RecordFailed_When_TheFrozenTargetDisappearedBeforeDispatch() + public async Task DispatchAsync_Should_SatisfyEveryTarget_When_TheMailWasAlreadyReadBeforeDispatch() { // arrange - // The session is gone by the time the target loop re-resolves it. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + var message = await SendEnqueuedMailAsync(actor, cancellationToken); + await _mail.MarkReadAsync([message.Id], actor, cancellationToken); var executor = new FakePingSessionExecutor(); - var dispatcher = new ActorWakeDispatcher( - _batches, - new AlwaysGoneSessionRegistryDecorator(_sessions), - _gateCoordinator, - executor, - _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, - _timeProvider); + var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert + // Satisfied, zero, no transport attempted, and no second message row written. Assert.NotNull(receipt); - Assert.Equal(MailWakeTargetStatus.Failed, receipt.Status); + Assert.Equal(MailWakeTargetStatus.Satisfied, receipt.Status); var target = Assert.Single(receipt.Targets); - Assert.Equal(MailWakeTargetStatus.Failed, target.Status); - Assert.Equal("session-gone", target.LastError); + Assert.Equal(actor, target.Target); + Assert.Equal(MailWakeTargetStatus.Satisfied, target.Status); + Assert.Equal("mail-already-read", target.LastError); Assert.Empty(executor.Calls); + var sent = await _mail.QuerySentAsync("pascal", null, cancellationToken); + Assert.Single(sent); } [Fact] - public async Task DispatchAsync_Should_RecordFailed_And_LeaveTheReboundGenerationUntouched_When_TheFrozenTargetFullyRebounds() + public async Task DispatchAsync_Should_DeliverAndSettleTheBatch_When_TheTransportSucceeds() { // arrange - // The decorator replaces the frozen session with the same session id on another host. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var frozen = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - var rebound = frozen with { Host = "host-other" }; - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); - var dispatcher = new ActorWakeDispatcher( - _batches, - new ReboundOnFindSessionRegistryDecorator(_sessions, frozen, rebound, Actor), - _gateCoordinator, - executor, - _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, - _timeProvider); + var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); + + // assert + Assert.NotNull(receipt); + Assert.Equal(MailWakeTargetStatus.Delivered, receipt.Status); + var target = Assert.Single(receipt.Targets); + Assert.Equal(actor, target.Target); + Assert.Equal(MailWakeTargetStatus.Delivered, target.Status); + Assert.Single(executor.Calls); + + // the batch settled: nothing left outstanding for a fresh dispatch. + var again = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); + Assert.Null(again); + } + + [Fact] + public async Task DispatchAsync_Should_RecordFailed_When_TheTransportEndsInAnUnacceptedTerminalFailure() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); + var executor = new FakePingSessionExecutor { NextReason = PingAttemptReason.Timeout }; + var dispatcher = CreateDispatcher(executor); + + // act + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); Assert.Equal(MailWakeTargetStatus.Failed, receipt.Status); var target = Assert.Single(receipt.Targets); - Assert.Equal(frozen, target.Target); Assert.Equal(MailWakeTargetStatus.Failed, target.Status); - Assert.Equal("session-gone", target.LastError); - Assert.Empty(executor.Calls); - - var reboundSession = await _sessions.FindByGenerationAsync(rebound, cancellationToken); - Assert.NotNull(reboundSession); - Assert.Equal(Actor, reboundSession.AgentName); - Assert.Equal(0, reboundSession.BlockBudgetUsed); + Assert.Equal(PingAttemptReason.Timeout.ToString(), target.LastError); } [Fact] @@ -285,14 +299,14 @@ public async Task DispatchAsync_Should_ClampTheAttemptDeadline_When_TheSharedDea // A deadline 200ms out, inside WakeDispatchPolicy.HandoffObservationReserve (500ms). var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); var dispatcher = CreateDispatcher(executor); var tightDeadline = _timeProvider.GetUtcNow() + TimeSpan.FromMilliseconds(200); // act - var receipt = await dispatcher.DispatchAsync(Actor, tightDeadline, cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, tightDeadline, cancellationToken); // assert Assert.NotNull(receipt); @@ -307,17 +321,17 @@ public async Task DispatchAsync_Should_ClampTheAttemptDeadline_When_TheSharedDea public async Task DispatchAsync_Should_AbandonInFlightTargets_When_TheBatchLeaseRenewalIsLost_And_AllowReclaimOnTheNextDispatch() { // arrange - // A single live session whose transport call hangs until cancelled. + // A single live agent whose transport call hangs until cancelled. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var hangingExecutor = new FakePingSessionExecutor { HangUntilCancelled = true }; var dispatcher = CreateDispatcher(hangingExecutor); // act // Wait for transport entry, then advance past the batch lease expiry. - var dispatchTask = dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var dispatchTask = dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); await hangingExecutor.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); _timeProvider.Advance(WakeDispatchPolicy.BatchLeaseDuration + TimeSpan.FromSeconds(5)); @@ -331,11 +345,11 @@ public async Task DispatchAsync_Should_AbandonInFlightTargets_When_TheBatchLease // An expired batch can be reclaimed by a fresh dispatch. var freshExecutor = new FakePingSessionExecutor(); var freshDispatcher = CreateDispatcher(freshExecutor); - var reclaimed = await freshDispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var reclaimed = await freshDispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); Assert.NotNull(reclaimed); Assert.Equal(MailWakeTargetStatus.Delivered, reclaimed.Status); - Assert.Equal(generation, Assert.Single(reclaimed.Targets).Target); + Assert.Equal(actor, Assert.Single(reclaimed.Targets).Target); } [Fact] @@ -345,22 +359,20 @@ public async Task DispatchAsync_Should_AbandonInFlightTargets_When_TheBatchRenew // TryRenewAsync throws instead of returning false. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var hangingExecutor = new FakePingSessionExecutor { HangUntilCancelled = true }; var dispatcher = new ActorWakeDispatcher( new ThrowingRenewMailWakeBatchStore(_batches), - _sessions, + _agentStore, _gateCoordinator, hangingExecutor, _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, _timeProvider); // act // Wait for transport entry, then advance past the renew interval but not the lease expiry. - var dispatchTask = dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var dispatchTask = dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); await hangingExecutor.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); _timeProvider.Advance(WakeDispatchPolicy.BatchRenewInterval + TimeSpan.FromSeconds(1)); @@ -375,42 +387,11 @@ public async Task DispatchAsync_Should_AbandonInFlightTargets_When_TheBatchRenew _timeProvider.Advance(WakeDispatchPolicy.BatchLeaseDuration); var freshExecutor = new FakePingSessionExecutor(); var freshDispatcher = CreateDispatcher(freshExecutor); - var reclaimed = await freshDispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var reclaimed = await freshDispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); Assert.NotNull(reclaimed); Assert.Equal(MailWakeTargetStatus.Delivered, reclaimed.Status); - Assert.Equal(generation, Assert.Single(reclaimed.Targets).Target); - } - - [Fact] - public async Task DispatchAsync_Should_ReturnNull_And_LeaveTheOtherInstancesWorkUntouched_When_TheNitroInstanceIdDiffers() - { - // arrange - // Enqueue wake work for this instance ("host-1"). - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); - var otherInstanceDispatcher = new ActorWakeDispatcher( - _batches, - _sessions, - _gateCoordinator, - new FakePingSessionExecutor(), - _mail, - new FixedInstanceIdProvider("host-2"), - _globalConfigDirectoryProvider, - _timeProvider); - - // act - var receipt = await otherInstanceDispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); - - // assert - Assert.Null(receipt); - - var hostOneDispatcher = CreateDispatcher(new FakePingSessionExecutor()); - var hostOneReceipt = await hostOneDispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); - Assert.NotNull(hostOneReceipt); - Assert.Equal(MailWakeTargetStatus.Delivered, hostOneReceipt.Status); + Assert.Equal(actor, Assert.Single(reclaimed.Targets).Target); } [Fact] @@ -420,22 +401,20 @@ public async Task DispatchAsync_Should_ReportFailed_When_ATerminalFailureRacesAC // The decorator records Delivered immediately before forwarding the failure write. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor { NextReason = PingAttemptReason.Timeout }; - var racingBatches = new RacingAcceptanceMailWakeBatchStoreDecorator(_batches, generation, acceptedGeneration: 1); + var racingBatches = new RacingAcceptanceMailWakeBatchStoreDecorator(_batches, actor, acceptedGeneration: 1); var dispatcher = new ActorWakeDispatcher( racingBatches, - _sessions, + _agentStore, _gateCoordinator, executor, _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, _timeProvider); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); @@ -446,108 +425,39 @@ public async Task DispatchAsync_Should_ReportFailed_When_ATerminalFailureRacesAC await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT status FROM mail_wake_targets WHERE session_id = @sessionId"; - command.Parameters.AddWithValue("@sessionId", generation.SessionId); + command.CommandText = "SELECT status FROM mail_wake_targets WHERE agent = @agent"; + command.Parameters.AddWithValue("@agent", actor); var status = (string)(await command.ExecuteScalarAsync(cancellationToken))!; Assert.Equal(MailWakeTargetStatus.Failed, status); } - /// - /// A board process may run the fallback dispatcher, but is not itself a - /// recipient target. The one coding session still receives the wake. - /// - [Fact] - public async Task DispatchAsync_Should_PingOnlyTheCodexTarget_When_TheActorAlsoHasABoardSession() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - - var boardGeneration = new AgentSessionGeneration( - AgentSessionHarness.NitroBoard, "board-1", InstanceId); - await _sessions.StartAsync( - boardGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.DbWatch, "local", - envActor: "pascal", cancellationToken); - - var codexGeneration = new AgentSessionGeneration( - AgentSessionHarness.Codex, "codex-session", InstanceId); - await _sessions.StartAsync( - codexGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: "pascal", cancellationToken); - - var message = await _mail.SendMessageAsync( - new MailMessageCreation - { - Sender = "codex-worker", - Subject = "status", - Body = "check", - To = ["pascal"], - WakePolicy = MailWakePolicy.Enqueue - }, - cancellationToken); - - var queueClient = new FakeCodexQueueClient(); - var ledger = new SessionDeliveryLedger(_fileSystem, _database); - var executor = new PingSessionExecutor( - _mail, ledger, queueClient, new NoopClaudePeerClient(), _sessions, _leases, _timeProvider, - new NoopOpencodeServerClient()); - var dispatcher = new ActorWakeDispatcher( - _batches, - _sessions, - _gateCoordinator, - executor, - _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, - _timeProvider); - - // act - var dispatchReceipt = await dispatcher.DispatchAsync("pascal", Deadline(), cancellationToken); - - // assert - Assert.NotNull(dispatchReceipt); - var codexTarget = Assert.Single(dispatchReceipt.Targets); - Assert.Equal(codexGeneration, codexTarget.Target); - Assert.Equal(MailWakeTargetStatus.Delivered, codexTarget.Status); - - var call = Assert.Single(queueClient.Calls); - using var document = System.Text.Json.JsonDocument.Parse( - call.Message[(call.Message.IndexOf('\n') + 1)..]); - var item = document.RootElement.GetProperty("items")[0]; - Assert.Equal( - ("thread-1", message.Id, "check"), - (call.ThreadId, item.GetProperty("id").GetString(), item.GetProperty("body").GetString())); - } - [Fact] public async Task DispatchAsync_Should_PersistLastPingAttemptAndResult_When_TheRealExecutorDispatches() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var queueClient = new FakeCodexQueueClient(); var executor = new PingSessionExecutor( - _mail, new SessionDeliveryLedger(_fileSystem, _database), queueClient, new NoopClaudePeerClient(), - _sessions, _leases, _timeProvider, new NoopOpencodeServerClient()); + _mail, new AgentDeliveryLedger(_fileSystem, _database), queueClient, new NoopClaudePeerClient(), + _agentStore, _leases, _timeProvider, new NoopOpencodeServerClient()); var dispatcher = new ActorWakeDispatcher( _batches, - _sessions, + _agentStore, _gateCoordinator, executor, _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, _timeProvider); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); Assert.Equal(MailWakeTargetStatus.Delivered, receipt.Status); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.NotNull(row!.LastPingAttempt); Assert.Equal(AgentPingResult.Ok, row.LastPingResult); } @@ -558,28 +468,26 @@ public async Task DispatchAsync_Should_PersistTheHealthOnlyResult_When_TheOpenco // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new PingSessionExecutor( - new NoUnreadMailStoreDecorator(_mail), new SessionDeliveryLedger(_fileSystem, _database), - new FakeCodexQueueClient(), new NoopClaudePeerClient(), _sessions, _leases, _timeProvider, + new NoUnreadMailStoreDecorator(_mail), new AgentDeliveryLedger(_fileSystem, _database), + new FakeCodexQueueClient(), new NoopClaudePeerClient(), _agentStore, _leases, _timeProvider, new NoopOpencodeServerClient()); var dispatcher = new ActorWakeDispatcher( _batches, - _sessions, + _agentStore, _gateCoordinator, executor, _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, _timeProvider); // act // The dispatcher sees unread mail; the executor's digest lookup returns none. - var firstReceipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); - var firstRow = await _sessions.FindByGenerationAsync(generation, cancellationToken); + var firstReceipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); + var firstRow = await _agentStore.FindAsync(actor, cancellationToken); // assert Assert.NotNull(firstRow!.LastPingAttempt); @@ -589,11 +497,11 @@ public async Task DispatchAsync_Should_PersistTheHealthOnlyResult_When_TheOpenco // act // Rearm the idle-push gate, advance past cooldown, and enqueue another message. - await _sessions.RearmIdlePushAsync(generation, cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); _timeProvider.Advance(PingPolicy.Cooldown + TimeSpan.FromSeconds(1)); - await SendEnqueuedMailAsync(cancellationToken); - var secondReceipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); - var secondRow = await _sessions.FindByGenerationAsync(generation, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); + var secondReceipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); + var secondRow = await _agentStore.FindAsync(actor, cancellationToken); // assert Assert.NotNull(secondRow!.LastPingAttempt); @@ -609,15 +517,15 @@ public async Task DispatchAsync_Should_PushTheDigestOnce_When_TheOpencodeSession // RearmIdlePushAsync arms the idle-push gate. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(receipt); @@ -629,25 +537,26 @@ public async Task DispatchAsync_Should_PushTheDigestOnce_When_TheOpencodeSession [Fact] public async Task DispatchAsync_Should_SuppressTheSecondPush_When_TheOpencodeIdleTransitionWasNeverRearmed() { - // arrange: a first dispatch already spent the one-shot idle-push - // claim (see DispatchAsync_Should_PushTheDigestOnce_When_TheOpencodeSessionIsIdleArmed). + // arrange + // A first dispatch already spent the one-shot idle-push claim. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); - await CreateDispatcher(new FakePingSessionExecutor()).DispatchAsync(Actor, Deadline(), cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); + await CreateDispatcher(new FakePingSessionExecutor()).DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // act // Advance past the gate's cooldown, then dispatch a second wake with no fresh rearm. _timeProvider.Advance(PingPolicy.Cooldown + TimeSpan.FromSeconds(1)); - await SendEnqueuedMailAsync(cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var suppressedExecutor = new FakePingSessionExecutor(); var suppressedReceipt = await CreateDispatcher(suppressedExecutor) - .DispatchAsync(Actor, Deadline(), cancellationToken); + .DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); - // assert: suppressed rather than pushed again. + // assert + // suppressed rather than pushed again. Assert.NotNull(suppressedReceipt); var suppressedTarget = Assert.Single(suppressedReceipt.Targets); Assert.Equal(MailWakeTargetStatus.Pending, suppressedTarget.Status); @@ -662,16 +571,17 @@ public async Task DispatchAsync_Should_OfferTheTarget_When_TheOpencodeSessionIsN // A session whose idle-push gate was never armed. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var executor = new FakePingSessionExecutor(); var dispatcher = CreateDispatcher(executor); // act - var receipt = await dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var receipt = await dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); - // assert: offered, not failed, and no transport was ever attempted. + // assert + // offered, not failed, and no transport was ever attempted. Assert.NotNull(receipt); var target = Assert.Single(receipt.Targets); Assert.Equal(MailWakeTargetStatus.Pending, target.Status); @@ -686,18 +596,18 @@ public async Task DispatchAsync_Should_DeliverTheOfferedTarget_When_TheIdleTrans // A first dispatch already offered the target as idle-not-armed. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); - await CreateDispatcher(new FakePingSessionExecutor()).DispatchAsync(Actor, Deadline(), cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); + await CreateDispatcher(new FakePingSessionExecutor()).DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); - // act: once a genuine prompt rearms the gate and the retry becomes - // due, the same still-unread mail is delivered. - await _sessions.RearmIdlePushAsync(generation, cancellationToken); + // act + // A genuine prompt rearms the gate, and the retry becomes due. + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); _timeProvider.Advance(WakeDispatchPolicy.OfferedRetryDelay + TimeSpan.FromSeconds(1)); var rearmedExecutor = new FakePingSessionExecutor(); var rearmedReceipt = await CreateDispatcher(rearmedExecutor) - .DispatchAsync(Actor, Deadline(), cancellationToken); + .DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.NotNull(rearmedReceipt); @@ -709,20 +619,20 @@ public async Task DispatchAsync_Should_DeliverTheOfferedTarget_When_TheIdleTrans public async Task DispatchAsync_Should_LeaveTheIdlePushClaimArmed_When_TheOpencodeSessionGateWasBusy() { // arrange - // The session ping gate is held by an unrelated attempt. + // The agent's ping gate is held by an unrelated attempt. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); await _gates.TryAcquireAsync( - generation, "external-holder", _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); + actor, "external-holder", _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var busyExecutor = new FakePingSessionExecutor(); - // act: the gate is busy, so the target is offered rather than - // failed, and no transport is ever attempted. - var busyReceipt = await CreateDispatcher(busyExecutor).DispatchAsync(Actor, Deadline(), cancellationToken); + // act + // The gate is busy, so the target is offered rather than failed. + var busyReceipt = await CreateDispatcher(busyExecutor).DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal("busy", Assert.Single(busyReceipt!.Targets).LastError); @@ -730,11 +640,11 @@ await _gates.TryAcquireAsync( // act // Release the gate and let the offered retry become due. - await _gates.ReleaseAsync(generation, "external-holder", cancellationToken); + await _gates.ReleaseAsync(actor, "external-holder", cancellationToken); _timeProvider.Advance(WakeDispatchPolicy.OfferedRetryDelay + TimeSpan.FromSeconds(1)); var deliveredExecutor = new FakePingSessionExecutor(); var deliveredReceipt = await CreateDispatcher(deliveredExecutor) - .DispatchAsync(Actor, Deadline(), cancellationToken); + .DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal(MailWakeTargetStatus.Delivered, deliveredReceipt?.Status); @@ -747,24 +657,25 @@ public async Task DispatchAsync_Should_RearmTheIdlePushClaim_When_TheOpencodeTra // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var failingExecutor = new FakePingSessionExecutor { NextReason = PingAttemptReason.EndpointGone }; - // act: the transport fails outright. - var failedReceipt = await CreateDispatcher(failingExecutor).DispatchAsync(Actor, Deadline(), cancellationToken); + // act + // the transport fails outright. + var failedReceipt = await CreateDispatcher(failingExecutor).DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal(MailWakeTargetStatus.Failed, failedReceipt?.Status); // act // New mail arrives after the failed attempt already rearmed the claim. - await SendEnqueuedMailAsync(cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var deliveredExecutor = new FakePingSessionExecutor(); var deliveredReceipt = await CreateDispatcher(deliveredExecutor) - .DispatchAsync(Actor, Deadline(), cancellationToken); + .DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal(MailWakeTargetStatus.Delivered, deliveredReceipt?.Status); @@ -778,15 +689,15 @@ public async Task DispatchAsync_Should_RearmTheIdlePushClaim_When_TheOpencodeAtt // The executor reports a successful ping that pushed nothing (PingSessionExecutor.HealthOnlyDetail). var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var healthOnlyExecutor = new FakePingSessionExecutor { NextDetail = PingSessionExecutor.HealthOnlyDetail }; // act var healthOnlyReceipt = await CreateDispatcher(healthOnlyExecutor) - .DispatchAsync(Actor, Deadline(), cancellationToken); + .DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal(MailWakeTargetStatus.Delivered, healthOnlyReceipt?.Status); @@ -794,9 +705,9 @@ public async Task DispatchAsync_Should_RearmTheIdlePushClaim_When_TheOpencodeAtt // act // Advance past the gate's cooldown, then dispatch again with the rearmed claim. _timeProvider.Advance(PingPolicy.Cooldown + TimeSpan.FromSeconds(1)); - await SendEnqueuedMailAsync(cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var pushExecutor = new FakePingSessionExecutor(); - var pushReceipt = await CreateDispatcher(pushExecutor).DispatchAsync(Actor, Deadline(), cancellationToken); + var pushReceipt = await CreateDispatcher(pushExecutor).DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal(MailWakeTargetStatus.Delivered, pushReceipt?.Status); @@ -810,16 +721,16 @@ public async Task DispatchAsync_Should_RearmTheIdlePushClaim_When_TheOpencodeDis // The idle-push claim is spent, then the transport call hangs. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync( + var actor = await SeedLiveSessionAsync( AgentSessionEndpointKind.OpencodeServer, "http://127.0.0.1:4096", cancellationToken); - await _sessions.RearmIdlePushAsync(generation, cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + await _agentStore.RearmIdlePushAsync(actor, cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var hangingExecutor = new FakePingSessionExecutor { HangUntilCancelled = true }; var dispatcher = CreateDispatcher(hangingExecutor); // act // Wait for transport entry, then advance past the batch lease expiry. - var dispatchTask = dispatcher.DispatchAsync(Actor, Deadline(), cancellationToken); + var dispatchTask = dispatcher.DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); await hangingExecutor.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); _timeProvider.Advance(WakeDispatchPolicy.BatchLeaseDuration + TimeSpan.FromSeconds(5)); var receipt = await dispatchTask.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); @@ -831,10 +742,10 @@ public async Task DispatchAsync_Should_RearmTheIdlePushClaim_When_TheOpencodeDis // act // New mail arrives after the aborted attempt already rearmed the claim. - await SendEnqueuedMailAsync(cancellationToken); + await SendEnqueuedMailAsync(actor, cancellationToken); var deliveredExecutor = new FakePingSessionExecutor(); var deliveredReceipt = await CreateDispatcher(deliveredExecutor) - .DispatchAsync(Actor, Deadline(), cancellationToken); + .DispatchAsync(actor, LeaderToken, Deadline(), cancellationToken); // assert Assert.Equal(MailWakeTargetStatus.Delivered, deliveredReceipt?.Status); @@ -859,54 +770,88 @@ public void AddNitroServices_Should_ResolveActorWakeDispatcher_When_BuiltFromThe private DateTimeOffset Deadline() => _timeProvider.GetUtcNow() + WakeDispatchPolicy.BatchDeadline; private ActorWakeDispatcher CreateDispatcher(FakePingSessionExecutor executor) - => new( - _batches, - _sessions, - _gateCoordinator, - executor, - _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, - _timeProvider); + => new(_batches, _agentStore, _gateCoordinator, executor, _mail, _timeProvider); + /// + /// Initializes the workspace database and acquires the fixed leader + /// lease every dispatch in this class fences its batch writes on. + /// private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) { await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) { } + + await _leaderStore.TryAcquireAsync( + LeaderToken, _timeProvider.GetUtcNow(), TimeSpan.FromDays(1), cancellationToken); } - private async Task SeedLiveSessionAsync( + /// + /// Mints an agent row with a live harness session and endpoint, + /// returning its allocated name. + /// + private async Task SeedLiveSessionAsync( string endpointKind, string endpointAddr, CancellationToken cancellationToken, string sessionId = "session-1") { - // Start a fresh session on the current Nitro instance. var harness = endpointKind switch { AgentSessionEndpointKind.ClaudePeer => AgentSessionHarness.ClaudeCode, AgentSessionEndpointKind.OpencodeServer => AgentSessionHarness.Opencode, _ => AgentSessionHarness.Codex }; - var generation = new AgentSessionGeneration(harness, sessionId, InstanceId); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", endpointKind, endpointAddr, - envActor: Actor, cancellationToken); + var result = await _agentStore.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = harness, + SessionId = sessionId, + HarnessVersion = "1.0.0", + Cwd = "/work", + WorkspacePath = "/work/.nitro/agents", + EndpointKind = endpointKind, + EndpointAddr = endpointAddr + }, + cancellationToken); - return generation; + return result.Row!.Name; } - private async Task SendEnqueuedMailAsync(CancellationToken cancellationToken) - => await _mail.SendMessageAsync( + /// + /// Registers the named agent directly against the unified agents table. + /// + private async Task SeedAgentAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + private async Task SendEnqueuedMailAsync(string actor, CancellationToken cancellationToken) + { + // Registers the mail sender behind the store's sender-usability check. + await SeedAgentAsync("pascal", cancellationToken); + + return await _mail.SendMessageAsync( new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", - To = [Actor], + To = [actor], WakePolicy = MailWakePolicy.Enqueue }, cancellationToken); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/AlwaysGoneSessionRegistryDecorator.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/AlwaysGoneSessionRegistryDecorator.cs deleted file mode 100644 index 2cbacf9ffff..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/AlwaysGoneSessionRegistryDecorator.cs +++ /dev/null @@ -1,86 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Agents; - -/// -/// Returns from . -/// Delegates all other members to . -/// -internal sealed class AlwaysGoneSessionRegistryDecorator(IAgentSessionRegistry inner) : IAgentSessionRegistry -{ - public Task StartAsync( - AgentSessionGeneration generation, string cwd, string workspacePath, string endpointKind, - string endpointAddr, string? envActor, CancellationToken cancellationToken) - => inner.StartAsync(generation, cwd, workspacePath, endpointKind, endpointAddr, envActor, cancellationToken); - - public Task ClaimAsync( - AgentSessionGeneration generation, string actor, bool forceRebind, CancellationToken cancellationToken) - => inner.ClaimAsync(generation, actor, forceRebind, cancellationToken); - - public Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.EndAsync(generation, cancellationToken); - - public Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - => Task.FromResult(null); - - public Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ResetBlockBudgetAsync(generation, cancellationToken); - - public Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.IncrementBlockBudgetAsync(generation, cancellationToken); - - public Task> ReapAsync(CancellationToken cancellationToken) - => inner.ReapAsync(cancellationToken); - - public Task> ListAsync(CancellationToken cancellationToken) - => inner.ListAsync(cancellationToken); - - public Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.TouchAsync(generation, cancellationToken); - - public Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - => inner.RecordHarnessVersionAsync(generation, harnessVersion, cancellationToken); - - public Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - => inner.SetRoleAsync(generation, role, cancellationToken); - - public Task> ListParticipantsAsync(CancellationToken cancellationToken) - => inner.ListParticipantsAsync(cancellationToken); - - public Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - => inner.FindBySessionIdAsync(harness, host, sessionId, cancellationToken); - - public Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - => inner.FindLiveClaimedByAgentNameAsync(agentName, cancellationToken); - - public Task TryClaimPingCooldownAsync( - AgentSessionRecord session, string attemptId, DateTimeOffset now, TimeSpan cooldown, - CancellationToken cancellationToken) - => inner.TryClaimPingCooldownAsync(session, attemptId, now, cooldown, cancellationToken); - - public Task WritePingResultAsync( - string harness, string sessionId, string attemptId, string result, string? detail, - CancellationToken cancellationToken) - => inner.WritePingResultAsync(harness, sessionId, attemptId, result, detail, cancellationToken); - - public Task RegisterAsync( - AgentSessionGeneration generation, string actor, string role, string client, bool forceRebind, - CancellationToken cancellationToken) - => inner.RegisterAsync(generation, actor, role, client, forceRebind, cancellationToken); - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ArmAnnouncementAsync(generation, cancellationToken); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimAnnouncementAsync(generation, cancellationToken); - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.RearmIdlePushAsync(generation, cancellationToken); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimIdlePushAsync(generation, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutor.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutor.cs index 2ff82d6b75b..acefd65ac70 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutor.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutor.cs @@ -5,8 +5,8 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// -/// A scriptable whose per-session -/// entries override , which defaults to +/// A scriptable whose per-actor +/// entries override , which defaults to /// . Signals on entry and waits /// for cancellation when is set. /// @@ -22,7 +22,7 @@ internal sealed class FakePingSessionExecutor : IPingSessionExecutor public string? NextDetail { get; set; } - public ConcurrentDictionary ReasonBySessionId { get; } = new(); + public ConcurrentDictionary ReasonByActor { get; } = new(); public TimeSpan ConcurrentDelay { get; set; } = TimeSpan.Zero; @@ -35,8 +35,6 @@ internal sealed class FakePingSessionExecutor : IPingSessionExecutor public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public Task ExecuteCodexThreadAsync( - string harness, - string sessionId, string actorName, string endpointAddr, string attemptId, @@ -45,28 +43,24 @@ public Task ExecuteCodexThreadAsync( CancellationToken cancellationToken) { RecordedDeadlines.Add(deadline); - return ExecuteAsync( - harness, sessionId, attemptId, isClaudePeer: false, isOpencodeServer: false, cancellationToken); + return ExecuteAsync(actorName, attemptId, isClaudePeer: false, isOpencodeServer: false, cancellationToken); } public Task ExecuteClaudePeerAsync( - string harness, - string sessionId, string actorName, + string sessionId, string attemptId, int slot, DateTimeOffset deadline, CancellationToken cancellationToken) { RecordedDeadlines.Add(deadline); - return ExecuteAsync( - harness, sessionId, attemptId, isClaudePeer: true, isOpencodeServer: false, cancellationToken); + return ExecuteAsync(actorName, attemptId, isClaudePeer: true, isOpencodeServer: false, cancellationToken); } public Task ExecuteOpencodeServerAsync( - string harness, - string sessionId, string actorName, + string sessionId, string endpointAddr, string? endpointSecret, string attemptId, @@ -75,19 +69,17 @@ public Task ExecuteOpencodeServerAsync( CancellationToken cancellationToken) { RecordedDeadlines.Add(deadline); - return ExecuteAsync( - harness, sessionId, attemptId, isClaudePeer: false, isOpencodeServer: true, cancellationToken); + return ExecuteAsync(actorName, attemptId, isClaudePeer: false, isOpencodeServer: true, cancellationToken); } private async Task ExecuteAsync( - string harness, - string sessionId, + string actorName, string attemptId, bool isClaudePeer, bool isOpencodeServer, CancellationToken cancellationToken) { - Calls.Add(new FakePingSessionExecutorCall(harness, sessionId, isClaudePeer, isOpencodeServer)); + Calls.Add(new FakePingSessionExecutorCall(actorName, isClaudePeer, isOpencodeServer)); Entered.TrySetResult(); var observed = Interlocked.Increment(ref _concurrent); @@ -109,15 +101,14 @@ private async Task ExecuteAsync( Interlocked.Decrement(ref _concurrent); } - var reason = ReasonBySessionId.GetValueOrDefault(sessionId, NextReason); + var reason = ReasonByActor.GetValueOrDefault(actorName, NextReason); return new PingAttemptOutcome( reason == PingAttemptReason.Ok ? AgentPingResult.Ok : AgentPingResult.Error, reason, Retryable: reason is PingAttemptReason.Timeout or PingAttemptReason.TransportError, Detail: NextDetail, - harness, - sessionId, + actorName, attemptId, DateTimeOffset.UtcNow); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutorCall.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutorCall.cs index 40ae284bc5a..aae17618884 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutorCall.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/FakePingSessionExecutorCall.cs @@ -1,4 +1,4 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; internal sealed record FakePingSessionExecutorCall( - string Harness, string SessionId, bool IsClaudePeer, bool IsOpencodeServer = false); + string ActorName, bool IsClaudePeer, bool IsOpencodeServer = false); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/MailWakeDaemonCoordinatorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/MailWakeDaemonCoordinatorTests.cs index 086a0eb64de..b85277c554b 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/MailWakeDaemonCoordinatorTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/MailWakeDaemonCoordinatorTests.cs @@ -1,52 +1,44 @@ using System.Collections.Concurrent; -using System.Globalization; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Time.Testing; namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// /// Exercises against a real workspace -/// database with a fast injected and real -/// wall-clock time (no FakeTimeProvider, so there is no race between -/// advancing a fake clock and a background loop reaching its next await): -/// first acquisition, staying standby behind another owner's live lease, -/// taking over once that lease expires, exactly one leader winning when two -/// coordinators race the same instance, the admission/execution loops -/// actually draining outstanding actor wake work through the reused -/// , self-degradation on a daemon-side -/// Claude access denial without disturbing the winning standby, and a -/// bounded, leadership-releasing graceful stop. +/// database: leadership acquisition and handoff, the admission and execution +/// loops, self-degradation, a graceful stop, and demotion on a lost or fenced lease. +/// Every test drives time exclusively through a and +/// synchronizes with the coordinator's background loops through its test hooks and +/// signals; the only real-time waits are generous +/// hang guards on those signals, never something a test relies on to pass. /// public sealed class MailWakeDaemonCoordinatorTests : IDisposable { private const string Actor = "codex-worker"; - private const string InstanceId = "host-1"; private static readonly MailWakeDaemonPolicy s_fastPolicy = new( - LeaderLeaseDuration: TimeSpan.FromMilliseconds(400), + LeaderLeaseDuration: TimeSpan.FromSeconds(10), HeartbeatInterval: TimeSpan.FromMilliseconds(60), AdmissionPollInterval: TimeSpan.FromMilliseconds(30), StandbyPollInterval: TimeSpan.FromMilliseconds(30), MaxConcurrentActorExecutions: 4, ShutdownWait: TimeSpan.FromSeconds(2)); - private static readonly TimeSpan s_waitTimeout = TimeSpan.FromSeconds(5); + private static readonly TimeSpan s_hangGuard = TimeSpan.FromSeconds(60); private readonly DirectoryInfo _tempRoot; private readonly string _workspaceDirectory; private readonly TestFileSystem _fileSystem; private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; - private readonly MailStore _mail; private readonly MailWakeBatchStore _batches; private readonly SessionGateCoordinator _gateCoordinator; - private readonly FixedInstanceIdProvider _instanceIdProvider = new(InstanceId); - private readonly FixedGlobalConfigDirectoryProvider _globalConfigDirectoryProvider; + private TestAgentSeeder _agentSeeder = null!; + private AgentStore _agentStore = null!; + private MailStore _mail = null!; public MailWakeDaemonCoordinatorTests() { @@ -55,41 +47,89 @@ public MailWakeDaemonCoordinatorTests() Directory.CreateDirectory(_workspaceDirectory); _fileSystem = new TestFileSystem(_tempRoot.FullName); _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, TimeProvider.System, _database); - _sessions = new AgentSessionRegistry( - _fileSystem, - TimeProvider.System, - _database, - _agentRegistry, - _instanceIdProvider, - new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName)); - _globalConfigDirectoryProvider = new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName); - _mail = new MailStore( - _fileSystem, TimeProvider.System, _database, _agentRegistry, _instanceIdProvider, - _globalConfigDirectoryProvider); _batches = new MailWakeBatchStore(_fileSystem, _database); - var gates = new SessionPingGateStore(_fileSystem, _database); + var gates = new AgentPingGateStore(_fileSystem, _database); var leases = new PingLeaseStore(_fileSystem, _database); _gateCoordinator = new SessionGateCoordinator(gates, leases); } + /// + /// Builds the agent seeder, agent store and mail store from , + /// so every store the coordinator reads or writes through shares the test's fake clock. + /// + private void CreateStores(FakeTimeProvider timeProvider) + { + _agentSeeder = new TestAgentSeeder(_workspaceDirectory, timeProvider, _database); + _agentStore = new AgentStore(_fileSystem, timeProvider, _database); + _mail = new MailStore(_fileSystem, timeProvider, _database, _agentStore); + } + public void Dispose() => _tempRoot.Delete(recursive: true); + /// + /// Seeds rows directly against the unified agents table for tests that need an + /// actor to exist without going through 's allocated-name contract. + /// + private sealed class TestAgentSeeder(string workspaceDirectory, TimeProvider timeProvider, AgentDatabase database) + { + /// + /// Ensures the named actor exists, leaving an existing row unchanged. + /// + public Task EnsureAsync(string name, CancellationToken cancellationToken) + => UpsertAsync(name, role: null, cancellationToken); + + /// + /// Registers the normalized name and role, refreshing last-seen time. + /// + public Task RegisterAsync(string name, string role, CancellationToken cancellationToken) + => UpsertAsync(name, role, cancellationToken); + + private async Task UpsertAsync(string name, string? role, CancellationToken cancellationToken) + { + await using var connection = await database.ConnectAsync(workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = role is null + ? """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO NOTHING; + """ + : """ + INSERT INTO agents (name, role, registered_at, started_at, last_seen_at) + VALUES (@name, @role, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET role = excluded.role, last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", timeProvider.GetUtcNow()); + + if (role is not null) + { + command.Parameters.AddWithValue("@role", role); + } + + await command.ExecuteNonQueryAsync(cancellationToken); + } + } + [Fact] public async Task StartAsync_Should_BecomeReady_When_NoOtherLeaderExists() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor()); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var ticks = new LoopTickSignal(); + await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), timeProvider, ticks: ticks); // act + var ready = ticks.WaitForNextTickAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); + await ready; // assert - Assert.Equal(1, coordinator.Status.Epoch); - Assert.Equal(await ReadLeaderOwnerIdAsync(cancellationToken), coordinator.Status.OwnerId); + Assert.NotNull(coordinator.Status.OwnerToken); + Assert.Equal(await ReadLeaderOwnerTokenAsync(cancellationToken), coordinator.Status.OwnerToken); await coordinator.StopAsync(cancellationToken); } @@ -100,18 +140,28 @@ public async Task StartAsync_Should_StayStandby_When_AnotherOwnerAlreadyHoldsALi // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); var leaderStore = new MailWakeDaemonLeaderStore(_fileSystem, _database); await leaderStore.TryAcquireAsync( - InstanceId, "other-owner", DateTimeOffset.UtcNow, TimeSpan.FromSeconds(30), cancellationToken); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor()); + "other-owner", timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); + var ticks = new LoopTickSignal(); + await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), timeProvider, ticks: ticks); // act await coordinator.StartAsync(cancellationToken); - await Task.Delay(s_fastPolicy.StandbyPollInterval * 5, cancellationToken); - // assert: never became ready while the other owner's lease is live. + for (var i = 0; i < 5; i++) + { + var tick = ticks.WaitForNextTickAsync(cancellationToken); + timeProvider.Advance(s_fastPolicy.StandbyPollInterval); + await tick; + } + + // assert + // never became ready while the other owner's lease is live. Assert.Equal(MailWakeDaemonState.Standby, coordinator.Status.State); - Assert.Null(coordinator.Status.Epoch); + Assert.Null(coordinator.Status.OwnerToken); await coordinator.StopAsync(cancellationToken); } @@ -123,71 +173,55 @@ public async Task StandbyCoordinator_Should_AcquireLeadership_When_ThePriorLease // A short-lived lease held by a different owner, acquired directly through the store. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); var leaderStore = new MailWakeDaemonLeaderStore(_fileSystem, _database); - var firstEpoch = await leaderStore.TryAcquireAsync( - InstanceId, "other-owner", DateTimeOffset.UtcNow, TimeSpan.FromMilliseconds(100), cancellationToken); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor()); + var firstAcquired = await leaderStore.TryAcquireAsync( + "other-owner", timeProvider.GetUtcNow(), s_fastPolicy.StandbyPollInterval, cancellationToken); + var ticks = new LoopTickSignal(); + await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), timeProvider, ticks: ticks); // act await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.StandbyPollInterval, + ticks.WaitForNextTickAsync, + () => coordinator.Status.State == MailWakeDaemonState.Ready, + cancellationToken); - // assert: took over with a fresh, incremented epoch. - Assert.Equal(1, firstEpoch); - Assert.Equal(2, coordinator.Status.Epoch); + // assert + // took over with its own token once the prior lease expired. + Assert.True(firstAcquired); + Assert.NotNull(coordinator.Status.OwnerToken); + Assert.NotEqual("other-owner", coordinator.Status.OwnerToken); await coordinator.StopAsync(cancellationToken); } [Fact] - public async Task TwoCoordinators_Should_ElectExactlyOneLeader_When_TheyRaceTheSameInstance() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await using var coordinatorA = CreateCoordinator(new FakePingSessionExecutor()); - await using var coordinatorB = CreateCoordinator(new FakePingSessionExecutor()); - - // act - await coordinatorA.StartAsync(cancellationToken); - await coordinatorB.StartAsync(cancellationToken); - await WaitUntilAsync( - () => coordinatorA.Status.State == MailWakeDaemonState.Ready - || coordinatorB.Status.State == MailWakeDaemonState.Ready, - cancellationToken); - await Task.Delay(s_fastPolicy.StandbyPollInterval * 5, cancellationToken); - - // assert: exactly one became ready with epoch 1, the other stayed - // standby. - var states = new[] { coordinatorA.Status.State, coordinatorB.Status.State }; - Assert.Single(states, s => s == MailWakeDaemonState.Ready); - Assert.Single(states, s => s == MailWakeDaemonState.Standby); - var readyEpoch = coordinatorA.Status.State == MailWakeDaemonState.Ready - ? coordinatorA.Status.Epoch - : coordinatorB.Status.Epoch; - Assert.Equal(1, readyEpoch); - - await coordinatorA.StopAsync(cancellationToken); - await coordinatorB.StopAsync(cancellationToken); - } - - [Fact] - public async Task RunningLeader_Should_DispatchOutstandingActorWork_Through_TheAdmissionAndExecutionLoops() + public async Task RunningLeader_Should_DispatchOutstandingActorWork_When_MailIsEnqueuedForALiveAgent() { // arrange - // Enqueue mail for a live session without calling the dispatcher directly. + // Enqueue mail for a live agent without calling the dispatcher directly. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(cancellationToken, actor); var executor = new FakePingSessionExecutor(); - await using var coordinator = CreateCoordinator(executor); + var ticks = new LoopTickSignal(); + await using var coordinator = CreateCoordinator(executor, timeProvider, ticks: ticks); // act await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => !executor.Calls.IsEmpty, cancellationToken); - await WaitUntilAsync( - async () => await ReadTargetStatusAsync(generation.SessionId, cancellationToken) == MailWakeTargetStatus.Delivered, + await executor.Entered.Task.WaitAsync(s_hangGuard, cancellationToken); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.AdmissionPollInterval, + ticks.WaitForNextTickAsync, + async () => await ReadTargetStatusAsync(actor, cancellationToken) == MailWakeTargetStatus.Delivered, cancellationToken); // assert @@ -200,58 +234,116 @@ await WaitUntilAsync( [Fact] public async Task RunningLeader_Should_DegradeAndReleaseLeadership_When_ItsOwnDispatchIsAccessDenied() { - // arrange: the daemon's own attempt at the only live target is - // itself denied Claude socket access. + // arrange + // The only live target denies Claude socket access. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.ClaudePeer, "peer-a", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.ClaudePeer, "peer-a", cancellationToken); + await SendEnqueuedMailAsync(cancellationToken, actor); var executor = new FakePingSessionExecutor(); - executor.ReasonBySessionId[generation.SessionId] = PingAttemptReason.AccessDenied; - await using var coordinator = CreateCoordinator(executor); + executor.ReasonByActor[actor] = PingAttemptReason.AccessDenied; + var releaseStore = new ReleaseSignalLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); + var leadershipEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var standbyTicks = new LoopTickSignal(); + var standbyTickCount = 0; + await using var coordinator = new MailWakeDaemonCoordinator( + releaseStore, + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, executor, _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + // Fires once leadership ends, before admission ticks stop. + AfterLeadershipEndedAsync = _ => + { + leadershipEnded.TrySetResult(); + return Task.CompletedTask; + }, + AfterStandbyTickAsync = ct => + { + Interlocked.Increment(ref standbyTickCount); + return standbyTicks.HookAsync(ct); + } + }; // act await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Degraded, cancellationToken); + await leadershipEnded.Task.WaitAsync(s_hangGuard, cancellationToken); + await releaseStore.Released.WaitAsync(s_hangGuard, cancellationToken); - // assert: degraded with the denial recorded, and it does not flap - // back to ready on its own within a few more poll cycles. - Assert.Equal("access-denied", coordinator.Status.LastError); - await Task.Delay(s_fastPolicy.StandbyPollInterval * 5, cancellationToken); - Assert.NotEqual(MailWakeDaemonState.Ready, coordinator.Status.State); + // The standby loop's first tick needs no clock advance, so wait for it before advancing. + var maybeFirstStandbyTick = standbyTicks.WaitForNextTickAsync(cancellationToken); + + if (Volatile.Read(ref standbyTickCount) == 0) + { + await maybeFirstStandbyTick; + } - // a differently privileged standby (a second coordinator instance) - // can take over immediately, without waiting out the lease. - await using var standby = CreateCoordinator(new FakePingSessionExecutor()); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.StandbyPollInterval, + standbyTicks.WaitForNextTickAsync, + () => Volatile.Read(ref standbyTickCount) >= 5, + cancellationToken); + + // A differently privileged standby (a second coordinator instance) takes over. + var standbyReadyTicks = new LoopTickSignal(); + await using var standby = new MailWakeDaemonCoordinator( + new MailWakeDaemonLeaderStore(_fileSystem, _database), + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, new FakePingSessionExecutor(), _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + AfterAdmissionTickAsync = standbyReadyTicks.HookAsync + }; await standby.StartAsync(cancellationToken); - await WaitUntilAsync(() => standby.Status.State == MailWakeDaemonState.Ready, cancellationToken); - Assert.Equal(2, standby.Status.Epoch); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.StandbyPollInterval, + standbyReadyTicks.WaitForNextTickAsync, + () => standby.Status.State == MailWakeDaemonState.Ready, + cancellationToken); + + // assert + // Degraded with the denial recorded, released without waiting out the lease. + Assert.Equal(MailWakeDaemonState.Degraded, coordinator.Status.State); + Assert.Equal("access-denied", coordinator.Status.LastError); + Assert.Null(coordinator.Status.OwnerToken); + Assert.NotNull(standby.Status.OwnerToken); + Assert.True(timeProvider.GetUtcNow() - timeProvider.Start < s_fastPolicy.LeaderLeaseDuration); await coordinator.StopAsync(cancellationToken); await standby.StopAsync(cancellationToken); } [Fact] - public async Task StopAsync_Should_ReturnWithinTheShutdownBudget_And_ReleaseLeadershipImmediately() + public async Task StopAsync_Should_ReturnWithinTheShutdownBudget_And_ReleaseLeadershipImmediately_When_CalledWhileLeading() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor()); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var ticks = new LoopTickSignal(); + await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), timeProvider, ticks: ticks); + var ready = ticks.WaitForNextTickAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); + await ready; // act - var stopwatch = System.Diagnostics.Stopwatch.StartNew(); - await coordinator.StopAsync(cancellationToken); - stopwatch.Stop(); + await coordinator.StopAsync(cancellationToken).WaitAsync(s_hangGuard, cancellationToken); // assert - Assert.True(stopwatch.Elapsed < s_fastPolicy.ShutdownWait, $"StopAsync took {stopwatch.Elapsed}."); + // The hang guard proves the run loop completed rather than timed out; the lease is reacquirable immediately. var leaderStore = new MailWakeDaemonLeaderStore(_fileSystem, _database); var reacquired = await leaderStore.TryAcquireAsync( - InstanceId, "someone-else", DateTimeOffset.UtcNow, TimeSpan.FromSeconds(30), cancellationToken); - Assert.NotNull(reacquired); + "someone-else", timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); + Assert.True(reacquired); } [Fact] @@ -261,13 +353,22 @@ public async Task StartAsync_Should_RecoverAndBecomeReady_When_TheLeaderStoreFau // The leader store throws a non-busy exception on the first acquire attempt. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); var faultingStore = new FaultingLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), faultingStore); + var ticks = new LoopTickSignal(); + var retryDelayArmed = new LoopTickSignal(); + await using var coordinator = CreateCoordinator( + new FakePingSessionExecutor(), timeProvider, faultingStore, ticks, retryDelayArmed); // act + var armed = retryDelayArmed.WaitForNextTickAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.LastError == "readonly", cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); + await faultingStore.Faulted.WaitAsync(s_hangGuard, cancellationToken); + await armed; + var ready = ticks.WaitForNextTickAsync(cancellationToken); + timeProvider.Advance(s_fastPolicy.StandbyPollInterval); + await ready; // assert Assert.Equal(MailWakeDaemonState.Ready, coordinator.Status.State); @@ -278,92 +379,307 @@ public async Task StartAsync_Should_RecoverAndBecomeReady_When_TheLeaderStoreFau public async Task RunningLeader_Should_DemoteToStandby_And_CancelInFlightDispatch_When_RenewalIsLost() { // arrange - // A live session with a hanging transport call, then the next heartbeat renewal is made to fail. + // A live agent with a hanging transport call, then the next heartbeat renewal is made to fail. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - var generation = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await SendEnqueuedMailAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(cancellationToken, actor); var executor = new FakePingSessionExecutor { HangUntilCancelled = true }; - var renewalLossStore = new RenewalLossLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); - await using var coordinator = CreateCoordinator(executor, renewalLossStore); + // A lost renewal also releases the lease, so nothing else contests it before the asserts run. + var releaseStore = new ReleaseSignalLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); + var renewalLossStore = new RenewalLossLeaderStore(releaseStore); + var leadershipEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var coordinator = new MailWakeDaemonCoordinator( + renewalLossStore, + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, executor, _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + // Fires only after the coordinator's own status update, safe to assert against. + AfterLeadershipEndedAsync = _ => + { + leadershipEnded.TrySetResult(); + return Task.CompletedTask; + } + }; // act await coordinator.StartAsync(cancellationToken); - await executor.Entered.Task.WaitAsync(s_waitTimeout, cancellationToken); + await executor.Entered.Task.WaitAsync(s_hangGuard, cancellationToken); renewalLossStore.FailNextRenewal(); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Standby, cancellationToken); + timeProvider.Advance(s_fastPolicy.HeartbeatInterval); + await leadershipEnded.Task.WaitAsync(s_hangGuard, cancellationToken); + await releaseStore.Released.WaitAsync(s_hangGuard, cancellationToken); - // assert: demoted, and the hung dispatch never got to record a - // delivery for the target it was cancelled mid-flight on. - var status = await ReadTargetStatusAsync(generation.SessionId, cancellationToken); + // assert + // Demoted, and the hung dispatch never recorded a delivery. + var status = await ReadTargetStatusAsync(actor, cancellationToken); Assert.NotEqual(MailWakeTargetStatus.Delivered, status); - Assert.Null(coordinator.Status.OwnerId); - Assert.Null(coordinator.Status.Epoch); + Assert.Null(coordinator.Status.OwnerToken); Assert.Null(coordinator.Status.LeaseExpiresAt); await coordinator.StopAsync(cancellationToken); } [Fact] - public async Task RunningLeader_Should_AdmitASecondActor_While_TheFirstActorsTransportIsBlocked() + public async Task RunningLeader_Should_DemoteToStandby_When_ASecondCoordinatorAcquiresItsExpiredLease() { - // arrange: two actors, each with a live session and enqueued mail; - // every transport call hangs until cancelled. + // arrange + // A gated leader store holds coordinator A's renewal in flight while B claims the row it already lost. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - const string secondActor = "codex-worker-2"; - await SeedLiveSessionAsync( - AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken, sessionId: "session-1", actor: Actor); - await SeedLiveSessionAsync( - AgentSessionEndpointKind.CodexThread, "thread-2", cancellationToken, sessionId: "session-2", - actor: secondActor); - await SendEnqueuedMailAsync(cancellationToken, Actor); - await SendEnqueuedMailAsync(cancellationToken, secondActor); - var executor = new FakePingSessionExecutor { HangUntilCancelled = true }; - await using var coordinator = CreateCoordinator(executor); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var actor = await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); + await SendEnqueuedMailAsync(cancellationToken, actor); + var sharedLeaderStore = new MailWakeDaemonLeaderStore(_fileSystem, _database); + var gatedLeaderStore = new GatedRenewalLeaderStore(sharedLeaderStore); + var executorA = new FakePingSessionExecutor { HangUntilCancelled = true }; + await using var coordinatorA = new MailWakeDaemonCoordinator( + gatedLeaderStore, + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, executorA, _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy); + var ticksB = new LoopTickSignal(); + await using var coordinatorB = new MailWakeDaemonCoordinator( + sharedLeaderStore, + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, new FakePingSessionExecutor(), _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + AfterAdmissionTickAsync = ticksB.HookAsync + }; + + // act + await coordinatorA.StartAsync(cancellationToken); + await executorA.Entered.Task.WaitAsync(s_hangGuard, cancellationToken); + var staleToken = coordinatorA.Status.OwnerToken!; + gatedLeaderStore.HoldNextRenewal(); + timeProvider.Advance(s_fastPolicy.LeaderLeaseDuration + s_fastPolicy.HeartbeatInterval); + var aStandbyWhileRenewalHeld = coordinatorA.Status.State; + + var readyB = ticksB.WaitForNextTickAsync(cancellationToken); + await coordinatorB.StartAsync(cancellationToken); + await readyB; + gatedLeaderStore.ReleaseHeldRenewal(); + await gatedLeaderStore.RenewalCompleted.WaitAsync(s_hangGuard, cancellationToken); + var (batchId, attemptId) = await ReadActiveBatchAsync(actor, cancellationToken); + var staleOutcomeAccepted = await _batches.TryRecordTargetOutcomeAsync( + batchId, actor, staleToken, attemptId, MailWakeTargetStatus.Delivered, + offeredGeneration: null, acceptedGeneration: 1, lastError: null, timeProvider.GetUtcNow(), cancellationToken); + var staleCompleteAccepted = await _batches.TryCompleteAsync( + batchId, staleToken, attemptId, timeProvider.GetUtcNow(), cancellationToken); + + // assert + Assert.Equal(MailWakeDaemonState.Standby, aStandbyWhileRenewalHeld); + var finalState = ( + AState: coordinatorA.Status.State, + AOwnerToken: coordinatorA.Status.OwnerToken, + ALeaseExpiresAt: coordinatorA.Status.LeaseExpiresAt, + RowOwnerToken: await ReadLeaderOwnerTokenAsync(cancellationToken), + StaleOutcomeAccepted: staleOutcomeAccepted, + StaleCompleteAccepted: staleCompleteAccepted, + TargetStatus: await ReadTargetStatusAsync(actor, cancellationToken)); + Assert.Equal( + (MailWakeDaemonState.Standby, null, null, coordinatorB.Status.OwnerToken, + false, false, MailWakeTargetStatus.Pending), + finalState); + + await coordinatorA.StopAsync(cancellationToken); + await coordinatorB.StopAsync(cancellationToken); + } + + [Fact] + public async Task Coordinator_Should_RejectAStaleTermsBatchWrite_When_ItReacquiresTheLeaseItReleased() + { + // arrange + // A batch claimed under the first term's owner token, left active when the coordinator stops. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + await _agentSeeder.EnsureAsync(Actor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, Actor); + var ticks = new LoopTickSignal(); + await using var coordinator = new MailWakeDaemonCoordinator( + new MailWakeDaemonLeaderStore(_fileSystem, _database), + new CountingDispatcher(), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + AfterAdmissionTickAsync = ticks.HookAsync, + AfterStandbyTickAsync = ticks.HookAsync + }; // act + var ready = ticks.WaitForNextTickAsync(cancellationToken); + await coordinator.StartAsync(cancellationToken); + await ready; + var staleToken = coordinator.Status.OwnerToken!; + const string attemptId = "attempt-1"; + var claim = await _batches.TryClaimAsync( + Actor, staleToken, attemptId, [Actor], timeProvider.GetUtcNow(), + s_fastPolicy.LeaderLeaseDuration, cancellationToken); + await coordinator.StopAsync(cancellationToken).WaitAsync(s_hangGuard, cancellationToken); + + var readyAgain = ticks.WaitForNextTickAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(500); + await readyAgain; + var freshToken = coordinator.Status.OwnerToken; + + var staleOutcomeAccepted = await _batches.TryRecordTargetOutcomeAsync( + claim!.BatchId, Actor, staleToken, attemptId, MailWakeTargetStatus.Delivered, + offeredGeneration: null, acceptedGeneration: claim.ClaimedGeneration, lastError: null, + timeProvider.GetUtcNow(), cancellationToken); + var staleCompleteAccepted = await _batches.TryCompleteAsync( + claim.BatchId, staleToken, attemptId, timeProvider.GetUtcNow(), cancellationToken); + + // assert + // A fresh term token was minted on reacquisition, and the orphaned term's writes are fenced out. + Assert.NotEqual(staleToken, freshToken); + Assert.False(staleOutcomeAccepted); + Assert.False(staleCompleteAccepted); + + await coordinator.StopAsync(cancellationToken); + } - while (executor.Calls.Select(c => c.SessionId).Distinct().Count() < 2) + [Fact] + public async Task AdmissionLoop_Should_StopDispatching_When_TheCachedLeaderLeaseHasLapsed() + { + // arrange + // A gated leader store holds the heartbeat's renewal in flight while the cached lease goes stale. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var gatedLeaderStore = new GatedRenewalLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); + var dispatcher = new CountingDispatcher(); + var ticks = new LoopTickSignal(); + var ticksAfterInsert = 0; + DateTimeOffset? insertedAt = null; + await using var coordinator = new MailWakeDaemonCoordinator( + gatedLeaderStore, dispatcher, _fileSystem, _database, timeProvider, s_fastPolicy) { - if (DateTime.UtcNow >= deadline) + AfterAdmissionTickAsync = ct => { - throw new TimeoutException("The second actor was not admitted within 500 ms."); + if (insertedAt is { } insertedAtValue && timeProvider.GetUtcNow() > insertedAtValue) + { + Interlocked.Increment(ref ticksAfterInsert); + } + + return ticks.HookAsync(ct); } + }; - await Task.Delay(TimeSpan.FromMilliseconds(5), cancellationToken); - } + // act + var ready = ticks.WaitForNextTickAsync(cancellationToken); + await coordinator.StartAsync(cancellationToken); + await ready; + gatedLeaderStore.HoldNextRenewal(); + timeProvider.Advance(s_fastPolicy.LeaderLeaseDuration + s_fastPolicy.HeartbeatInterval); + await _agentSeeder.EnsureAsync(Actor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, Actor); + insertedAt = timeProvider.GetUtcNow(); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.AdmissionPollInterval, + ticks.WaitForNextTickAsync, + () => Volatile.Read(ref ticksAfterInsert) > 0, + cancellationToken); + gatedLeaderStore.ReleaseHeldRenewal(); - // assert: both actors were admitted concurrently, well within - // 500 ms of the first call, while neither transport had completed. - Assert.Equal(2, executor.Calls.Select(c => c.SessionId).Distinct().Count()); + // assert + // The lapsed cached lease stopped admission before the heartbeat's held renewal ever returned. + Assert.Equal(0, dispatcher.DispatchCount); + Assert.Equal(MailWakeDaemonState.Standby, coordinator.Status.State); await coordinator.StopAsync(cancellationToken); } [Fact] - public async Task RunningLeader_Should_IgnoreOutboxRows_Of_AnotherNitroInstance() + public async Task RunningLeader_Should_ReleaseLeadershipAfterTheHeldRenewalReturns_When_ItsOwnDispatchIsAccessDenied() { - // arrange: a due outbox row exists, but for a different Nitro - // instance; this instance itself has no outstanding work at all. + // arrange + // The heartbeat's renewal is held in flight while an access-denied dispatch degrades the leader. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await InsertDueOutboxRowAsync("host-2", cancellationToken); - var executor = new FakePingSessionExecutor(); - await using var coordinator = CreateCoordinator(executor); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + await _agentSeeder.EnsureAsync(Actor, cancellationToken); + var events = new ConcurrentQueue(); + var leaderStore = new OrderedReleaseLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database), events); + var dispatcher = new AlwaysDeniedDispatcher(); + var ticks = new LoopTickSignal(); + await using var coordinator = new MailWakeDaemonCoordinator( + leaderStore, dispatcher, _fileSystem, _database, timeProvider, s_fastPolicy) + { + AfterAdmissionTickAsync = ticks.HookAsync + }; + + // act + var ready = ticks.WaitForNextTickAsync(cancellationToken); + await coordinator.StartAsync(cancellationToken); + await ready; + leaderStore.HoldNextRenewal(); + timeProvider.Advance(s_fastPolicy.HeartbeatInterval); + await leaderStore.HeldEntered.WaitAsync(s_hangGuard, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, Actor); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.AdmissionPollInterval, + ticks.WaitForNextTickAsync, + () => coordinator.Status.State == MailWakeDaemonState.Degraded, + cancellationToken); + leaderStore.ReleaseHeldRenewal(); + await leaderStore.Released.WaitAsync(s_hangGuard, cancellationToken); + + // assert + Assert.Equal(["renewal-completed", "release-attempted"], events); + + await coordinator.StopAsync(cancellationToken); + } + + [Fact] + public async Task RunningLeader_Should_AdmitASecondActor_When_TheFirstActorsTransportIsBlocked() + { + // arrange + // Two due actors, both hanging on their dispatch until cancelled. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + const string firstActor = "actor-1"; + const string secondActor = "actor-2"; + await _agentSeeder.EnsureAsync(firstActor, cancellationToken); + await _agentSeeder.EnsureAsync(secondActor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, firstActor); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, secondActor); + var dispatcher = new ConcurrentEntryDispatcher(expectedActors: 2); + var ticks = new LoopTickSignal(); + await using var coordinator = new MailWakeDaemonCoordinator( + new MailWakeDaemonLeaderStore(_fileSystem, _database), dispatcher, _fileSystem, _database, timeProvider, s_fastPolicy) + { + AfterAdmissionTickAsync = ticks.HookAsync + }; // act + var firstTick = ticks.WaitForNextTickAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); - await Task.Delay(s_fastPolicy.AdmissionPollInterval * 5, cancellationToken); + await firstTick; - // assert: never dispatched to, or touched, the other instance's row. - Assert.Empty(executor.Calls); - var row = await ReadOutboxRowAsync("host-2", cancellationToken); - Assert.Equal((0L, 1L), row); + // assert + // Both actors entered their dispatch within the first admission tick, while the first was still blocked. + Assert.Equal(2, dispatcher.EnteredCount); await coordinator.StopAsync(cancellationToken); } @@ -371,19 +687,37 @@ public async Task RunningLeader_Should_IgnoreOutboxRows_Of_AnotherNitroInstance( [Fact] public async Task StartAsync_Should_BecomeReady_When_TheLeaderStoreIsBusyTwice() { - // arrange: the leader store throws SQLITE_BUSY on the first two - // acquire attempts, then succeeds. + // arrange + // The leader store throws SQLITE_BUSY on the first two acquire attempts. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); var busyStore = new BusyLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database), busyAcquireCalls: 2); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), busyStore); + var ticks = new LoopTickSignal(); + var retryDelayArmed = new LoopTickSignal(); + await using var coordinator = CreateCoordinator( + new FakePingSessionExecutor(), timeProvider, busyStore, ticks, retryDelayArmed); // act + var firstDelayArmed = retryDelayArmed.WaitForNextTickAsync(cancellationToken); + var firstCall = busyStore.WaitForNextCallAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); + await firstCall; + await firstDelayArmed; - // assert: retried through both busy attempts and became ready on the - // third, without recording an error. + var secondDelayArmed = retryDelayArmed.WaitForNextTickAsync(cancellationToken); + var secondCall = busyStore.WaitForNextCallAsync(cancellationToken); + timeProvider.Advance(MailWakeDaemonRetryPolicy.ComputeDelay(1)); + await secondCall; + await secondDelayArmed; + + var ready = ticks.WaitForNextTickAsync(cancellationToken); + timeProvider.Advance(MailWakeDaemonRetryPolicy.ComputeDelay(2)); + await ready; + + // assert + // Retried through both busy attempts and became ready on the third. Assert.Equal(3, busyStore.AcquireCalls); Assert.Null(coordinator.Status.LastError); @@ -397,18 +731,56 @@ public async Task StartAsync_Should_GiveUpTheTick_And_RetryOnTheNextStandbyPoll_ // The leader store throws SQLITE_BUSY on the first five acquire attempts, then succeeds. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); var busyStore = new BusyLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database), busyAcquireCalls: 5); - await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), busyStore); + var standbyTicks = new LoopTickSignal(); + var admissionTicks = new LoopTickSignal(); + var retryDelayArmed = new LoopTickSignal(); + await using var coordinator = new MailWakeDaemonCoordinator( + busyStore, + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, new FakePingSessionExecutor(), _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + AfterStandbyTickAsync = standbyTicks.HookAsync, + AfterAdmissionTickAsync = admissionTicks.HookAsync, + AfterRetryDelayArmedAsync = retryDelayArmed.HookAsync + }; // act + var firstDelayArmed = retryDelayArmed.WaitForNextTickAsync(cancellationToken); + var firstCall = busyStore.WaitForNextCallAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync( - () => coordinator.Status.State == MailWakeDaemonState.Ready, - cancellationToken, - timeout: TimeSpan.FromSeconds(10)); + await firstCall; + await firstDelayArmed; + + for (var attempt = 1; attempt < 4; attempt++) + { + var nextDelayArmed = retryDelayArmed.WaitForNextTickAsync(cancellationToken); + var nextCall = busyStore.WaitForNextCallAsync(cancellationToken); + timeProvider.Advance(MailWakeDaemonRetryPolicy.ComputeDelay(attempt)); + await nextCall; + await nextDelayArmed; + } + + // Call #5 exhausts the attempt budget, so it moves straight to the standby-poll hook. + var fifthCall = busyStore.WaitForNextCallAsync(cancellationToken); + var standbyTick = standbyTicks.WaitForNextTickAsync(cancellationToken); + timeProvider.Advance(MailWakeDaemonRetryPolicy.ComputeDelay(4)); + await fifthCall; + await standbyTick; - // assert: five attempts exhausted the first tick's busy retries, and - // a sixth attempt on the next standby poll succeeded. + var sixthCall = busyStore.WaitForNextCallAsync(cancellationToken); + var ready = admissionTicks.WaitForNextTickAsync(cancellationToken); + timeProvider.Advance(s_fastPolicy.StandbyPollInterval); + await sixthCall; + await ready; + + // assert + // Five attempts exhausted the first tick, and a sixth succeeded on the next poll. Assert.Equal(6, busyStore.AcquireCalls); Assert.Null(coordinator.Status.LastError); @@ -422,34 +794,56 @@ public async Task StartAsync_Should_Throw_When_APriorStopTimedOut_And_TheRunLoop // The only outstanding actor's dispatch hangs forever and ignores cancellation. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); - await SeedLiveSessionAsync(AgentSessionEndpointKind.CodexThread, "thread-1", cancellationToken); - await InsertDueOutboxRowAsync(InstanceId, cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + await _agentSeeder.EnsureAsync(Actor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, Actor); var shortShutdownPolicy = s_fastPolicy with { ShutdownWait = TimeSpan.FromMilliseconds(50) }; var dispatcher = new HangingDispatcher(); + var releaseStore = new ReleaseSignalLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); + var ticks = new LoopTickSignal(); + var stopWaitArmed = new LoopTickSignal(); + var leadershipEndedEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var parkGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var coordinator = new MailWakeDaemonCoordinator( - new MailWakeDaemonLeaderStore(_fileSystem, _database), + releaseStore, dispatcher, _fileSystem, _database, - _instanceIdProvider, - _globalConfigDirectoryProvider, - TimeProvider.System, - shortShutdownPolicy); + timeProvider, + shortShutdownPolicy) + { + AfterAdmissionTickAsync = ticks.HookAsync, + // Parks the run loop before its own drain bound, so StopAsync's bound times out first. + AfterLeadershipEndedAsync = _ => + { + leadershipEndedEntered.TrySetResult(); + return parkGate.Task; + }, + AfterShutdownWaitArmedAsync = stopWaitArmed.HookAsync + }; + var ready = ticks.WaitForNextTickAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Ready, cancellationToken); - await WaitUntilAsync(() => dispatcher.EnteredCount > 0, cancellationToken); - await coordinator.StopAsync(cancellationToken); + await ready; + await dispatcher.Entered.Task.WaitAsync(s_hangGuard, cancellationToken); + + // act + // A still-alive orphaned run loop keeps StartAsync's guard throwing for this instance. + var stopWaitArmedWait = stopWaitArmed.WaitForNextTickAsync(cancellationToken); + var stopping = coordinator.StopAsync(cancellationToken); + await stopWaitArmedWait; + await leadershipEndedEntered.Task.WaitAsync(s_hangGuard, cancellationToken); + timeProvider.Advance(shortShutdownPolicy.ShutdownWait); + await stopping; + var restart = () => coordinator.StartAsync(cancellationToken); - // act & assert: a still-alive orphaned run loop keeps StartAsync's - // guard throwing for this instance. - await Assert.ThrowsAsync(() => coordinator.StartAsync(cancellationToken)); + // assert + await Assert.ThrowsAsync(restart); - // Release the dispatch and wait for leadership cleanup before disposing the coordinator. - var leaseExpiresBeforeRelease = await ReadLeaderExpiresAtAsync(cancellationToken); + // Release the parked run loop and the dispatch, then wait for leadership cleanup. + parkGate.TrySetResult(); dispatcher.Release(); - await WaitUntilAsync( - async () => await ReadLeaderExpiresAtAsync(cancellationToken) != leaseExpiresBeforeRelease, - cancellationToken); + await releaseStore.Released.WaitAsync(s_hangGuard, cancellationToken); await coordinator.DisposeAsync(); } @@ -460,34 +854,57 @@ public async Task RunningLeader_Should_ReleaseLeadership_And_CancelSiblings_When // One actor is denied access, a second hangs on transport, and release throws SQLITE_BUSY once. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); const string deniedActor = "denied-actor"; const string hungActor = "hung-actor"; - await _agentRegistry.EnsureImplicitAsync(deniedActor, cancellationToken); - await _agentRegistry.EnsureImplicitAsync(hungActor, cancellationToken); - await InsertDueOutboxRowAsync(InstanceId, cancellationToken, deniedActor); - await InsertDueOutboxRowAsync(InstanceId, cancellationToken, hungActor); + await _agentSeeder.EnsureAsync(deniedActor, cancellationToken); + await _agentSeeder.EnsureAsync(hungActor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, deniedActor); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, hungActor); var events = new ConcurrentQueue(); var dispatcher = new DeniedThenHangingDispatcher(deniedActor, events); var busyReleaseStore = new BusyReleaseLeaderStore( new MailWakeDaemonLeaderStore(_fileSystem, _database), busyReleaseCalls: 1, events); + var retryDelayArmed = new LoopTickSignal(); await using var coordinator = new MailWakeDaemonCoordinator( - busyReleaseStore, - dispatcher, - _fileSystem, - _database, - _instanceIdProvider, - _globalConfigDirectoryProvider, - TimeProvider.System, - s_fastPolicy); + busyReleaseStore, dispatcher, _fileSystem, _database, timeProvider, s_fastPolicy) + { + AfterRetryDelayArmedAsync = retryDelayArmed.HookAsync + }; // act + var firstDelayArmed = retryDelayArmed.WaitForNextTickAsync(cancellationToken); + var firstReleaseAttempt = busyReleaseStore.WaitForNextReleaseAttemptAsync(cancellationToken); await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => coordinator.Status.State == MailWakeDaemonState.Degraded, cancellationToken); + await firstReleaseAttempt; + await firstDelayArmed; + + var secondReleaseAttempt = busyReleaseStore.WaitForNextReleaseAttemptAsync(cancellationToken); + timeProvider.Advance(MailWakeDaemonRetryPolicy.ComputeDelay(1)); + await secondReleaseAttempt; + await busyReleaseStore.Released.WaitAsync(s_hangGuard, cancellationToken); - // the busy-retried release only completes ~250ms (the policy's - // initial backoff) after the first, busy attempt, so wait for the - // actual retry rather than for Degraded alone. - await WaitUntilAsync(() => busyReleaseStore.ReleaseCalls >= 2, cancellationToken); + // A differently privileged standby takes over, proving the release reached the database. + var standbyReadyTicks = new LoopTickSignal(); + await using var standby = new MailWakeDaemonCoordinator( + new MailWakeDaemonLeaderStore(_fileSystem, _database), + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, new FakePingSessionExecutor(), _mail, timeProvider), + _fileSystem, + _database, + timeProvider, + s_fastPolicy) + { + AfterAdmissionTickAsync = standbyReadyTicks.HookAsync, + AfterStandbyTickAsync = standbyReadyTicks.HookAsync + }; + await standby.StartAsync(cancellationToken); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.StandbyPollInterval, + standbyReadyTicks.WaitForNextTickAsync, + () => standby.Status.State == MailWakeDaemonState.Ready, + cancellationToken); // assert Assert.Equal(2, busyReleaseStore.ReleaseCalls); @@ -497,14 +914,7 @@ public async Task RunningLeader_Should_ReleaseLeadership_And_CancelSiblings_When Assert.True( cancelledIndex >= 0 && releasedIndex >= 0 && cancelledIndex < releasedIndex, $"Expected \"{hungActor}-cancelled\" before \"release-attempted\". Events: [{string.Join(", ", ordered)}]"); - - // a differently privileged standby can take over immediately, - // proving the release actually reached the database rather than - // leaving this instance wedged as leader. - await using var standby = CreateCoordinator(new FakePingSessionExecutor()); - await standby.StartAsync(cancellationToken); - await WaitUntilAsync(() => standby.Status.State == MailWakeDaemonState.Ready, cancellationToken); - Assert.Equal(2, standby.Status.Epoch); + Assert.NotNull(standby.Status.OwnerToken); await coordinator.StopAsync(cancellationToken); await standby.StopAsync(cancellationToken); @@ -517,55 +927,149 @@ public async Task RunningLeader_Should_NeverExceedMaxConcurrentActorExecutions_W // Five due actors under a policy capped at four concurrent executions. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); var actors = Enumerable.Range(1, 5).Select(i => $"actor-{i}").ToArray(); foreach (var actor in actors) { - await _agentRegistry.EnsureImplicitAsync(actor, cancellationToken); - await InsertDueOutboxRowAsync(InstanceId, cancellationToken, actor); + await _agentSeeder.EnsureAsync(actor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, actor); } - var dispatcher = new ConcurrencyTrackingDispatcher(); + var dispatcher = new ConcurrencyTrackingDispatcher(capacity: s_fastPolicy.MaxConcurrentActorExecutions); + var ticks = new LoopTickSignal(); await using var coordinator = new MailWakeDaemonCoordinator( - new MailWakeDaemonLeaderStore(_fileSystem, _database), - dispatcher, - _fileSystem, - _database, - _instanceIdProvider, - _globalConfigDirectoryProvider, - TimeProvider.System, - s_fastPolicy); + new MailWakeDaemonLeaderStore(_fileSystem, _database), dispatcher, _fileSystem, _database, timeProvider, s_fastPolicy) + { + AfterAdmissionTickAsync = ticks.HookAsync + }; // act await coordinator.StartAsync(cancellationToken); - await WaitUntilAsync(() => dispatcher.CompletedActors.Distinct().Count() >= actors.Length, cancellationToken); + await dispatcher.CapacityReached.WaitAsync(s_hangGuard, cancellationToken); + dispatcher.ReleaseAll(); + await AdvanceUntilAsync( + timeProvider, + s_fastPolicy.AdmissionPollInterval, + ticks.WaitForNextTickAsync, + () => dispatcher.CompletedActors.Distinct().Count() >= actors.Length, + cancellationToken); - // assert: the gate's own capacity was actually reached, and never - // exceeded, while draining all five actors. + // assert + // The gate's capacity was reached, and never exceeded, while draining all five actors. Assert.Equal(s_fastPolicy.MaxConcurrentActorExecutions, dispatcher.MaxObservedConcurrency); await coordinator.StopAsync(cancellationToken); } + [Fact] + public async Task RunningLeader_Should_ReleaseLeadershipAndReturnToStandby_When_ItsHeartbeatRenewalThrows() + { + // arrange + // F3: the next heartbeat renewal throws instead of returning false. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + var releaseStore = new ReleaseSignalLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); + var throwingStore = new ThrowingRenewalLeaderStore(releaseStore); + var ticks = new LoopTickSignal(); + await using var coordinator = CreateCoordinator(new FakePingSessionExecutor(), timeProvider, throwingStore, ticks); + + // act + var ready = ticks.WaitForNextTickAsync(cancellationToken); + await coordinator.StartAsync(cancellationToken); + await ready; + throwingStore.FailNextRenewal(); + timeProvider.Advance(s_fastPolicy.HeartbeatInterval); + await throwingStore.RenewalFaulted.WaitAsync(s_hangGuard, cancellationToken); + await releaseStore.Released.WaitAsync(s_hangGuard, cancellationToken); + var reacquired = await new MailWakeDaemonLeaderStore(_fileSystem, _database).TryAcquireAsync( + "someone-else", timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); + + // assert + // Demoted locally, and the lease was actually released rather than left held until natural expiry. + Assert.Equal(MailWakeDaemonState.Standby, coordinator.Status.State); + Assert.True(reacquired); + + await coordinator.StopAsync(cancellationToken); + } + + [Fact] + public async Task RunningLeader_Should_ReleaseLeadershipAfterTheShutdownWait_When_ADispatchIgnoresCancellation() + { + // arrange + // F4: the only due actor's dispatch hangs forever and ignores cancellation, then the heartbeat renewal is lost. + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + CreateStores(timeProvider); + await _agentSeeder.EnsureAsync(Actor, cancellationToken); + await InsertDueOutboxRowAsync(cancellationToken, timeProvider, Actor); + var dispatcher = new HangingDispatcher(); + var releaseStore = new ReleaseSignalLeaderStore(new MailWakeDaemonLeaderStore(_fileSystem, _database)); + var renewalLossStore = new RenewalLossLeaderStore(releaseStore); + var ticks = new LoopTickSignal(); + var leadershipEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var shutdownWaitArmed = new LoopTickSignal(); + await using var coordinator = new MailWakeDaemonCoordinator( + renewalLossStore, dispatcher, _fileSystem, _database, timeProvider, s_fastPolicy) + { + AfterAdmissionTickAsync = ticks.HookAsync, + AfterLeadershipEndedAsync = _ => + { + leadershipEnded.TrySetResult(); + return Task.CompletedTask; + }, + AfterShutdownWaitArmedAsync = shutdownWaitArmed.HookAsync + }; + + // act + var ready = ticks.WaitForNextTickAsync(cancellationToken); + await coordinator.StartAsync(cancellationToken); + await ready; + await dispatcher.Entered.Task.WaitAsync(s_hangGuard, cancellationToken); + var shutdownWaitArmedWait = shutdownWaitArmed.WaitForNextTickAsync(cancellationToken); + renewalLossStore.FailNextRenewal(); + timeProvider.Advance(s_fastPolicy.HeartbeatInterval); + await leadershipEnded.Task.WaitAsync(s_hangGuard, cancellationToken); + await shutdownWaitArmedWait; + timeProvider.Advance(s_fastPolicy.ShutdownWait); + await releaseStore.Released.WaitAsync(s_hangGuard, cancellationToken); + var reacquired = await new MailWakeDaemonLeaderStore(_fileSystem, _database).TryAcquireAsync( + "someone-else", timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); + + // assert + // Released within the shutdown budget even though the stuck dispatch never returned, + // and the log names the stuck actor rather than staying generic. + Assert.Contains("shutdown", coordinator.Status.LastError, StringComparison.OrdinalIgnoreCase); + Assert.Contains(Actor, coordinator.Status.LastError, StringComparison.Ordinal); + Assert.True(reacquired); + + // The stuck dispatch is released now so its orphaned task and the drain can both finish. + dispatcher.Release(); + await coordinator.StopAsync(cancellationToken); + } + private MailWakeDaemonCoordinator CreateCoordinator( - FakePingSessionExecutor executor, IMailWakeDaemonLeaderStore? leaderStore = null) + FakePingSessionExecutor executor, + TimeProvider timeProvider, + IMailWakeDaemonLeaderStore? leaderStore = null, + LoopTickSignal? ticks = null, + LoopTickSignal? retryDelayArmed = null) => new( leaderStore ?? new MailWakeDaemonLeaderStore(_fileSystem, _database), - new ActorWakeDispatcher( - _batches, - _sessions, - _gateCoordinator, - executor, - _mail, - _instanceIdProvider, - _globalConfigDirectoryProvider, - TimeProvider.System), + new ActorWakeDispatcher(_batches, _agentStore, _gateCoordinator, executor, _mail, timeProvider), _fileSystem, _database, - _instanceIdProvider, - _globalConfigDirectoryProvider, - TimeProvider.System, - s_fastPolicy); + timeProvider, + s_fastPolicy) + { + AfterAdmissionTickAsync = ticks is null ? null : ticks.HookAsync, + AfterStandbyTickAsync = ticks is null ? null : ticks.HookAsync, + AfterRetryDelayArmedAsync = retryDelayArmed is null ? null : retryDelayArmed.HookAsync + }; private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) { @@ -574,24 +1078,39 @@ private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) } } - private async Task SeedLiveSessionAsync( - string endpointKind, string endpointAddr, CancellationToken cancellationToken, - string sessionId = "session-1", string actor = Actor) + /// + /// Mints an agent row with a live harness session and endpoint, + /// returning its allocated name. + /// + private async Task SeedLiveSessionAsync( + string endpointKind, string endpointAddr, CancellationToken cancellationToken, string sessionId = "session-1") { var harness = endpointKind == AgentSessionEndpointKind.ClaudePeer ? AgentSessionHarness.ClaudeCode : AgentSessionHarness.Codex; - var generation = new AgentSessionGeneration(harness, sessionId, InstanceId); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", endpointKind, endpointAddr, envActor: actor, + var result = await _agentStore.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = harness, + SessionId = sessionId, + HarnessVersion = "1.0.0", + Cwd = "/work", + WorkspacePath = "/work/.nitro/agents", + EndpointKind = endpointKind, + EndpointAddr = endpointAddr + }, cancellationToken); - return generation; + return result.Row!.Name; } - private async Task SendEnqueuedMailAsync(CancellationToken cancellationToken, string actor = Actor) - => await _mail.SendMessageAsync( + private async Task SendEnqueuedMailAsync(CancellationToken cancellationToken, string actor) + { + // Registers the mail sender behind the store's sender-usability check. + await _agentSeeder.RegisterAsync("pascal", role: "", cancellationToken); + + return await _mail.SendMessageAsync( new MailMessageCreation { Sender = "pascal", @@ -601,162 +1120,183 @@ private async Task SendEnqueuedMailAsync(CancellationToken cancella WakePolicy = MailWakePolicy.Enqueue }, cancellationToken); + } - private async Task ReadTargetStatusAsync(string sessionId, CancellationToken cancellationToken) + private async Task ReadTargetStatusAsync(string agent, CancellationToken cancellationToken) { await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT status FROM mail_wake_targets WHERE session_id = @sessionId"; - command.Parameters.AddWithValue("@sessionId", sessionId); + command.CommandText = "SELECT status FROM mail_wake_targets WHERE agent = @agent"; + command.Parameters.AddWithValue("@agent", agent); return (string?)await command.ExecuteScalarAsync(cancellationToken); } - private async Task ReadLeaderOwnerIdAsync(CancellationToken cancellationToken) + /// + /// Reads the actor's active batch id and attempt id. + /// + private async Task<(string BatchId, string AttemptId)> ReadActiveBatchAsync( + string actor, CancellationToken cancellationToken) { await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT owner_id FROM mail_wake_daemons WHERE nitro_instance_id = @nitroInstanceId"; - command.Parameters.AddWithValue("@nitroInstanceId", InstanceId); - return (string?)await command.ExecuteScalarAsync(cancellationToken); + command.CommandText = + "SELECT batch_id, attempt_id FROM mail_wake_batches WHERE actor = @actor AND status = 'active'"; + command.Parameters.AddWithValue("@actor", actor); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + await reader.ReadAsync(cancellationToken); + return (reader.GetString(0), reader.GetString(1)); } - private async Task ReadLeaderExpiresAtAsync(CancellationToken cancellationToken) + private async Task ReadLeaderOwnerTokenAsync(CancellationToken cancellationToken) { await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); - command.CommandText = "SELECT expires_at FROM mail_wake_daemons WHERE nitro_instance_id = @nitroInstanceId"; - command.Parameters.AddWithValue("@nitroInstanceId", InstanceId); - var value = (string?)await command.ExecuteScalarAsync(cancellationToken); - return value is null ? null : DateTimeOffset.Parse(value, CultureInfo.InvariantCulture); + command.CommandText = "SELECT owner_token FROM mail_wake_daemons WHERE id = 1"; + return (string?)await command.ExecuteScalarAsync(cancellationToken); } private async Task InsertDueOutboxRowAsync( - string nitroInstanceId, CancellationToken cancellationToken, string actor = Actor) + CancellationToken cancellationToken, FakeTimeProvider timeProvider, string actor = Actor) { await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); await using var command = connection.CreateCommand(); command.CommandText = """ - INSERT INTO mail_wake_outbox ( - nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at - ) - VALUES (@nitroInstanceId, @actor, 1, 0, @now, @now) + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES (@actor, 1, 0, @now, @now) """; - command.Parameters.AddWithValue("@nitroInstanceId", nitroInstanceId); command.Parameters.AddWithValue("@actor", actor); - command.Parameters.AddWithValue("@now", DateTimeOffset.UtcNow.AddSeconds(-1)); + command.Parameters.AddWithValue("@now", timeProvider.GetUtcNow()); await command.ExecuteNonQueryAsync(cancellationToken); } - private async Task<(long SettledGeneration, long RequestedGeneration)> ReadOutboxRowAsync( - string nitroInstanceId, CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "SELECT settled_generation, requested_generation FROM mail_wake_outbox " - + "WHERE nitro_instance_id = @nitroInstanceId"; - command.Parameters.AddWithValue("@nitroInstanceId", nitroInstanceId); - await using var reader = await command.ExecuteReaderAsync(cancellationToken); - await reader.ReadAsync(cancellationToken); - return (reader.GetInt64(0), reader.GetInt64(1)); - } - - private static async Task WaitUntilAsync( - Func condition, CancellationToken cancellationToken, TimeSpan? timeout = null) + /// + /// Repeatedly advances by until + /// is observed true. Each iteration arms + /// 's next signal before advancing the clock, so the + /// tick that advance triggers can never race ahead of the wait that observes it. + /// + private static async Task AdvanceUntilAsync( + FakeTimeProvider timeProvider, + TimeSpan step, + Func waitForNextTickAsync, + Func condition, + CancellationToken cancellationToken) { - var deadline = DateTime.UtcNow + (timeout ?? s_waitTimeout); - while (!condition()) { - if (DateTime.UtcNow >= deadline) - { - throw new TimeoutException("Condition was not met within the timeout."); - } - - await Task.Delay(TimeSpan.FromMilliseconds(15), cancellationToken); + var tick = waitForNextTickAsync(cancellationToken); + timeProvider.Advance(step); + await tick; } } - private static async Task WaitUntilAsync(Func> condition, CancellationToken cancellationToken) + private static async Task AdvanceUntilAsync( + FakeTimeProvider timeProvider, + TimeSpan step, + Func waitForNextTickAsync, + Func> condition, + CancellationToken cancellationToken) { - var deadline = DateTime.UtcNow + s_waitTimeout; - while (!await condition()) { - if (DateTime.UtcNow >= deadline) - { - throw new TimeoutException("Condition was not met within the timeout."); - } - - await Task.Delay(TimeSpan.FromMilliseconds(15), cancellationToken); + var tick = waitForNextTickAsync(cancellationToken); + timeProvider.Advance(step); + await tick; } } } +/// +/// A repeatable signal for a coordinator loop hook (AfterAdmissionTickAsync or +/// AfterStandbyTickAsync): each call to reads the +/// currently armed completion source, which fulfills the next time the +/// loop invokes it. Callers must call before whatever action +/// triggers the next tick, so the wait cannot race a tick that fires before it is armed. Bounded +/// by a generous real-time hang guard so a genuinely broken test fails instead of hanging. +/// +internal sealed class LoopTickSignal +{ + private static readonly TimeSpan s_hangGuard = TimeSpan.FromSeconds(60); + + private TaskCompletionSource _next = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task HookAsync(CancellationToken cancellationToken) + { + var completed = Interlocked.Exchange( + ref _next, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + completed.TrySetResult(); + return Task.CompletedTask; + } + + public Task WaitForNextTickAsync(CancellationToken cancellationToken) + => Volatile.Read(ref _next).Task.WaitAsync(s_hangGuard, cancellationToken); +} + /// /// Delegates every call to , except the first /// call, which throws a non-busy -/// instead. +/// instead and signals beforehand. /// internal sealed class FaultingLeaderStore(IMailWakeDaemonLeaderStore inner) : IMailWakeDaemonLeaderStore { + private readonly TaskCompletionSource _faulted = new(TaskCreationOptions.RunContinuationsAsynchronously); private int _acquireCalls; - public Task TryAcquireAsync( - string nitroInstanceId, string ownerId, DateTimeOffset now, TimeSpan leaseDuration, - CancellationToken cancellationToken) + public Task Faulted => _faulted.Task; + + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) { if (Interlocked.Increment(ref _acquireCalls) == 1) { + _faulted.TrySetResult(); throw new SqliteException("readonly", 8); // SQLITE_READONLY, not SQLITE_BUSY/LOCKED. } - return inner.TryAcquireAsync(nitroInstanceId, ownerId, now, leaseDuration, cancellationToken); + return inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); } - public Task TryRenewAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, TimeSpan leaseDuration, - string? lastError, CancellationToken cancellationToken) - => inner.TryRenewAsync(nitroInstanceId, ownerId, epoch, now, leaseDuration, lastError, cancellationToken); + public Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); - public Task TryReleaseAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, CancellationToken cancellationToken) - => inner.TryReleaseAsync(nitroInstanceId, ownerId, epoch, now, cancellationToken); + public Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + => inner.TryReleaseAsync(token, now, cancellationToken); } /// /// Delegates every call to , except that the first /// calls to -/// throw a for SQLITE_BUSY instead. +/// throw a for SQLITE_BUSY instead. Each attempt +/// (busy or not) signals 's next tick. /// internal sealed class BusyLeaderStore(IMailWakeDaemonLeaderStore inner, int busyAcquireCalls) : IMailWakeDaemonLeaderStore { + private readonly LoopTickSignal _calls = new(); private int _acquireCalls; public int AcquireCalls => Volatile.Read(ref _acquireCalls); - public Task TryAcquireAsync( - string nitroInstanceId, string ownerId, DateTimeOffset now, TimeSpan leaseDuration, - CancellationToken cancellationToken) + public Task WaitForNextCallAsync(CancellationToken cancellationToken) => _calls.WaitForNextTickAsync(cancellationToken); + + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) { - if (Interlocked.Increment(ref _acquireCalls) <= busyAcquireCalls) + var call = Interlocked.Increment(ref _acquireCalls); + _ = _calls.HookAsync(cancellationToken); + + if (call <= busyAcquireCalls) { throw new SqliteException("busy", 5); // SQLITE_BUSY } - return inner.TryAcquireAsync(nitroInstanceId, ownerId, now, leaseDuration, cancellationToken); + return inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); } - public Task TryRenewAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, TimeSpan leaseDuration, - string? lastError, CancellationToken cancellationToken) - => inner.TryRenewAsync(nitroInstanceId, ownerId, epoch, now, leaseDuration, lastError, cancellationToken); + public Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); - public Task TryReleaseAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, CancellationToken cancellationToken) - => inner.TryReleaseAsync(nitroInstanceId, ownerId, epoch, now, cancellationToken); + public Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + => inner.TryReleaseAsync(token, now, cancellationToken); } /// @@ -764,38 +1304,49 @@ public Task TryReleaseAsync( /// calls to /// throw a for SQLITE_BUSY instead. Each /// attempt (busy or not) is optionally logged to -/// as "release-attempted", for asserting ordering against other -/// recorded events. +/// as "release-attempted" and signals 's +/// next tick, for asserting ordering against other recorded events. /// internal sealed class BusyReleaseLeaderStore( IMailWakeDaemonLeaderStore inner, int busyReleaseCalls, ConcurrentQueue? events = null) : IMailWakeDaemonLeaderStore { + private readonly LoopTickSignal _releaseAttempts = new(); + private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously); private int _releaseCalls; public int ReleaseCalls => Volatile.Read(ref _releaseCalls); - public Task TryAcquireAsync( - string nitroInstanceId, string ownerId, DateTimeOffset now, TimeSpan leaseDuration, - CancellationToken cancellationToken) - => inner.TryAcquireAsync(nitroInstanceId, ownerId, now, leaseDuration, cancellationToken); + /// + /// Resolves once a non-busy call has actually reached the + /// database and returned, unlike which fires + /// on entry to every attempt, busy or not. + /// + public Task Released => _released.Task; - public Task TryRenewAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, TimeSpan leaseDuration, - string? lastError, CancellationToken cancellationToken) - => inner.TryRenewAsync(nitroInstanceId, ownerId, epoch, now, leaseDuration, lastError, cancellationToken); + public Task WaitForNextReleaseAttemptAsync(CancellationToken cancellationToken) + => _releaseAttempts.WaitForNextTickAsync(cancellationToken); - public Task TryReleaseAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, CancellationToken cancellationToken) + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); + + public Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); + + public async Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) { events?.Enqueue("release-attempted"); + var call = Interlocked.Increment(ref _releaseCalls); + _ = _releaseAttempts.HookAsync(cancellationToken); - if (Interlocked.Increment(ref _releaseCalls) <= busyReleaseCalls) + if (call <= busyReleaseCalls) { throw new SqliteException("busy", 5); // SQLITE_BUSY } - return inner.TryReleaseAsync(nitroInstanceId, ownerId, epoch, now, cancellationToken); + var released = await inner.TryReleaseAsync(token, now, cancellationToken); + _released.TrySetResult(); + return released; } } @@ -814,20 +1365,17 @@ internal sealed class DeniedThenHangingDispatcher(string deniedActor, Concurrent private int _deniedDispatchCount; public async Task DispatchAsync( - string actor, DateTimeOffset deadline, CancellationToken cancellationToken) + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) { if (actor == deniedActor && Interlocked.Increment(ref _deniedDispatchCount) == 1) { // Never race ahead of the sibling actually being in flight. await _hungRegistered.Task; - var target = new AgentSessionGeneration( - AgentSessionHarness.ClaudeCode, "denied-session", "host-1"); - return new ActorWakeReceipt( actor, "denied", - [new ActorWakeTargetReceipt(target, MailWakeTargetStatus.Pending, null, null, "access-denied")]); + [new ActorWakeTargetReceipt(actor, MailWakeTargetStatus.Pending, null, null, "access-denied")]); } var cancelled = new TaskCompletionSource( @@ -855,12 +1403,15 @@ internal sealed class DeniedThenHangingDispatcher(string deniedActor, Concurrent } /// -/// Records the peak number of concurrent calls -/// and every actor a call completed for, without touching any real session, -/// mail, or dispatch machinery. +/// Every call blocks after being counted, once +/// concurrent calls are observed, and completes +/// . Every call unblocks together once +/// is called. /// -internal sealed class ConcurrencyTrackingDispatcher : IActorWakeDispatcher +internal sealed class ConcurrencyTrackingDispatcher(int capacity) : IActorWakeDispatcher { + private readonly TaskCompletionSource _capacityReached = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously); private int _concurrent; private int _maxObservedConcurrency; @@ -868,21 +1419,23 @@ internal sealed class ConcurrencyTrackingDispatcher : IActorWakeDispatcher public ConcurrentBag CompletedActors { get; } = []; + public Task CapacityReached => _capacityReached.Task; + + public void ReleaseAll() => _released.TrySetResult(); + public async Task DispatchAsync( - string actor, DateTimeOffset deadline, CancellationToken cancellationToken) + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) { var observed = Interlocked.Increment(ref _concurrent); InterlockedMax(ref _maxObservedConcurrency, observed); - try + if (observed >= capacity) { - await Task.Delay(TimeSpan.FromMilliseconds(80), cancellationToken); - } - finally - { - Interlocked.Decrement(ref _concurrent); + _capacityReached.TrySetResult(); } + await _released.Task; + Interlocked.Decrement(ref _concurrent); CompletedActors.Add(actor); return null; } @@ -904,24 +1457,57 @@ private static void InterlockedMax(ref int target, int observed) } } +/// +/// Records each distinct actor's entry and completes once +/// distinct actors have entered, then hangs every +/// call until its own fires. +/// +internal sealed class ConcurrentEntryDispatcher(int expectedActors) : IActorWakeDispatcher +{ + private readonly TaskCompletionSource _allEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ConcurrentDictionary _entered = new(StringComparer.Ordinal); + + public Task AllEntered => _allEntered.Task; + + public int EnteredCount => _entered.Count; + + public async Task DispatchAsync( + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) + { + if (_entered.TryAdd(actor, true) && _entered.Count >= expectedActors) + { + _allEntered.TrySetResult(); + } + + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + catch (OperationCanceledException) + { + } + + return null; + } +} + /// /// Blocks every call on an internal gate until /// is called, ignoring the call's own cancellation -/// token. +/// token. Signals once a call has entered. /// internal sealed class HangingDispatcher : IActorWakeDispatcher { private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously); - private int _enteredCount; - public int EnteredCount => Volatile.Read(ref _enteredCount); + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public void Release() => _gate.TrySetResult(); public async Task DispatchAsync( - string actor, DateTimeOffset deadline, CancellationToken cancellationToken) + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) { - Interlocked.Increment(ref _enteredCount); + Entered.TrySetResult(); await _gate.Task; return null; } @@ -931,7 +1517,10 @@ internal sealed class HangingDispatcher : IActorWakeDispatcher /// Delegates every call to , except that once /// has been called, every subsequent /// call returns false without reaching -/// . +/// . Callers that need to know when the coordinator has +/// actually processed the rejection should synchronize through one of its own +/// hooks (for example AfterLeadershipEndedAsync), not through this store: +/// a signal raised here fires before the coordinator's own state update, not after it. /// internal sealed class RenewalLossLeaderStore(IMailWakeDaemonLeaderStore inner) : IMailWakeDaemonLeaderStore { @@ -939,19 +1528,194 @@ internal sealed class RenewalLossLeaderStore(IMailWakeDaemonLeaderStore inner) : public void FailNextRenewal() => _failRenewal = true; - public Task TryAcquireAsync( - string nitroInstanceId, string ownerId, DateTimeOffset now, TimeSpan leaseDuration, - CancellationToken cancellationToken) - => inner.TryAcquireAsync(nitroInstanceId, ownerId, now, leaseDuration, cancellationToken); + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); + + public Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => _failRenewal ? Task.FromResult(false) : inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); + + public Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + => inner.TryReleaseAsync(token, now, cancellationToken); +} + +/// +/// Delegates every call to , except that once +/// has been called, the next +/// call throws instead of renewing, signaling beforehand. +/// +internal sealed class ThrowingRenewalLeaderStore(IMailWakeDaemonLeaderStore inner) : IMailWakeDaemonLeaderStore +{ + private readonly TaskCompletionSource _renewalFaulted = new(TaskCreationOptions.RunContinuationsAsynchronously); + private volatile bool _failRenewal; - public Task TryRenewAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, TimeSpan leaseDuration, - string? lastError, CancellationToken cancellationToken) - => _failRenewal + public Task RenewalFaulted => _renewalFaulted.Task; + + public void FailNextRenewal() => _failRenewal = true; + + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); + + public Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + { + if (_failRenewal) + { + _renewalFaulted.TrySetResult(); + throw new InvalidOperationException("Simulated renewal fault."); + } + + return inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); + } + + public Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + => inner.TryReleaseAsync(token, now, cancellationToken); +} + +/// +/// Delegates every call to and completes +/// once has been called and has returned. Every +/// call made after that fails without reaching +/// , so the same coordinator instance cannot race a test's own +/// direct acquire attempt for the lease it just gave up. +/// +internal sealed class ReleaseSignalLeaderStore(IMailWakeDaemonLeaderStore inner) : IMailWakeDaemonLeaderStore +{ + private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Released => _released.Task; + + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => _released.Task.IsCompleted ? Task.FromResult(false) - : inner.TryRenewAsync(nitroInstanceId, ownerId, epoch, now, leaseDuration, lastError, cancellationToken); + : inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); + + public Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); - public Task TryReleaseAsync( - string nitroInstanceId, string ownerId, long epoch, DateTimeOffset now, CancellationToken cancellationToken) - => inner.TryReleaseAsync(nitroInstanceId, ownerId, epoch, now, cancellationToken); + public async Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + { + var released = await inner.TryReleaseAsync(token, now, cancellationToken); + _released.TrySetResult(); + return released; + } +} + +/// +/// Counts every call without touching any real +/// session, mail, or dispatch machinery. +/// +internal sealed class CountingDispatcher : IActorWakeDispatcher +{ + private int _dispatchCount; + + public int DispatchCount => Volatile.Read(ref _dispatchCount); + + public Task DispatchAsync( + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _dispatchCount); + return Task.FromResult(null); + } +} + +/// +/// Delegates every call to , except that after +/// the next call +/// awaits before delegating. +/// resolves with that delegated call's result. +/// +internal sealed class GatedRenewalLeaderStore(IMailWakeDaemonLeaderStore inner) : IMailWakeDaemonLeaderStore +{ + private readonly TaskCompletionSource _renewalCompleted = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + private TaskCompletionSource? _gate; + + public Task RenewalCompleted => _renewalCompleted.Task; + + public void HoldNextRenewal() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + public void ReleaseHeldRenewal() => _gate?.TrySetResult(); + + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); + + public async Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + { + if (_gate is { } gate) + { + await gate.Task; + } + + var renewed = await inner.TryRenewAsync(token, now, leaseDuration, cancellationToken); + _renewalCompleted.TrySetResult(renewed); + return renewed; + } + + public Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + => inner.TryReleaseAsync(token, now, cancellationToken); +} + +/// +/// Delegates every call to , except that after +/// the next call marks +/// and awaits before completing +/// against with no cancellation, then records +/// "renewal-completed" into . Every +/// call records "release-attempted" before delegating +/// and signals once it returns. +/// +internal sealed class OrderedReleaseLeaderStore(IMailWakeDaemonLeaderStore inner, ConcurrentQueue events) + : IMailWakeDaemonLeaderStore +{ + private readonly TaskCompletionSource _heldEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously); + private TaskCompletionSource? _gate; + + public Task HeldEntered => _heldEntered.Task; + + public Task Released => _released.Task; + + public void HoldNextRenewal() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + public void ReleaseHeldRenewal() => _gate?.TrySetResult(); + + public Task TryAcquireAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => inner.TryAcquireAsync(token, now, leaseDuration, cancellationToken); + + public async Task TryRenewAsync(string token, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + { + if (_gate is { } gate) + { + _heldEntered.TrySetResult(); + await gate.Task; + } + + // Simulates a renewal already in flight against the database: it runs to + // completion rather than being cut short by the caller's own cancellation. + var renewed = await inner.TryRenewAsync(token, now, leaseDuration, CancellationToken.None); + events.Enqueue("renewal-completed"); + return renewed; + } + + public async Task TryReleaseAsync(string token, DateTimeOffset now, CancellationToken cancellationToken) + { + events.Enqueue("release-attempted"); + var released = await inner.TryReleaseAsync(token, now, cancellationToken); + _released.TrySetResult(); + return released; + } +} + +/// +/// Returns a pending, access-denied receipt for whichever actor it is dispatched for, +/// on every call, without touching any real session, mail, or dispatch machinery. +/// +internal sealed class AlwaysDeniedDispatcher : IActorWakeDispatcher +{ + public Task DispatchAsync( + string actor, string leaderToken, DateTimeOffset deadline, CancellationToken cancellationToken) + => Task.FromResult(new ActorWakeReceipt( + actor, + "denied", + [new ActorWakeTargetReceipt(actor, MailWakeTargetStatus.Pending, null, null, "access-denied")])); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/PingSessionExecutorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/PingSessionExecutorTests.cs index 27c4db706c6..2511f0d062a 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/PingSessionExecutorTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/PingSessionExecutorTests.cs @@ -2,7 +2,6 @@ using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; using ChilliCream.Nitro.CommandLine.Tests.Hook; using Microsoft.Extensions.Time.Testing; @@ -15,12 +14,8 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// public sealed class PingSessionExecutorTests : IDisposable { - private const string Harness = AgentSessionHarness.Codex; - private const string SessionId = "session-1"; - private const string Actor = "codex-worker"; private const string ThreadId = "thread-1"; private const string OpencodeSessionId = "opencode-session-1"; - private const string OpencodeActor = "opencode-worker"; private const string OpencodeServerUrl = "http://127.0.0.1:4096"; private readonly DirectoryInfo _tempRoot; @@ -28,16 +23,13 @@ public sealed class PingSessionExecutorTests : IDisposable private readonly TestFileSystem _fileSystem; private readonly FakeTimeProvider _timeProvider; private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; + private readonly AgentStore _agentStore; private readonly MailStore _mail; - private readonly SessionDeliveryLedger _ledger; + private readonly AgentDeliveryLedger _ledger; private readonly PingLeaseStore _leases; private readonly FakeCodexQueueClient _queueClient; private readonly FakeClaudePeerClient _claudePeerClient; private readonly FakeOpencodeServerClient _opencodeClient; - private readonly AgentSessionGeneration _generation; - private readonly AgentSessionGeneration _opencodeGeneration; public PingSessionExecutorTests() { @@ -47,22 +39,13 @@ public PingSessionExecutorTests() _fileSystem = new TestFileSystem(_tempRoot.FullName); _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, _timeProvider, _database); - _sessions = new AgentSessionRegistry( - _fileSystem, - _timeProvider, - _database, - _agentRegistry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName)); - _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentRegistry); - _ledger = new SessionDeliveryLedger(_fileSystem, _database); + _agentStore = new AgentStore(_fileSystem, _timeProvider, _database); + _mail = new MailStore(_fileSystem, _timeProvider, _database, _agentStore); + _ledger = new AgentDeliveryLedger(_fileSystem, _database); _leases = new PingLeaseStore(_fileSystem, _database); _queueClient = new FakeCodexQueueClient(); _claudePeerClient = new FakeClaudePeerClient(); _opencodeClient = new FakeOpencodeServerClient(); - _generation = new AgentSessionGeneration(Harness, SessionId, "host-1"); - _opencodeGeneration = new AgentSessionGeneration(AgentSessionHarness.Opencode, OpencodeSessionId, "host-1"); } public void Dispose() => _tempRoot.Delete(recursive: true); @@ -72,23 +55,23 @@ public async Task ExecuteCodexThreadAsync_Should_QueueTheDigestAndRecordOk_When_ { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); var message = await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert var call = Assert.Single(_queueClient.Calls); Assert.Equal((ThreadId, message.Id, "check"), Digest(call.ThreadId, call.Message)); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal((AgentPingResult.Ok, AgentPingResult.Ok), (outcome.Result, row!.LastPingResult)); } @@ -97,21 +80,21 @@ public async Task ExecuteCodexThreadAsync_Should_ReleaseTheLease_When_ItComplete { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var now = _timeProvider.GetUtcNow(); var slot = await _leases.TryAcquireAsync(attemptId, now, TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); - // assert: the slot is free again, so a fresh attempt reclaims the - // exact same slot number. + // assert + // The slot is free again, so a fresh attempt reclaims the exact same slot number. var reacquired = await _leases.TryAcquireAsync("attempt-next", now, TimeSpan.FromSeconds(30), cancellationToken); Assert.Equal(slot, reacquired); } @@ -121,11 +104,11 @@ public async Task ExecuteCodexThreadAsync_Should_RecordError_When_TheTransportCa { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _queueClient.NextResult = CodexQueueResult.Error; @@ -133,7 +116,7 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.Error, outcome.Result); @@ -145,11 +128,11 @@ public async Task ExecuteCodexThreadAsync_Should_RecordEndpointGone_When_TheTran // arrange // Fixture-evidenced signature for a dead/unknown codex thread. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _queueClient.NextResult = CodexQueueResult.EndpointGone; @@ -157,11 +140,11 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.EndpointGone, outcome.Result); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(AgentPingResult.EndpointGone, row!.LastPingResult); } @@ -170,23 +153,23 @@ public async Task ExecuteClaudePeerAsync_Should_SendTheDigestAndRecordOk_When_Un { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); var message = await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteClaudePeerAsync( - Harness, SessionId, Actor, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, "peer-session", attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert var call = Assert.Single(_claudePeerClient.Calls); - Assert.Equal((SessionId, message.Id, "check"), Digest(call.SessionId, call.Message)); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + Assert.Equal(("peer-session", message.Id, "check"), Digest(call.SessionId, call.Message)); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal((AgentPingResult.Ok, AgentPingResult.Ok), (outcome.Result, row!.LastPingResult)); } @@ -195,25 +178,25 @@ public async Task ExecuteClaudePeerAsync_Should_ReturnOutcomeMatchingTheDurableR { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteClaudePeerAsync( - Harness, SessionId, Actor, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, "peer-session", attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); - // assert: the typed outcome exactly matches what was durably written. - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + // assert + // the typed outcome exactly matches what was durably written. + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(row!.LastPingResult, outcome.Result); Assert.Equal(row.LastPingDetail, outcome.Detail); - Assert.Equal(Harness, outcome.Harness); - Assert.Equal(SessionId, outcome.SessionId); + Assert.Equal(actor, outcome.ActorName); Assert.Equal(attemptId, outcome.AttemptId); } @@ -222,11 +205,11 @@ public async Task ExecuteClaudePeerAsync_Should_ReturnAccessDeniedReason_When_Th { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _claudePeerClient.NextOutcome = ClaudePeerSendOutcome.AccessDenied; @@ -234,15 +217,15 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteClaudePeerAsync( - Harness, SessionId, Actor, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, "peer-session", attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); - // assert: the coarse CHECK-compatible result stays "error", but the - // typed reason and detail stay specific. + // assert + // The coarse CHECK-compatible result stays "error", but the reason and detail stay specific. Assert.Equal(AgentPingResult.Error, outcome.Result); Assert.Equal(PingAttemptReason.AccessDenied, outcome.Reason); Assert.False(outcome.Retryable); Assert.Equal(ClaudePeerSendOutcome.AccessDenied.Detail, outcome.Detail); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(row!.LastPingDetail, outcome.Detail); } @@ -251,11 +234,11 @@ public async Task ExecuteClaudePeerAsync_Should_ReturnInvalidAuthReason_When_The { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _claudePeerClient.NextOutcome = ClaudePeerSendOutcome.InvalidAuth; @@ -263,7 +246,7 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteClaudePeerAsync( - Harness, SessionId, Actor, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, "peer-session", attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.Error, outcome.Result); @@ -276,11 +259,11 @@ public async Task ExecuteCodexThreadAsync_Should_NotExposeTransportDetail_When_T { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _queueClient.NextResult = CodexQueueResult.Error; @@ -288,7 +271,7 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(PingAttemptReason.TransportError, outcome.Reason); @@ -302,30 +285,28 @@ public async Task ExecuteClaudePeerAsync_Should_NotOverwriteTheRow_When_TheAttem // arrange // A newer attempt claims the cooldown before the stale attempt executes. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var staleAttemptId = await ClaimAttemptAsync(cancellationToken); + var staleAttemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( staleAttemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); - var freshSession = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + // The claim's own cooldown gate requires the prior attempt to have aged past + // it, so the clock advances before the newer attempt claims the cooldown. + _timeProvider.Advance(PingPolicy.Cooldown + TimeSpan.FromSeconds(1)); var newerAttemptId = $"attempt-{Guid.NewGuid():N}"; - await _sessions.TryClaimPingCooldownAsync( - freshSession!, - newerAttemptId, - _timeProvider.GetUtcNow() + PingPolicy.Cooldown + TimeSpan.FromSeconds(1), - PingPolicy.Cooldown, - cancellationToken); + await _agentStore.TryClaimPingCooldownAsync( + actor, PingPolicy.Cooldown, newerAttemptId, cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteClaudePeerAsync( - Harness, SessionId, Actor, staleAttemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, "peer-session", staleAttemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.Ok, outcome.Result); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(newerAttemptId, row!.LastPingAttempt); Assert.Null(row.LastPingResult); } @@ -336,15 +317,15 @@ public async Task ExecuteCodexThreadAsync_Should_RecordOkWithoutCallingTheTransp // arrange // The inbox is empty. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.Ok, outcome.Result); @@ -356,11 +337,11 @@ public async Task ExecuteCodexThreadAsync_Should_RecordTimeout_When_TheTransport { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = new PingSessionExecutor( @@ -368,19 +349,19 @@ await _mail.SendMessageAsync( _ledger, new NeverCompletingCodexQueueClient(), _claudePeerClient, - _sessions, + _agentStore, _leases, _timeProvider, _opencodeClient); // act var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, + actor, ThreadId, attemptId, slot!.Value, _timeProvider.GetUtcNow() + TimeSpan.FromMilliseconds(50), cancellationToken); // assert Assert.Equal(AgentPingResult.Timeout, outcome.Result); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(AgentPingResult.Timeout, row!.LastPingResult); } @@ -389,60 +370,61 @@ public async Task ExecuteCodexThreadAsync_Should_RecordTimeoutWithoutInvokingThe { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); - // act: startup latency across the process boundary already ate the - // whole budget by the time this attempt runs. + // act + // Startup latency already ate the whole budget by the time this attempt runs. var outcome = await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, + actor, ThreadId, attemptId, slot!.Value, _timeProvider.GetUtcNow() - TimeSpan.FromSeconds(1), cancellationToken); // assert Assert.Equal(AgentPingResult.Timeout, outcome.Result); Assert.Empty(_queueClient.Calls); - var row = await _sessions.FindByGenerationAsync(_generation, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(AgentPingResult.Timeout, row!.LastPingResult); } [Fact] public async Task ExecuteCodexThreadAsync_Should_LeaveTheMessageUnread_When_ItQueuesTheDigest() { - // arrange: pushing the body to the thread never means it was read. + // arrange + // pushing the body to the thread never means it was read. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeSessionAsync(cancellationToken); + var actor = await InitializeAgentAsync(cancellationToken); var message = await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [Actor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var unreadBefore = await _mail.CountUnreadAsync(Actor, cancellationToken); - var attemptId = await ClaimAttemptAsync(cancellationToken); + var unreadBefore = await _mail.CountUnreadAsync(actor, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act await executor.ExecuteCodexThreadAsync( - Harness, SessionId, Actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); + actor, ThreadId, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); - // assert: the pushed payload says unread, the message is still in the - // unread inbox, and the unread count is unchanged. + // assert + // The pushed payload says unread, the message stays in the unread inbox. var call = Assert.Single(_queueClient.Calls); Assert.False(DigestRead(call.Message)); var unread = await _mail.QueryInboxAsync( - new MailInboxFilter { Actor = Actor, UnreadOnly = true }, cancellationToken); + new MailInboxFilter { Actor = actor, UnreadOnly = true }, cancellationToken); Assert.Contains(unread, m => m.Id == message.Id); - Assert.Equal(unreadBefore, await _mail.CountUnreadAsync(Actor, cancellationToken)); + Assert.Equal(unreadBefore, await _mail.CountUnreadAsync(actor, cancellationToken)); } private PingSessionExecutor CreateExecutor() => new( - _mail, _ledger, _queueClient, _claudePeerClient, _sessions, _leases, _timeProvider, _opencodeClient); + _mail, _ledger, _queueClient, _claudePeerClient, _agentStore, _leases, _timeProvider, _opencodeClient); private static (string Endpoint, string Id, string Body) Digest(string endpoint, string digest) { @@ -466,26 +448,82 @@ private static bool DigestRead(string digest) /// private DateTimeOffset FarFutureDeadline() => _timeProvider.GetUtcNow() + TimeSpan.FromSeconds(5); - private async Task InitializeSessionAsync(CancellationToken cancellationToken) + /// + /// Registers the named agent directly against the unified agents table. + /// + private async Task SeedAgentAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES (@name, @now, @now, @now) + ON CONFLICT (name) DO UPDATE SET last_seen_at = excluded.last_seen_at; + """; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Initializes the workspace and mints an agent row with a Codex + /// harness session, returning its allocated name. + /// + private async Task InitializeAgentAsync(CancellationToken cancellationToken) { await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) { } - await _sessions.StartAsync( - _generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, ThreadId, - envActor: Actor, cancellationToken); + // Registers the mail sender used throughout this fixture's digests. + await SeedAgentAsync("pascal", cancellationToken); + + var result = await _agentStore.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = AgentSessionHarness.Codex, + SessionId = "session-1", + HarnessVersion = "1.0.0", + Cwd = "/work", + WorkspacePath = "/work/.nitro/agents", + EndpointKind = AgentSessionEndpointKind.CodexThread, + EndpointAddr = ThreadId + }, + cancellationToken); + + return result.Row!.Name; } - private async Task InitializeOpencodeSessionAsync(string? secret, CancellationToken cancellationToken) + /// + /// Initializes the workspace and mints an agent row with an opencode + /// harness session, returning its allocated name. + /// + private async Task InitializeOpencodeAgentAsync(string? secret, CancellationToken cancellationToken) { await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) { } - await _sessions.StartAsync( - _opencodeGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.OpencodeServer, - OpencodeServerUrl, secret, envActor: OpencodeActor, cancellationToken); + // Registers the mail sender used throughout this fixture's digests. + await SeedAgentAsync("pascal", cancellationToken); + + var result = await _agentStore.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = AgentSessionHarness.Opencode, + SessionId = OpencodeSessionId, + HarnessVersion = "1.0.0", + Cwd = "/work", + WorkspacePath = "/work/.nitro/agents", + EndpointKind = AgentSessionEndpointKind.OpencodeServer, + EndpointAddr = OpencodeServerUrl, + EndpointSecret = secret + }, + cancellationToken); + + return result.Row!.Name; } /// @@ -493,15 +531,10 @@ await _sessions.StartAsync( /// eventual result write, mirroring what the notifier does before /// spawning (or, here, directly invoking) the executor. /// - private Task ClaimAttemptAsync(CancellationToken cancellationToken) - => ClaimAttemptAsync(_generation, cancellationToken); - - private async Task ClaimAttemptAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) + private async Task ClaimAttemptAsync(string actor, CancellationToken cancellationToken) { - var session = await _sessions.FindByGenerationAsync(generation, cancellationToken); var attemptId = $"attempt-{Guid.NewGuid():N}"; - await _sessions.TryClaimPingCooldownAsync( - session!, attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); + await _agentStore.TryClaimPingCooldownAsync(actor, TimeSpan.FromSeconds(60), attemptId, cancellationToken); return attemptId; } @@ -510,18 +543,18 @@ public async Task ExecuteOpencodeServerAsync_Should_PushThePrefixedDigestAndReco { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync("s3cret", cancellationToken); + var actor = await InitializeOpencodeAgentAsync("s3cret", cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [OpencodeActor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, "s3cret", + actor, OpencodeSessionId, OpencodeServerUrl, "s3cret", attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert @@ -536,18 +569,18 @@ await _mail.SendMessageAsync( [Fact] public async Task ExecuteOpencodeServerAsync_Should_PingWithoutPushing_When_NoUnreadMailExists() { - // arrange: the mail that triggered this attempt was already read by - // the time it ran, so this is a health-only ping, not a delivery. + // arrange + // The mail that triggered this attempt was already read, so this is a health-only ping. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync(secret: null, cancellationToken); - var attemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var actor = await InitializeOpencodeAgentAsync(secret: null, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert @@ -564,8 +597,8 @@ public async Task ExecuteOpencodeServerAsync_Should_RecordEndpointGone_When_TheP // arrange // The inbox is empty and the fake client reports EndpointGone. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync(secret: null, cancellationToken); - var attemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var actor = await InitializeOpencodeAgentAsync(secret: null, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _opencodeClient.NextPingResult = AgentPingResult.EndpointGone; @@ -573,12 +606,12 @@ public async Task ExecuteOpencodeServerAsync_Should_RecordEndpointGone_When_TheP // act var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.EndpointGone, outcome.Result); - var row = await _sessions.FindByGenerationAsync(_opencodeGeneration, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(AgentPingResult.EndpointGone, row!.LastPingResult); } @@ -587,11 +620,11 @@ public async Task ExecuteOpencodeServerAsync_Should_RecordEndpointGone_When_TheP { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync(secret: null, cancellationToken); + var actor = await InitializeOpencodeAgentAsync(secret: null, cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [OpencodeActor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _opencodeClient.NextPushResult = AgentPingResult.EndpointGone; @@ -599,7 +632,7 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert @@ -610,14 +643,14 @@ await _mail.SendMessageAsync( [Fact] public async Task ExecuteOpencodeServerAsync_Should_RecordTimeout_When_ThePushSignalsATimeout() { - // arrange: proves the ok/timeout/error result vocabulary maps - // through unchanged for the opencode transport too. + // arrange + // The ok/timeout/error result vocabulary maps through unchanged for opencode too. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync(secret: null, cancellationToken); + var actor = await InitializeOpencodeAgentAsync(secret: null, cancellationToken); await _mail.SendMessageAsync( - new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [OpencodeActor] }, + new MailMessageCreation { Sender = "pascal", Subject = "status", Body = "check", To = [actor] }, cancellationToken); - var attemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); _opencodeClient.NextPushResult = AgentPingResult.Timeout; @@ -625,7 +658,7 @@ await _mail.SendMessageAsync( // act var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); // assert @@ -636,30 +669,31 @@ await _mail.SendMessageAsync( [Fact] public async Task ExecuteOpencodeServerAsync_Should_RewriteTheRow_When_TheHealthOnlyPingRepeatsThePriorOutcome() { - // arrange: an earlier health-only ping already recorded ok/health-only. + // arrange + // an earlier health-only ping already recorded ok/health-only. var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync(secret: null, cancellationToken); - var firstAttemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var actor = await InitializeOpencodeAgentAsync(secret: null, cancellationToken); + var firstAttemptId = await ClaimAttemptAsync(actor, cancellationToken); var firstSlot = await _leases.TryAcquireAsync( firstAttemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, firstAttemptId, firstSlot!.Value, FarFutureDeadline(), cancellationToken); // act // A fresh claim, then a health-only ping that reports the same outcome as before. _timeProvider.Advance(TimeSpan.FromSeconds(61)); - var secondAttemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var secondAttemptId = await ClaimAttemptAsync(actor, cancellationToken); var secondSlot = await _leases.TryAcquireAsync( secondAttemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, secondAttemptId, secondSlot!.Value, FarFutureDeadline(), cancellationToken); // assert Assert.Equal(AgentPingResult.Ok, outcome.Result); - var row = await _sessions.FindByGenerationAsync(_opencodeGeneration, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(AgentPingResult.Ok, row!.LastPingResult); Assert.Equal(PingSessionExecutor.HealthOnlyDetail, row.LastPingDetail); } @@ -667,23 +701,24 @@ await executor.ExecuteOpencodeServerAsync( [Fact] public async Task ExecuteOpencodeServerAsync_Should_WriteTheRow_When_TheHealthOnlyPingFirstReachesItsOkState() { - // arrange: no known previous state (a fresh row's first ping ever). + // arrange + // no known previous state (a fresh row's first ping ever). var cancellationToken = TestContext.Current.CancellationToken; - await InitializeOpencodeSessionAsync(secret: null, cancellationToken); - var attemptId = await ClaimAttemptAsync(_opencodeGeneration, cancellationToken); + var actor = await InitializeOpencodeAgentAsync(secret: null, cancellationToken); + var attemptId = await ClaimAttemptAsync(actor, cancellationToken); var slot = await _leases.TryAcquireAsync( attemptId, _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(30), cancellationToken); var executor = CreateExecutor(); // act var outcome = await executor.ExecuteOpencodeServerAsync( - AgentSessionHarness.Opencode, OpencodeSessionId, OpencodeActor, OpencodeServerUrl, null, + actor, OpencodeSessionId, OpencodeServerUrl, null, attemptId, slot!.Value, FarFutureDeadline(), cancellationToken); - // assert: the first health-only ping always writes, since there is - // no prior recorded state to compare it against. + // assert + // The first health-only ping always writes, since there is no prior state to compare. Assert.Equal(AgentPingResult.Ok, outcome.Result); - var row = await _sessions.FindByGenerationAsync(_opencodeGeneration, cancellationToken); + var row = await _agentStore.FindAsync(actor, cancellationToken); Assert.Equal(AgentPingResult.Ok, row!.LastPingResult); Assert.Equal(PingSessionExecutor.HealthOnlyDetail, row.LastPingDetail); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/RacingAcceptanceMailWakeBatchStoreDecorator.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/RacingAcceptanceMailWakeBatchStoreDecorator.cs index 07476e1e9a3..eb1d4453576 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/RacingAcceptanceMailWakeBatchStoreDecorator.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/RacingAcceptanceMailWakeBatchStoreDecorator.cs @@ -9,15 +9,15 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// Delegates all other calls to . /// internal sealed class RacingAcceptanceMailWakeBatchStoreDecorator( - IMailWakeBatchStore inner, AgentSessionGeneration racedTarget, long acceptedGeneration) : IMailWakeBatchStore + IMailWakeBatchStore inner, string racedTarget, long acceptedGeneration) : IMailWakeBatchStore { private bool _raced; public Task TryClaimAsync( - string nitroInstanceId, string actor, string ownerId, string attemptId, - IReadOnlyList targets, DateTimeOffset now, TimeSpan leaseDuration, + string actor, string ownerId, string attemptId, + IReadOnlyList targets, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) - => inner.TryClaimAsync(nitroInstanceId, actor, ownerId, attemptId, targets, now, leaseDuration, cancellationToken); + => inner.TryClaimAsync(actor, ownerId, attemptId, targets, now, leaseDuration, cancellationToken); public Task TryRenewAsync( string batchId, string ownerId, string attemptId, DateTimeOffset now, TimeSpan leaseDuration, @@ -34,7 +34,7 @@ public Task TryReleaseAsync( => inner.TryReleaseAsync(batchId, ownerId, attemptId, now, retryAt, lastError, cancellationToken); public async Task TryRecordTargetOutcomeAsync( - string batchId, AgentSessionGeneration target, string ownerId, string attemptId, string status, + string batchId, string target, string ownerId, string attemptId, string status, long? offeredGeneration, long? acceptedGeneration_, string? lastError, DateTimeOffset now, CancellationToken cancellationToken) { diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ReboundOnFindSessionRegistryDecorator.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ReboundOnFindSessionRegistryDecorator.cs deleted file mode 100644 index 814ee424f85..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ReboundOnFindSessionRegistryDecorator.cs +++ /dev/null @@ -1,103 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Agents; - -/// -/// On the first lookup of , ends that session and starts -/// and claims before forwarding the lookup. -/// Delegates all other calls to . -/// -internal sealed class ReboundOnFindSessionRegistryDecorator( - IAgentSessionRegistry inner, AgentSessionGeneration frozen, AgentSessionGeneration rebound, string actor) - : IAgentSessionRegistry -{ - private bool _rebound; - - public Task StartAsync( - AgentSessionGeneration generation, string cwd, string workspacePath, string endpointKind, - string endpointAddr, string? envActor, CancellationToken cancellationToken) - => inner.StartAsync(generation, cwd, workspacePath, endpointKind, endpointAddr, envActor, cancellationToken); - - public Task ClaimAsync( - AgentSessionGeneration generation, string actor2, bool forceRebind, CancellationToken cancellationToken) - => inner.ClaimAsync(generation, actor2, forceRebind, cancellationToken); - - public Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.EndAsync(generation, cancellationToken); - - public async Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - { - if (!_rebound && generation == frozen) - { - _rebound = true; - await inner.EndAsync(frozen, cancellationToken); - await inner.StartAsync( - rebound, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-rebound", - envActor: actor, cancellationToken); - await inner.ClaimAsync(rebound, actor, forceRebind: false, cancellationToken); - } - - return await inner.FindByGenerationAsync(generation, cancellationToken); - } - - public Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ResetBlockBudgetAsync(generation, cancellationToken); - - public Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.IncrementBlockBudgetAsync(generation, cancellationToken); - - public Task> ReapAsync(CancellationToken cancellationToken) - => inner.ReapAsync(cancellationToken); - - public Task> ListAsync(CancellationToken cancellationToken) - => inner.ListAsync(cancellationToken); - - public Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.TouchAsync(generation, cancellationToken); - - public Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - => inner.RecordHarnessVersionAsync(generation, harnessVersion, cancellationToken); - - public Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - => inner.SetRoleAsync(generation, role, cancellationToken); - - public Task> ListParticipantsAsync(CancellationToken cancellationToken) - => inner.ListParticipantsAsync(cancellationToken); - - public Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - => inner.FindBySessionIdAsync(harness, host, sessionId, cancellationToken); - - public Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - => inner.FindLiveClaimedByAgentNameAsync(agentName, cancellationToken); - - public Task TryClaimPingCooldownAsync( - AgentSessionRecord session, string attemptId, DateTimeOffset now, TimeSpan cooldown, - CancellationToken cancellationToken) - => inner.TryClaimPingCooldownAsync(session, attemptId, now, cooldown, cancellationToken); - - public Task WritePingResultAsync( - string harness, string sessionId, string attemptId, string result, string? detail, - CancellationToken cancellationToken) - => inner.WritePingResultAsync(harness, sessionId, attemptId, result, detail, cancellationToken); - - public Task RegisterAsync( - AgentSessionGeneration generation, string actor2, string role, string client, bool forceRebind, - CancellationToken cancellationToken) - => inner.RegisterAsync(generation, actor2, role, client, forceRebind, cancellationToken); - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ArmAnnouncementAsync(generation, cancellationToken); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimAnnouncementAsync(generation, cancellationToken); - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.RearmIdlePushAsync(generation, cancellationToken); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => inner.ClaimIdlePushAsync(generation, cancellationToken); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/SessionGateCoordinatorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/SessionGateCoordinatorTests.cs index cd3fe2da501..fb313ed3a73 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/SessionGateCoordinatorTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/SessionGateCoordinatorTests.cs @@ -1,11 +1,12 @@ using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// /// Exercises against real -/// and +/// and /// instances: reserving a free target holds both the gate and a lease slot /// together, a busy gate and a full lease pool are distinguished, a /// rejected capacity attempt never leaves the gate held, a successful @@ -14,14 +15,14 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// public sealed class SessionGateCoordinatorTests : IDisposable { - private static readonly AgentSessionGeneration s_targetA = new("claude-code", "session-1", "host-1"); - private static readonly AgentSessionGeneration s_targetB = new("claude-code", "session-2", "host-1"); + private const string TargetA = "agent-a"; + private const string TargetB = "agent-b"; private readonly DirectoryInfo _tempRoot; private readonly string _workspaceDirectory; private readonly TestFileSystem _fileSystem; private readonly AgentDatabase _database; - private readonly SessionPingGateStore _gates; + private readonly AgentPingGateStore _gates; private readonly PingLeaseStore _leases; private readonly SessionGateCoordinator _coordinator; @@ -32,7 +33,7 @@ public SessionGateCoordinatorTests() Directory.CreateDirectory(_workspaceDirectory); _fileSystem = new TestFileSystem(_tempRoot.FullName); _database = new AgentDatabase(); - _gates = new SessionPingGateStore(_fileSystem, _database); + _gates = new AgentPingGateStore(_fileSystem, _database); _leases = new PingLeaseStore(_fileSystem, _database); _coordinator = new SessionGateCoordinator(_gates, _leases); } @@ -48,12 +49,12 @@ public async Task TryReserveAsync_Should_ReserveBothTheGateAndALeaseSlot_When_Fr var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); // act - var result = await _coordinator.TryReserveAsync(s_targetA, "attempt-1", now, cancellationToken); + var result = await _coordinator.TryReserveAsync(TargetA, "attempt-1", now, cancellationToken); // assert Assert.NotNull(result.Reservation); Assert.Null(result.Failure); - Assert.Equal(s_targetA, result.Reservation.Target); + Assert.Equal(TargetA, result.Reservation.Target); Assert.InRange(result.Reservation.Slot, 1, 4); } @@ -64,10 +65,11 @@ public async Task TryReserveAsync_Should_ReturnGateBusy_When_TheGateIsAlreadyHel var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _coordinator.TryReserveAsync(s_targetA, "attempt-1", now, cancellationToken); + await _coordinator.TryReserveAsync(TargetA, "attempt-1", now, cancellationToken); - // act: a second attempt against the exact same target generation. - var result = await _coordinator.TryReserveAsync(s_targetA, "attempt-2", now, cancellationToken); + // act + // a second attempt against the exact same target. + var result = await _coordinator.TryReserveAsync(TargetA, "attempt-2", now, cancellationToken); // assert Assert.Null(result.Reservation); @@ -77,8 +79,8 @@ public async Task TryReserveAsync_Should_ReturnGateBusy_When_TheGateIsAlreadyHel [Fact] public async Task TryReserveAsync_Should_ReturnCapacityDropped_And_ReleaseTheGate_When_EveryLeaseSlotIsHeld() { - // arrange: every one of the four shared lease slots is already held - // by unrelated attempts. + // arrange + // Every one of the four shared lease slots is already held by unrelated attempts. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); @@ -89,7 +91,7 @@ public async Task TryReserveAsync_Should_ReturnCapacityDropped_And_ReleaseTheGat } // act - var result = await _coordinator.TryReserveAsync(s_targetA, "attempt-1", now, cancellationToken); + var result = await _coordinator.TryReserveAsync(TargetA, "attempt-1", now, cancellationToken); // assert Assert.Null(result.Reservation); @@ -98,12 +100,12 @@ public async Task TryReserveAsync_Should_ReturnCapacityDropped_And_ReleaseTheGat // the gate this attempt reserved before hitting capacity was // released again, so an immediate retry for the same target is not // blocked by a gate this rejected attempt never should have kept. - var retryResult = await _coordinator.TryReserveAsync(s_targetB, "attempt-2", now, cancellationToken); + var retryResult = await _coordinator.TryReserveAsync(TargetB, "attempt-2", now, cancellationToken); Assert.Null(retryResult.Reservation); Assert.Equal(WakeReservationFailure.CapacityDropped, retryResult.Failure); var gateStillHeld = await _gates.TryAcquireAsync( - s_targetA, "attempt-3", now, TimeSpan.FromSeconds(30), cancellationToken); + TargetA, "attempt-3", now, TimeSpan.FromSeconds(30), cancellationToken); Assert.True(gateStillHeld); } @@ -114,20 +116,20 @@ public async Task CompleteAsync_Should_StartACooldown_When_Successful() var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var reserved = await _coordinator.TryReserveAsync(s_targetA, "attempt-1", now, cancellationToken); + var reserved = await _coordinator.TryReserveAsync(TargetA, "attempt-1", now, cancellationToken); // act await _coordinator.CompleteAsync(reserved.Reservation!, success: true, now, cancellationToken); - // assert: a fresh attempt against the same generation, immediately - // after, finds the gate still busy (the cooldown), not free. - var retry = await _coordinator.TryReserveAsync(s_targetA, "attempt-2", now, cancellationToken); + // assert + // A fresh attempt against the same target immediately after finds the gate still busy. + var retry = await _coordinator.TryReserveAsync(TargetA, "attempt-2", now, cancellationToken); Assert.Null(retry.Reservation); Assert.Equal(WakeReservationFailure.GateBusy, retry.Failure); // and after the cooldown elapses, it is free again. var afterCooldown = await _coordinator.TryReserveAsync( - s_targetA, "attempt-3", now + PingPolicy.Cooldown + TimeSpan.FromSeconds(1), cancellationToken); + TargetA, "attempt-3", now + PingPolicy.Cooldown + TimeSpan.FromSeconds(1), cancellationToken); Assert.NotNull(afterCooldown.Reservation); } @@ -138,13 +140,13 @@ public async Task CompleteAsync_Should_ReleaseImmediately_When_Unsuccessful() var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var reserved = await _coordinator.TryReserveAsync(s_targetA, "attempt-1", now, cancellationToken); + var reserved = await _coordinator.TryReserveAsync(TargetA, "attempt-1", now, cancellationToken); // act await _coordinator.CompleteAsync(reserved.Reservation!, success: false, now, cancellationToken); // assert - var retry = await _coordinator.TryReserveAsync(s_targetA, "attempt-2", now, cancellationToken); + var retry = await _coordinator.TryReserveAsync(TargetA, "attempt-2", now, cancellationToken); Assert.NotNull(retry.Reservation); } @@ -155,12 +157,13 @@ public async Task CompleteAsync_Should_ReleaseTheLeaseSlot_Regardless() var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var reserved = await _coordinator.TryReserveAsync(s_targetA, "attempt-1", now, cancellationToken); + var reserved = await _coordinator.TryReserveAsync(TargetA, "attempt-1", now, cancellationToken); // act await _coordinator.CompleteAsync(reserved.Reservation!, success: true, now, cancellationToken); - // assert: all four slots are free again (only one was ever taken). + // assert + // all four slots are free again (only one was ever taken). var acquired = await Task.WhenAll(Enumerable.Range(1, 4).Select(i => _leases.TryAcquireAsync($"probe-{i}", now, TimeSpan.FromSeconds(30), cancellationToken))); Assert.All(acquired, slot => Assert.NotNull(slot)); @@ -168,8 +171,19 @@ public async Task CompleteAsync_Should_ReleaseTheLeaseSlot_Regardless() private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) { - await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - } + await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await SeedAgentAsync(connection, TargetA, cancellationToken); + await SeedAgentAsync(connection, TargetB, cancellationToken); + } + + private static async Task SeedAgentAsync( + SqliteConnection connection, string name, CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.CommandText = + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + "(@name, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');"; + command.Parameters.AddWithValue("@name", name); + await command.ExecuteNonQueryAsync(cancellationToken); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ThrowingRenewMailWakeBatchStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ThrowingRenewMailWakeBatchStore.cs index 572cf724e81..b0c3985e209 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ThrowingRenewMailWakeBatchStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Notify/ThrowingRenewMailWakeBatchStore.cs @@ -9,10 +9,10 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; internal sealed class ThrowingRenewMailWakeBatchStore(IMailWakeBatchStore inner) : IMailWakeBatchStore { public Task TryClaimAsync( - string nitroInstanceId, string actor, string ownerId, string attemptId, - IReadOnlyList targets, DateTimeOffset now, TimeSpan leaseDuration, + string actor, string ownerId, string attemptId, + IReadOnlyList targets, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) - => inner.TryClaimAsync(nitroInstanceId, actor, ownerId, attemptId, targets, now, leaseDuration, cancellationToken); + => inner.TryClaimAsync(actor, ownerId, attemptId, targets, now, leaseDuration, cancellationToken); public Task TryRenewAsync( string batchId, string ownerId, string attemptId, DateTimeOffset now, TimeSpan leaseDuration, @@ -29,7 +29,7 @@ public Task TryReleaseAsync( => inner.TryReleaseAsync(batchId, ownerId, attemptId, now, retryAt, lastError, cancellationToken); public Task TryRecordTargetOutcomeAsync( - string batchId, AgentSessionGeneration target, string ownerId, string attemptId, string status, + string batchId, string target, string ownerId, string attemptId, string status, long? offeredGeneration, long? acceptedGeneration, string? lastError, DateTimeOffset now, CancellationToken cancellationToken) => inner.TryRecordTargetOutcomeAsync( diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ActingActorResolverTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ActingActorResolverTests.cs index 93b18db9223..6aa305a5925 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ActingActorResolverTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ActingActorResolverTests.cs @@ -1,15 +1,18 @@ using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Extensions.Time.Testing; namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// /// Covers : a name is never inferred from /// the ambient session, only validated against the actors this workspace -/// allocated. +/// allocated, and every resolve is a presence beat. /// public sealed class ActingActorResolverTests : IDisposable { private readonly DirectoryInfo _tempRoot = Directory.CreateTempSubdirectory("nitro-acting-actor-tests"); + private readonly FakeTimeProvider _timeProvider = + new(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)); public void Dispose() => _tempRoot.Delete(recursive: true); @@ -19,13 +22,13 @@ public async Task ResolveAsync_Should_ReturnTheNormalizedActor_When_ItWasAllocat // arrange var cancellationToken = TestContext.Current.CancellationToken; var (resolver, agents) = await CreateAsync(cancellationToken); - await agents.EnsureImplicitAsync("maya", cancellationToken); + var agent = await agents.LoginAsync(cancellationToken); // act - var actor = await resolver.ResolveAsync("Maya", cancellationToken); + var actor = await resolver.ResolveAsync(agent.Name.ToUpperInvariant(), cancellationToken); // assert - Assert.Equal("maya", actor); + Assert.Equal(agent.Name, actor); } [Fact] @@ -64,7 +67,41 @@ public async Task ResolveAsync_Should_Throw_When_NoActorIsGiven() exception.Message); } - private async Task<(ActingActorResolver Resolver, AgentRegistry Agents)> CreateAsync( + [Fact] + public async Task ResolveAsync_Should_Throw_When_TheActorWasDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + var (resolver, agents) = await CreateAsync(cancellationToken); + var agent = await agents.LoginAsync(cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var exception = await Assert.ThrowsAsync( + () => resolver.ResolveAsync(agent.Name, cancellationToken)); + + // assert + Assert.Equal($"Agent '{agent.Name}' was deleted.", exception.Message); + } + + [Fact] + public async Task ResolveAsync_Should_BumpLastSeenAt_When_TheActorWasAllocated() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + var (resolver, agents) = await CreateAsync(cancellationToken); + var agent = await agents.LoginAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + await resolver.ResolveAsync(agent.Name, cancellationToken); + + // assert + var row = await agents.FindAsync(agent.Name, cancellationToken); + Assert.Equal(_timeProvider.GetUtcNow(), row?.LastSeenAt); + } + + private async Task<(ActingActorResolver Resolver, AgentStore Agents)> CreateAsync( CancellationToken cancellationToken) { var fileSystem = new TestFileSystem(_tempRoot.FullName); @@ -76,8 +113,26 @@ public async Task ResolveAsync_Should_Throw_When_NoActorIsGiven() { } - var agents = new AgentRegistry(fileSystem, TimeProvider.System, database); + var agents = new AgentStore(fileSystem, _timeProvider, database); return (new ActingActorResolver(agents), agents); } + + /// + /// Soft-deletes the named agent directly, bypassing the store, since delete mechanics + /// are a separate ticket. + /// + private async Task MarkDeletedAsync(string name, CancellationToken cancellationToken) + { + var workspace = AgentWorkspace.GetDirectory(_tempRoot.FullName); + + await using var connection = await new AgentDatabase().ConnectAsync(workspace, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET deleted_at = @now WHERE name = @name"; + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentActorAllocatorTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentActorAllocatorTests.cs new file mode 100644 index 00000000000..409a0cd58c0 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentActorAllocatorTests.cs @@ -0,0 +1,163 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Time.Testing; + +namespace ChilliCream.Nitro.CommandLine.Tests.Agents; + +/// +/// Exercises : the name pool it draws from, tombstone +/// exclusion, and suffixing once the pool is exhausted. +/// +public sealed class AgentActorAllocatorTests : IDisposable +{ + private static readonly string[] s_roleWords = + ["orchestrator", "planner", "implementer", "reviewer", "researcher"]; + + private readonly DirectoryInfo _tempRoot; + private readonly string _workspaceDirectory; + private readonly FakeTimeProvider _timeProvider; + private readonly AgentDatabase _database; + + public AgentActorAllocatorTests() + { + _tempRoot = Directory.CreateTempSubdirectory("nitro-agent-actor-allocator-tests"); + _workspaceDirectory = AgentWorkspace.GetDirectory(_tempRoot.FullName); + Directory.CreateDirectory(_workspaceDirectory); + _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); + _database = new AgentDatabase(); + } + + public void Dispose() => _tempRoot.Delete(recursive: true); + + // ---------- Pool ---------- + + [Fact] + public void BaseActors_Should_ContainAtLeast300DistinctValidNames_When_PoolIsRead() + { + // arrange + var names = AgentActorAllocator.BaseActors; + + // act + var distinctCount = names.Distinct(StringComparer.Ordinal).Count(); + + // assert + Assert.True(names.Count >= 300, $"Expected at least 300 names, found {names.Count}."); + Assert.Equal(names.Count, distinctCount); + Assert.All(names, name => Assert.Equal(name, MailAgentName.Normalize(name))); + } + + [Fact] + public void BaseActors_Should_ExcludeRoleWords_When_PoolIsRead() + { + // act + var collisions = AgentActorAllocator.BaseActors.Intersect(s_roleWords, StringComparer.Ordinal); + + // assert + Assert.Empty(collisions); + } + + // ---------- Tombstone exclusion ---------- + + [Fact] + public async Task AllocateAsync_Should_SkipName_When_ItIsATombstoneInAgents() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var pool = AgentActorAllocator.BaseActors; + var freeName = pool[0]; + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await SeedAgentsAsync(connection, pool.Skip(1), tombstoned: true); + + // act + var actor = await AllocateAsync(connection, cancellationToken); + + // assert + Assert.Equal(freeName, actor); + } + + // ---------- Exhaustion ---------- + + [Fact] + public async Task AllocateAsync_Should_AppendSuffixStartingAtTwo_When_PoolIsExhausted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var pool = AgentActorAllocator.BaseActors; + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await SeedAgentsAsync(connection, pool, tombstoned: false); + + // act + var actor = await AllocateAsync(connection, cancellationToken); + + // assert + Assert.EndsWith("-2", actor, StringComparison.Ordinal); + Assert.Contains(actor[..^2], pool); + } + + [Fact] + public async Task AllocateAsync_Should_IncrementSuffix_When_TheFirstSuffixedNameIsAlsoTaken() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitializeWorkspaceAsync(cancellationToken); + var pool = AgentActorAllocator.BaseActors; + await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); + await SeedAgentsAsync(connection, pool, tombstoned: false); + await SeedAgentsAsync(connection, pool.Select(name => $"{name}-2"), tombstoned: false); + + // act + var actor = await AllocateAsync(connection, cancellationToken); + + // assert + Assert.EndsWith("-3", actor, StringComparison.Ordinal); + Assert.Contains(actor[..^2], pool); + } + + private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) + { + await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) + { + } + } + + private static async Task AllocateAsync(SqliteConnection connection, CancellationToken cancellationToken) + { + await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + var actor = await AgentActorAllocator.AllocateAsync(connection, transaction); + await transaction.CommitAsync(cancellationToken); + + return actor; + } + + /// + /// Inserts one bare agents row per name, stamping deleted_at for a tombstone row or + /// leaving it null for a live one. + /// + private async Task SeedAgentsAsync(SqliteConnection connection, IEnumerable names, bool tombstoned) + { + var now = _timeProvider.GetUtcNow(); + + await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync( + TestContext.Current.CancellationToken); + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = + "INSERT INTO agents (name, registered_at, started_at, last_seen_at, deleted_at) " + + "VALUES ($name, $now, $now, $now, $deletedAt);"; + var nameParameter = command.Parameters.Add("$name", SqliteType.Text); + command.Parameters.AddWithValue("$now", now); + var deletedAtParameter = command.Parameters.Add("$deletedAt", SqliteType.Text); + deletedAtParameter.Value = tombstoned ? now : DBNull.Value; + + foreach (var name in names) + { + nameParameter.Value = name; + await command.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } + + await transaction.CommitAsync(TestContext.Current.CancellationToken); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDatabaseTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDatabaseTests.cs index ad0bff7b1e4..0b57f5b5acc 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDatabaseTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDatabaseTests.cs @@ -37,251 +37,44 @@ public async Task InitializeAsync_Should_CreateAllSchemasAndStampCurrentVersion_ // assert var version = await QueryScalarLongAsync(connection, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - var taskTableCount = await QueryScalarLongAsync( - connection, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'tasks'", - cancellationToken); - var mailTableCount = await QueryScalarLongAsync( + var tables = await QueryExistingSqliteObjectsAsync( connection, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'messages'", + "table", + [ + "tasks", "messages", "agents", + "ping_leases", "agent_deliveries", "agent_ping_gates", + "mail_wake_outbox", "mail_wake_batches", "mail_wake_targets", "mail_wake_daemons" + ], cancellationToken); - var agentTableCount = await QueryScalarLongAsync( + + var indexes = await QueryExistingSqliteObjectsAsync( connection, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agents'", + "index", + [ + "idx_mail_wake_outbox_due", "idx_mail_wake_batches_one_active_per_actor", + "idx_mail_wake_batches_expires", "idx_agent_ping_gates_expires" + ], cancellationToken); - Assert.Equal(1, taskTableCount); - Assert.Equal(1, mailTableCount); - Assert.Equal(1, agentTableCount); - - foreach (var sessionTable in new[] - { - "agent_sessions", "session_deliveries", "ping_leases", - "mail_wake_outbox", "mail_wake_batches", "mail_wake_targets", "mail_wake_daemons", - "session_ping_gates" - }) - { - var sessionTableCount = await QueryScalarLongAsync( - connection, - $"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '{sessionTable}'", - cancellationToken); - Assert.Equal(1, sessionTableCount); - } - - foreach (var index in new[] - { - "idx_mail_wake_outbox_due", "idx_mail_wake_batches_one_active_per_actor", - "idx_mail_wake_batches_expires", "idx_session_ping_gates_expires" - }) - { - var indexCount = await QueryScalarLongAsync( - connection, - $"SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = '{index}'", - cancellationToken); - Assert.Equal(1, indexCount); - } - - var columns = (await QueryColumnNamesAsync(connection, "agents", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.Contains("role", columns); - Assert.Contains("implicit", columns); - Assert.Contains("client", columns); - - var sessionColumns = (await QueryColumnNamesAsync(connection, "agent_sessions", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.Contains("role", sessionColumns); - Assert.Contains("harness_version", sessionColumns); - Assert.DoesNotContain("pid", sessionColumns); - Assert.DoesNotContain("proc_start", sessionColumns); - } - - [Fact] - public async Task InitializeAsync_Should_PreserveTasksAndResetIdentityAndMail_When_UpgradingV8() - { - var cancellationToken = TestContext.Current.CancellationToken; - - await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - await ExecuteAsync( - connection, - """ - INSERT INTO tasks (id, title, created_at, updated_at) - VALUES ('task-1', 'Keep me', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - INSERT INTO agents (name, registered_at, last_seen_at) - VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - INSERT INTO messages (id, thread_id, sender, subject, body, created_at) - VALUES ('mail-1', 'mail-1', 'maya', 'Old mail', 'Discard me', '2026-01-10T12:00:00+00:00'); - INSERT INTO message_recipients (message_id, recipient, ordinal) - VALUES ('mail-1', 'maya', 0); - """, - cancellationToken); - await ExecuteAsync(connection, "PRAGMA user_version = 8", cancellationToken); - } - - await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - Assert.Equal(1, await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM tasks", cancellationToken)); - Assert.Equal(0, await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM messages", cancellationToken)); - Assert.Equal(0, await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM agents", cancellationToken)); - Assert.Equal(AgentDatabase.CurrentVersion, - await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken)); - } - - [Fact] - public async Task InitializeAsync_Should_UpgradeV11AndPreserveRows_When_TakeoverTablesAreMissing() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - await ExecuteAsync( - connection, - """ - INSERT INTO tasks (id, title, created_at, updated_at) - VALUES ('task-v11', 'Preserve me', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - DROP TABLE agent_takeover_items; - DROP TABLE agent_takeovers; - PRAGMA user_version = 11; - """, - cancellationToken); - } - - // act - await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // assert - Assert.Equal(AgentDatabase.CurrentVersion, - await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken)); - Assert.Equal("Preserve me", await QueryScalarStringAsync( - upgraded, "SELECT title FROM tasks WHERE id = 'task-v11'", cancellationToken)); - Assert.Equal(1, await QueryScalarLongAsync( - upgraded, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_takeovers'", - cancellationToken)); - Assert.Equal(1, await QueryScalarLongAsync( - upgraded, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_takeover_items'", - cancellationToken)); - } - - [Fact] - public async Task InitializeAsync_Should_LeaveTakeoverRowsUnchanged_When_DatabaseIsCurrent() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - await ExecuteAsync( - connection, - """ - INSERT INTO agent_takeovers ( - id, from_actor, to_actor, actor, created_at, forced, role, reason - ) VALUES ( - 'to-current', 'maya', 'nora', 'maya', '2026-01-10T12:00:00+00:00', 1, NULL, NULL - ); - """, - cancellationToken); - } - - // act - await using var reopened = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // assert - Assert.Equal(AgentDatabase.CurrentVersion, - await QueryScalarLongAsync(reopened, "PRAGMA user_version", cancellationToken)); - Assert.Equal(1, await QueryScalarLongAsync( - reopened, "SELECT COUNT(*) FROM agent_takeovers WHERE id = 'to-current'", cancellationToken)); - } - - [Fact] - public void IsUpgradableVersion_Should_ReturnTrue_When_VersionIs11() - { - // act - var isUpgradable = AgentDatabase.IsUpgradableVersion(11); - // assert - Assert.True(isUpgradable); - } - - [Fact] - public async Task InitializeAsync_Should_BeIdempotent_When_CalledAgainOnCurrentVersion() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - } - - // act - await using var second = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // assert - var version = await QueryScalarLongAsync(second, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - } - - [Fact] - public async Task InitializeAsync_Should_UpgradeAgentSessionIdentityHarnessConstraint_When_ConstraintPredatesOpencode() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - await ExecuteAsync( - connection, - """ - DROP TABLE agent_session_identities; - CREATE TABLE agent_session_identities ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), - session_id TEXT NOT NULL, - actor TEXT NOT NULL UNIQUE REFERENCES agents (name), - role TEXT NOT NULL DEFAULT '', - actor_revision INTEGER NOT NULL DEFAULT 1 CHECK (actor_revision > 0), - created_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id) - ); - CREATE INDEX idx_agent_session_identities_actor - ON agent_session_identities (actor); - PRAGMA user_version = 11; - """, - cancellationToken); - } - - // act - await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await ExecuteAsync( - upgraded, - """ - INSERT INTO agents (name, registered_at, last_seen_at) - VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - INSERT INTO agent_session_identities ( - harness, session_id, actor, created_at, last_seen_at - ) VALUES ( - 'opencode', 'session-1', 'maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00' - ); - """, - cancellationToken); + var columns = await QueryColumnNamesAsync(connection, "agents", cancellationToken); - // assert - Assert.Equal(AgentDatabase.CurrentVersion, - await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken)); - Assert.Equal("opencode", await QueryScalarStringAsync( - upgraded, - "SELECT harness FROM agent_session_identities WHERE session_id = 'session-1'", - cancellationToken)); + Snapshot.Create() + .Add(version, "Version") + .Add(tables, "Tables") + .Add(indexes, "Indexes") + .Add(columns, "AgentColumns") + .MatchMarkdownSnapshot(); } /// - /// Seeds a raw v13-shaped agent_sessions table, predating the v14 - /// announcement_pending and idle_push_armed columns, with - /// one populated row. InitializeAsync must add both columns defaulted - /// to 0, without losing the existing row, and stamp the current - /// version. + /// Seeds a raw v14-shaped database: the old six-column agents table, a + /// task, and a piece of mail sent by the seeded agent. InitializeAsync must + /// wipe the agent-domain tables, lay the new agents columns, and leave + /// tasks and mail untouched. /// [Fact] - public async Task InitializeAsync_Should_AddAnnouncementAndIdlePushColumns_When_ExistingVersionIsV13() + public async Task InitializeAsync_Should_WipeAgentDomainTablesAndPreserveTasksAndMail_When_ExistingVersionIsV14() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -289,6 +82,8 @@ public async Task InitializeAsync_Should_AddAnnouncementAndIdlePushColumns_When_ $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) { await connection.OpenAsync(cancellationToken); + await ExecuteAsync(connection, "PRAGMA foreign_keys = ON;", cancellationToken); + await ExecuteAsync(connection, TaskStoreSchema.Create, cancellationToken); await ExecuteAsync( connection, """ @@ -300,45 +95,25 @@ CREATE TABLE agents ( implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)), client TEXT NOT NULL DEFAULT '' ); + """, + cancellationToken); + await ExecuteAsync(connection, MailStoreSchema.Create, cancellationToken); - CREATE TABLE agent_sessions ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode', 'nitro-board')), - session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'opencode-server', 'db-watch', 'none')), - endpoint_addr TEXT NOT NULL, - endpoint_secret TEXT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - role TEXT NOT NULL DEFAULT '', - harness_version TEXT NOT NULL DEFAULT '', - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), - PRIMARY KEY (harness, session_id) - ); + await ExecuteAsync( + connection, + """ + INSERT INTO tasks (id, title, created_at, updated_at) + VALUES ('task-1', 'Keep me', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'opencode'); + VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'claude-code'); - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'opencode', 'session-v13', 'maya', 'explicit', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'opencode-server', 'http://127.0.0.1:4096', - '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00' - ); + INSERT INTO messages (id, thread_id, sender, subject, body, created_at) + VALUES ('mail-1', 'mail-1', 'maya', 'Old mail', 'Keep me too', '2026-01-10T12:00:00+00:00'); + INSERT INTO message_recipients (message_id, recipient, ordinal) + VALUES ('mail-1', 'maya', 0); - PRAGMA user_version = 13; + PRAGMA user_version = 14; """, cancellationToken); } @@ -347,38 +122,64 @@ INSERT INTO agent_sessions ( await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - Assert.Equal(AgentDatabase.CurrentVersion, - await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken)); - - var columns = (await QueryColumnNamesAsync(upgraded, "agent_sessions", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.Contains("announcement_pending", columns); - Assert.Contains("idle_push_armed", columns); - - var survivingIdentity = await QueryScalarStringAsync( - upgraded, + var state = new + { + Version = await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken), + Tasks = await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM tasks", cancellationToken), + Messages = await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM messages", cancellationToken), + MessageRecipients = + await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM message_recipients", cancellationToken), + Agents = await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM agents", cancellationToken), + AgentColumns = await QueryColumnNamesAsync(upgraded, "agents", cancellationToken) + }; + + state.MatchInlineSnapshot( """ - SELECT agent_name || '|' || host || '|' || endpoint_addr - FROM agent_sessions - WHERE session_id = 'session-v13' - """, - cancellationToken); - Assert.Equal("maya|host-a|http://127.0.0.1:4096", survivingIdentity); - - var armedFlags = await QueryScalarLongAsync( - upgraded, - "SELECT announcement_pending + idle_push_armed FROM agent_sessions WHERE session_id = 'session-v13'", - cancellationToken); - Assert.Equal(0, armedFlags); + { + "Version": 18, + "Tasks": 1, + "Messages": 1, + "MessageRecipients": 1, + "Agents": 0, + "AgentColumns": [ + "name", + "role", + "harness", + "harness_version", + "session_id", + "cwd", + "workspace_path", + "registered_at", + "started_at", + "last_seen_at", + "ended_at", + "deleted_at", + "endpoint_kind", + "endpoint_addr", + "endpoint_secret", + "block_budget_used", + "last_ping_at", + "last_ping_attempt", + "last_ping_result", + "last_ping_detail", + "announcement_pending", + "idle_push_armed" + ] + } + """); } /// - /// Tests upgrading a v13 database with Opencode endpoint and announcement - /// fields but no takeover tables. Preserves the seeded session and agent values - /// while adding takeover tables and stamping the current version. + /// Seeds a raw v15-shaped database: mail tables still built with the old + /// REFERENCES agents (name) constraints, holding a message from an + /// agent that no longer exists (what the agent-domain rebuild that runs + /// on every schema bump used to leave behind as a foreign key orphan). + /// InitializeAsync must rebuild the mail tables without those foreign + /// keys, and the pre-existing message and its read state must survive + /// untouched. /// [Fact] - public async Task InitializeAsync_Should_AddTakeoverLedgerTables_When_ExistingVersionIsPreMergeBranchStamped13() + public async Task InitializeAsync_Should_RemoveMailForeignKeysAndPreserveOrphanedMail_When_ExistingVersionIsV15() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -386,60 +187,37 @@ public async Task InitializeAsync_Should_AddTakeoverLedgerTables_When_ExistingVe $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) { await connection.OpenAsync(cancellationToken); + await ExecuteAsync(connection, "PRAGMA foreign_keys = OFF;", cancellationToken); await ExecuteAsync( connection, """ - CREATE TABLE agents ( - name TEXT PRIMARY KEY, - registered_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - role TEXT NOT NULL DEFAULT '', - implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)), - client TEXT NOT NULL DEFAULT '' + CREATE TABLE messages ( + id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + in_reply_to TEXT REFERENCES messages (id), + sender TEXT NOT NULL REFERENCES agents (name), + subject TEXT NOT NULL CHECK (length(subject) BETWEEN 1 AND 500), + body TEXT NOT NULL, + created_at TEXT NOT NULL ); - CREATE TABLE agent_sessions ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode', 'nitro-board')), - session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'opencode-server', 'db-watch', 'none')), - endpoint_addr TEXT NOT NULL, - endpoint_secret TEXT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - role TEXT NOT NULL DEFAULT '', - harness_version TEXT NOT NULL DEFAULT '', - announcement_pending INTEGER NOT NULL DEFAULT 0 CHECK (announcement_pending IN (0, 1)), - idle_push_armed INTEGER NOT NULL DEFAULT 0 CHECK (idle_push_armed IN (0, 1)), - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), - PRIMARY KEY (harness, session_id) + CREATE TABLE message_recipients ( + message_id TEXT NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + recipient TEXT NOT NULL REFERENCES agents (name), + kind TEXT NOT NULL DEFAULT 'to' CHECK (kind IN ('to', 'cc')), + ordinal INTEGER NOT NULL CHECK (ordinal >= 0), + read_at TEXT, + archived_at TEXT, + PRIMARY KEY (message_id, recipient), + UNIQUE (message_id, ordinal) ); - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'opencode'); - - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, endpoint_secret, started_at, last_beat_at, - announcement_pending, idle_push_armed - ) VALUES ( - 'opencode', 'session-premerge13', 'maya', 'explicit', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'opencode-server', 'http://127.0.0.1:4096', 'top-secret', - '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', - 1, 1 - ); + INSERT INTO messages (id, thread_id, sender, subject, body, created_at) + VALUES ('mail-1', 'mail-1', 'ghost', 'Old mail', 'Keep me', '2026-01-10T12:00:00+00:00'); + INSERT INTO message_recipients (message_id, recipient, ordinal, read_at) + VALUES ('mail-1', 'ghost', 0, '2026-01-11T09:00:00+00:00'); - PRAGMA user_version = 13; + PRAGMA user_version = 15; """, cancellationToken); } @@ -448,46 +226,42 @@ INSERT INTO agent_sessions ( await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - Assert.Equal(AgentDatabase.CurrentVersion, - await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken)); + var orphanCount = await QueryScalarLongAsync( + upgraded, "SELECT COUNT(*) FROM pragma_foreign_key_check", cancellationToken); + Assert.Equal(0, orphanCount); - Assert.Equal(1, await QueryScalarLongAsync( - upgraded, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_takeovers'", - cancellationToken)); - Assert.Equal(1, await QueryScalarLongAsync( - upgraded, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_takeover_items'", - cancellationToken)); - - var survivingSession = await QueryScalarStringAsync( - upgraded, + var state = new + { + Version = await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken), + Sender = await QueryScalarStringAsync( + upgraded, "SELECT sender FROM messages WHERE id = 'mail-1'", cancellationToken), + Subject = await QueryScalarStringAsync( + upgraded, "SELECT subject FROM messages WHERE id = 'mail-1'", cancellationToken), + ReadAt = await QueryScalarStringAsync( + upgraded, + "SELECT read_at FROM message_recipients WHERE message_id = 'mail-1' AND recipient = 'ghost'", + cancellationToken) + }; + + state.MatchInlineSnapshot( """ - SELECT agent_name || '|' || endpoint_addr || '|' || endpoint_secret - FROM agent_sessions - WHERE session_id = 'session-premerge13' - """, - cancellationToken); - Assert.Equal("maya|http://127.0.0.1:4096|top-secret", survivingSession); - - var preservedFlags = await QueryScalarLongAsync( - upgraded, - "SELECT announcement_pending + idle_push_armed FROM agent_sessions " - + "WHERE session_id = 'session-premerge13'", - cancellationToken); - Assert.Equal(2, preservedFlags); - - var survivingAgent = await QueryScalarStringAsync( - upgraded, "SELECT client FROM agents WHERE name = 'maya'", cancellationToken); - Assert.Equal("opencode", survivingAgent); + { + "Version": 18, + "Sender": "ghost", + "Subject": "Old mail", + "ReadAt": "2026-01-11T09:00:00+00:00" + } + """); } /// - /// Tests upgrading a v2 agents table with an existing row to the current schema, - /// including default role, implicit, and client values and a session table. + /// Seeds a raw v16-shaped database with the pre-agent-model wake tables: + /// a Nitro instance id on the outbox, batches, and daemon lease, and + /// targets keyed by (harness, session_id, host). InitializeAsync must + /// wipe them and lay down the current agent-keyed shape. /// [Fact] - public async Task InitializeAsync_Should_UpgradeAgentsTableInPlace_When_ExistingVersionIsUpgradable() + public async Task InitializeAsync_Should_ReplaceOldShapedWakeTables_When_ExistingVersionIsV16() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -495,110 +269,131 @@ public async Task InitializeAsync_Should_UpgradeAgentsTableInPlace_When_Existing $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) { await connection.OpenAsync(cancellationToken); + await ExecuteAsync(connection, "PRAGMA foreign_keys = OFF;", cancellationToken); await ExecuteAsync( connection, """ - CREATE TABLE agents ( - name TEXT PRIMARY KEY, - registered_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL + CREATE TABLE mail_wake_outbox ( + nitro_instance_id TEXT NOT NULL, + actor TEXT NOT NULL REFERENCES agents (name), + requested_generation INTEGER NOT NULL DEFAULT 0 CHECK (requested_generation >= 0), + settled_generation INTEGER NOT NULL DEFAULT 0 + CHECK (settled_generation >= 0 AND settled_generation <= requested_generation), + due_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (nitro_instance_id, actor) ); - INSERT INTO agents (name, registered_at, last_seen_at) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - PRAGMA user_version = 2; - """, - cancellationToken); - } - - // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); + CREATE TABLE mail_wake_batches ( + batch_id TEXT PRIMARY KEY, + nitro_instance_id TEXT NOT NULL, + actor TEXT NOT NULL, + claimed_generation INTEGER NOT NULL CHECK (claimed_generation >= 0), + owner_id TEXT NOT NULL, + attempt_id TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'completed', 'released')), + claimed_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + completed_at TEXT NULL, + last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200), + FOREIGN KEY (nitro_instance_id, actor) REFERENCES mail_wake_outbox (nitro_instance_id, actor) + ); - var name = await QueryScalarStringAsync( - connection2, "SELECT name FROM agents WHERE name = 'claude'", cancellationToken); - var role = await QueryScalarStringAsync( - connection2, "SELECT role FROM agents WHERE name = 'claude'", cancellationToken); - var isImplicit = await QueryScalarLongAsync( - connection2, "SELECT implicit FROM agents WHERE name = 'claude'", cancellationToken); - var client = await QueryScalarStringAsync( - connection2, "SELECT client FROM agents WHERE name = 'claude'", cancellationToken); - Assert.Equal("claude", name); - Assert.Equal("", role); - Assert.Equal(0, isImplicit); - Assert.Equal("", client); - - var agentSessionsTableCount = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_sessions'", - cancellationToken); - Assert.Equal(1, agentSessionsTableCount); - } + CREATE TABLE mail_wake_targets ( + batch_id TEXT NOT NULL REFERENCES mail_wake_batches (batch_id) ON DELETE CASCADE, + harness TEXT NOT NULL + CHECK (harness IN ('claude-code', 'codex', 'copilot', 'opencode', 'nitro-board')), + session_id TEXT NOT NULL, + host TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'delivered', 'satisfied', 'delegated', 'skipped', 'failed')), + offered_generation INTEGER NULL CHECK (offered_generation IS NULL OR offered_generation >= 0), + accepted_generation INTEGER NULL CHECK (accepted_generation IS NULL OR accepted_generation >= 0), + last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200), + updated_at TEXT NOT NULL, + PRIMARY KEY (batch_id, harness, session_id, host) + ); - /// - /// Tests adding client metadata and a session table to a database stamped v3 - /// while preserving the existing agent role. - /// - [Fact] - public async Task InitializeAsync_Should_AddClientColumn_When_ExistingVersionIsCurrentButPredatesClient() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = new SqliteConnection( - $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) - { - await connection.OpenAsync(cancellationToken); - await ExecuteAsync( - connection, - """ - CREATE TABLE agents ( - name TEXT PRIMARY KEY, - registered_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - role TEXT NOT NULL DEFAULT '', - implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)) + CREATE TABLE mail_wake_daemons ( + nitro_instance_id TEXT PRIMARY KEY, + owner_id TEXT NOT NULL, + epoch INTEGER NOT NULL CHECK (epoch >= 1), + leased_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200) ); - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0); - PRAGMA user_version = 3; + + PRAGMA user_version = 16; """, cancellationToken); } // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - - var columns = (await QueryColumnNamesAsync(connection2, "agents", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.Contains("client", columns); - - var role = await QueryScalarStringAsync( - connection2, "SELECT role FROM agents WHERE name = 'claude'", cancellationToken); - var client = await QueryScalarStringAsync( - connection2, "SELECT client FROM agents WHERE name = 'claude'", cancellationToken); - Assert.Equal("backend", role); - Assert.Equal("", client); - - var agentSessionsTableCount = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_sessions'", - cancellationToken); - Assert.Equal(1, agentSessionsTableCount); + var state = new + { + Version = await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken), + OutboxColumns = await QueryColumnNamesAsync(upgraded, "mail_wake_outbox", cancellationToken), + BatchColumns = await QueryColumnNamesAsync(upgraded, "mail_wake_batches", cancellationToken), + TargetColumns = await QueryColumnNamesAsync(upgraded, "mail_wake_targets", cancellationToken), + DaemonColumns = await QueryColumnNamesAsync(upgraded, "mail_wake_daemons", cancellationToken) + }; + + state.MatchInlineSnapshot( + """ + { + "Version": 18, + "OutboxColumns": [ + "actor", + "requested_generation", + "settled_generation", + "due_at", + "updated_at" + ], + "BatchColumns": [ + "batch_id", + "actor", + "claimed_generation", + "owner_id", + "attempt_id", + "status", + "claimed_at", + "expires_at", + "completed_at", + "last_error" + ], + "TargetColumns": [ + "batch_id", + "agent", + "status", + "offered_generation", + "accepted_generation", + "last_error", + "updated_at" + ], + "DaemonColumns": [ + "id", + "owner_token", + "acquired_at", + "heartbeat_at", + "expires_at" + ] + } + """); } /// - /// Tests upgrading v4 session metadata with blank role and harness-version - /// defaults and no process-scope column. Preserves the session, its delivery - /// row, and the bound agent's role. + /// Seeds a raw v17-shaped database: the current, foreign-key-free task and mail + /// tables, an agents table still carrying the transitional implicit + /// and client columns, and the old agent_sessions and + /// agent_session_identities tables. InitializeAsync must drop the session + /// tables, wipe the agent-domain rows, lay down the current agents columns, + /// and leave the mail already present untouched. /// [Fact] - public async Task InitializeAsync_Should_UpgradeAgentSessionsMetadataColumns_When_ExistingVersionIsV4() + public async Task InitializeAsync_Should_DropSessionTablesAndPreserveMail_When_ExistingVersionIsV17() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -606,448 +401,280 @@ public async Task InitializeAsync_Should_UpgradeAgentSessionsMetadataColumns_Whe $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) { await connection.OpenAsync(cancellationToken); - await ExecuteAsync(connection, "PRAGMA foreign_keys = ON;", cancellationToken); + await ExecuteAsync(connection, "PRAGMA foreign_keys = OFF;", cancellationToken); + await ExecuteAsync(connection, TaskStoreSchema.Create, cancellationToken); + await ExecuteAsync(connection, MailStoreSchema.Create, cancellationToken); await ExecuteAsync( connection, """ CREATE TABLE agents ( name TEXT PRIMARY KEY, + role TEXT NOT NULL DEFAULT '', + harness TEXT NULL, + harness_version TEXT NOT NULL DEFAULT '', + session_id TEXT NULL, + cwd TEXT NOT NULL DEFAULT '', + workspace_path TEXT NOT NULL DEFAULT '', registered_at TEXT NOT NULL, + started_at TEXT NOT NULL, last_seen_at TEXT NOT NULL, - role TEXT NOT NULL DEFAULT '', - implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)), + ended_at TEXT NULL, + deleted_at TEXT NULL, + endpoint_kind TEXT NOT NULL DEFAULT 'none', + endpoint_addr TEXT NOT NULL DEFAULT '', + endpoint_secret TEXT NULL, + block_budget_used INTEGER NOT NULL DEFAULT 0, + last_ping_at TEXT NULL, + last_ping_attempt TEXT NULL, + last_ping_result TEXT NULL, + last_ping_detail TEXT NULL, + announcement_pending INTEGER NOT NULL DEFAULT 0, + idle_push_armed INTEGER NOT NULL DEFAULT 0, + implicit INTEGER NOT NULL DEFAULT 0, client TEXT NOT NULL DEFAULT '' ); CREATE TABLE agent_sessions ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), + harness TEXT NOT NULL, session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - pid INTEGER NOT NULL CHECK (pid > 0), - proc_start TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'none')), - endpoint_addr TEXT NOT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), + agent_name TEXT NULL, PRIMARY KEY (harness, session_id) ); - CREATE INDEX idx_agent_sessions_name ON agent_sessions (agent_name); - CREATE INDEX idx_agent_sessions_pid ON agent_sessions (host, pid); - - CREATE TABLE session_deliveries ( + CREATE TABLE agent_session_identities ( harness TEXT NOT NULL, session_id TEXT NOT NULL, - message_id TEXT NOT NULL, - channel TEXT NOT NULL CHECK (channel IN ('digest', 'gate', 'ping')), - delivered_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, message_id, channel), - FOREIGN KEY (harness, session_id) - REFERENCES agent_sessions (harness, session_id) ON DELETE CASCADE - ); - - CREATE TABLE ping_leases ( - slot INTEGER PRIMARY KEY CHECK (slot BETWEEN 1 AND 4), - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL + actor TEXT NOT NULL, + PRIMARY KEY (harness, session_id) ); + """, + cancellationToken); - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'claude-code'); - - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, pid, proc_start, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', 'session-v4', 'claude', 'explicit', 'host-a', 4242, '2026-01-10T12:00:00+00:00', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); + await ExecuteAsync( + connection, + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at, implicit, client) + VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', + '2026-01-10T12:00:00+00:00', 0, 'claude-code'); - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-v4', 'msg-1', 'digest', '2026-01-10T12:00:00+00:00'); + INSERT INTO messages (id, thread_id, sender, subject, body, created_at) + VALUES ('mail-1', 'mail-1', 'maya', 'Old mail', 'Keep me', '2026-01-10T12:00:00+00:00'); + INSERT INTO message_recipients (message_id, recipient, ordinal) + VALUES ('mail-1', 'maya', 0); - PRAGMA user_version = 4; + PRAGMA user_version = 17; """, cancellationToken); } // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - - var sessionColumns = (await QueryColumnNamesAsync(connection2, "agent_sessions", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.Contains("role", sessionColumns); - Assert.Contains("harness_version", sessionColumns); - Assert.DoesNotContain("process_scope", sessionColumns); - - var agentName = await QueryScalarStringAsync( - connection2, "SELECT agent_name FROM agent_sessions WHERE session_id = 'session-v4'", cancellationToken); - Assert.Equal("claude", agentName); - - var role = await QueryScalarStringAsync( - connection2, "SELECT role FROM agent_sessions WHERE session_id = 'session-v4'", cancellationToken); - var harnessVersion = await QueryScalarStringAsync( - connection2, - "SELECT harness_version FROM agent_sessions WHERE session_id = 'session-v4'", - cancellationToken); - Assert.Equal("", role); - Assert.Equal("", harnessVersion); - - var deliveryCount = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-v4'", - cancellationToken); - Assert.Equal(1, deliveryCount); - - var agentRole = await QueryScalarStringAsync( - connection2, "SELECT role FROM agents WHERE name = 'claude'", cancellationToken); - Assert.Equal("backend", agentRole); + var state = new + { + Version = await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken), + Messages = await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM messages", cancellationToken), + MessageRecipients = + await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM message_recipients", cancellationToken), + Agents = await QueryScalarLongAsync(upgraded, "SELECT COUNT(*) FROM agents", cancellationToken), + AgentColumns = await QueryColumnNamesAsync(upgraded, "agents", cancellationToken), + SessionTables = await QueryScalarLongAsync( + upgraded, + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' " + + "AND name IN ('agent_sessions', 'agent_session_identities')", + cancellationToken) + }; + + state.MatchInlineSnapshot( + """ + { + "Version": 18, + "Messages": 1, + "MessageRecipients": 1, + "Agents": 0, + "AgentColumns": [ + "name", + "role", + "harness", + "harness_version", + "session_id", + "cwd", + "workspace_path", + "registered_at", + "started_at", + "last_seen_at", + "ended_at", + "deleted_at", + "endpoint_kind", + "endpoint_addr", + "endpoint_secret", + "block_budget_used", + "last_ping_at", + "last_ping_attempt", + "last_ping_result", + "last_ping_detail", + "announcement_pending", + "idle_push_armed" + ], + "SessionTables": 0 + } + """); } /// - /// Tests upgrading a v5 session to the current schema without process-start - /// columns, preserving its role and delivery row. + /// Opening an already-current database, whether for the first time after + /// creation or a second time in a row, never wipes the agents already in it. /// [Fact] - public async Task InitializeAsync_Should_DropTheProcessColumns_When_ExistingVersionIsV5() + public async Task InitializeAsync_Should_PreserveAgentRows_When_ReopeningACurrentDatabase() { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = new SqliteConnection( - $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) + await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) { - await connection.OpenAsync(cancellationToken); - await ExecuteAsync(connection, "PRAGMA foreign_keys = ON;", cancellationToken); await ExecuteAsync( connection, """ - CREATE TABLE agents ( - name TEXT PRIMARY KEY, - registered_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - role TEXT NOT NULL DEFAULT '', - implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)), - client TEXT NOT NULL DEFAULT '' - ); - - CREATE TABLE agent_sessions ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), - session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - pid INTEGER NOT NULL CHECK (pid > 0), - proc_start TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'none')), - endpoint_addr TEXT NOT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - role TEXT NOT NULL DEFAULT '', - harness_version TEXT NOT NULL DEFAULT '', - process_scope TEXT NOT NULL DEFAULT '', - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), - PRIMARY KEY (harness, session_id) - ); - - CREATE INDEX idx_agent_sessions_name ON agent_sessions (agent_name); - CREATE INDEX idx_agent_sessions_pid ON agent_sessions (host, pid); - - CREATE TABLE session_deliveries ( - harness TEXT NOT NULL, - session_id TEXT NOT NULL, - message_id TEXT NOT NULL, - channel TEXT NOT NULL CHECK (channel IN ('digest', 'gate', 'ping')), - delivered_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, message_id, channel), - FOREIGN KEY (harness, session_id) - REFERENCES agent_sessions (harness, session_id) ON DELETE CASCADE - ); - - CREATE TABLE ping_leases ( - slot INTEGER PRIMARY KEY CHECK (slot BETWEEN 1 AND 4), - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL - ); + INSERT INTO agents (name, registered_at, started_at, last_seen_at, harness, session_id) + VALUES ('leia', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', + '2026-01-10T12:00:00+00:00', 'claude-code', 'session-current'); + """, + cancellationToken); + } - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'claude-code'); + // act: open the already-current database twice more. + await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) + { + } - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, pid, proc_start, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - role, harness_version, process_scope - ) VALUES ( - 'claude-code', 'session-v5', 'claude', 'explicit', 'host-a', 4242, '2026-01-10T12:00:00.000000+00:00', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00', 'backend', '1.2.3', 'pidns:4242' - ); + await using var reopened = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-v5', 'msg-1', 'digest', '2026-01-10T12:00:00+00:00'); + // assert + Assert.Equal(AgentDatabase.CurrentVersion, + await QueryScalarLongAsync(reopened, "PRAGMA user_version", cancellationToken)); + Assert.Equal(1, await QueryScalarLongAsync( + reopened, "SELECT COUNT(*) FROM agents WHERE name = 'leia'", cancellationToken)); + } - PRAGMA user_version = 5; + [Fact] + public async Task InitializeAsync_Should_UpgradeV11AndPreserveRows_When_TakeoverTablesAreMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) + { + await ExecuteAsync( + connection, + """ + INSERT INTO tasks (id, title, created_at, updated_at) + VALUES ('task-v11', 'Preserve me', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + DROP TABLE agent_takeover_items; + DROP TABLE agent_takeovers; + PRAGMA user_version = 11; """, cancellationToken); } // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await using var upgraded = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - - var sessionColumns = (await QueryColumnNamesAsync(connection2, "agent_sessions", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.DoesNotContain("proc_start", sessionColumns); - Assert.DoesNotContain("proc_start_legacy", sessionColumns); - - var role = await QueryScalarStringAsync( - connection2, "SELECT role FROM agent_sessions WHERE session_id = 'session-v5'", cancellationToken); - Assert.Equal("backend", role); - - var deliveryCount = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-v5'", - cancellationToken); - Assert.Equal(1, deliveryCount); + Assert.Equal(AgentDatabase.CurrentVersion, + await QueryScalarLongAsync(upgraded, "PRAGMA user_version", cancellationToken)); + Assert.Equal("Preserve me", await QueryScalarStringAsync( + upgraded, "SELECT title FROM tasks WHERE id = 'task-v11'", cancellationToken)); + Assert.Equal(1, await QueryScalarLongAsync( + upgraded, + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_takeovers'", + cancellationToken)); + Assert.Equal(1, await QueryScalarLongAsync( + upgraded, + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'agent_takeover_items'", + cancellationToken)); } - /// - /// Tests upgrading a v4 ping-result constraint to accept unsupported - /// while preserving the session and delivery cascade. Invalid ping results - /// remain rejected. - /// [Fact] - public async Task InitializeAsync_Should_RebuildAgentSessionsCheckConstraint_When_ExistingV4DatabasePredatesUnsupported() + public async Task InitializeAsync_Should_LeaveTakeoverRowsUnchanged_When_DatabaseIsCurrent() { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = new SqliteConnection( - $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) + await using (var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) { - await connection.OpenAsync(cancellationToken); - await ExecuteAsync(connection, "PRAGMA foreign_keys = ON;", cancellationToken); await ExecuteAsync( connection, """ - CREATE TABLE agents ( - name TEXT PRIMARY KEY, - registered_at TEXT NOT NULL, - last_seen_at TEXT NOT NULL, - role TEXT NOT NULL DEFAULT '', - implicit INTEGER NOT NULL DEFAULT 0 CHECK (implicit IN (0, 1)), - client TEXT NOT NULL DEFAULT '' - ); - - CREATE TABLE agent_sessions ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), - session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - pid INTEGER NOT NULL CHECK (pid > 0), - proc_start TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'none')), - endpoint_addr TEXT NOT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), - PRIMARY KEY (harness, session_id) - ); - - CREATE INDEX idx_agent_sessions_name ON agent_sessions (agent_name); - CREATE INDEX idx_agent_sessions_pid ON agent_sessions (host, pid); - - CREATE TABLE session_deliveries ( - harness TEXT NOT NULL, - session_id TEXT NOT NULL, - message_id TEXT NOT NULL, - channel TEXT NOT NULL CHECK (channel IN ('digest', 'gate', 'ping')), - delivered_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, message_id, channel), - FOREIGN KEY (harness, session_id) - REFERENCES agent_sessions (harness, session_id) ON DELETE CASCADE - ); - - CREATE TABLE ping_leases ( - slot INTEGER PRIMARY KEY CHECK (slot BETWEEN 1 AND 4), - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL - ); - - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, pid, proc_start, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - last_ping_result + INSERT INTO agent_takeovers ( + id, from_actor, to_actor, actor, created_at, forced, role, reason ) VALUES ( - 'claude-code', 'session-old', NULL, 'none', 'host-a', 4242, '2026-01-10T12:00:00+00:00', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00', 'ok' + 'to-current', 'maya', 'nora', 'maya', '2026-01-10T12:00:00+00:00', 1, NULL, NULL ); - - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-old', 'msg-1', 'digest', '2026-01-10T12:00:00+00:00'); - - PRAGMA user_version = 4; """, cancellationToken); } // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await using var reopened = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - - var existingLastPingResult = await QueryScalarStringAsync( - connection2, - "SELECT last_ping_result FROM agent_sessions WHERE session_id = 'session-old'", - cancellationToken); - Assert.Equal("ok", existingLastPingResult); - - var sessionColumns = (await QueryColumnNamesAsync(connection2, "agent_sessions", cancellationToken)) - .ToHashSet(StringComparer.Ordinal); - Assert.DoesNotContain("pid", sessionColumns); - Assert.DoesNotContain("proc_start", sessionColumns); - - var deliveryCount = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-old'", - cancellationToken); - Assert.Equal(1, deliveryCount); - - await ExecuteAsync( - connection2, - "UPDATE agent_sessions SET last_ping_result = 'unsupported' WHERE session_id = 'session-old';", - cancellationToken); - var updatedLastPingResult = await QueryScalarStringAsync( - connection2, - "SELECT last_ping_result FROM agent_sessions WHERE session_id = 'session-old'", - cancellationToken); - Assert.Equal("unsupported", updatedLastPingResult); + Assert.Equal(AgentDatabase.CurrentVersion, + await QueryScalarLongAsync(reopened, "PRAGMA user_version", cancellationToken)); + Assert.Equal(1, await QueryScalarLongAsync( + reopened, "SELECT COUNT(*) FROM agent_takeovers WHERE id = 'to-current'", cancellationToken)); + } - // Deleting the session still cascades to its delivery row. - await ExecuteAsync( - connection2, "DELETE FROM agent_sessions WHERE session_id = 'session-old';", cancellationToken); - var deliveryCountAfterCascade = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-old'", - cancellationToken); - Assert.Equal(0, deliveryCountAfterCascade); + [Fact] + public void IsUpgradableVersion_Should_ReturnTrue_When_VersionIs11() + { + // act + var isUpgradable = AgentDatabase.IsUpgradableVersion(11); - await Assert.ThrowsAsync(() => ExecuteAsync( - connection2, - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - last_ping_result - ) VALUES ( - 'claude-code', 'session-invalid', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00', 'not-a-real-result' - ); - """, - cancellationToken)); + // assert + Assert.True(isUpgradable); } - /// - /// Tests that a fresh session table accepts unsupported as a ping result. - /// [Fact] - public async Task InitializeAsync_Should_AcceptUnsupportedLastPingResult_When_DatabaseIsFreshlyCreated() + public async Task InitializeAsync_Should_BeIdempotent_When_CalledAgainOnCurrentVersion() { // arrange var cancellationToken = TestContext.Current.CancellationToken; - await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await InsertAgentSessionAsync(connection, "session-fresh", cancellationToken); + await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) + { + } // act - await ExecuteAsync( - connection, - "UPDATE agent_sessions SET last_ping_result = 'unsupported' WHERE session_id = 'session-fresh';", - cancellationToken); + await using var second = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // assert - var lastPingResult = await QueryScalarStringAsync( - connection, - "SELECT last_ping_result FROM agent_sessions WHERE session_id = 'session-fresh'", - cancellationToken); - Assert.Equal("unsupported", lastPingResult); + var version = await QueryScalarLongAsync(second, "PRAGMA user_version;", cancellationToken); + Assert.Equal(AgentDatabase.CurrentVersion, version); } /// - /// Tests that a fresh session table accepts the nitro-board harness - /// and db-watch endpoint. + /// Tests that the unified agents table accepts unsupported as a ping result. /// [Fact] - public async Task InitializeAsync_Should_AcceptNitroBoardHarnessAndDbWatchEndpoint_When_DatabaseIsFreshlyCreated() + public async Task InitializeAsync_Should_AcceptUnsupportedLastPingResult_When_DatabaseIsFreshlyCreated() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await ExecuteAsync( + connection, + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + "('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", + cancellationToken); // act await ExecuteAsync( connection, - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'nitro-board', 'board-fresh', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'db-watch', 'local', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); - """, + "UPDATE agents SET last_ping_result = 'unsupported' WHERE name = 'maya';", cancellationToken); // assert - var harness = await QueryScalarStringAsync( - connection, "SELECT harness FROM agent_sessions WHERE session_id = 'board-fresh'", cancellationToken); - var endpointKind = await QueryScalarStringAsync( - connection, - "SELECT endpoint_kind FROM agent_sessions WHERE session_id = 'board-fresh'", - cancellationToken); - Assert.Equal("nitro-board", harness); - Assert.Equal("db-watch", endpointKind); + var lastPingResult = await QueryScalarStringAsync( + connection, "SELECT last_ping_result FROM agents WHERE name = 'maya'", cancellationToken); + Assert.Equal("unsupported", lastPingResult); } [Fact] @@ -1168,92 +795,58 @@ await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) [InlineData(5)] [InlineData(6)] [InlineData(7)] + [InlineData(17)] public async Task ConnectAsync_Should_Throw_When_VersionIsUpgradable(int upgradableVersion) { // arrange var cancellationToken = TestContext.Current.CancellationToken; await StampVersionOnNewFileAsync(upgradableVersion, cancellationToken); - // act & assert - await Assert.ThrowsAsync( + // act + var exception = await Record.ExceptionAsync( () => _database.ConnectAsync(_workspaceDirectory, cancellationToken)); + + // assert + Assert.IsType(exception); } /// - /// Round trip against the real schema with foreign_keys=ON (verified - /// explicitly): insert an unclaimed agent_sessions row (no agent, - /// binding_kind = 'none'), then claim it by pointing - /// agent_name at a real row in agents and flipping - /// binding_kind to 'explicit'. Also proves the FK actually - /// enforces: claiming with a name that is not in agents fails. + /// agent_deliveries.channel is CHECK-constrained to + /// digest, gate, or ping. /// [Fact] - public async Task AgentSessionsTable_Should_InsertUnclaimedRowThenClaimIt_When_ForeignKeysAreOn() + public async Task AgentDeliveriesTable_Should_RejectUnknownChannel_When_CheckConstraintFires() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - var foreignKeysEnabled = await QueryScalarLongAsync(connection, "PRAGMA foreign_keys;", cancellationToken); - Assert.Equal(1, foreignKeysEnabled); - await ExecuteAsync( connection, - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', 'session-1', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); - """, + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + "('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", cancellationToken); - // act: the row starts unclaimed. - var unclaimedAgentName = await QueryScalarStringAsync( - connection, "SELECT agent_name FROM agent_sessions WHERE session_id = 'session-1'", cancellationToken); - var unclaimedBindingKind = await QueryScalarStringAsync( - connection, "SELECT binding_kind FROM agent_sessions WHERE session_id = 'session-1'", cancellationToken); - Assert.Null(unclaimedAgentName); - Assert.Equal("none", unclaimedBindingKind); - - // Claiming with an unregistered agent must fail the FK check. - await Assert.ThrowsAsync(() => ExecuteAsync( + // act + var exception = await Record.ExceptionAsync(() => ExecuteAsync( connection, - "UPDATE agent_sessions SET agent_name = 'ghost', binding_kind = 'explicit' " - + "WHERE session_id = 'session-1';", + """ + INSERT INTO agent_deliveries (agent, message_id, channel, delivered_at) + VALUES ('maya', 'msg-1', 'unknown-channel', '2026-01-10T12:00:00+00:00'); + """, cancellationToken)); - await ExecuteAsync( - connection, - "INSERT INTO agents (name, registered_at, last_seen_at) VALUES " - + "('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", - cancellationToken); - - await ExecuteAsync( - connection, - "UPDATE agent_sessions SET agent_name = 'claude', binding_kind = 'explicit' " - + "WHERE session_id = 'session-1';", - cancellationToken); - - // assert: claiming against a real agent succeeds. - var claimedAgentName = await QueryScalarStringAsync( - connection, "SELECT agent_name FROM agent_sessions WHERE session_id = 'session-1'", cancellationToken); - var claimedBindingKind = await QueryScalarStringAsync( - connection, "SELECT binding_kind FROM agent_sessions WHERE session_id = 'session-1'", cancellationToken); - Assert.Equal("claude", claimedAgentName); - Assert.Equal("explicit", claimedBindingKind); + // assert + Assert.IsType(exception); } /// - /// The cross-column CHECK (binding_kind = 'none') = (agent_name IS NULL) - /// rejects a row that claims to be bound (binding_kind = 'explicit') - /// while carrying no agent name. + /// ping_leases.slot is CHECK-constrained to the fixed four-slot + /// concurrency cap; 0 and 5 both fall outside it. /// - [Fact] - public async Task AgentSessionsTable_Should_RejectMismatchedBindingKindAndAgentName_When_CheckConstraintFires() + [Theory] + [InlineData(0)] + [InlineData(5)] + public async Task PingLeasesTable_Should_RejectSlotOutsideRange_When_CheckConstraintFires(int slot) { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -1262,175 +855,147 @@ public async Task AgentSessionsTable_Should_RejectMismatchedBindingKindAndAgentN // act & assert await Assert.ThrowsAsync(() => ExecuteAsync( connection, - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', 'session-2', NULL, 'explicit', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); + $""" + INSERT INTO ping_leases (slot, attempt_id, acquired_at, expires_at) + VALUES ({slot}, 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:05+00:00'); """, cancellationToken)); } /// - /// The cross-column CHECK (endpoint_kind = 'none') = (endpoint_addr = '') - /// rejects a row that names a real endpoint kind while carrying no - /// address. + /// The inclusive ends of the range, 1 and 4, are accepted. /// - [Fact] - public async Task AgentSessionsTable_Should_RejectActiveEndpointKindWithEmptyAddress_When_CheckConstraintFires() + [Theory] + [InlineData(1)] + [InlineData(4)] + public async Task PingLeasesTable_Should_AcceptSlotWithinRange_When_AtTheInclusiveBounds(int slot) { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - // act & assert - await Assert.ThrowsAsync(() => ExecuteAsync( + // act + await ExecuteAsync( connection, - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', 'session-3', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'claude-peer', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); + $""" + INSERT INTO ping_leases (slot, attempt_id, acquired_at, expires_at) + VALUES ({slot}, 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:05+00:00'); """, - cancellationToken)); + cancellationToken); + + // assert + var count = await QueryScalarLongAsync( + connection, $"SELECT COUNT(*) FROM ping_leases WHERE slot = {slot}", cancellationToken); + Assert.Equal(1, count); } /// - /// The same cross-column CHECK also rejects the opposite mismatch: a - /// non-empty address while endpoint_kind claims there is none. + /// The partial unique index idx_agents_session rejects a second row + /// that claims the same (harness, session_id) pair. /// [Fact] - public async Task AgentSessionsTable_Should_RejectNoneEndpointKindWithNonEmptyAddress_When_CheckConstraintFires() + public async Task AgentsTable_Should_RejectDuplicateHarnessSessionId_When_PartialUniqueIndexFires() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // act & assert - await Assert.ThrowsAsync(() => ExecuteAsync( + await ExecuteAsync( connection, """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', 'session-4', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', 'peer-a', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); + INSERT INTO agents (name, registered_at, started_at, last_seen_at, harness, session_id) + VALUES ('maya', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', + '2026-01-10T12:00:00+00:00', 'claude-code', 'session-dup'); """, - cancellationToken)); - } - - /// - /// session_deliveries.channel is CHECK-constrained to - /// digest, gate, or ping. - /// - [Fact] - public async Task SessionDeliveriesTable_Should_RejectUnknownChannel_When_CheckConstraintFires() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await InsertAgentSessionAsync(connection, "session-5", cancellationToken); + cancellationToken); - // act & assert - await Assert.ThrowsAsync(() => ExecuteAsync( + // act + var exception = await Assert.ThrowsAsync(() => ExecuteAsync( connection, """ - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-5', 'msg-1', 'unknown-channel', '2026-01-10T12:00:00+00:00'); + INSERT INTO agents (name, registered_at, started_at, last_seen_at, harness, session_id) + VALUES ('nora', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', + '2026-01-10T12:00:00+00:00', 'claude-code', 'session-dup'); """, cancellationToken)); + + // assert + Assert.Equal(2067, exception.SqliteExtendedErrorCode); } /// - /// session_deliveries rows cascade-delete with their owning - /// agent_sessions row. + /// idx_agents_session only covers rows with a non-null harness, so + /// any number of login-only rows (both columns null) coexist. /// [Fact] - public async Task SessionDeliveriesTable_Should_CascadeDelete_When_OwningAgentSessionRowIsDeleted() + public async Task AgentsTable_Should_AllowMultipleLoginOnlyRows_When_HarnessIsNull() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await InsertAgentSessionAsync(connection, "session-6", cancellationToken); + + // act await ExecuteAsync( connection, """ - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-6', 'msg-1', 'digest', '2026-01-10T12:00:00+00:00'); + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES ('codex', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); """, cancellationToken); - // act - await ExecuteAsync( - connection, "DELETE FROM agent_sessions WHERE session_id = 'session-6';", cancellationToken); - // assert - var remaining = await QueryScalarLongAsync( - connection, - "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-6'", - cancellationToken); - Assert.Equal(0, remaining); + var loginOnlyCount = await QueryScalarLongAsync( + connection, "SELECT COUNT(*) FROM agents WHERE harness IS NULL", cancellationToken); + Assert.Equal(2, loginOnlyCount); } /// - /// ping_leases.slot is CHECK-constrained to the fixed four-slot - /// concurrency cap; 0 and 5 both fall outside it. + /// agent_deliveries.agent references agents (name); an unknown + /// agent name is rejected. /// - [Theory] - [InlineData(0)] - [InlineData(5)] - public async Task PingLeasesTable_Should_RejectSlotOutsideRange_When_CheckConstraintFires(int slot) + [Fact] + public async Task AgentDeliveriesTable_Should_RejectUnknownAgent_When_ForeignKeyFires() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - // act & assert - await Assert.ThrowsAsync(() => ExecuteAsync( + // act + var exception = await Assert.ThrowsAsync(() => ExecuteAsync( connection, - $""" - INSERT INTO ping_leases (slot, attempt_id, acquired_at, expires_at) - VALUES ({slot}, 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:05+00:00'); + """ + INSERT INTO agent_deliveries (agent, message_id, channel, delivered_at) + VALUES ('ghost', 'msg-1', 'digest', '2026-01-10T12:00:00+00:00'); """, cancellationToken)); + + // assert + Assert.Equal(787, exception.SqliteExtendedErrorCode); } /// - /// The inclusive ends of the range, 1 and 4, are accepted. + /// agent_ping_gates.agent references agents (name); an unknown + /// agent name is rejected. /// - [Theory] - [InlineData(1)] - [InlineData(4)] - public async Task PingLeasesTable_Should_AcceptSlotWithinRange_When_AtTheInclusiveBounds(int slot) + [Fact] + public async Task AgentPingGatesTable_Should_RejectUnknownAgent_When_ForeignKeyFires() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); // act - await ExecuteAsync( + var exception = await Assert.ThrowsAsync(() => ExecuteAsync( connection, - $""" - INSERT INTO ping_leases (slot, attempt_id, acquired_at, expires_at) - VALUES ({slot}, 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:05+00:00'); + """ + INSERT INTO agent_ping_gates (agent, attempt_id, acquired_at, expires_at) + VALUES ('ghost', 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); """, - cancellationToken); + cancellationToken)); // assert - var count = await QueryScalarLongAsync( - connection, $"SELECT COUNT(*) FROM ping_leases WHERE slot = {slot}", cancellationToken); - Assert.Equal(1, count); + Assert.Equal(787, exception.SqliteExtendedErrorCode); } /// @@ -1448,8 +1013,8 @@ public async Task TaskAndMail_Should_ShareOneDatabaseFile_When_UsingTheUnifiedWo new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); var fileSystem = new TestFileSystem(_tempRoot.FullName); var taskStore = new TaskStore(fileSystem, timeProvider, _database); - var agentRegistry = new AgentRegistry(fileSystem, timeProvider, _database); - var mailStore = new MailStore(fileSystem, timeProvider, _database, agentRegistry); + var agentStore = new AgentStore(fileSystem, timeProvider, _database); + var mailStore = new MailStore(fileSystem, timeProvider, _database, agentStore); await taskStore.InitializeWorkspaceAsync(_workspaceDirectory, "acme", cancellationToken); @@ -1463,7 +1028,17 @@ public async Task TaskAndMail_Should_ShareOneDatabaseFile_When_UsingTheUnifiedWo Actor = "claude" }, cancellationToken); - await agentRegistry.RegisterAsync("codex", role: "", client: "", cancellationToken); + + await using (var agentSeedConnection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken)) + { + await ExecuteAsync( + agentSeedConnection, + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + "('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'), " + + "('codex', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", + cancellationToken); + } + var message = await mailStore.SendMessageAsync( new MailMessageCreation { @@ -1492,11 +1067,13 @@ public async Task TaskAndMail_Should_ShareOneDatabaseFile_When_UsingTheUnifiedWo } /// - /// Tests adding mail-wake and session-ping-gate tables and indexes to a - /// database stamped v6 that lacks them, preserving its seeded rows. + /// Tests adding mail-wake and ping-gate tables and indexes to a database + /// stamped v6 that lacks them. Agent-domain rows (agents, ping_leases) are + /// wiped by the blanket agent-domain reset; mail is a non-agent table and + /// survives. /// [Fact] - public async Task InitializeAsync_Should_AddMailWakeAndSessionPingGateTables_When_ExistingVersionIsV6() + public async Task InitializeAsync_Should_AddMailWakeAndAgentPingGateTables_When_ExistingVersionIsV6() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -1508,14 +1085,14 @@ public async Task InitializeAsync_Should_AddMailWakeAndSessionPingGateTables_Whe await ExecuteAsync(connection, TaskStoreSchema.Create, cancellationToken); await ExecuteAsync(connection, AgentRegistrySchema.Create, cancellationToken); await ExecuteAsync(connection, MailStoreSchema.Create, cancellationToken); - await ExecuteAsync(connection, AgentSessionSchema.Create, cancellationToken); + await ExecuteAsync(connection, PingLeaseSchema.Create, cancellationToken); await ExecuteAsync( connection, """ - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'claude-code'), - ('codex', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '', 0, 'codex'); + INSERT INTO agents (name, registered_at, started_at, last_seen_at, role) + VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend'), + ('codex', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', ''); INSERT INTO messages (id, thread_id, sender, subject, body, created_at) VALUES ('msg-v6', 'thread-v6', 'claude', 'Status', 'Merged.', '2026-01-10T12:00:00+00:00'); @@ -1523,19 +1100,6 @@ INSERT INTO messages (id, thread_id, sender, subject, body, created_at) INSERT INTO message_recipients (message_id, recipient, kind, ordinal) VALUES ('msg-v6', 'codex', 'to', 0); - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - role, harness_version - ) VALUES ( - 'claude-code', 'session-v6', 'claude', 'explicit', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00', 'backend', '1.2.3' - ); - - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-v6', 'msg-v6', 'digest', '2026-01-10T12:00:00+00:00'); - INSERT INTO ping_leases (slot, attempt_id, acquired_at, expires_at) VALUES (1, 'attempt-v6', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:05+00:00'); @@ -1549,386 +1113,77 @@ INSERT INTO ping_leases (slot, attempt_id, acquired_at, expires_at) // assert var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - foreach (var newTable in new[] - { - "mail_wake_outbox", "mail_wake_batches", "mail_wake_targets", "mail_wake_daemons", - "session_ping_gates" - }) - { - var tableCount = await QueryScalarLongAsync( - connection2, - $"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '{newTable}'", - cancellationToken); - Assert.Equal(1, tableCount); - } + var tables = await QueryExistingSqliteObjectsAsync( + connection2, + "table", + [ + "mail_wake_outbox", "mail_wake_batches", "mail_wake_targets", "mail_wake_daemons", + "agent_ping_gates" + ], + cancellationToken); - foreach (var index in new[] - { - "idx_mail_wake_outbox_due", "idx_mail_wake_batches_one_active_per_actor", - "idx_mail_wake_batches_expires", "idx_session_ping_gates_expires" - }) - { - var indexCount = await QueryScalarLongAsync( - connection2, - $"SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = '{index}'", - cancellationToken); - Assert.Equal(1, indexCount); - } + var indexes = await QueryExistingSqliteObjectsAsync( + connection2, + "index", + [ + "idx_mail_wake_outbox_due", "idx_mail_wake_batches_one_active_per_actor", + "idx_mail_wake_batches_expires", "idx_agent_ping_gates_expires" + ], + cancellationToken); var agentCount = await QueryScalarLongAsync(connection2, "SELECT COUNT(*) FROM agents", cancellationToken); var messageCount = await QueryScalarLongAsync(connection2, "SELECT COUNT(*) FROM messages", cancellationToken); var recipientCount = await QueryScalarLongAsync(connection2, "SELECT COUNT(*) FROM message_recipients", cancellationToken); - var sessionCount = - await QueryScalarLongAsync(connection2, "SELECT COUNT(*) FROM agent_sessions", cancellationToken); - var deliveryCount = - await QueryScalarLongAsync(connection2, "SELECT COUNT(*) FROM session_deliveries", cancellationToken); var leaseCount = await QueryScalarLongAsync(connection2, "SELECT COUNT(*) FROM ping_leases", cancellationToken); - Assert.Equal(2, agentCount); - Assert.Equal(1, messageCount); - Assert.Equal(1, recipientCount); - Assert.Equal(1, sessionCount); - Assert.Equal(1, deliveryCount); - Assert.Equal(1, leaseCount); - } - - /// - /// Tests upgrading a v7 session table to accept nitro-board and - /// db-watch, preserving session metadata, delivery rows, and their cascade. - /// - [Fact] - public async Task InitializeAsync_Should_UpgradeAgentSessionsHarnessCheckConstraint_When_ExistingVersionIsV7() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = new SqliteConnection( - $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) - { - await connection.OpenAsync(cancellationToken); - await ExecuteAsync(connection, "PRAGMA foreign_keys = ON;", cancellationToken); - await ExecuteAsync(connection, TaskStoreSchema.Create, cancellationToken); - await ExecuteAsync(connection, AgentRegistrySchema.Create, cancellationToken); - await ExecuteAsync(connection, MailStoreSchema.Create, cancellationToken); - await ExecuteAsync( - connection, - """ - CREATE TABLE agent_sessions ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), - session_id TEXT NOT NULL, - agent_name TEXT NULL REFERENCES agents (name), - binding_kind TEXT NOT NULL DEFAULT 'none' CHECK (binding_kind IN ('none', 'env', 'explicit')), - host TEXT NOT NULL, - pid INTEGER NOT NULL CHECK (pid > 0), - proc_start TEXT NOT NULL, - cwd TEXT NOT NULL, - workspace_path TEXT NOT NULL, - endpoint_kind TEXT NOT NULL CHECK (endpoint_kind IN ('claude-peer', 'codex-thread', 'copilot-extension', 'none')), - endpoint_addr TEXT NOT NULL, - started_at TEXT NOT NULL, - last_beat_at TEXT NOT NULL, - block_budget_used INTEGER NOT NULL DEFAULT 0 CHECK (block_budget_used >= 0), - last_ping_at TEXT NULL, - last_ping_attempt TEXT NULL, - last_ping_result TEXT NULL CHECK (last_ping_result IN ('ok', 'spawn-failed', 'endpoint-gone', 'timeout', 'capacity-dropped', 'error', 'unsupported') OR last_ping_result IS NULL), - last_ping_detail TEXT NULL CHECK (last_ping_detail IS NULL OR length(last_ping_detail) <= 200), - role TEXT NOT NULL DEFAULT '', - harness_version TEXT NOT NULL DEFAULT '', - process_scope TEXT NOT NULL DEFAULT '', - proc_start_legacy INTEGER NOT NULL DEFAULT 0 CHECK (proc_start_legacy IN (0, 1)), - CHECK ((binding_kind = 'none') = (agent_name IS NULL)), - CHECK ((endpoint_kind = 'none') = (endpoint_addr = '')), - PRIMARY KEY (harness, session_id) - ); - - CREATE INDEX idx_agent_sessions_name ON agent_sessions (agent_name); - CREATE INDEX idx_agent_sessions_pid ON agent_sessions (host, pid); - - CREATE TABLE session_deliveries ( - harness TEXT NOT NULL, - session_id TEXT NOT NULL, - message_id TEXT NOT NULL, - channel TEXT NOT NULL CHECK (channel IN ('digest', 'gate', 'ping')), - delivered_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, message_id, channel), - FOREIGN KEY (harness, session_id) - REFERENCES agent_sessions (harness, session_id) ON DELETE CASCADE - ); - - CREATE TABLE ping_leases ( - slot INTEGER PRIMARY KEY CHECK (slot BETWEEN 1 AND 4), - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL - ); - """, - cancellationToken); - await ExecuteAsync(connection, MailWakeSchema.Create, cancellationToken); - await ExecuteAsync(connection, SessionPingGateSchema.Create, cancellationToken); - - await ExecuteAsync( - connection, - """ - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'claude-code'); - - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, pid, proc_start, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at, - role, harness_version, process_scope, proc_start_legacy - ) VALUES ( - 'claude-code', 'session-v7', 'claude', 'explicit', 'host-a', 4242, '123456', - '/tmp/work', '/tmp/work/.nitro/agents', 'claude-peer', 'peer-a', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00', 'backend', '1.2.3', 'pidns:4242', 0 - ); - - INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) - VALUES ('claude-code', 'session-v7', 'msg-1', 'digest', '2026-01-10T12:00:00+00:00'); - - PRAGMA user_version = 7; - """, - cancellationToken); - } - - // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - - var role = await QueryScalarStringAsync( - connection2, "SELECT role FROM agent_sessions WHERE session_id = 'session-v7'", cancellationToken); - var harnessVersion = await QueryScalarStringAsync( - connection2, - "SELECT harness_version FROM agent_sessions WHERE session_id = 'session-v7'", - cancellationToken); - var endpointKind = await QueryScalarStringAsync( - connection2, "SELECT endpoint_kind FROM agent_sessions WHERE session_id = 'session-v7'", cancellationToken); - Assert.Equal("backend", role); - Assert.Equal("1.2.3", harnessVersion); - Assert.Equal("claude-peer", endpointKind); - - var deliveryCount = await QueryScalarLongAsync( - connection2, "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-v7'", cancellationToken); - Assert.Equal(1, deliveryCount); - - // The new harness and endpoint_kind values are now writable. - await ExecuteAsync( - connection2, - """ - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'nitro-board', 'board-1', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'db-watch', 'local', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); - """, - cancellationToken); - - var boardSessionCount = await QueryScalarLongAsync( - connection2, "SELECT COUNT(*) FROM agent_sessions WHERE harness = 'nitro-board'", cancellationToken); - Assert.Equal(1, boardSessionCount); - - // Deleting the session still cascades to its delivery row. - await ExecuteAsync( - connection2, "DELETE FROM agent_sessions WHERE session_id = 'session-v7';", cancellationToken); - var deliveryCountAfterCascade = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM session_deliveries WHERE session_id = 'session-v7'", - cancellationToken); - Assert.Equal(0, deliveryCountAfterCascade); - } - - /// - /// Tests upgrading v7 wake-target and ping-gate tables to accept - /// nitro-board, preserving existing rows and the wake-target cascade. - /// - [Fact] - public async Task InitializeAsync_Should_UpgradeMailWakeTargetsAndSessionPingGatesHarnessCheckConstraint_When_ExistingVersionIsV7() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using (var connection = new SqliteConnection( - $"Data Source={AgentWorkspace.GetDatabasePath(_workspaceDirectory)};Pooling=False")) - { - await connection.OpenAsync(cancellationToken); - await ExecuteAsync(connection, "PRAGMA foreign_keys = ON;", cancellationToken); - await ExecuteAsync(connection, TaskStoreSchema.Create, cancellationToken); - await ExecuteAsync(connection, AgentRegistrySchema.Create, cancellationToken); - await ExecuteAsync(connection, MailStoreSchema.Create, cancellationToken); - await ExecuteAsync(connection, AgentSessionSchema.Create, cancellationToken); - await ExecuteAsync(connection, MailWakeSchema.Create, cancellationToken); - await ExecuteAsync(connection, SessionPingGateSchema.Create, cancellationToken); - - // Downgrade mail_wake_targets and session_ping_gates to their pre-v8 harness CHECK constraint. - await ExecuteAsync( - connection, - """ - DROP TABLE mail_wake_targets; - CREATE TABLE mail_wake_targets ( - batch_id TEXT NOT NULL REFERENCES mail_wake_batches (batch_id) ON DELETE CASCADE, - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), - session_id TEXT NOT NULL, - host TEXT NOT NULL, - pid INTEGER NOT NULL CHECK (pid > 0), - proc_start TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending' - CHECK (status IN ('pending', 'delivered', 'satisfied', 'delegated', 'skipped', 'failed')), - offered_generation INTEGER NULL CHECK (offered_generation IS NULL OR offered_generation >= 0), - accepted_generation INTEGER NULL CHECK (accepted_generation IS NULL OR accepted_generation >= 0), - last_error TEXT NULL CHECK (last_error IS NULL OR length(last_error) <= 200), - updated_at TEXT NOT NULL, - PRIMARY KEY (batch_id, harness, session_id, host, pid, proc_start) - ); - - DROP TABLE session_ping_gates; - CREATE TABLE session_ping_gates ( - harness TEXT NOT NULL CHECK (harness IN ('claude-code', 'codex', 'copilot')), - session_id TEXT NOT NULL, - host TEXT NOT NULL, - pid INTEGER NOT NULL CHECK (pid > 0), - proc_start TEXT NOT NULL, - attempt_id TEXT NOT NULL, - acquired_at TEXT NOT NULL, - expires_at TEXT NOT NULL, - PRIMARY KEY (harness, session_id, host, pid, proc_start) - ); - CREATE INDEX idx_session_ping_gates_expires ON session_ping_gates (expires_at); - """, - cancellationToken); - - await ExecuteAsync( - connection, - """ - INSERT INTO agents (name, registered_at, last_seen_at, role, implicit, client) - VALUES ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', 'backend', 0, 'claude-code'); - - INSERT INTO mail_wake_outbox (nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at) - VALUES ('instance-a', 'claude', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - - INSERT INTO mail_wake_batches ( - batch_id, nitro_instance_id, actor, claimed_generation, owner_id, attempt_id, - status, claimed_at, expires_at - ) VALUES ( - 'batch-v7', 'instance-a', 'claude', 1, 'owner-1', 'attempt-1', - 'active', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00' - ); - - INSERT INTO mail_wake_targets (batch_id, harness, session_id, host, pid, proc_start, status, updated_at) - VALUES ('batch-v7', 'claude-code', 'session-v7', 'host-a', 4242, '2026-01-10T12:00:00+00:00', - 'pending', '2026-01-10T12:00:00+00:00'); - - INSERT INTO session_ping_gates (harness, session_id, host, pid, proc_start, attempt_id, acquired_at, expires_at) - VALUES ('claude-code', 'session-v7', 'host-a', 4242, '2026-01-10T12:00:00+00:00', - 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); - - PRAGMA user_version = 7; - """, - cancellationToken); - } - - // act - await using var connection2 = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // assert - var version = await QueryScalarLongAsync(connection2, "PRAGMA user_version;", cancellationToken); - Assert.Equal(AgentDatabase.CurrentVersion, version); - var targetStatus = await QueryScalarStringAsync( - connection2, - "SELECT status FROM mail_wake_targets WHERE batch_id = 'batch-v7'", - cancellationToken); - Assert.Equal("pending", targetStatus); - - var gateAttemptId = await QueryScalarStringAsync( - connection2, - "SELECT attempt_id FROM session_ping_gates WHERE session_id = 'session-v7'", - cancellationToken); - Assert.Equal("attempt-1", gateAttemptId); - - // The new harness value is now writable on both tables. - await ExecuteAsync( - connection2, - """ - INSERT INTO mail_wake_targets (batch_id, harness, session_id, host, status, updated_at) - VALUES ('batch-v7', 'nitro-board', 'board-v8', 'host-a', 'pending', '2026-01-10T12:00:00+00:00'); - - INSERT INTO session_ping_gates (harness, session_id, host, attempt_id, acquired_at, expires_at) - VALUES ('nitro-board', 'board-v8', 'host-a', 'attempt-2', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); - """, - cancellationToken); - - var boardTargetCount = await QueryScalarLongAsync( - connection2, "SELECT COUNT(*) FROM mail_wake_targets WHERE harness = 'nitro-board'", cancellationToken); - var boardGateCount = await QueryScalarLongAsync( - connection2, "SELECT COUNT(*) FROM session_ping_gates WHERE harness = 'nitro-board'", cancellationToken); - Assert.Equal(1, boardTargetCount); - Assert.Equal(1, boardGateCount); - - // Deleting the batch still cascades to its target rows. - await ExecuteAsync( - connection2, "DELETE FROM mail_wake_batches WHERE batch_id = 'batch-v7';", cancellationToken); - var targetCountAfterCascade = await QueryScalarLongAsync( - connection2, - "SELECT COUNT(*) FROM mail_wake_targets WHERE batch_id = 'batch-v7'", - cancellationToken); - Assert.Equal(0, targetCountAfterCascade); + Snapshot.Create() + .Add(version, "Version") + .Add(tables, "Tables") + .Add(indexes, "Indexes") + .Add(agentCount, "AgentCount") + .Add(messageCount, "MessageCount") + .Add(recipientCount, "RecipientCount") + .Add(leaseCount, "LeaseCount") + .MatchMarkdownSnapshot(); } /// - /// Tests that fresh wake-target and ping-gate tables accept nitro-board. + /// mail_wake_targets.agent references agents (name); an + /// unknown agent name is rejected. /// [Fact] - public async Task InitializeAsync_Should_AcceptNitroBoardHarnessInMailWakeTargetsAndSessionPingGates_When_DatabaseIsFreshlyCreated() + public async Task MailWakeTargetsTable_Should_RejectUnknownAgent_When_ForeignKeyFires() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await ExecuteAsync( - connection, - "INSERT INTO agents (name, registered_at, last_seen_at) VALUES " - + "('pascal', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", - cancellationToken); await ExecuteAsync( connection, """ - INSERT INTO mail_wake_outbox (nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at) - VALUES ('instance-a', 'pascal', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - + INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES + ('pascal', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES ('pascal', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); INSERT INTO mail_wake_batches ( - batch_id, nitro_instance_id, actor, claimed_generation, owner_id, attempt_id, - status, claimed_at, expires_at + batch_id, actor, claimed_generation, owner_id, attempt_id, status, claimed_at, expires_at ) VALUES ( - 'batch-fresh', 'instance-a', 'pascal', 1, 'owner-1', 'attempt-1', + 'batch-fresh', 'pascal', 1, 'owner-1', 'attempt-1', 'active', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00' ); """, cancellationToken); - // act - await ExecuteAsync( + // act & assert + await Assert.ThrowsAsync(() => ExecuteAsync( connection, """ - INSERT INTO mail_wake_targets (batch_id, harness, session_id, host, status, updated_at) - VALUES ('batch-fresh', 'nitro-board', 'board-fresh', 'host-a', 'pending', '2026-01-10T12:00:00+00:00'); - - INSERT INTO session_ping_gates (harness, session_id, host, attempt_id, acquired_at, expires_at) - VALUES ('nitro-board', 'board-fresh', 'host-a', 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); + INSERT INTO mail_wake_targets (batch_id, agent, status, updated_at) + VALUES ('batch-fresh', 'ghost', 'pending', '2026-01-10T12:00:00+00:00'); """, - cancellationToken); - - // assert - var targetHarness = await QueryScalarStringAsync( - connection, "SELECT harness FROM mail_wake_targets WHERE session_id = 'board-fresh'", cancellationToken); - var gateHarness = await QueryScalarStringAsync( - connection, "SELECT harness FROM session_ping_gates WHERE session_id = 'board-fresh'", cancellationToken); - Assert.Equal("nitro-board", targetHarness); - Assert.Equal("nitro-board", gateHarness); + cancellationToken)); } /// @@ -1943,24 +1198,23 @@ public async Task MailWakeOutboxTable_Should_RejectSettledGenerationAboveRequest await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); await ExecuteAsync( connection, - "INSERT INTO agents (name, registered_at, last_seen_at) VALUES " - + "('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + "('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", cancellationToken); // act & assert await Assert.ThrowsAsync(() => ExecuteAsync( connection, """ - INSERT INTO mail_wake_outbox (nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at) - VALUES ('instance-a', 'claude', 1, 2, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES ('claude', 1, 2, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); """, cancellationToken)); } /// /// At most one active mail_wake_batches row exists per - /// (nitro_instance_id, actor), enforced by - /// idx_mail_wake_batches_one_active_per_actor. + /// actor, enforced by idx_mail_wake_batches_one_active_per_actor. /// [Fact] public async Task MailWakeBatchesTable_Should_RejectSecondActiveBatch_When_UniqueIndexFires() @@ -1971,15 +1225,14 @@ public async Task MailWakeBatchesTable_Should_RejectSecondActiveBatch_When_Uniqu await ExecuteAsync( connection, """ - INSERT INTO agents (name, registered_at, last_seen_at) VALUES - ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - INSERT INTO mail_wake_outbox (nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at) - VALUES ('instance-a', 'claude', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES + ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES ('claude', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); INSERT INTO mail_wake_batches ( - batch_id, nitro_instance_id, actor, claimed_generation, owner_id, attempt_id, - status, claimed_at, expires_at + batch_id, actor, claimed_generation, owner_id, attempt_id, status, claimed_at, expires_at ) VALUES ( - 'batch-1', 'instance-a', 'claude', 1, 'owner-1', 'attempt-1', + 'batch-1', 'claude', 1, 'owner-1', 'attempt-1', 'active', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00' ); """, @@ -1990,10 +1243,9 @@ await Assert.ThrowsAsync(() => ExecuteAsync( connection, """ INSERT INTO mail_wake_batches ( - batch_id, nitro_instance_id, actor, claimed_generation, owner_id, attempt_id, - status, claimed_at, expires_at + batch_id, actor, claimed_generation, owner_id, attempt_id, status, claimed_at, expires_at ) VALUES ( - 'batch-2', 'instance-a', 'claude', 1, 'owner-2', 'attempt-2', + 'batch-2', 'claude', 1, 'owner-2', 'attempt-2', 'active', '2026-01-10T12:00:01+00:00', '2026-01-10T12:00:31+00:00' ); """, @@ -2002,122 +1254,61 @@ INSERT INTO mail_wake_batches ( /// /// mail_wake_targets rows cascade-delete with their owning - /// mail_wake_batches row, but a target row's own generation - /// columns carry no foreign key against agent_sessions: deleting - /// the live session row must never touch the durable target row. + /// mail_wake_batches row when the batch itself is deleted. /// [Fact] - public async Task MailWakeTargetsTable_Should_SurviveAgentSessionDeletion_When_OwningBatchStillExists() + public async Task MailWakeTargetsTable_Should_CascadeDelete_When_TheOwningBatchIsDeleted() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await InsertAgentSessionAsync(connection, "session-target", cancellationToken); await ExecuteAsync( connection, """ - INSERT INTO agents (name, registered_at, last_seen_at) VALUES - ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); - INSERT INTO mail_wake_outbox (nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at) - VALUES ('instance-a', 'claude', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES + ('claude', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES ('claude', 1, 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); INSERT INTO mail_wake_batches ( - batch_id, nitro_instance_id, actor, claimed_generation, owner_id, attempt_id, - status, claimed_at, expires_at + batch_id, actor, claimed_generation, owner_id, attempt_id, status, claimed_at, expires_at ) VALUES ( - 'batch-target', 'instance-a', 'claude', 1, 'owner-1', 'attempt-1', + 'batch-target', 'claude', 1, 'owner-1', 'attempt-1', 'active', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00' ); - INSERT INTO mail_wake_targets (batch_id, harness, session_id, host, status, updated_at) - VALUES ('batch-target', 'claude-code', 'session-target', 'host-a', 'pending', '2026-01-10T12:00:00+00:00'); + INSERT INTO mail_wake_targets (batch_id, agent, status, updated_at) + VALUES ('batch-target', 'claude', 'pending', '2026-01-10T12:00:00+00:00'); """, cancellationToken); // act await ExecuteAsync( - connection, "DELETE FROM agent_sessions WHERE session_id = 'session-target';", cancellationToken); + connection, "DELETE FROM mail_wake_batches WHERE batch_id = 'batch-target';", cancellationToken); // assert var targetCount = await QueryScalarLongAsync( connection, "SELECT COUNT(*) FROM mail_wake_targets WHERE batch_id = 'batch-target'", cancellationToken); - Assert.Equal(1, targetCount); - } - - /// - /// mail_wake_daemons.epoch must be at least 1. - /// - [Fact] - public async Task MailWakeDaemonsTable_Should_RejectEpochBelowOne_When_CheckConstraintFires() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - - // act & assert - await Assert.ThrowsAsync(() => ExecuteAsync( - connection, - """ - INSERT INTO mail_wake_daemons (nitro_instance_id, owner_id, epoch, leased_at, expires_at) - VALUES ('instance-a', 'owner-1', 0, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); - """, - cancellationToken)); - } - - /// - /// Tests that a session ping gate survives deletion of the corresponding session row. - /// - [Fact] - public async Task SessionPingGatesTable_Should_SurviveAgentSessionDeletion_When_NoForeignKeyTiesThem() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await InsertAgentSessionAsync(connection, "session-gate", cancellationToken); - await ExecuteAsync( - connection, - """ - INSERT INTO session_ping_gates (harness, session_id, host, attempt_id, acquired_at, expires_at) - VALUES ('claude-code', 'session-gate', 'host-a', 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); - """, - cancellationToken); - - // act - await ExecuteAsync( - connection, "DELETE FROM agent_sessions WHERE session_id = 'session-gate';", cancellationToken); - - // assert - var gateCount = await QueryScalarLongAsync( - connection, - "SELECT COUNT(*) FROM session_ping_gates WHERE session_id = 'session-gate'", - cancellationToken); - Assert.Equal(1, gateCount); + Assert.Equal(0, targetCount); } /// - /// Tests that the ping-gate primary key rejects a duplicate - /// (harness, session_id, host) generation. + /// mail_wake_daemons.id only ever accepts 1: the table + /// holds a single row. /// [Fact] - public async Task SessionPingGatesTable_Should_RejectDuplicateGeneration_When_PrimaryKeyFires() + public async Task MailWakeDaemonsTable_Should_RejectASecondRow_When_CheckConstraintFires() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); - await ExecuteAsync( - connection, - """ - INSERT INTO session_ping_gates (harness, session_id, host, attempt_id, acquired_at, expires_at) - VALUES ('claude-code', 'session-dup', 'host-a', 'attempt-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); - """, - cancellationToken); // act & assert await Assert.ThrowsAsync(() => ExecuteAsync( connection, """ - INSERT INTO session_ping_gates (harness, session_id, host, attempt_id, acquired_at, expires_at) - VALUES ('claude-code', 'session-dup', 'host-a', 'attempt-2', '2026-01-10T12:00:01+00:00', '2026-01-10T12:00:31+00:00'); + INSERT INTO mail_wake_daemons (id, owner_token, acquired_at, heartbeat_at, expires_at) + VALUES (2, 'owner-1', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:30+00:00'); """, cancellationToken)); } @@ -2159,6 +1350,35 @@ private static async Task QueryScalarLongAsync( return result is null or DBNull ? null : result.ToString(); } + /// + /// Returns the subset of that exist in + /// sqlite_master under the given object + /// ("table" or "index"), in candidate order. + /// + private static async Task> QueryExistingSqliteObjectsAsync( + SqliteConnection connection, + string type, + IReadOnlyList candidates, + CancellationToken cancellationToken) + { + var present = new List(); + + foreach (var candidate in candidates) + { + var count = await QueryScalarLongAsync( + connection, + $"SELECT COUNT(*) FROM sqlite_master WHERE type = '{type}' AND name = '{candidate}'", + cancellationToken); + + if (count == 1) + { + present.Add(candidate); + } + } + + return present; + } + private static async Task> QueryColumnNamesAsync( SqliteConnection connection, string tableName, @@ -2189,24 +1409,4 @@ private static async Task ExecuteAsync( await command.ExecuteNonQueryAsync(cancellationToken); } - - /// - /// Inserts a minimal, otherwise-valid agent_sessions row with the - /// given session id, for tests that only care about a dependent table. - /// - private static Task InsertAgentSessionAsync( - SqliteConnection connection, string sessionId, CancellationToken cancellationToken) - => ExecuteAsync( - connection, - $""" - INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at - ) VALUES ( - 'claude-code', '{sessionId}', NULL, 'none', 'host-a', - '/tmp/work', '/tmp/work/.nitro/agents', 'none', '', '2026-01-10T12:00:00+00:00', - '2026-01-10T12:00:00+00:00' - ); - """, - cancellationToken); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDeliveryLedgerTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDeliveryLedgerTests.cs new file mode 100644 index 00000000000..ba434b7914b --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentDeliveryLedgerTests.cs @@ -0,0 +1,131 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; + +namespace ChilliCream.Nitro.CommandLine.Tests.Agents; + +/// +/// Exercises 's per-agent delivery +/// reservations directly against a real workspace database. +/// +public sealed class AgentDeliveryLedgerTests : IDisposable +{ + private readonly DirectoryInfo _tempRoot; + private readonly string _workspaceDirectory; + private readonly TestFileSystem _fileSystem; + private readonly AgentDatabase _database; + private readonly AgentDeliveryLedger _ledger; + + public AgentDeliveryLedgerTests() + { + _tempRoot = Directory.CreateTempSubdirectory("nitro-agent-delivery-ledger-tests"); + _workspaceDirectory = AgentWorkspace.GetDirectory(_tempRoot.FullName); + Directory.CreateDirectory(_workspaceDirectory); + _fileSystem = new TestFileSystem(_tempRoot.FullName); + _database = new AgentDatabase(); + _ledger = new AgentDeliveryLedger(_fileSystem, _database); + } + + public void Dispose() => _tempRoot.Delete(recursive: true); + + [Fact] + public async Task ReserveAsync_Should_KeyTheReservationByAgent_When_TwoAgentsReserveTheSameMessage() + { + // arrange + // the same message id reserved for two different agents. + var cancellationToken = TestContext.Current.CancellationToken; + await using (var connection = await InitializeWorkspaceAsync(cancellationToken)) + { + await SeedAgentAsync(connection, "alice", cancellationToken); + await SeedAgentAsync(connection, "bob", cancellationToken); + } + var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); + + // act + var aliceReserved = await _ledger.ReserveAsync("alice", ["msg-1"], "ping", now, cancellationToken); + var bobReserved = await _ledger.ReserveAsync("bob", ["msg-1"], "ping", now, cancellationToken); + + // assert + // reserving under one agent never blocks the same message id under another. + Assert.Equal(["msg-1"], aliceReserved); + Assert.Equal(["msg-1"], bobReserved); + } + + [Fact] + public async Task ReserveAsync_Should_ReturnNoClaim_When_TheSameAgentReservesTheSameMessageTwice() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using (var connection = await InitializeWorkspaceAsync(cancellationToken)) + { + await SeedAgentAsync(connection, "alice", cancellationToken); + } + var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); + await _ledger.ReserveAsync("alice", ["msg-1"], "ping", now, cancellationToken); + + // act + var secondReservation = await _ledger.ReserveAsync("alice", ["msg-1"], "ping", now, cancellationToken); + + // assert + Assert.Empty(secondReservation); + } + + [Fact] + public async Task FindDeliveredAsync_Should_ReturnOnlyTheMatchingAgentsMessages_When_AnotherAgentHoldsTheSameId() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using (var connection = await InitializeWorkspaceAsync(cancellationToken)) + { + await SeedAgentAsync(connection, "alice", cancellationToken); + await SeedAgentAsync(connection, "bob", cancellationToken); + } + var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); + await _ledger.ReserveAsync("bob", ["msg-1"], "digest", now, cancellationToken); + + // act + var aliceDelivered = await _ledger.FindDeliveredAsync("alice", ["msg-1"], cancellationToken); + var bobDelivered = await _ledger.FindDeliveredAsync("bob", ["msg-1"], cancellationToken); + + // assert + Assert.Empty(aliceDelivered); + Assert.Equal(["msg-1"], bobDelivered); + } + + [Fact] + public async Task ReleaseAsync_Should_FreeOnlyTheReleasedAgentsReservation_When_TwoAgentsHoldTheSameMessage() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using (var connection = await InitializeWorkspaceAsync(cancellationToken)) + { + await SeedAgentAsync(connection, "alice", cancellationToken); + await SeedAgentAsync(connection, "bob", cancellationToken); + } + var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); + await _ledger.ReserveAsync("alice", ["msg-1"], "ping", now, cancellationToken); + await _ledger.ReserveAsync("bob", ["msg-1"], "ping", now, cancellationToken); + + // act + await _ledger.ReleaseAsync("alice", ["msg-1"], "ping", cancellationToken); + var aliceReReserved = await _ledger.ReserveAsync("alice", ["msg-1"], "ping", now, cancellationToken); + var bobDelivered = await _ledger.FindDeliveredAsync("bob", ["msg-1"], cancellationToken); + + // assert + Assert.Equal(["msg-1"], aliceReReserved); + Assert.Equal(["msg-1"], bobDelivered); + } + + private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) + => await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + + private static async Task SeedAgentAsync( + SqliteConnection connection, string name, CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.CommandText = + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + "(@name, '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');"; + command.Parameters.AddWithValue("@name", name); + await command.ExecuteNonQueryAsync(cancellationToken); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentHarnessDisplayTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentHarnessDisplayTests.cs new file mode 100644 index 00000000000..14792395f11 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentHarnessDisplayTests.cs @@ -0,0 +1,26 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Agents; + +/// +/// Exercises : the canonical harness ids and the +/// login-only fallback. +/// +public sealed class AgentHarnessDisplayTests +{ + [Theory] + [InlineData("claude-code", "Claude Code")] + [InlineData("codex", "Codex")] + [InlineData("copilot", "Copilot")] + [InlineData("opencode", "OpenCode")] + [InlineData(null, "-")] + [InlineData("", "-")] + public void Name_Should_ReturnDisplayName_When_GivenAHarnessId(string? harness, string expected) + { + // act + var name = AgentHarnessDisplay.Name(harness); + + // assert + Assert.Equal(expected, name); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentRegistryTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentRegistryTests.cs deleted file mode 100644 index 26d034fece3..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentRegistryTests.cs +++ /dev/null @@ -1,301 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; -using Microsoft.Extensions.Time.Testing; - -namespace ChilliCream.Nitro.CommandLine.Tests.Agents; - -/// -/// Exercises against a real SQLite workspace: -/// register, touch, get, and list, including role and implicit semantics. -/// -public sealed class AgentRegistryTests : IDisposable -{ - private readonly DirectoryInfo _tempRoot; - private readonly string _workingDirectory; - private readonly string _workspaceDirectory; - private readonly FakeTimeProvider _timeProvider; - private readonly AgentRegistry _registry; - - public AgentRegistryTests() - { - _tempRoot = Directory.CreateTempSubdirectory("nitro-agent-registry-tests"); - _workingDirectory = Path.Combine(_tempRoot.FullName, "acme"); - Directory.CreateDirectory(_workingDirectory); - _workspaceDirectory = AgentWorkspace.GetDirectory(_workingDirectory); - - _timeProvider = new FakeTimeProvider( - new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); - - _registry = new AgentRegistry(new TestFileSystem(_workingDirectory), _timeProvider, new AgentDatabase()); - } - - public void Dispose() => _tempRoot.Delete(recursive: true); - - private async Task InitWorkspaceAsync(CancellationToken cancellationToken) - { - Directory.CreateDirectory(_workspaceDirectory); - await new AgentDatabase().InitializeAsync(_workspaceDirectory, cancellationToken); - } - - [Fact] - public async Task RegisterAsync_Should_InsertNewAgent_When_NotRegistered() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - - // act - var agent = await _registry.RegisterAsync("Claude", role: "", client: "", cancellationToken); - - // assert - Assert.Equal("claude", agent.Name); - Assert.Equal("", agent.Role); - Assert.False(agent.Implicit); - Assert.Equal(_timeProvider.GetUtcNow(), agent.RegisteredAt); - Assert.Equal(_timeProvider.GetUtcNow(), agent.LastSeenAt); - } - - [Fact] - public async Task RegisterAsync_Should_NormalizeRoleLowercase() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - - // act - var agent = await _registry.RegisterAsync("claude", role: "Backend", client: "", cancellationToken); - - // assert - Assert.Equal("backend", agent.Role); - } - - [Fact] - public async Task RegisterAsync_Should_BumpLastSeenAt_When_AlreadyRegistered() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - var first = await _registry.RegisterAsync("claude", role: "", client: "", cancellationToken); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var second = await _registry.RegisterAsync("claude", role: "", client: "", cancellationToken); - - // assert - Assert.Equal(first.RegisteredAt, second.RegisteredAt); - Assert.Equal(_timeProvider.GetUtcNow(), second.LastSeenAt); - Assert.NotEqual(second.RegisteredAt, second.LastSeenAt); - } - - [Fact] - public async Task RegisterAsync_Should_OverwriteRole_When_CalledAgainWithoutRole() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.RegisterAsync("claude", role: "backend", client: "", cancellationToken); - - // act - var agent = await _registry.RegisterAsync("claude", role: "", client: "", cancellationToken); - - // assert - Assert.Equal("", agent.Role); - } - - [Fact] - public async Task RegisterAsync_Should_ClearImplicit_When_RowWasImplicit() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.TouchAsync("claude", cancellationToken); - - // act - var agent = await _registry.RegisterAsync("claude", role: "backend", client: "", cancellationToken); - - // assert - Assert.False(agent.Implicit); - } - - [Fact] - public async Task TouchAsync_Should_InsertNewAgent_WithEmptyRole_When_NotRegistered() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - - // act - var agent = await _registry.TouchAsync("claude", cancellationToken); - - // assert - Assert.Equal("claude", agent.Name); - Assert.Equal("", agent.Role); - Assert.False(agent.Implicit); - } - - [Fact] - public async Task TouchAsync_Should_PreserveRole_When_AlreadyRegisteredWithRole() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.RegisterAsync("claude", role: "backend", client: "", cancellationToken); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var agent = await _registry.TouchAsync("claude", cancellationToken); - - // assert - Assert.Equal("backend", agent.Role); - Assert.Equal(_timeProvider.GetUtcNow(), agent.LastSeenAt); - } - - [Fact] - public async Task EnsureImplicitAsync_Should_InsertImplicitAgent_When_NotRegistered() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - - // act - var agent = await _registry.EnsureImplicitAsync("dave", cancellationToken); - - // assert - Assert.Equal("dave", agent.Name); - Assert.Equal("", agent.Role); - Assert.True(agent.Implicit); - Assert.Equal(_timeProvider.GetUtcNow(), agent.RegisteredAt); - Assert.Equal(_timeProvider.GetUtcNow(), agent.LastSeenAt); - } - - [Fact] - public async Task EnsureImplicitAsync_Should_ReturnExistingRowUnchanged_When_AlreadyRegistered() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - var registered = await _registry.RegisterAsync("dave", role: "backend", client: "", cancellationToken); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var agent = await _registry.EnsureImplicitAsync("dave", cancellationToken); - - // assert - Assert.Equal("backend", agent.Role); - Assert.False(agent.Implicit); - Assert.Equal(registered.LastSeenAt, agent.LastSeenAt); - } - - [Fact] - public async Task EnsureImplicitAsync_Should_ReturnExistingImplicitRowUnchanged_When_AlreadyImplicit() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - var first = await _registry.EnsureImplicitAsync("dave", cancellationToken); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var second = await _registry.EnsureImplicitAsync("dave", cancellationToken); - - // assert - Assert.True(second.Implicit); - Assert.Equal(first.LastSeenAt, second.LastSeenAt); - } - - [Fact] - public async Task GetAsync_Should_ReturnNull_When_NotRegistered() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - - // act - var agent = await _registry.GetAsync("nobody", cancellationToken); - - // assert - Assert.Null(agent); - } - - [Fact] - public async Task ListAsync_Should_ReturnAllOrderedByName_When_NoFilterGiven() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.RegisterAsync("bob", role: "", client: "", cancellationToken); - await _registry.RegisterAsync("alice", role: "", client: "", cancellationToken); - - // act - var agents = await _registry.ListAsync(role: null, staleBefore: null, cancellationToken); - - // assert - Assert.Equal(["alice", "bob"], agents.Select(a => a.Name)); - } - - [Fact] - public async Task ListAsync_Should_FilterByExactRole() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.RegisterAsync("alice", role: "backend", client: "", cancellationToken); - await _registry.RegisterAsync("bob", role: "frontend", client: "", cancellationToken); - - // act - var agents = await _registry.ListAsync(role: "backend", staleBefore: null, cancellationToken); - - // assert - var agent = Assert.Single(agents); - Assert.Equal("alice", agent.Name); - } - - [Fact] - public async Task ListAsync_Should_FilterByStaleBefore() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.RegisterAsync("stale-agent", role: "", client: "", cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(31)); - await _registry.RegisterAsync("fresh-agent", role: "", client: "", cancellationToken); - - // act - var agents = await _registry.ListAsync( - role: null, staleBefore: _timeProvider.GetUtcNow() - TimeSpan.FromDays(30), cancellationToken); - - // assert - var agent = Assert.Single(agents); - Assert.Equal("stale-agent", agent.Name); - } - - [Fact] - public async Task ListAsync_Should_FilterByRoleAndStaleBefore_Together() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitWorkspaceAsync(cancellationToken); - await _registry.RegisterAsync("stale-backend", role: "backend", client: "", cancellationToken); - await _registry.RegisterAsync("stale-frontend", role: "frontend", client: "", cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(31)); - await _registry.RegisterAsync("fresh-backend", role: "backend", client: "", cancellationToken); - - // act - var agents = await _registry.ListAsync( - role: "backend", staleBefore: _timeProvider.GetUtcNow() - TimeSpan.FromDays(30), cancellationToken); - - // assert - var agent = Assert.Single(agents); - Assert.Equal("stale-backend", agent.Name); - } - - [Fact] - public async Task ListAsync_Should_Throw_When_NoWorkspaceExists() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - - // act & assert - await Assert.ThrowsAsync( - () => _registry.ListAsync(role: null, staleBefore: null, cancellationToken)); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentRowTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentRowTests.cs new file mode 100644 index 00000000000..48155422111 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentRowTests.cs @@ -0,0 +1,157 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Data.Sqlite; + +namespace ChilliCream.Nitro.CommandLine.Tests.Agents; + +/// +/// Tests that round-trips every column of the +/// unified agents table. +/// +public sealed class AgentRowTests : IDisposable +{ + private readonly DirectoryInfo _tempRoot; + private readonly string _workspaceDirectory; + private readonly AgentDatabase _database; + + public AgentRowTests() + { + _tempRoot = Directory.CreateTempSubdirectory("nitro-agent-row-tests"); + _workspaceDirectory = AgentWorkspace.GetDirectory(_tempRoot.FullName); + Directory.CreateDirectory(_workspaceDirectory); + _database = new AgentDatabase(); + } + + public void Dispose() => _tempRoot.Delete(recursive: true); + + [Fact] + public async Task ReadFrom_Should_RoundTripEveryColumn_When_AllOptionalValuesArePresent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await ExecuteAsync( + connection, + """ + INSERT INTO agents ( + name, role, harness, harness_version, session_id, cwd, workspace_path, + registered_at, started_at, last_seen_at, ended_at, deleted_at, + endpoint_kind, endpoint_addr, endpoint_secret, block_budget_used, + last_ping_at, last_ping_attempt, last_ping_result, last_ping_detail, + announcement_pending, idle_push_armed + ) VALUES ( + 'maya', 'backend', 'claude-code', '1.2.3', 'session-full', '/tmp/work', + '/tmp/work/.nitro/agents', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:01+00:00', + '2026-01-10T12:00:02+00:00', '2026-01-10T12:00:03+00:00', '2026-01-10T12:00:04+00:00', + 'claude-peer', 'peer-a', 'secret-a', 2, + '2026-01-10T12:00:05+00:00', 'attempt-1', 'ok', 'all good', + 1, 1 + ); + """, + cancellationToken); + + // act + var row = await ReadRowAsync(connection, "maya", cancellationToken); + + // assert + row.MatchInlineSnapshot( + """ + { + "Name": "maya", + "Role": "backend", + "Harness": "claude-code", + "HarnessVersion": "1.2.3", + "SessionId": "session-full", + "Cwd": "/tmp/work", + "WorkspacePath": "/tmp/work/.nitro/agents", + "RegisteredAt": "2026-01-10T12:00:00+00:00", + "StartedAt": "2026-01-10T12:00:01+00:00", + "LastSeenAt": "2026-01-10T12:00:02+00:00", + "EndedAt": "2026-01-10T12:00:03+00:00", + "DeletedAt": "2026-01-10T12:00:04+00:00", + "EndpointKind": "claude-peer", + "EndpointAddr": "peer-a", + "EndpointSecret": "secret-a", + "BlockBudgetUsed": 2, + "LastPingAt": "2026-01-10T12:00:05+00:00", + "LastPingAttempt": "attempt-1", + "LastPingResult": "ok", + "LastPingDetail": "all good", + "AnnouncementPending": true, + "IdlePushArmed": true, + "IsDeleted": true + } + """); + } + + [Fact] + public async Task ReadFrom_Should_RoundTripEveryColumn_When_AllOptionalValuesAreNull() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await using var connection = await _database.InitializeAsync(_workspaceDirectory, cancellationToken); + await ExecuteAsync( + connection, + """ + INSERT INTO agents (name, registered_at, started_at, last_seen_at) + VALUES ('codex', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00'); + """, + cancellationToken); + + // act + var row = await ReadRowAsync(connection, "codex", cancellationToken); + + // assert + row.MatchInlineSnapshot( + """ + { + "Name": "codex", + "Role": "", + "Harness": null, + "HarnessVersion": "", + "SessionId": null, + "Cwd": "", + "WorkspacePath": "", + "RegisteredAt": "2026-01-10T12:00:00+00:00", + "StartedAt": "2026-01-10T12:00:00+00:00", + "LastSeenAt": "2026-01-10T12:00:00+00:00", + "EndedAt": null, + "DeletedAt": null, + "EndpointKind": "none", + "EndpointAddr": "", + "EndpointSecret": null, + "BlockBudgetUsed": 0, + "LastPingAt": null, + "LastPingAttempt": null, + "LastPingResult": null, + "LastPingDetail": null, + "AnnouncementPending": false, + "IdlePushArmed": false, + "IsDeleted": false + } + """); + } + + private static async Task ReadRowAsync( + SqliteConnection connection, string name, CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {AgentRow.Columns} FROM agents WHERE name = @name"; + command.Parameters.AddWithValue("@name", name); + + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + await reader.ReadAsync(cancellationToken); + + return AgentRow.ReadFrom(reader); + } + + private static async Task ExecuteAsync( + SqliteConnection connection, + string sql, + CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.CommandText = sql; + + await command.ExecuteNonQueryAsync(cancellationToken); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentSessionRegistryTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentSessionRegistryTests.cs deleted file mode 100644 index 56dd4d8c4d4..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentSessionRegistryTests.cs +++ /dev/null @@ -1,1596 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; -using Microsoft.Extensions.Time.Testing; - -namespace ChilliCream.Nitro.CommandLine.Tests.Agents; - -/// -/// Exercises 's lifecycle: SessionStart -/// binding and generation handling, the claim state machine, conditional -/// SessionEnd, reaping, and the one-row-per-session participant read model. -/// -public sealed class AgentSessionRegistryTests : IDisposable -{ - private const string Harness = AgentSessionHarness.ClaudeCode; - private const string CurrentHost = "host-current"; - private const string RemoteHost = "host-remote"; - - /// - /// A second Nitro instance id, for the same (harness, session id) seen - /// under a generation this instance does not own. - /// - private const string OtherHost = "host-other"; - - private readonly DirectoryInfo _tempRoot; - private readonly string _workspaceDirectory; - private readonly TestFileSystem _fileSystem; - private readonly FakeTimeProvider _timeProvider; - private readonly AgentDatabase _database; - private readonly AgentRegistry _agentRegistry; - private readonly AgentSessionRegistry _sessions; - - public AgentSessionRegistryTests() - { - _tempRoot = Directory.CreateTempSubdirectory("nitro-agent-session-registry-tests"); - _workspaceDirectory = AgentWorkspace.GetDirectory(_tempRoot.FullName); - Directory.CreateDirectory(_workspaceDirectory); - _fileSystem = new TestFileSystem(_tempRoot.FullName); - _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); - _database = new AgentDatabase(); - _agentRegistry = new AgentRegistry(_fileSystem, _timeProvider, _database); - - _sessions = new AgentSessionRegistry( - _fileSystem, - _timeProvider, - _database, - _agentRegistry, - new FixedInstanceIdProvider(CurrentHost), - new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName)); - } - - public void Dispose() => _tempRoot.Delete(recursive: true); - - // ---------- StartAsync ---------- - - [Fact] - public async Task StartAsync_Should_AssignActor_When_NoEnvActorGiven() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - - // act - var record = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // assert - Assert.Contains(record.AgentName, AgentActorAllocator.BaseActors); - Assert.Equal(AgentSessionBindingKind.Explicit, record.BindingKind); - } - - [Fact] - public async Task StartAsync_Should_CreateEnvBoundRow_When_EnvActorGiven() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - - // act - var record = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - - // assert - Assert.Equal("pascal", record.AgentName); - Assert.Equal(AgentSessionBindingKind.Env, record.BindingKind); - } - - [Fact] - public async Task StartAsync_Should_StoreOpencodeServerEndpointAndCredential_When_OpencodeSessionStarts() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = new AgentSessionGeneration(AgentSessionHarness.Opencode, "session-1", CurrentHost); - - // act - var record = await _sessions.StartAsync( - generation, - "/work", - "/work/.nitro/agents", - AgentSessionEndpointKind.OpencodeServer, - "http://127.0.0.1:4096", - "server-password", - envActor: null, - cancellationToken); - - // assert - Assert.Equal(AgentSessionEndpointKind.OpencodeServer, record.EndpointKind); - Assert.Equal("http://127.0.0.1:4096", record.EndpointAddr); - Assert.Equal("server-password", record.EndpointSecret); - var identity = Assert.Single(await _sessions.ListIdentitiesAsync(cancellationToken)); - Assert.Equal(AgentSessionHarness.Opencode, identity.Identity.Harness); - } - - [Theory] - [InlineData(AgentSessionHarness.ClaudeCode)] - [InlineData(AgentSessionHarness.Codex)] - [InlineData(AgentSessionHarness.Copilot)] - [InlineData(AgentSessionHarness.NitroBoard)] - public async Task StartAsync_Should_NotStoreOpencodeServerCredential_When_NonOpencodeSessionStarts( - string harness) - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = new AgentSessionGeneration(harness, "session-1", CurrentHost); - - // act - var record = await _sessions.StartAsync( - generation, - "/work", - "/work/.nitro/agents", - AgentSessionEndpointKind.OpencodeServer, - "http://127.0.0.1:4096", - "server-password", - envActor: null, - cancellationToken); - - // assert - Assert.Null(record.EndpointSecret); - } - - [Fact] - public async Task StartAsync_Should_UseEveryBaseActorBeforeSuffixingTheNextWave() - { - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var actors = new List(); - - for (var i = 0; i <= AgentActorAllocator.BaseActors.Count; i++) - { - var record = await _sessions.StartAsync( - Generation($"session-{i}"), - "/work", - "/work/.nitro/agents", - AgentSessionEndpointKind.None, - "", - envActor: null, - cancellationToken); - actors.Add(record.AgentName!); - } - - Assert.Equal( - AgentActorAllocator.BaseActors.Order(StringComparer.Ordinal), - actors.Take(AgentActorAllocator.BaseActors.Count).Order(StringComparer.Ordinal)); - Assert.EndsWith("-1", actors[^1], StringComparison.Ordinal); - Assert.Contains(actors[^1][..^2], AgentActorAllocator.BaseActors); - } - - [Fact] - public async Task StartAsync_Should_ReconcileLiveRow_When_LegacySessionHasNoIdentity() - { - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-legacy"); - await _sessions.StartAsync( - generation, - "/work", - "/work/.nitro/agents", - AgentSessionEndpointKind.None, - "", - envActor: "legacy-actor", - cancellationToken); - await InsertDeliveryAsync(generation, "message-old", cancellationToken); - - await using (var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken)) - await using (var command = connection.CreateCommand()) - { - command.CommandText = - "DELETE FROM agent_session_identities WHERE harness = $harness AND session_id = $sessionId"; - command.Parameters.AddWithValue("$harness", generation.Harness); - command.Parameters.AddWithValue("$sessionId", generation.SessionId); - await command.ExecuteNonQueryAsync(cancellationToken); - } - - var reconciled = await _sessions.StartAsync( - generation, - "/work", - "/work/.nitro/agents", - AgentSessionEndpointKind.None, - "", - envActor: null, - cancellationToken); - - Assert.Contains(reconciled.AgentName, AgentActorAllocator.BaseActors); - Assert.Equal(0, await CountDeliveriesAsync(generation, cancellationToken)); - var identity = Assert.Single(await _sessions.ListIdentitiesAsync(cancellationToken)); - Assert.Equal(reconciled.AgentName, identity.Identity.Actor); - } - - [Fact] - public async Task StartAsync_Should_DefaultRoleAndHarnessVersion_When_RowIsCreated() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - - // act - var record = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // assert - Assert.Equal("", record.Role); - Assert.Equal("", record.HarnessVersion); - } - - [Fact] - public async Task FindByGenerationAsync_Should_RoundTripRoleAndHarnessVersion() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await SetSessionMetadataAsync(generation, "frontend", "1.2.3-beta", cancellationToken); - - // act - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - - // assert - Assert.Equal("frontend", row!.Role); - Assert.Equal("1.2.3-beta", row.HarnessVersion); - } - - [Fact] - public async Task StartAsync_Should_PreserveHarnessMetadataAndRole_When_SameGenerationDuplicateSessionStart() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await SetSessionMetadataAsync(generation, "backend", "2.1.0", cancellationToken); - - // act: a duplicate SessionStart for the exact same generation must - // not reset metadata captured after the row was first created. - var record = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // assert - Assert.Equal("backend", record.Role); - Assert.Equal("2.1.0", record.HarnessVersion); - } - - [Fact] - public async Task StartAsync_Should_ResetHarnessMetadataAndRole_When_GenerationChanges() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var firstGeneration = Generation("session-1"); - await _sessions.StartAsync( - firstGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await SetSessionMetadataAsync(firstGeneration, "backend", "2.1.0", cancellationToken); - - var restartedGeneration = firstGeneration with { Host = OtherHost }; - - // act - // Start the same session with a different host. - var record = await _sessions.StartAsync( - restartedGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // assert - Assert.Equal("", record.Role); - Assert.Equal("", record.HarnessVersion); - } - - [Fact] - public async Task StartAsync_Should_PreserveState_When_SameGenerationDuplicateSessionStart() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - var claimed = await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - Assert.Equal(AgentSessionBindingKind.Explicit, claimed.Session.BindingKind); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var record = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "someone-else", cancellationToken); - - // assert - Assert.Equal("pascal", record.AgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, record.BindingKind); - Assert.True(record.LastBeatAt > claimed.Session.LastBeatAt); - } - - [Fact] - public async Task StartAsync_Should_ResetLedgerAndRebind_When_GenerationChanges() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var firstGeneration = Generation("session-1"); - await _sessions.StartAsync( - firstGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - await _sessions.ClaimAsync(firstGeneration, "pascal", forceRebind: false, cancellationToken); - await InsertDeliveryAsync(firstGeneration, "msg-1", cancellationToken); - - var restartedGeneration = firstGeneration with { Host = OtherHost }; - - // act - // Change the host while retaining the harness and session id. - var record = await _sessions.StartAsync( - restartedGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "someone-else", cancellationToken); - - // assert - Assert.Equal("pascal", record.AgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, record.BindingKind); - Assert.Equal(0, record.BlockBudgetUsed); - Assert.Equal(0, await CountDeliveriesAsync(firstGeneration, cancellationToken)); - } - - // ---------- ClaimAsync state machine ---------- - - [Fact] - public async Task ClaimAsync_Should_Bind_When_NoneToExplicit() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var result = await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal(AgentSessionBindingKind.None, result.PreviousBindingKind); - Assert.Null(result.PreviousAgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, result.Session.BindingKind); - Assert.Equal("pascal", result.Session.AgentName); - } - - [Fact] - public async Task ClaimAsync_Should_PromoteProvenanceWithoutResettingLedger_When_EnvToExplicitSameActor() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - await InsertDeliveryAsync(generation, "msg-1", cancellationToken); - - // act - var result = await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal(AgentSessionBindingKind.Env, result.PreviousBindingKind); - Assert.Equal("pascal", result.PreviousAgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, result.Session.BindingKind); - Assert.Equal(1, await CountDeliveriesAsync(generation, cancellationToken)); - } - - [Fact] - public async Task ClaimAsync_Should_RebindAndResetLedger_When_EnvToExplicitDifferentActor() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - await InsertDeliveryAsync(generation, "msg-1", cancellationToken); - - // act - var result = await _sessions.ClaimAsync(generation, "codex", forceRebind: false, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal(AgentSessionBindingKind.Explicit, result.Session.BindingKind); - Assert.Equal("codex", result.Session.AgentName); - Assert.Equal(0, await CountDeliveriesAsync(generation, cancellationToken)); - } - - [Fact] - public async Task ClaimAsync_Should_NoOp_When_ExplicitToExplicitSameActor() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - await InsertDeliveryAsync(generation, "msg-1", cancellationToken); - - // act - var result = await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - - // assert - Assert.False(result.Changed); - Assert.Equal(1, await CountDeliveriesAsync(generation, cancellationToken)); - } - - [Fact] - public async Task ClaimAsync_Should_Throw_When_ExplicitToExplicitDifferentActorWithoutForceRebind() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - - // act & assert - var exception = await Assert.ThrowsAsync( - () => _sessions.ClaimAsync(generation, "codex", forceRebind: false, cancellationToken)); - Assert.Contains("--force-rebind", exception.Message); - } - - [Fact] - public async Task ClaimAsync_Should_RebindAndResetLedger_When_ForceRebindOverridesExistingExplicitClaim() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - await InsertDeliveryAsync(generation, "msg-1", cancellationToken); - - // act - var result = await _sessions.ClaimAsync(generation, "codex", forceRebind: true, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal("codex", result.Session.AgentName); - Assert.Equal(0, await CountDeliveriesAsync(generation, cancellationToken)); - } - - [Fact] - public async Task ClaimAsync_Should_Throw_When_GenerationDoesNotMatchAnyRow() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - var staleGeneration = generation with { Host = OtherHost }; - - // act & assert - await Assert.ThrowsAsync( - () => _sessions.ClaimAsync(staleGeneration, "pascal", forceRebind: false, cancellationToken)); - } - - // ---------- RegisterAsync ---------- - - [Fact] - public async Task RegisterAsync_Should_UpsertIdentityAndBindTheUnboundSession_When_BlankToRolePromotion() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var result = await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "claude-code", forceRebind: false, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal("pascal", result.Agent.Name); - Assert.Equal("orchestrator", result.Agent.Role); - Assert.Equal("claude-code", result.Agent.Client); - Assert.Equal("pascal", result.Session.AgentName); - Assert.Equal(AgentSessionBindingKind.Explicit, result.Session.BindingKind); - Assert.Equal("orchestrator", result.Session.Role); - } - - [Fact] - public async Task RegisterAsync_Should_NormalizeRole_When_Written() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var result = await _sessions.RegisterAsync( - generation, "pascal", " Backend ", "", forceRebind: false, cancellationToken); - - // assert - Assert.Equal("backend", result.Agent.Role); - Assert.Equal("backend", result.Session.Role); - } - - [Fact] - public async Task RegisterAsync_Should_BeIdempotent_When_SameActorAndRoleAreRepeated() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - var first = await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var result = await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - - // assert - Assert.False(result.Changed); - Assert.Equal("orchestrator", result.Session.Role); - Assert.True(result.Session.LastBeatAt > first.Session.LastBeatAt); - } - - [Fact] - public async Task RegisterAsync_Should_UpdateRole_When_RoleChanges() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - - // act - var result = await _sessions.RegisterAsync( - generation, "pascal", "planner", "", forceRebind: false, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal("planner", result.Agent.Role); - Assert.Equal("planner", result.Session.Role); - } - - [Fact] - public async Task RegisterAsync_Should_PromoteEnvBoundToExplicit_When_SameActorRegisters() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - - // act - var result = await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal(AgentSessionBindingKind.Env, result.PreviousBindingKind); - Assert.Equal(AgentSessionBindingKind.Explicit, result.Session.BindingKind); - } - - [Fact] - public async Task RegisterAsync_Should_Throw_When_ConflictingActorWithoutForceRebind() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("codex", cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - - // act & assert - var exception = await Assert.ThrowsAsync( - () => _sessions.RegisterAsync( - generation, "codex", "worker", "", forceRebind: false, cancellationToken)); - Assert.Contains("--force-rebind", exception.Message); - } - - [Fact] - public async Task RegisterAsync_Should_RollBackTheIdentityUpsert_When_TheClaimTransitionThrows() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("codex", cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - await _agentRegistry.RegisterAsync("codex", "original-role", "", cancellationToken); - - // act - await Assert.ThrowsAsync( - () => _sessions.RegisterAsync( - generation, "codex", "new-role", "", forceRebind: false, cancellationToken)); - - // assert - var codex = await _agentRegistry.GetAsync("codex", cancellationToken); - Assert.Equal("original-role", codex!.Role); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal("pascal", row!.AgentName); - } - - [Fact] - public async Task RegisterAsync_Should_RebindAndResetLedger_When_ForceRebindOverridesConflictingActor() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("codex", cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken); - await InsertDeliveryAsync(generation, "msg-1", cancellationToken); - - // act - var result = await _sessions.RegisterAsync( - generation, "codex", "worker", "", forceRebind: true, cancellationToken); - - // assert - Assert.True(result.Changed); - Assert.Equal("codex", result.Session.AgentName); - Assert.Equal("worker", result.Session.Role); - Assert.Equal(0, await CountDeliveriesAsync(generation, cancellationToken)); - } - - [Fact] - public async Task RegisterAsync_Should_Throw_When_NoRowMatchesTheGeneration() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - await _agentRegistry.EnsureImplicitAsync("pascal", cancellationToken); - var generation = Generation("session-1"); - - // act & assert - await Assert.ThrowsAsync( - () => _sessions.RegisterAsync( - generation, "pascal", "orchestrator", "", forceRebind: false, cancellationToken)); - } - - // ---------- FindByProcessAsync ---------- - - // ---------- FindBySessionIdAsync ---------- - - [Fact] - public async Task FindBySessionIdAsync_Should_ReturnTheRow_When_ItExists() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1") with { Harness = AgentSessionHarness.Codex }; - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "session-1", - envActor: null, cancellationToken); - - // act - var row = await _sessions.FindBySessionIdAsync( - AgentSessionHarness.Codex, CurrentHost, "session-1", cancellationToken); - - // assert - Assert.NotNull(row); - Assert.Equal(generation.Host, row.Host); - } - - [Fact] - public async Task FindBySessionIdAsync_Should_ReturnNull_When_NoRowMatches() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - - // act - var row = await _sessions.FindBySessionIdAsync( - AgentSessionHarness.Codex, CurrentHost, "session-missing", cancellationToken); - - // assert - Assert.Null(row); - } - - [Fact] - public async Task FindBySessionIdAsync_Should_ReturnNull_When_TheRowBelongsToADifferentHost() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var remoteGeneration = Generation("session-1") - with - { Harness = AgentSessionHarness.Codex, Host = RemoteHost }; - await _sessions.StartAsync( - remoteGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "session-1", - envActor: null, cancellationToken); - - // act - var row = await _sessions.FindBySessionIdAsync( - AgentSessionHarness.Codex, CurrentHost, "session-1", cancellationToken); - - // assert - Assert.Null(row); - } - - // ---------- EndAsync ---------- - - [Fact] - public async Task EndAsync_Should_DeleteRowAndCascadeDeliveries_When_GenerationMatches() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - await InsertDeliveryAsync(generation, "msg-1", cancellationToken); - - // act - var deleted = await _sessions.EndAsync(generation, cancellationToken); - - // assert - Assert.True(deleted); - Assert.Equal(0, await CountSessionRowsAsync(generation, cancellationToken)); - Assert.Equal(0, await CountDeliveriesAsync(generation, cancellationToken)); - } - - [Fact] - public async Task EndAsync_Should_BeNoOp_When_LateSessionEndTargetsASupersededGeneration() - { - // arrange - // Replace the session with a generation on another host before ending the original. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var originalGeneration = Generation("session-1"); - await _sessions.StartAsync( - originalGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - await _sessions.StartAsync( - originalGeneration with { Host = OtherHost }, "/work", "/work/.nitro/agents", - AgentSessionEndpointKind.None, "", envActor: "pascal", cancellationToken); - - // act - var deleted = await _sessions.EndAsync(originalGeneration, cancellationToken); - - // assert - Assert.False(deleted); - Assert.Equal(1, await CountSessionRowsAsync(originalGeneration with { Host = OtherHost }, cancellationToken)); - } - - // ---------- ReapAsync / ListAsync ---------- - - [Fact] - public async Task ReapAsync_Should_DeleteStaleCurrentInstanceRow() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var deadGeneration = Generation("session-dead"); - await _sessions.StartAsync( - deadGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - - // act - var reaped = await _sessions.ReapAsync(cancellationToken); - - // assert - Assert.Single(reaped); - Assert.Equal("session-dead", reaped[0].SessionId); - Assert.Equal(0, await CountSessionRowsAsync(deadGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_NotTouchFreshlyBeatenCurrentInstanceRow() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var aliveGeneration = Generation("session-alive"); - await _sessions.StartAsync( - aliveGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var reaped = await _sessions.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(aliveGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_NotTouchStaleRemoteRow() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var remoteDeadGeneration = Generation("session-remote") with { Host = RemoteHost }; - await _sessions.StartAsync( - remoteDeadGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - - // act - var reaped = await _sessions.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(remoteDeadGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_NotDeleteRow_When_ItWasSupersededByANewerAliveGenerationFirst() - { - // arrange: a fresh SessionStart replaces the dead row with a live generation before the reaper runs. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var deadGeneration = Generation("session-1"); - await _sessions.StartAsync( - deadGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - var aliveGeneration = deadGeneration with { Host = OtherHost }; - await _sessions.StartAsync( - aliveGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var reaped = await _sessions.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(aliveGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_KeepReplacement_When_HarnessChangesAfterSelection() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var staleGeneration = Generation("session-stale"); - var replacementGeneration = staleGeneration with { Harness = AgentSessionHarness.Codex }; - await _sessions.StartAsync( - staleGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - await _sessions.StartAsync( - replacementGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - var reaper = CreateSessionRegistry(async (candidate, token) => - { - await _sessions.EndAsync(staleGeneration, token); - await SetSessionLastBeatAtAsync(replacementGeneration, candidate.LastBeatAt, token); - }); - - // act - var reaped = await reaper.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(replacementGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_KeepReplacement_When_SessionIdChangesAfterSelection() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var staleGeneration = Generation("session-stale"); - var replacementGeneration = Generation("session-replacement"); - await _sessions.StartAsync( - staleGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - await _sessions.StartAsync( - replacementGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - var reaper = CreateSessionRegistry(async (candidate, token) => - { - await _sessions.EndAsync(staleGeneration, token); - await SetSessionLastBeatAtAsync(replacementGeneration, candidate.LastBeatAt, token); - }); - - // act - var reaped = await reaper.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(replacementGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_KeepSupersedingGeneration_When_HostChangesAfterSelection() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var staleGeneration = Generation("session-stale"); - var replacementGeneration = staleGeneration with { Host = OtherHost }; - await _sessions.StartAsync( - staleGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - var reaper = CreateSessionRegistry(async (candidate, token) => - { - await _sessions.StartAsync( - replacementGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, token); - await SetSessionLastBeatAtAsync(replacementGeneration, candidate.LastBeatAt, token); - }); - - // act - var reaped = await reaper.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(replacementGeneration, cancellationToken)); - } - - [Fact] - public async Task ReapAsync_Should_KeepNewlyBeatenGeneration_When_HeartbeatChangesAfterSelection() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var staleGeneration = Generation("session-stale"); - await _sessions.StartAsync( - staleGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - var reaper = CreateSessionRegistry( - (candidate, token) => _sessions.TouchAsync(staleGeneration, token)); - - // act - var reaped = await reaper.ReapAsync(cancellationToken); - - // assert - Assert.Empty(reaped); - Assert.Equal(1, await CountSessionRowsAsync(staleGeneration, cancellationToken)); - } - - [Fact] - public async Task ListAsync_Should_ComputeStates_When_MixOfOnlineUnreachableAndRemoteRows() - { - // arrange - // Advance the clock after the first row so only that row is stale. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - - var dead = Generation("session-dead"); - await _sessions.StartAsync( - dead, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - - var online = Generation("session-online"); - await _sessions.StartAsync( - online, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.ClaudePeer, "peer-a", - envActor: null, cancellationToken); - - var unreachable = Generation("session-unreachable"); - await _sessions.StartAsync( - unreachable, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - var remote = Generation("session-remote") with { Host = RemoteHost }; - await _sessions.StartAsync( - remote, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var views = await _sessions.ListAsync(cancellationToken); - - // assert - Assert.Equal(3, views.Count); - Assert.Equal(AgentSessionState.Online, views.Single(v => v.Session.SessionId == "session-online").State); - Assert.Equal( - AgentSessionState.Unreachable, views.Single(v => v.Session.SessionId == "session-unreachable").State); - Assert.Equal(AgentSessionState.Remote, views.Single(v => v.Session.SessionId == "session-remote").State); - Assert.DoesNotContain(views, v => v.Session.SessionId == "session-dead"); - } - - // ---------- TouchAsync ---------- - - [Fact] - public async Task TouchAsync_Should_AdvanceLastBeatAt_Without_ChangingOtherFields() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var started = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(generation, "pascal", forceRebind: false, cancellationToken); - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - - // act - var touched = await _sessions.TouchAsync(generation, cancellationToken); - - // assert - Assert.True(touched); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.True(row!.LastBeatAt > started.LastBeatAt); - Assert.Equal(AgentSessionBindingKind.Explicit, row.BindingKind); - Assert.Equal("pascal", row.AgentName); - Assert.Equal(0, row.BlockBudgetUsed); - } - - [Fact] - public async Task TouchAsync_Should_ReturnFalse_When_SessionHasAlreadyEnded() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.EndAsync(generation, cancellationToken); - - // act - var touched = await _sessions.TouchAsync(generation, cancellationToken); - - // assert - Assert.False(touched); - } - - [Fact] - public async Task TouchAsync_Should_ReturnFalse_When_GenerationIsStale() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var originalGeneration = Generation("session-1"); - await _sessions.StartAsync( - originalGeneration, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.StartAsync( - originalGeneration with { Host = OtherHost }, "/work", "/work/.nitro/agents", - AgentSessionEndpointKind.None, "", envActor: null, cancellationToken); - - // act - var touched = await _sessions.TouchAsync(originalGeneration, cancellationToken); - - // assert - Assert.False(touched); - } - - // ---------- SetRoleAsync ---------- - - [Fact] - public async Task SetRoleAsync_Should_SetTheSessionsOwnRole_Without_TouchingBindingOrCounters() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: "pascal", cancellationToken); - - // act - var updated = await _sessions.SetRoleAsync(generation, "operator", cancellationToken); - - // assert - Assert.True(updated); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal("operator", row!.Role); - Assert.Equal(AgentSessionBindingKind.Env, row.BindingKind); - Assert.Equal("pascal", row.AgentName); - } - - [Fact] - public async Task SetRoleAsync_Should_Normalize_TheSameWayAgentRoleNormalizeDoes() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - await _sessions.SetRoleAsync(generation, " Operator ", cancellationToken); - - // assert - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal("operator", row!.Role); - } - - [Fact] - public async Task SetRoleAsync_Should_ReturnFalse_When_GenerationMatchesNoRow() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-missing"); - - // act - var updated = await _sessions.SetRoleAsync(generation, "operator", cancellationToken); - - // assert - Assert.False(updated); - } - - // ---------- ListParticipantsAsync ---------- - - [Fact] - public async Task ListParticipantsAsync_Should_ReturnOneRowPerSession_When_MultipleSessionsExist() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var first = Generation("session-1"); - await _sessions.StartAsync( - first, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - var second = Generation("session-2"); - await _sessions.StartAsync( - second, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var participants = await _sessions.ListParticipantsAsync(cancellationToken); - - // assert - Assert.Equal(["session-1", "session-2"], participants.Select(p => p.Session.SessionId).Order()); - } - - [Fact] - public async Task ListParticipantsAsync_Should_JoinAssignedActorForEveryCodingSession() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var claimed = Generation("session-claimed"); - await _sessions.StartAsync( - claimed, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.ClaudePeer, "peer-1", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(claimed, "pascal", forceRebind: false, cancellationToken); - - var unclaimed = Generation("session-unclaimed"); - await _sessions.StartAsync( - unclaimed, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - - // act - var participants = await _sessions.ListParticipantsAsync(cancellationToken); - - // assert - var claimedParticipant = Assert.Single(participants, p => p.Session.SessionId == "session-claimed"); - Assert.Equal("pascal", claimedParticipant.Agent?.Name); - Assert.Equal(AgentSessionState.Online, claimedParticipant.State); - - var assignedParticipant = Assert.Single(participants, p => p.Session.SessionId == "session-unclaimed"); - Assert.Equal(assignedParticipant.Session.AgentName, assignedParticipant.Agent?.Name); - } - - [Fact] - public async Task ListParticipantsAsync_Should_ResolveSharedAgentIdentity_When_MultipleSessionsBindTheSameAgent() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var first = Generation("session-1"); - await _sessions.StartAsync( - first, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(first, "pascal", forceRebind: false, cancellationToken); - - var second = Generation("session-2"); - await _sessions.StartAsync( - second, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(second, "pascal", forceRebind: false, cancellationToken); - - // act - var participants = await _sessions.ListParticipantsAsync(cancellationToken); - - // assert - Assert.Equal(2, participants.Count); - Assert.All(participants, p => Assert.Equal("pascal", p.Agent?.Name)); - } - - [Fact] - public async Task ListParticipantsAsync_Should_ReapStaleCurrentInstanceRow_Before_Listing() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var dead = Generation("session-dead"); - await _sessions.StartAsync( - dead, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - - // act - var participants = await _sessions.ListParticipantsAsync(cancellationToken); - - // assert - Assert.Empty(participants); - } - - // ---------- SelfClaimAsync ---------- - - // ---------- FindLiveClaimedByAgentNameAsync ---------- - - [Fact] - public async Task FindLiveClaimedByAgentNameAsync_Should_ReturnOnlyCurrentHostLiveSessionsClaimedByTheActor() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - - var dead = Generation("session-dead"); - await _sessions.StartAsync( - dead, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(dead, "pascal", forceRebind: false, cancellationToken); - _timeProvider.Advance(TimeSpan.FromDays(2)); - - var mine = Generation("session-mine"); - await _sessions.StartAsync( - mine, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(mine, "pascal", forceRebind: false, cancellationToken); - - var someoneElse = Generation("session-someone-else"); - await _sessions.StartAsync( - someoneElse, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(someoneElse, "codex", forceRebind: false, cancellationToken); - - var remote = Generation("session-remote") with { Host = RemoteHost }; - await _sessions.StartAsync( - remote, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.None, "", - envActor: null, cancellationToken); - await _sessions.ClaimAsync(remote, "pascal", forceRebind: false, cancellationToken); - - // act - var live = await _sessions.FindLiveClaimedByAgentNameAsync("pascal", cancellationToken); - - // assert: only liveness excludes the dead local row. - var row = Assert.Single(live); - Assert.Equal("session-mine", row.SessionId); - } - - // ---------- TryClaimPingCooldownAsync ---------- - - [Fact] - public async Task TryClaimPingCooldownAsync_Should_Claim_When_NoPriorAttempt() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - var now = _timeProvider.GetUtcNow(); - - // act - var claimed = await _sessions.TryClaimPingCooldownAsync( - session, "attempt-1", now, TimeSpan.FromSeconds(60), cancellationToken); - - // assert - Assert.True(claimed); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal("attempt-1", row!.LastPingAttempt); - Assert.Null(row.LastPingResult); - Assert.Equal(now, row.LastPingAt); - } - - [Fact] - public async Task TryClaimPingCooldownAsync_Should_ReturnFalse_When_StillWithinCooldown() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - var first = _timeProvider.GetUtcNow(); - await _sessions.TryClaimPingCooldownAsync(session, "attempt-1", first, TimeSpan.FromSeconds(60), cancellationToken); - _timeProvider.Advance(TimeSpan.FromSeconds(30)); - - // act - var claimed = await _sessions.TryClaimPingCooldownAsync( - session, "attempt-2", _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); - - // assert - Assert.False(claimed); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal("attempt-1", row!.LastPingAttempt); - } - - [Fact] - public async Task TryClaimPingCooldownAsync_Should_ReturnTrue_When_CooldownElapsed() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - var first = _timeProvider.GetUtcNow(); - await _sessions.TryClaimPingCooldownAsync(session, "attempt-1", first, TimeSpan.FromSeconds(60), cancellationToken); - _timeProvider.Advance(TimeSpan.FromSeconds(61)); - - // act - var claimed = await _sessions.TryClaimPingCooldownAsync( - session, "attempt-2", _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); - - // assert - Assert.True(claimed); - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal("attempt-2", row!.LastPingAttempt); - } - - [Fact] - public async Task TryClaimPingCooldownAsync_Should_ReturnFalse_When_GenerationNoLongerMatches() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - await _sessions.EndAsync(generation, cancellationToken); - - // act - var claimed = await _sessions.TryClaimPingCooldownAsync( - session, "attempt-1", _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); - - // assert - Assert.False(claimed); - } - - [Fact] - public async Task TryClaimPingCooldownAsync_Should_HaveExactlyOneWinner_When_ConcurrentClaimsRaceTheSameSession() - { - // arrange: separate connections racing the same session row. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - var now = _timeProvider.GetUtcNow(); - - // act - var results = await ConcurrentTestHarness.RunAsync( - 5, - i => CreateSessionRegistry().TryClaimPingCooldownAsync( - session, $"attempt-{i}", now, TimeSpan.FromSeconds(60), cancellationToken)); - - // assert - Assert.Equal(1, results.Count(claimed => claimed)); - } - - // ---------- WritePingResultAsync ---------- - - [Fact] - public async Task WritePingResultAsync_Should_Write_When_AttemptIdMatches() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - await _sessions.TryClaimPingCooldownAsync( - session, "attempt-1", _timeProvider.GetUtcNow(), TimeSpan.FromSeconds(60), cancellationToken); - - // act - await _sessions.WritePingResultAsync( - Harness, "session-1", "attempt-1", AgentPingResult.Ok, null, cancellationToken); - - // assert - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Equal(AgentPingResult.Ok, row!.LastPingResult); - } - - [Fact] - public async Task WritePingResultAsync_Should_BeANoOp_When_AttemptIdIsStale() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var generation = Generation("session-1"); - var session = await _sessions.StartAsync( - generation, "/work", "/work/.nitro/agents", AgentSessionEndpointKind.CodexThread, "thread-1", - envActor: null, cancellationToken); - await _sessions.TryClaimPingCooldownAsync( - session, "attempt-1", _timeProvider.GetUtcNow(), TimeSpan.Zero, cancellationToken); - _timeProvider.Advance(TimeSpan.FromSeconds(1)); - await _sessions.TryClaimPingCooldownAsync( - session, "attempt-2", _timeProvider.GetUtcNow(), TimeSpan.Zero, cancellationToken); - - // act - // Complete attempt-1 after attempt-2 has claimed the cooldown. - await _sessions.WritePingResultAsync( - Harness, "session-1", "attempt-1", AgentPingResult.Timeout, null, cancellationToken); - - // assert - var row = await _sessions.FindByGenerationAsync(generation, cancellationToken); - Assert.Null(row!.LastPingResult); - Assert.Equal("attempt-2", row.LastPingAttempt); - } - - // ---------- helpers ---------- - - private static AgentSessionGeneration Generation(string sessionId) - => new(Harness, sessionId, CurrentHost); - - private AgentSessionRegistry CreateSessionRegistry( - Func? onStaleReapCandidateCapturedAsync = null) - => new( - _fileSystem, - _timeProvider, - _database, - new AgentRegistry(_fileSystem, _timeProvider, _database), - new FixedInstanceIdProvider(CurrentHost), - new FixedGlobalConfigDirectoryProvider(_tempRoot.FullName)) - { - OnStaleReapCandidateCapturedAsync = onStaleReapCandidateCapturedAsync - }; - - private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) - { - await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - } - } - - private async Task InsertDeliveryAsync( - AgentSessionGeneration generation, string messageId, CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "INSERT INTO session_deliveries (harness, session_id, message_id, channel, delivered_at) " - + "VALUES ($harness, $sessionId, $messageId, 'digest', $now);"; - command.Parameters.AddWithValue("$harness", generation.Harness); - command.Parameters.AddWithValue("$sessionId", generation.SessionId); - command.Parameters.AddWithValue("$messageId", messageId); - command.Parameters.AddWithValue("$now", _timeProvider.GetUtcNow()); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - /// - /// Sets the v5 role and harness_version columns directly via raw SQL, - /// standing in for the production callers that populate them. - /// - private async Task SetSessionMetadataAsync( - AgentSessionGeneration generation, - string role, - string harnessVersion, - CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET role = $role, harness_version = $harnessVersion " - + "WHERE harness = $harness AND session_id = $sessionId AND host = $host;"; - command.Parameters.AddWithValue("$role", role); - command.Parameters.AddWithValue("$harnessVersion", harnessVersion); - command.Parameters.AddWithValue("$harness", generation.Harness); - command.Parameters.AddWithValue("$sessionId", generation.SessionId); - command.Parameters.AddWithValue("$host", generation.Host); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - private async Task SetSessionLastBeatAtAsync( - AgentSessionGeneration generation, - DateTimeOffset lastBeatAt, - CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "UPDATE agent_sessions SET last_beat_at = $lastBeatAt " - + "WHERE harness = $harness AND session_id = $sessionId AND host = $host;"; - command.Parameters.AddWithValue("$lastBeatAt", lastBeatAt); - command.Parameters.AddWithValue("$harness", generation.Harness); - command.Parameters.AddWithValue("$sessionId", generation.SessionId); - command.Parameters.AddWithValue("$host", generation.Host); - - await command.ExecuteNonQueryAsync(cancellationToken); - } - - private async Task CountDeliveriesAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "SELECT COUNT(*) FROM session_deliveries WHERE harness = $harness AND session_id = $sessionId;"; - command.Parameters.AddWithValue("$harness", generation.Harness); - command.Parameters.AddWithValue("$sessionId", generation.SessionId); - - return Convert.ToInt64(await command.ExecuteScalarAsync(cancellationToken)); - } - - private async Task CountSessionRowsAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - { - await using var connection = await _database.ConnectAsync(_workspaceDirectory, cancellationToken); - await using var command = connection.CreateCommand(); - command.CommandText = - "SELECT COUNT(*) FROM agent_sessions WHERE harness = $harness AND session_id = $sessionId " - + "AND host = $host;"; - command.Parameters.AddWithValue("$harness", generation.Harness); - command.Parameters.AddWithValue("$sessionId", generation.SessionId); - command.Parameters.AddWithValue("$host", generation.Host); - - return Convert.ToInt64(await command.ExecuteScalarAsync(cancellationToken)); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentStateResolverTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentStateResolverTests.cs new file mode 100644 index 00000000000..e0e32a4be66 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentStateResolverTests.cs @@ -0,0 +1,128 @@ +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Agents; + +/// +/// Exercises : the boundary of the online window, its idle +/// side, and the precedence of deleted, ended and unreachable rows over it. +/// +public sealed class AgentStateResolverTests +{ + private static readonly DateTimeOffset s_now = + new(2026, 1, 1, 12, 0, 0, TimeSpan.Zero); + + private static AgentRow CreateRow() => new() + { + Name = "maya", + Role = AgentRole.Implementer, + Harness = "claude-code", + HarnessVersion = "1.0.0", + SessionId = "session-1", + Cwd = "/repo", + WorkspacePath = "/repo", + RegisteredAt = s_now, + StartedAt = s_now, + LastSeenAt = s_now, + EndedAt = null, + DeletedAt = null, + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1", + EndpointSecret = null, + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; + + [Fact] + public void Resolve_Should_ReturnOnline_When_LastBeatIsWithinTheWindow() + { + // arrange + var row = CreateRow() with { LastSeenAt = s_now - TimeSpan.FromMinutes(29).Add(TimeSpan.FromSeconds(59)) }; + + // act + var state = AgentStateResolver.Resolve(row, s_now); + + // assert + Assert.Equal(AgentState.Online, state); + } + + [Fact] + public void Resolve_Should_ReturnIdle_When_LastBeatIsJustPastTheWindow() + { + // arrange + var row = CreateRow() with { LastSeenAt = s_now - TimeSpan.FromMinutes(30).Add(TimeSpan.FromSeconds(1)) }; + + // act + var state = AgentStateResolver.Resolve(row, s_now); + + // assert + Assert.Equal(AgentState.Idle, state); + } + + [Fact] + public void Resolve_Should_ReturnOffline_When_EndedAtIsSetWithAFreshBeat() + { + // arrange + var row = CreateRow() with { EndedAt = s_now }; + + // act + var state = AgentStateResolver.Resolve(row, s_now); + + // assert + Assert.Equal(AgentState.Offline, state); + } + + [Fact] + public void Resolve_Should_ReturnUnreachable_When_EndpointKindIsNoneWithAFreshBeat() + { + // arrange + // Covers login-only agents, whose endpoint kind is always none. + var row = CreateRow() with + { + Harness = null, + SessionId = null, + EndpointKind = AgentSessionEndpointKind.None, + EndpointAddr = string.Empty + }; + + // act + var state = AgentStateResolver.Resolve(row, s_now); + + // assert + Assert.Equal(AgentState.Unreachable, state); + } + + [Fact] + public void Resolve_Should_ReturnUnreachable_When_EndpointKindIsNoneWithAStaleBeat() + { + // arrange + // The endpoint-none check runs before the idle window check, so age never matters here. + var row = CreateRow() with + { + Harness = null, + SessionId = null, + EndpointKind = AgentSessionEndpointKind.None, + EndpointAddr = string.Empty, + LastSeenAt = s_now - TimeSpan.FromDays(30) + }; + + // act + var state = AgentStateResolver.Resolve(row, s_now); + + // assert + Assert.Equal(AgentState.Unreachable, state); + } + + [Fact] + public void Resolve_Should_ReturnOffline_When_DeletedAtIsSetWithAFreshBeatAndAnEndpoint() + { + // arrange + var row = CreateRow() with { DeletedAt = s_now }; + + // act + var state = AgentStateResolver.Resolve(row, s_now); + + // assert + Assert.Equal(AgentState.Offline, state); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentStoreTests.cs new file mode 100644 index 00000000000..b6cee3342c5 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/AgentStoreTests.cs @@ -0,0 +1,1384 @@ +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using Microsoft.Extensions.Time.Testing; + +namespace ChilliCream.Nitro.CommandLine.Tests.Agents; + +/// +/// Exercises against a real SQLite workspace: login, harness +/// session start, touch, end, role, and lookup semantics over the unified agents table. +/// +public sealed class AgentStoreTests : IDisposable +{ + private const string Harness = AgentSessionHarness.ClaudeCode; + private const string SessionId = "session-1"; + + private readonly DirectoryInfo _tempRoot; + private readonly string _workingDirectory; + private readonly string _workspaceDirectory; + private readonly FakeTimeProvider _timeProvider; + private readonly AgentStore _store; + + public AgentStoreTests() + { + _tempRoot = Directory.CreateTempSubdirectory("nitro-agent-store-tests"); + _workingDirectory = Path.Combine(_tempRoot.FullName, "acme"); + Directory.CreateDirectory(_workingDirectory); + _workspaceDirectory = AgentWorkspace.GetDirectory(_workingDirectory); + + _timeProvider = new FakeTimeProvider( + new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); + + _store = new AgentStore(new TestFileSystem(_workingDirectory), _timeProvider, new AgentDatabase()); + } + + public void Dispose() => _tempRoot.Delete(recursive: true); + + private async Task InitWorkspaceAsync(CancellationToken cancellationToken) + { + Directory.CreateDirectory(_workspaceDirectory); + await new AgentDatabase().InitializeAsync(_workspaceDirectory, cancellationToken); + } + + private static AgentSessionStartRequest CreateRequest( + string harness = Harness, + string sessionId = SessionId, + string harnessVersion = "1.0.0", + string cwd = "/repo", + string workspacePath = "/repo/.nitro/agents", + string endpointKind = AgentSessionEndpointKind.ClaudePeer, + string endpointAddr = "peer-addr", + string? endpointSecret = null) => new() + { + Harness = harness, + SessionId = sessionId, + HarnessVersion = harnessVersion, + Cwd = cwd, + WorkspacePath = workspacePath, + EndpointKind = endpointKind, + EndpointAddr = endpointAddr, + EndpointSecret = endpointSecret + }; + + /// + /// Soft-deletes the named agent directly, bypassing the store, so tests can exercise + /// the deleted-row behavior this ticket's delete mechanics have not implemented yet. + /// + private async Task MarkDeletedAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await new AgentDatabase().ConnectAsync(_workspaceDirectory, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "UPDATE agents SET deleted_at = @now WHERE name = @name"; + command.Parameters.AddWithValue("@now", _timeProvider.GetUtcNow()); + command.Parameters.AddWithValue("@name", name); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Inserts one row for the named agent into each wake and ping side table, so a delete + /// test can prove they are all removed. + /// + private async Task InsertSideRowsAsync(string name, CancellationToken cancellationToken) + { + await using var connection = await new AgentDatabase().ConnectAsync(_workspaceDirectory, cancellationToken); + var now = _timeProvider.GetUtcNow(); + + async Task ExecuteAsync(string sql) + { + await using var command = connection.CreateCommand(); + command.CommandText = sql; + command.Parameters.AddWithValue("@name", name); + command.Parameters.AddWithValue("@now", now); + await command.ExecuteNonQueryAsync(cancellationToken); + } + + await ExecuteAsync( + "INSERT INTO agent_deliveries (agent, message_id, channel, delivered_at) " + + "VALUES (@name, 'msg-1', 'digest', @now)"); + await ExecuteAsync( + "INSERT INTO agent_ping_gates (agent, attempt_id, acquired_at, expires_at) " + + "VALUES (@name, 'attempt-1', @now, @now)"); + await ExecuteAsync( + "INSERT INTO mail_wake_outbox (actor, due_at, updated_at) VALUES (@name, @now, @now)"); + await ExecuteAsync( + "INSERT INTO mail_wake_batches " + + "(batch_id, actor, claimed_generation, owner_id, attempt_id, claimed_at, expires_at) " + + "VALUES ('batch-1', @name, 0, 'owner-1', 'attempt-1', @now, @now)"); + await ExecuteAsync( + "INSERT INTO mail_wake_targets (batch_id, agent, updated_at) VALUES ('batch-1', @name, @now)"); + } + + /// + /// Counts the named agent's rows across the wake and ping side tables. + /// + private async Task<(long Deliveries, long PingGates, long Outbox, long Batches, long Targets)> CountSideRowsAsync( + string name, CancellationToken cancellationToken) + { + await using var connection = await new AgentDatabase().ConnectAsync(_workspaceDirectory, cancellationToken); + + async Task CountAsync(string sql) + { + await using var command = connection.CreateCommand(); + command.CommandText = sql; + command.Parameters.AddWithValue("@name", name); + return (long)(await command.ExecuteScalarAsync(cancellationToken))!; + } + + return ( + Deliveries: await CountAsync("SELECT COUNT(*) FROM agent_deliveries WHERE agent = @name"), + PingGates: await CountAsync("SELECT COUNT(*) FROM agent_ping_gates WHERE agent = @name"), + Outbox: await CountAsync("SELECT COUNT(*) FROM mail_wake_outbox WHERE actor = @name"), + Batches: await CountAsync("SELECT COUNT(*) FROM mail_wake_batches WHERE actor = @name"), + Targets: await CountAsync("SELECT COUNT(*) FROM mail_wake_targets WHERE agent = @name")); + } + + /// + /// Inserts a minimal in-progress task assigned to the named agent, directly into the + /// shared workspace database. + /// + private async Task InsertInProgressTaskAsync(string taskId, string assignee, CancellationToken cancellationToken) + { + await using var connection = await new AgentDatabase().ConnectAsync(_workspaceDirectory, cancellationToken); + var now = _timeProvider.GetUtcNow(); + + await using var command = connection.CreateCommand(); + command.CommandText = + """ + INSERT INTO tasks (id, title, status, priority, task_type, assignee, created_at, updated_at) + VALUES (@id, 'Task', @status, 2, 'task', @assignee, @now, @now) + """; + command.Parameters.AddWithValue("@id", taskId); + command.Parameters.AddWithValue("@status", TaskStates.InProgress); + command.Parameters.AddWithValue("@assignee", assignee); + command.Parameters.AddWithValue("@now", now); + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + /// + /// Reads the named task's status and assignee directly from the shared workspace database. + /// + private async Task<(string Status, string? Assignee)> QueryTaskAsync( + string taskId, CancellationToken cancellationToken) + { + await using var connection = await new AgentDatabase().ConnectAsync(_workspaceDirectory, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT status, assignee FROM tasks WHERE id = @id"; + command.Parameters.AddWithValue("@id", taskId); + + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + await reader.ReadAsync(cancellationToken); + + return (reader.GetString(0), reader.IsDBNull(1) ? null : reader.GetString(1)); + } + + /// + /// Reads the named task's recorded event types, in insertion order, directly from the + /// shared workspace database. + /// + private async Task> QueryTaskEventTypesAsync(string taskId, CancellationToken cancellationToken) + { + await using var connection = await new AgentDatabase().ConnectAsync(_workspaceDirectory, cancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT event_type FROM events WHERE task_id = @id ORDER BY id"; + command.Parameters.AddWithValue("@id", taskId); + + var eventTypes = new List(); + + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + + while (await reader.ReadAsync(cancellationToken)) + { + eventTypes.Add(reader.GetString(0)); + } + + return eventTypes; + } + + [Fact] + public async Task LoginAsync_Should_MintLoginOnlyAgent_When_Called() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var agent = await _store.LoginAsync(cancellationToken); + + // assert + Assert.Null(agent.Harness); + Assert.Null(agent.SessionId); + Assert.Equal("", agent.Role); + Assert.Equal(_timeProvider.GetUtcNow(), agent.RegisteredAt); + Assert.Equal(agent.RegisteredAt, agent.StartedAt); + } + + [Fact] + public async Task LoginAsync_Should_MintDistinctNames_When_CalledTwice() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var first = await _store.LoginAsync(cancellationToken); + var second = await _store.LoginAsync(cancellationToken); + + // assert + Assert.NotEqual(first.Name, second.Name); + } + + [Fact] + public async Task StartSessionAsync_Should_MintAgent_When_SessionUnknown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var result = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // assert + Assert.Equal(AgentSessionStartKind.Minted, result.Kind); + Assert.Equal(Harness, result.Row?.Harness); + Assert.Equal(SessionId, result.Row?.SessionId); + Assert.Equal("", result.Row?.Role); + Assert.Equal(_timeProvider.GetUtcNow(), result.Row?.StartedAt); + } + + [Fact] + public async Task StartSessionAsync_Should_ReuseRowAndRefreshFields_When_SessionKnown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(harnessVersion: "1.0.0"), cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var result = await _store.StartSessionAsync( + CreateRequest(harnessVersion: "2.0.0", cwd: "/repo2"), cancellationToken); + + // assert + Assert.Equal(AgentSessionStartKind.Reused, result.Kind); + Assert.Equal(minted.Row?.Name, result.Row?.Name); + Assert.Equal("2.0.0", result.Row?.HarnessVersion); + Assert.Equal("/repo2", result.Row?.Cwd); + Assert.Equal(_timeProvider.GetUtcNow(), result.Row?.LastSeenAt); + } + + [Fact] + public async Task StartSessionAsync_Should_KeepStartedAtAndRegisteredAt_When_SessionKnown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var result = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // assert + Assert.Equal(minted.Row?.StartedAt, result.Row?.StartedAt); + Assert.Equal(minted.Row?.RegisteredAt, result.Row?.RegisteredAt); + } + + [Fact] + public async Task StartSessionAsync_Should_KeepHarnessVersion_When_RequestVersionEmpty() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await _store.StartSessionAsync(CreateRequest(harnessVersion: "1.0.0"), cancellationToken); + + // act + var result = await _store.StartSessionAsync(CreateRequest(harnessVersion: ""), cancellationToken); + + // assert + Assert.Equal("1.0.0", result.Row?.HarnessVersion); + } + + [Fact] + public async Task StartSessionAsync_Should_ClearEndedAtAndKeepStartedAt_When_ResumingEndedSession() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.EndSessionAsync(Harness, SessionId, cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var result = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // assert + Assert.Equal(AgentSessionStartKind.Reused, result.Kind); + Assert.Null(result.Row?.EndedAt); + Assert.Equal(minted.Row?.StartedAt, result.Row?.StartedAt); + Assert.Equal(minted.Row?.Name, result.Row?.Name); + } + + [Fact] + public async Task StartSessionAsync_Should_ReturnIgnoredAndWriteNothing_When_SessionBelongsToDeletedAgent() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var result = await _store.StartSessionAsync(CreateRequest(harnessVersion: "9.9.9"), cancellationToken); + var stored = await _store.FindBySessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.Equal(AgentSessionStartKind.Ignored, result.Kind); + Assert.Null(result.Row); + Assert.Equal(minted.Row.LastSeenAt, stored?.LastSeenAt); + Assert.Equal(minted.Row.HarnessVersion, stored?.HarnessVersion); + } + + [Fact] + public async Task StartSessionAsync_Should_Throw_When_HarnessUnknown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var exception = await Assert.ThrowsAsync( + () => _store.StartSessionAsync(CreateRequest(harness: "typo"), cancellationToken)); + + // assert + Assert.Equal("harness", exception.ParamName); + Assert.Empty(await _store.ListAsync(cancellationToken)); + } + + [Fact] + public async Task TouchSessionAsync_Should_UpdateLastSeenAt_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await _store.StartSessionAsync(CreateRequest(), cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var touched = await _store.TouchSessionAsync(Harness, SessionId, cancellationToken); + var row = await _store.FindBySessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.True(touched); + Assert.Equal(_timeProvider.GetUtcNow(), row?.LastSeenAt); + } + + [Fact] + public async Task TouchSessionAsync_Should_ReturnFalse_When_RowMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var touched = await _store.TouchSessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.False(touched); + } + + [Fact] + public async Task TouchSessionAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var touched = await _store.TouchSessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.False(touched); + } + + [Fact] + public async Task TouchSessionAsync_Should_Throw_When_HarnessUnknown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var exception = await Assert.ThrowsAsync( + () => _store.TouchSessionAsync("typo", SessionId, cancellationToken)); + + // assert + Assert.Equal("harness", exception.ParamName); + } + + [Fact] + public async Task TouchAsync_Should_UpdateLastSeenAt_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var touched = await _store.TouchAsync(agent.Name, cancellationToken); + var row = await _store.FindAsync(agent.Name, cancellationToken); + + // assert + Assert.True(touched); + Assert.Equal(_timeProvider.GetUtcNow(), row?.LastSeenAt); + } + + [Fact] + public async Task TouchAsync_Should_ReturnFalse_When_RowMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var touched = await _store.TouchAsync("nobody", cancellationToken); + + // assert + Assert.False(touched); + } + + [Fact] + public async Task TouchAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var touched = await _store.TouchAsync(agent.Name, cancellationToken); + + // assert + Assert.False(touched); + } + + [Fact] + public async Task EndSessionAsync_Should_SetEndedAt_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var ended = await _store.EndSessionAsync(Harness, SessionId, cancellationToken); + var row = await _store.FindBySessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.True(ended); + Assert.Equal(_timeProvider.GetUtcNow(), row?.EndedAt); + } + + [Fact] + public async Task EndSessionAsync_Should_ReturnFalse_When_RowMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var ended = await _store.EndSessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.False(ended); + } + + [Fact] + public async Task EndSessionAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var ended = await _store.EndSessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.False(ended); + } + + [Fact] + public async Task SetRoleAsync_Should_WriteRoleAndBumpLastSeenAt_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var updated = await _store.SetRoleAsync(agent.Name, "Implementer", cancellationToken); + + // assert + Assert.Equal("implementer", updated?.Role); + Assert.Equal(_timeProvider.GetUtcNow(), updated?.LastSeenAt); + } + + [Fact] + public async Task SetRoleAsync_Should_BeNoOpExceptLastSeenAt_When_RoleUnchanged() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + var first = await _store.SetRoleAsync(agent.Name, "implementer", cancellationToken); + _timeProvider.Advance(TimeSpan.FromMinutes(5)); + + // act + var second = await _store.SetRoleAsync(agent.Name, "implementer", cancellationToken); + + // assert + Assert.Equal(first?.Role, second?.Role); + Assert.Equal(first?.StartedAt, second?.StartedAt); + Assert.Equal(_timeProvider.GetUtcNow(), second?.LastSeenAt); + Assert.NotEqual(first?.LastSeenAt, second?.LastSeenAt); + } + + [Fact] + public async Task SetRoleAsync_Should_ReturnNull_When_RowMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var updated = await _store.SetRoleAsync("nobody", "implementer", cancellationToken); + + // assert + Assert.Null(updated); + } + + [Fact] + public async Task SetRoleAsync_Should_ReturnNull_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var updated = await _store.SetRoleAsync(agent.Name, "implementer", cancellationToken); + + // assert + Assert.Null(updated); + } + + [Fact] + public async Task FindAsync_Should_ReturnRow_When_Exists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + + // act + var found = await _store.FindAsync(agent.Name, cancellationToken); + + // assert + Assert.Equal(agent.Name, found?.Name); + } + + [Fact] + public async Task FindAsync_Should_ReturnNull_When_NotFound() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var found = await _store.FindAsync("nobody", cancellationToken); + + // assert + Assert.Null(found); + } + + [Fact] + public async Task FindAsync_Should_ReturnDeletedRow_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var found = await _store.FindAsync(agent.Name, cancellationToken); + + // assert + Assert.NotNull(found); + Assert.True(found.IsDeleted); + } + + [Fact] + public async Task FindBySessionAsync_Should_ReturnRow_When_Exists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var found = await _store.FindBySessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.Equal(minted.Row?.Name, found?.Name); + } + + [Fact] + public async Task FindBySessionAsync_Should_ReturnNull_When_NotFound() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var found = await _store.FindBySessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.Null(found); + } + + [Fact] + public async Task FindBySessionAsync_Should_ReturnDeletedRow_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var found = await _store.FindBySessionAsync(Harness, SessionId, cancellationToken); + + // assert + Assert.NotNull(found); + Assert.True(found.IsDeleted); + } + + [Fact] + public async Task ListAsync_Should_ExcludeDeletedRows_When_SomeAreDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var active = await _store.LoginAsync(cancellationToken); + var deleted = await _store.LoginAsync(cancellationToken); + await MarkDeletedAsync(deleted.Name, cancellationToken); + + // act + var agents = await _store.ListAsync(cancellationToken); + + // assert + var agent = Assert.Single(agents); + Assert.Equal(active.Name, agent.Name); + } + + [Fact] + public async Task ListAsync_Should_ReturnEmpty_When_NoAgents() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var agents = await _store.ListAsync(cancellationToken); + + // assert + Assert.Empty(agents); + } + + [Fact] + public async Task SetEndpointAsync_Should_WriteEndpoint_When_KindIsNotOpencodeServer() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var updated = await _store.SetEndpointAsync( + minted.Row!.Name, AgentSessionEndpointKind.ClaudePeer, "peer-2", "ignored", cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.True(updated); + Assert.Equal(AgentSessionEndpointKind.ClaudePeer, row?.EndpointKind); + Assert.Equal("peer-2", row?.EndpointAddr); + Assert.Null(row?.EndpointSecret); + } + + [Fact] + public async Task SetEndpointAsync_Should_KeepCredential_When_OpencodeServerBelongsToOpencodeHarness() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync( + CreateRequest(harness: AgentSessionHarness.Opencode), cancellationToken); + + // act + var updated = await _store.SetEndpointAsync( + minted.Row!.Name, + AgentSessionEndpointKind.OpencodeServer, + "http://127.0.0.1:4096", + "server-password", + cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.True(updated); + Assert.Equal("server-password", row?.EndpointSecret); + } + + [Fact] + public async Task SetEndpointAsync_Should_DropCredential_When_OpencodeServerBelongsToNonOpencodeHarness() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var updated = await _store.SetEndpointAsync( + minted.Row!.Name, + AgentSessionEndpointKind.OpencodeServer, + "http://127.0.0.1:4096", + "server-password", + cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.True(updated); + Assert.Null(row?.EndpointSecret); + } + + [Fact] + public async Task SetEndpointAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var updated = await _store.SetEndpointAsync( + minted.Row.Name, AgentSessionEndpointKind.ClaudePeer, "peer-2", null, cancellationToken); + + // assert + Assert.False(updated); + } + + [Fact] + public async Task ResetBlockBudgetAsync_Should_ResetToZero_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.IncrementBlockBudgetAsync(minted.Row!.Name, cancellationToken); + await _store.IncrementBlockBudgetAsync(minted.Row.Name, cancellationToken); + + // act + var result = await _store.ResetBlockBudgetAsync(minted.Row.Name, cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Equal(0, result); + Assert.Equal(0, row?.BlockBudgetUsed); + } + + [Fact] + public async Task ResetBlockBudgetAsync_Should_BeNoOp_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var result = await _store.ResetBlockBudgetAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Equal(0, result); + } + + [Fact] + public async Task IncrementBlockBudgetAsync_Should_ReturnIncrementedValue_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var first = await _store.IncrementBlockBudgetAsync(minted.Row!.Name, cancellationToken); + var second = await _store.IncrementBlockBudgetAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Equal(1, first); + Assert.Equal(2, second); + } + + [Fact] + public async Task IncrementBlockBudgetAsync_Should_ReturnZero_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var result = await _store.IncrementBlockBudgetAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Equal(0, result); + } + + [Fact] + public async Task TryClaimPingCooldownAsync_Should_Claim_When_NoPriorAttempt() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var claimed = await _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.FromSeconds(60), "attempt-1", cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.True(claimed); + Assert.Equal("attempt-1", row?.LastPingAttempt); + Assert.Equal(_timeProvider.GetUtcNow(), row?.LastPingAt); + } + + [Fact] + public async Task TryClaimPingCooldownAsync_Should_ReturnFalse_When_StillWithinCooldown() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.FromSeconds(60), "attempt-1", cancellationToken); + _timeProvider.Advance(TimeSpan.FromSeconds(30)); + + // act + var claimed = await _store.TryClaimPingCooldownAsync( + minted.Row.Name, TimeSpan.FromSeconds(60), "attempt-2", cancellationToken); + + // assert + Assert.False(claimed); + } + + [Fact] + public async Task TryClaimPingCooldownAsync_Should_ReturnTrue_When_CooldownElapsed() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.FromSeconds(60), "attempt-1", cancellationToken); + _timeProvider.Advance(TimeSpan.FromSeconds(61)); + + // act + var claimed = await _store.TryClaimPingCooldownAsync( + minted.Row.Name, TimeSpan.FromSeconds(60), "attempt-2", cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.True(claimed); + Assert.Equal("attempt-2", row?.LastPingAttempt); + } + + [Fact] + public async Task TryClaimPingCooldownAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var claimed = await _store.TryClaimPingCooldownAsync( + minted.Row.Name, TimeSpan.FromSeconds(60), "attempt-1", cancellationToken); + + // assert + Assert.False(claimed); + } + + [Fact] + public async Task TryClaimPingCooldownAsync_Should_HaveExactlyOneWinner_When_ConcurrentClaimsRaceTheSameRow() + { + // arrange + // each call opens its own connection against the same agent row + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + + // act + var results = await ConcurrentTestHarness.RunAsync( + 5, + i => _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.FromSeconds(60), $"attempt-{i}", cancellationToken)); + + // assert + Assert.Equal(1, results.Count(claimed => claimed)); + } + + [Fact] + public async Task WritePingResultAsync_Should_Write_When_AttemptIdMatches() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.FromSeconds(60), "attempt-1", cancellationToken); + + // act + await _store.WritePingResultAsync( + minted.Row.Name, "attempt-1", AgentPingResult.Ok, "all good", cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Equal(AgentPingResult.Ok, row?.LastPingResult); + Assert.Equal("all good", row?.LastPingDetail); + } + + [Fact] + public async Task WritePingResultAsync_Should_BeANoOp_When_AttemptIdIsStale() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.Zero, "attempt-1", cancellationToken); + await _store.TryClaimPingCooldownAsync( + minted.Row.Name, TimeSpan.Zero, "attempt-2", cancellationToken); + + // act + await _store.WritePingResultAsync( + minted.Row.Name, "attempt-1", AgentPingResult.Timeout, null, cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Null(row?.LastPingResult); + } + + [Fact] + public async Task WritePingResultAsync_Should_BeANoOp_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + await _store.TryClaimPingCooldownAsync( + minted.Row!.Name, TimeSpan.FromSeconds(60), "attempt-1", cancellationToken); + await MarkDeletedAsync(minted.Row.Name, cancellationToken); + + // act + await _store.WritePingResultAsync( + minted.Row.Name, "attempt-1", AgentPingResult.Ok, null, cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.Null(row?.LastPingResult); + } + + [Fact] + public async Task ArmAnnouncementAsync_Should_SetPending_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + + // act + await _store.ArmAnnouncementAsync(agent.Name, cancellationToken); + var pending = await _store.IsAnnouncementPendingAsync(agent.Name, cancellationToken); + + // assert + Assert.True(pending); + } + + [Fact] + public async Task ArmAnnouncementAsync_Should_BeNoOp_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + await _store.ArmAnnouncementAsync(agent.Name, cancellationToken); + var pending = await _store.IsAnnouncementPendingAsync(agent.Name, cancellationToken); + + // assert + Assert.False(pending); + } + + [Fact] + public async Task ClaimAnnouncementAsync_Should_ClearPendingAndReturnTrue_When_Pending() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await _store.ArmAnnouncementAsync(agent.Name, cancellationToken); + + // act + var claimed = await _store.ClaimAnnouncementAsync(agent.Name, cancellationToken); + var pending = await _store.IsAnnouncementPendingAsync(agent.Name, cancellationToken); + + // assert + Assert.True(claimed); + Assert.False(pending); + } + + [Fact] + public async Task ClaimAnnouncementAsync_Should_ReturnFalse_When_NothingPending() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + + // act + var claimed = await _store.ClaimAnnouncementAsync(agent.Name, cancellationToken); + + // assert + Assert.False(claimed); + } + + [Fact] + public async Task ClaimAnnouncementAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await _store.ArmAnnouncementAsync(agent.Name, cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var claimed = await _store.ClaimAnnouncementAsync(agent.Name, cancellationToken); + + // assert + Assert.False(claimed); + } + + [Fact] + public async Task IsAnnouncementPendingAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await _store.ArmAnnouncementAsync(agent.Name, cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var pending = await _store.IsAnnouncementPendingAsync(agent.Name, cancellationToken); + + // assert + Assert.False(pending); + } + + [Fact] + public async Task RearmIdlePushAsync_Should_SetArmed_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + + // act + await _store.RearmIdlePushAsync(agent.Name, cancellationToken); + var claimed = await _store.ClaimIdlePushAsync(agent.Name, cancellationToken); + + // assert + Assert.True(claimed); + } + + [Fact] + public async Task RearmIdlePushAsync_Should_BeNoOp_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + await _store.RearmIdlePushAsync(agent.Name, cancellationToken); + var claimed = await _store.ClaimIdlePushAsync(agent.Name, cancellationToken); + + // assert + Assert.False(claimed); + } + + [Fact] + public async Task ClaimIdlePushAsync_Should_ClaimOnceAndReturnFalseAfter_When_Armed() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await _store.RearmIdlePushAsync(agent.Name, cancellationToken); + + // act + var first = await _store.ClaimIdlePushAsync(agent.Name, cancellationToken); + var second = await _store.ClaimIdlePushAsync(agent.Name, cancellationToken); + + // assert + Assert.True(first); + Assert.False(second); + } + + [Fact] + public async Task ClaimIdlePushAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await _store.RearmIdlePushAsync(agent.Name, cancellationToken); + await MarkDeletedAsync(agent.Name, cancellationToken); + + // act + var claimed = await _store.ClaimIdlePushAsync(agent.Name, cancellationToken); + + // assert + Assert.False(claimed); + } + + [Fact] + public async Task RecordHarnessVersionAsync_Should_WriteVersion_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(harnessVersion: "1.0.0"), cancellationToken); + + // act + var updated = await _store.RecordHarnessVersionAsync(minted.Row!.Name, "2.0.0", cancellationToken); + var row = await _store.FindAsync(minted.Row.Name, cancellationToken); + + // assert + Assert.True(updated); + Assert.Equal("2.0.0", row?.HarnessVersion); + } + + [Fact] + public async Task RecordHarnessVersionAsync_Should_ReturnFalse_When_RowDeleted() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(harnessVersion: "1.0.0"), cancellationToken); + await MarkDeletedAsync(minted.Row!.Name, cancellationToken); + + // act + var updated = await _store.RecordHarnessVersionAsync(minted.Row.Name, "2.0.0", cancellationToken); + + // assert + Assert.False(updated); + } + + [Fact] + public async Task DeleteAsync_Should_ReturnFalse_When_RowMissing() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + + // act + var deleted = await _store.DeleteAsync("nobody", cancellationToken); + + // assert + Assert.False(deleted); + } + + [Fact] + public async Task DeleteAsync_Should_ReturnFalse_When_CalledTwice() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + + // act + var first = await _store.DeleteAsync(agent.Name, cancellationToken); + var second = await _store.DeleteAsync(agent.Name, cancellationToken); + + // assert + Assert.True(first); + Assert.False(second); + } + + [Fact] + public async Task DeleteAsync_Should_StampAndClearTheRow_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + var name = minted.Row!.Name; + await _store.IncrementBlockBudgetAsync(name, cancellationToken); + await _store.TryClaimPingCooldownAsync(name, TimeSpan.FromMinutes(1), "attempt-1", cancellationToken); + await _store.WritePingResultAsync(name, "attempt-1", "ok", "detail", cancellationToken); + await _store.ArmAnnouncementAsync(name, cancellationToken); + await _store.RearmIdlePushAsync(name, cancellationToken); + + // act + var deleted = await _store.DeleteAsync(name, cancellationToken); + var row = await _store.FindAsync(name, cancellationToken); + + // assert + Assert.True(deleted); + Snapshot.Create() + .Add(row!.IsDeleted, "IsDeleted") + .Add(row.EndpointKind, "EndpointKind") + .Add(row.EndpointAddr, "EndpointAddr") + .Add(row.EndpointSecret, "EndpointSecret") + .Add(row.LastPingAt, "LastPingAt") + .Add(row.LastPingAttempt, "LastPingAttempt") + .Add(row.LastPingResult, "LastPingResult") + .Add(row.LastPingDetail, "LastPingDetail") + .Add(row.AnnouncementPending, "AnnouncementPending") + .Add(row.IdlePushArmed, "IdlePushArmed") + .Add(row.BlockBudgetUsed, "BlockBudgetUsed") + .MatchMarkdownSnapshot(); + } + + [Fact] + public async Task DeleteAsync_Should_RemoveWakeAndPingSideRows_When_RowExists() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await InsertSideRowsAsync(agent.Name, cancellationToken); + + // act + var deleted = await _store.DeleteAsync(agent.Name, cancellationToken); + var counts = await CountSideRowsAsync(agent.Name, cancellationToken); + + // assert + Assert.True(deleted); + Snapshot.Create() + .Add(counts.Deliveries, "Deliveries") + .Add(counts.PingGates, "PingGates") + .Add(counts.Outbox, "Outbox") + .Add(counts.Batches, "Batches") + .Add(counts.Targets, "Targets") + .MatchMarkdownSnapshot(); + } + + [Fact] + public async Task DeleteAsync_Should_ReleaseInProgressTaskAndRecordEvent_When_AgentHasAssignedTask() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var agent = await _store.LoginAsync(cancellationToken); + await InsertInProgressTaskAsync("acme-1", agent.Name, cancellationToken); + + // act + var deleted = await _store.DeleteAsync(agent.Name, cancellationToken); + var (status, assignee) = await QueryTaskAsync("acme-1", cancellationToken); + var eventTypes = await QueryTaskEventTypesAsync("acme-1", cancellationToken); + + // assert + Assert.True(deleted); + Snapshot.Create() + .Add(status, "Status") + .Add(assignee, "Assignee") + .Add(eventTypes, "EventTypes") + .MatchMarkdownSnapshot(); + } + + [Fact] + public async Task DeleteInactiveAsync_Should_DeleteOfflineAndIdleRows_When_Called() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var online = await _store.StartSessionAsync(CreateRequest(sessionId: "online"), cancellationToken); + var unreachable = await _store.StartSessionAsync( + CreateRequest( + sessionId: "unreachable", endpointKind: AgentSessionEndpointKind.None, endpointAddr: ""), + cancellationToken); + var idle = await _store.StartSessionAsync(CreateRequest(sessionId: "idle"), cancellationToken); + var offline = await _store.StartSessionAsync(CreateRequest(sessionId: "offline"), cancellationToken); + await _store.EndSessionAsync(Harness, "offline", cancellationToken); + _timeProvider.Advance(AgentStateResolver.OnlineWindow + TimeSpan.FromMinutes(1)); + await _store.TouchSessionAsync(Harness, "online", cancellationToken); + await _store.TouchSessionAsync(Harness, "unreachable", cancellationToken); + + // act + var deletedCount = await _store.DeleteInactiveAsync(cancellationToken); + var onlineRow = await _store.FindAsync(online.Row!.Name, cancellationToken); + var unreachableRow = await _store.FindAsync(unreachable.Row!.Name, cancellationToken); + var idleRow = await _store.FindAsync(idle.Row!.Name, cancellationToken); + var offlineRow = await _store.FindAsync(offline.Row!.Name, cancellationToken); + + // assert + Snapshot.Create() + .Add(deletedCount, "DeletedCount") + .Add(onlineRow!.IsDeleted, "OnlineDeleted") + .Add(unreachableRow!.IsDeleted, "UnreachableDeleted") + .Add(idleRow!.IsDeleted, "IdleDeleted") + .Add(offlineRow!.IsDeleted, "OfflineDeleted") + .MatchMarkdownSnapshot(); + } + + [Fact] + public async Task StartSessionAsync_Should_ReturnIgnored_When_SessionBelongsToAgentDeletedViaDeleteAsync() + { + // arrange + var cancellationToken = TestContext.Current.CancellationToken; + await InitWorkspaceAsync(cancellationToken); + var minted = await _store.StartSessionAsync(CreateRequest(), cancellationToken); + var deleted = await _store.DeleteAsync(minted.Row!.Name, cancellationToken); + + // act + var result = await _store.StartSessionAsync(CreateRequest(harnessVersion: "9.9.9"), cancellationToken); + + // assert + Assert.True(deleted); + Assert.Equal(AgentSessionStartKind.Ignored, result.Kind); + Assert.Null(result.Row); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ClaudeSessionActivityReaderTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ClaudeSessionActivityReaderTests.cs deleted file mode 100644 index fcf7396bb39..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/ClaudeSessionActivityReaderTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.HookRuntime; - -public sealed class ClaudeSessionActivityReaderTests -{ - [Fact] - public void GetStatus_Should_ReturnNull_When_StatusIsNotAString() - { - // arrange - var reader = new ClaudeSessionActivityReader(sessionFileReader: _ => "{\"status\":1}"); - - // act - var status = reader.GetStatus("session-1"); - - // assert - Assert.Null(status); - } - - [Fact] - public void GetStatus_Should_ReturnNull_When_DiscoveredSessionFileRootIsAnArray() - { - // arrange - using var directory = new TemporaryDirectory(); - File.WriteAllText(Path.Combine(directory.Root.FullName, "session.json"), "[]"); - var reader = new ClaudeSessionActivityReader( - sessionFileReader: sessionId => - ClaudeSessionActivityReader.ReadSessionFile(directory.Root.FullName, sessionId)); - - // act - var status = reader.GetStatus("session-1"); - - // assert - Assert.Null(status); - } - - [Fact] - public void GetStatus_Should_ReturnTheStatus_When_DiscoveredSessionFileIsValid() - { - // arrange - using var directory = new TemporaryDirectory(); - File.WriteAllText( - Path.Combine(directory.Root.FullName, "session.json"), - "{\"sessionId\":\"session-1\",\"status\":\"working\"}"); - var reader = new ClaudeSessionActivityReader( - sessionFileReader: sessionId => - ClaudeSessionActivityReader.ReadSessionFile(directory.Root.FullName, sessionId)); - - // act - var status = reader.GetStatus("session-1"); - - // assert - Assert.Equal("working", status); - } - - [Fact] - public void GetStatus_Should_ReturnNull_When_SessionFileRootIsAnArray() - { - // arrange - var reader = new ClaudeSessionActivityReader(sessionFileReader: _ => "[]"); - - // act - var status = reader.GetStatus("session-1"); - - // assert - Assert.Null(status); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeBatchStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeBatchStoreTests.cs index 9409c040e98..4cfcb2651b0 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeBatchStoreTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeBatchStoreTests.cs @@ -1,3 +1,4 @@ +using ChilliCream.Nitro.CommandLine.Services.Notify; using ChilliCream.Nitro.CommandLine.Services.Workspace; using Microsoft.Data.Sqlite; @@ -10,17 +11,16 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// public sealed class MailWakeBatchStoreTests : IDisposable { - private const string InstanceId = "instance-a"; private const string Actor = "claude"; - private static readonly AgentSessionGeneration s_target = - new("claude-code", "session-1", "host-a"); + private static readonly TimeSpan s_longLeaderLease = TimeSpan.FromDays(1); private readonly DirectoryInfo _tempRoot; private readonly string _workspaceDirectory; private readonly TestFileSystem _fileSystem; private readonly AgentDatabase _database; private readonly MailWakeBatchStore _batches; + private readonly MailWakeDaemonLeaderStore _leaderStore; public MailWakeBatchStoreTests() { @@ -30,6 +30,7 @@ public MailWakeBatchStoreTests() _fileSystem = new TestFileSystem(_tempRoot.FullName); _database = new AgentDatabase(); _batches = new MailWakeBatchStore(_fileSystem, _database); + _leaderStore = new MailWakeDaemonLeaderStore(_fileSystem, _database); } public void Dispose() => _tempRoot.Delete(recursive: true); @@ -44,7 +45,7 @@ public async Task TryClaimAsync_Should_ReturnNull_When_NoOutboxRowExists() // act var claim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-1", "attempt-1", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-1", "attempt-1", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.Null(claim); @@ -64,7 +65,7 @@ public async Task TryClaimAsync_Should_ReturnNull_When_SettledGenerationAlreadyE // act var claim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-1", "attempt-1", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-1", "attempt-1", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.Null(claim); @@ -85,7 +86,7 @@ await SeedOutboxAsync( // act var claim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-1", "attempt-1", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-1", "attempt-1", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.Null(claim); @@ -102,15 +103,16 @@ public async Task TryClaimAsync_Should_ClaimGenerationAndMaterializeTargets_When await SeedActorAsync(seedConnection, cancellationToken); await SeedOutboxAsync(seedConnection, requestedGeneration: 3, settledGeneration: 1, dueAt: now, cancellationToken); } + await AcquireLeaderLeaseAsync("owner-1", now, s_longLeaderLease, cancellationToken); // act var claim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-1", "attempt-1", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-1", "attempt-1", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.NotNull(claim); Assert.Equal(3, claim.ClaimedGeneration); - Assert.Equal([s_target], claim.Targets); + Assert.Equal([Actor], claim.Targets); await using var connection = await ConnectAsync(cancellationToken); var targetCount = await ExecuteScalarLongAsync( @@ -131,12 +133,13 @@ public async Task TryClaimAsync_Should_ReturnNull_When_AnActiveBatchAlreadyExist await SeedActorAsync(connection, cancellationToken); await SeedOutboxAsync(connection, requestedGeneration: 2, settledGeneration: 0, dueAt: now, cancellationToken); } + await AcquireLeaderLeaseAsync("owner-1", now, s_longLeaderLease, cancellationToken); var firstClaim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-1", "attempt-1", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-1", "attempt-1", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // act var secondClaim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-2", "attempt-2", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-2", "attempt-2", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.NotNull(firstClaim); @@ -146,7 +149,8 @@ public async Task TryClaimAsync_Should_ReturnNull_When_AnActiveBatchAlreadyExist [Fact] public async Task TryClaimAsync_Should_ReturnNull_When_TheActiveBatchLeaseHasNotExpiredYet() { - // arrange: a batch claimed with a 10s lease. + // arrange + // a batch claimed with a 10s lease. var cancellationToken = TestContext.Current.CancellationToken; var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); var firstClaim = await SeedClaimedBatchAsync(now, TimeSpan.FromSeconds(10), cancellationToken); @@ -154,7 +158,7 @@ public async Task TryClaimAsync_Should_ReturnNull_When_TheActiveBatchLeaseHasNot // act // Attempt a second claim five seconds into the ten-second lease. var secondClaim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-2", "attempt-2", [s_target], now + TimeSpan.FromSeconds(5), + Actor, "owner-2", "attempt-2", [Actor], now + TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), cancellationToken); // assert @@ -165,14 +169,18 @@ public async Task TryClaimAsync_Should_ReturnNull_When_TheActiveBatchLeaseHasNot [Fact] public async Task TryClaimAsync_Should_ReclaimTheActor_When_TheActiveBatchLeaseHasExpired() { - // arrange: a batch claimed with a 10s lease. + // arrange + // a batch claimed with a 10s lease. var cancellationToken = TestContext.Current.CancellationToken; var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); var firstClaim = await SeedClaimedBatchAsync(now, TimeSpan.FromSeconds(10), cancellationToken); - // act: a new owner claims 11s later, after the lease expired. + // act + // owner-1 steps down and a new owner takes the leader lease before claiming 11s later. + await _leaderStore.TryReleaseAsync("owner-1", now + TimeSpan.FromSeconds(11), cancellationToken); + await AcquireLeaderLeaseAsync("owner-2", now + TimeSpan.FromSeconds(11), s_longLeaderLease, cancellationToken); var secondClaim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-2", "attempt-2", [s_target], now + TimeSpan.FromSeconds(11), + Actor, "owner-2", "attempt-2", [Actor], now + TimeSpan.FromSeconds(11), TimeSpan.FromSeconds(10), cancellationToken); // assert @@ -187,15 +195,19 @@ public async Task TryClaimAsync_Should_ReclaimTheActor_When_TheActiveBatchLeaseH [Fact] public async Task TryCompleteAsync_Should_ReturnFalse_When_BatchWasReclaimedAfterExpiry() { - // arrange: the original batch's lease expires and a new owner reclaims the actor. + // arrange + // the original batch's lease expires and a new owner reclaims the actor. var cancellationToken = TestContext.Current.CancellationToken; var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); var firstClaim = await SeedClaimedBatchAsync(now, TimeSpan.FromSeconds(10), cancellationToken); + await _leaderStore.TryReleaseAsync("owner-1", now + TimeSpan.FromSeconds(11), cancellationToken); + await AcquireLeaderLeaseAsync("owner-2", now + TimeSpan.FromSeconds(11), s_longLeaderLease, cancellationToken); await _batches.TryClaimAsync( - InstanceId, Actor, "owner-2", "attempt-2", [s_target], now + TimeSpan.FromSeconds(11), + Actor, "owner-2", "attempt-2", [Actor], now + TimeSpan.FromSeconds(11), TimeSpan.FromSeconds(10), cancellationToken); - // act: the stale owner tries to complete the batch it no longer holds. + // act + // the stale owner tries to complete the batch it no longer holds. var completed = await _batches.TryCompleteAsync( firstClaim.BatchId, "owner-1", "attempt-1", now + TimeSpan.FromSeconds(12), cancellationToken); @@ -204,7 +216,7 @@ await _batches.TryClaimAsync( await using var connection = await ConnectAsync(cancellationToken); var settledGeneration = await ExecuteScalarLongAsync( connection, - $"SELECT settled_generation FROM mail_wake_outbox WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}'", + $"SELECT settled_generation FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); Assert.Equal(0, settledGeneration); } @@ -212,7 +224,8 @@ await _batches.TryClaimAsync( [Fact] public async Task TryClaimAsync_Should_ClaimExactlyOnce_When_ConcurrentCallersRaceTheSameActor() { - // arrange: separate connections (Pooling=False, matching production) racing the same actor. + // arrange + // separate connections (Pooling=False, matching production) racing the same actor. var cancellationToken = TestContext.Current.CancellationToken; var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); await using (var connection = await InitializeWorkspaceAsync(cancellationToken)) @@ -220,14 +233,17 @@ public async Task TryClaimAsync_Should_ClaimExactlyOnce_When_ConcurrentCallersRa await SeedActorAsync(connection, cancellationToken); await SeedOutboxAsync(connection, requestedGeneration: 1, settledGeneration: 0, dueAt: now, cancellationToken); } + await AcquireLeaderLeaseAsync("owner-1", now, s_longLeaderLease, cancellationToken); // act + // Every racer shares the current leader's token; only the attempt id distinguishes them. var results = await ConcurrentTestHarness.RunAsync( 6, i => new MailWakeBatchStore(_fileSystem, _database).TryClaimAsync( - InstanceId, Actor, $"owner-{i}", $"attempt-{i}", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken)); + Actor, "owner-1", $"attempt-{i}", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken)); - // assert: exactly one caller claimed the batch. + // assert + // exactly one caller claimed the batch. Assert.Single(results, claim => claim is not null); } @@ -284,7 +300,7 @@ public async Task TryCompleteAsync_Should_SettleTheClaimedGeneration_When_OwnerA await using var connection = await ConnectAsync(cancellationToken); var settledGeneration = await ExecuteScalarLongAsync( connection, - $"SELECT settled_generation FROM mail_wake_outbox WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}'", + $"SELECT settled_generation FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); Assert.Equal(2, settledGeneration); var status = await ExecuteScalarStringAsync( @@ -305,8 +321,7 @@ public async Task TryCompleteAsync_Should_NotSettlePastTheClaimedGeneration_When { await ExecuteAsync( connection, - "UPDATE mail_wake_outbox SET requested_generation = 2 " - + $"WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}';", + $"UPDATE mail_wake_outbox SET requested_generation = 2 WHERE actor = '{Actor}';", cancellationToken); } @@ -318,7 +333,7 @@ await ExecuteAsync( await using var assertConnection = await ConnectAsync(cancellationToken); var settledGeneration = await ExecuteScalarLongAsync( assertConnection, - $"SELECT settled_generation FROM mail_wake_outbox WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}'", + $"SELECT settled_generation FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); Assert.Equal(1, settledGeneration); } @@ -347,10 +362,13 @@ public async Task TryReleaseAsync_Should_FreeTheActorForANewClaim_When_OwnerAndA var claim = await SeedClaimedBatchAsync(now, TimeSpan.FromSeconds(30), cancellationToken); // act + // owner-1 steps down and a new owner takes the leader lease before reclaiming. var released = await _batches.TryReleaseAsync( claim.BatchId, "owner-1", "attempt-1", now, retryAt: null, lastError: "spawn-failed", cancellationToken); + await _leaderStore.TryReleaseAsync("owner-1", now, cancellationToken); + await AcquireLeaderLeaseAsync("owner-2", now, s_longLeaderLease, cancellationToken); var reclaimed = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-2", "attempt-2", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + Actor, "owner-2", "attempt-2", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.True(released); @@ -373,7 +391,7 @@ public async Task TryReleaseAsync_Should_PushDueAtForward_When_RetryAtIsGiven() await using var connection = await ConnectAsync(cancellationToken); var dueAt = await ExecuteScalarStringAsync( connection, - $"SELECT due_at FROM mail_wake_outbox WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}'", + $"SELECT due_at FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); Assert.Equal(retryAt, DateTimeOffset.Parse(dueAt!, System.Globalization.CultureInfo.InvariantCulture)); } @@ -397,7 +415,7 @@ public async Task TryReleaseAsync_Should_ReturnFalseAndLeaveDueAtUnchanged_When_ await using var connection = await ConnectAsync(cancellationToken); var dueAt = await ExecuteScalarStringAsync( connection, - $"SELECT due_at FROM mail_wake_outbox WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}'", + $"SELECT due_at FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); Assert.Equal(now, DateTimeOffset.Parse(dueAt!, System.Globalization.CultureInfo.InvariantCulture)); } @@ -418,7 +436,7 @@ await _batches.TryReleaseAsync( await using var connection = await ConnectAsync(cancellationToken); var dueAt = await ExecuteScalarStringAsync( connection, - $"SELECT due_at FROM mail_wake_outbox WHERE nitro_instance_id = '{InstanceId}' AND actor = '{Actor}'", + $"SELECT due_at FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); Assert.Equal(now, DateTimeOffset.Parse(dueAt!, System.Globalization.CultureInfo.InvariantCulture)); } @@ -433,7 +451,7 @@ public async Task TryRecordTargetOutcomeAsync_Should_UpdateTheTargetRow_When_Bat // act var recorded = await _batches.TryRecordTargetOutcomeAsync( - claim.BatchId, s_target, "owner-1", "attempt-1", "delivered", + claim.BatchId, Actor, "owner-1", "attempt-1", "delivered", offeredGeneration: null, acceptedGeneration: 1, lastError: null, now, cancellationToken); // assert @@ -457,51 +475,83 @@ public async Task TryRecordTargetOutcomeAsync_Should_ReturnFalse_When_AttemptIdD // act var recorded = await _batches.TryRecordTargetOutcomeAsync( - claim.BatchId, s_target, "owner-1", "attempt-stale", "delivered", + claim.BatchId, Actor, "owner-1", "attempt-stale", "delivered", + offeredGeneration: null, acceptedGeneration: 1, lastError: null, now, cancellationToken); + + // assert + Assert.False(recorded); + } + + [Fact] + public async Task TryRecordTargetOutcomeAsync_Should_ReturnFalse_When_OwnerNoLongerHoldsTheLeaderLease() + { + // arrange + // owner-1's batch stays active while a second owner takes over the leader lease. + var cancellationToken = TestContext.Current.CancellationToken; + var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); + var claim = await SeedClaimedBatchAsync(now, TimeSpan.FromSeconds(30), cancellationToken); + await _leaderStore.TryReleaseAsync("owner-1", now, cancellationToken); + await AcquireLeaderLeaseAsync("owner-2", now, s_longLeaderLease, cancellationToken); + + // act + var recorded = await _batches.TryRecordTargetOutcomeAsync( + claim.BatchId, Actor, "owner-1", "attempt-1", "delivered", offeredGeneration: null, acceptedGeneration: 1, lastError: null, now, cancellationToken); // assert Assert.False(recorded); + await using var connection = await ConnectAsync(cancellationToken); + var status = await ExecuteScalarStringAsync( + connection, $"SELECT status FROM mail_wake_targets WHERE batch_id = '{claim.BatchId}'", cancellationToken); + Assert.Equal(MailWakeTargetStatus.Pending, status); } [Fact] - public async Task TryClaimAsync_Should_YieldAnIndependentClaim_When_ADifferentNitroInstanceClaimsTheSameActor() + public async Task TryCompleteAsync_Should_ReturnFalse_When_OwnerNoLongerHoldsTheLeaderLease() { // arrange + // owner-1's batch stays active while a second owner takes over the leader lease. + var cancellationToken = TestContext.Current.CancellationToken; + var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); + var claim = await SeedClaimedBatchAsync(now, TimeSpan.FromSeconds(30), cancellationToken); + await _leaderStore.TryReleaseAsync("owner-1", now, cancellationToken); + await AcquireLeaderLeaseAsync("owner-2", now, s_longLeaderLease, cancellationToken); + + // act + var completed = await _batches.TryCompleteAsync(claim.BatchId, "owner-1", "attempt-1", now, cancellationToken); + + // assert + Assert.False(completed); + await using var connection = await ConnectAsync(cancellationToken); + var status = await ExecuteScalarStringAsync( + connection, $"SELECT status FROM mail_wake_batches WHERE batch_id = '{claim.BatchId}'", cancellationToken); + Assert.Equal("active", status); + } + + [Fact] + public async Task TryClaimAsync_Should_ReturnNull_When_OwnerDoesNotHoldTheLeaderLease() + { + // arrange + // A second owner holds the leader lease; owner-1 holds none and attempts to claim anyway. var cancellationToken = TestContext.Current.CancellationToken; var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - const string otherInstanceId = "instance-b"; await using (var connection = await InitializeWorkspaceAsync(cancellationToken)) { await SeedActorAsync(connection, cancellationToken); await SeedOutboxAsync(connection, requestedGeneration: 1, settledGeneration: 0, dueAt: now, cancellationToken); - await SeedOutboxAsync( - connection, requestedGeneration: 1, settledGeneration: 0, dueAt: now, cancellationToken, - instanceId: otherInstanceId); } - var claimA = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-a", "attempt-a", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + await AcquireLeaderLeaseAsync("owner-2", now, s_longLeaderLease, cancellationToken); // act - var claimB = await _batches.TryClaimAsync( - otherInstanceId, Actor, "owner-b", "attempt-b", [s_target], now, TimeSpan.FromSeconds(30), cancellationToken); + var claim = await _batches.TryClaimAsync( + Actor, "owner-1", "attempt-1", [Actor], now, TimeSpan.FromSeconds(30), cancellationToken); // assert - Assert.NotNull(claimA); - Assert.NotNull(claimB); - Assert.NotEqual(claimA.BatchId, claimB.BatchId); - - var crossRenewed = await _batches.TryRenewAsync( - claimA.BatchId, "owner-b", "attempt-b", now, TimeSpan.FromSeconds(30), cancellationToken); - Assert.False(crossRenewed); - - var crossCompleted = await _batches.TryCompleteAsync( - claimA.BatchId, "owner-b", "attempt-b", now, cancellationToken); - Assert.False(crossCompleted); - - // instance-a's own owner still completes its own batch normally. - var completedA = await _batches.TryCompleteAsync(claimA.BatchId, "owner-a", "attempt-a", now, cancellationToken); - Assert.True(completedA); + Assert.Null(claim); + await using var connection2 = await ConnectAsync(cancellationToken); + var settledGeneration = await ExecuteScalarLongAsync( + connection2, $"SELECT settled_generation FROM mail_wake_outbox WHERE actor = '{Actor}'", cancellationToken); + Assert.Equal(0, settledGeneration); } private async Task SeedClaimedBatchAsync( @@ -512,13 +562,21 @@ private async Task SeedClaimedBatchAsync( await SeedActorAsync(connection, cancellationToken); await SeedOutboxAsync(connection, requestedGeneration, settledGeneration: 0, dueAt: now, cancellationToken); } + await AcquireLeaderLeaseAsync("owner-1", now, s_longLeaderLease, cancellationToken); var claim = await _batches.TryClaimAsync( - InstanceId, Actor, "owner-1", "attempt-1", [s_target], now, leaseDuration, cancellationToken); + Actor, "owner-1", "attempt-1", [Actor], now, leaseDuration, cancellationToken); return claim ?? throw new InvalidOperationException("Failed to seed a claimed batch for the test."); } + /// + /// Acquires the single shared mail-wake leader lease for . + /// + private async Task AcquireLeaderLeaseAsync( + string owner, DateTimeOffset now, TimeSpan leaseDuration, CancellationToken cancellationToken) + => await _leaderStore.TryAcquireAsync(owner, now, leaseDuration, cancellationToken); + private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) => await _database.InitializeAsync(_workspaceDirectory, cancellationToken); @@ -528,8 +586,8 @@ private async Task ConnectAsync(CancellationToken cancellation private static async Task SeedActorAsync(SqliteConnection connection, CancellationToken cancellationToken) => await ExecuteAsync( connection, - "INSERT INTO agents (name, registered_at, last_seen_at) VALUES " - + $"('{Actor}', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", + "INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES " + + $"('{Actor}', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00', '2026-01-10T12:00:00+00:00');", cancellationToken); private static async Task SeedOutboxAsync( @@ -537,17 +595,15 @@ private static async Task SeedOutboxAsync( long requestedGeneration, long settledGeneration, DateTimeOffset dueAt, - CancellationToken cancellationToken, - string instanceId = InstanceId) + CancellationToken cancellationToken) { // Bind dueAt with the same timestamp representation used by the store. await using var command = connection.CreateCommand(); command.CommandText = """ - INSERT INTO mail_wake_outbox (nitro_instance_id, actor, requested_generation, settled_generation, due_at, updated_at) - VALUES (@instanceId, @actor, @requestedGeneration, @settledGeneration, @dueAt, @dueAt); + INSERT INTO mail_wake_outbox (actor, requested_generation, settled_generation, due_at, updated_at) + VALUES (@actor, @requestedGeneration, @settledGeneration, @dueAt, @dueAt); """; - command.Parameters.AddWithValue("@instanceId", instanceId); command.Parameters.AddWithValue("@actor", Actor); command.Parameters.AddWithValue("@requestedGeneration", requestedGeneration); command.Parameters.AddWithValue("@settledGeneration", settledGeneration); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeDaemonLeaderStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeDaemonLeaderStoreTests.cs index 9187c107fe5..9a58312bb6c 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeDaemonLeaderStoreTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/MailWakeDaemonLeaderStoreTests.cs @@ -4,13 +4,11 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Agents; /// /// Exercises 's leader election over -/// the one persistent mail_wake_daemons row per Nitro instance, -/// directly against a real workspace database. +/// the single persistent mail_wake_daemons row, directly against a +/// real workspace database. /// public sealed class MailWakeDaemonLeaderStoreTests : IDisposable { - private const string InstanceId = "instance-a"; - private readonly DirectoryInfo _tempRoot; private readonly string _workspaceDirectory; private readonly TestFileSystem _fileSystem; @@ -30,7 +28,7 @@ public MailWakeDaemonLeaderStoreTests() public void Dispose() => _tempRoot.Delete(recursive: true); [Fact] - public async Task TryAcquireAsync_Should_ReturnEpochOne_When_NoLeaderRowExistsYet() + public async Task TryAcquireAsync_Should_ReturnTrue_When_NoLeaseRowExistsYet() { // arrange var cancellationToken = TestContext.Current.CancellationToken; @@ -38,85 +36,84 @@ public async Task TryAcquireAsync_Should_ReturnEpochOne_When_NoLeaderRowExistsYe var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); // act - var epoch = await _leader.TryAcquireAsync(InstanceId, "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); + var acquired = await _leader.TryAcquireAsync("token-1", now, TimeSpan.FromSeconds(30), cancellationToken); // assert - Assert.Equal(1, epoch); + Assert.True(acquired); } [Fact] - public async Task TryAcquireAsync_Should_ReturnNull_When_ALiveLeaseIsAlreadyHeld() + public async Task TryAcquireAsync_Should_ReturnFalse_When_ALiveLeaseIsAlreadyHeld() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _leader.TryAcquireAsync(InstanceId, "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); + await _leader.TryAcquireAsync("token-1", now, TimeSpan.FromSeconds(30), cancellationToken); // act - var epoch = await _leader.TryAcquireAsync(InstanceId, "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); + // even the same holder cannot re-acquire; it must renew instead. + var acquired = await _leader.TryAcquireAsync("token-1", now, TimeSpan.FromSeconds(30), cancellationToken); // assert - Assert.Null(epoch); + Assert.False(acquired); } [Fact] - public async Task TryAcquireAsync_Should_IncrementEpoch_When_StealingAnExpiredLease() + public async Task TryAcquireAsync_Should_Succeed_When_StealingAnExpiredLease() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var firstEpoch = - await _leader.TryAcquireAsync(InstanceId, "owner-1", acquiredAt, TimeSpan.FromSeconds(30), cancellationToken); + await _leader.TryAcquireAsync("token-1", acquiredAt, TimeSpan.FromSeconds(30), cancellationToken); var later = acquiredAt + TimeSpan.FromSeconds(31); // act - var secondEpoch = - await _leader.TryAcquireAsync(InstanceId, "owner-2", later, TimeSpan.FromSeconds(30), cancellationToken); + var acquired = await _leader.TryAcquireAsync("token-2", later, TimeSpan.FromSeconds(30), cancellationToken); // assert - Assert.Equal(1, firstEpoch); - Assert.Equal(2, secondEpoch); + Assert.True(acquired); + var renewedByOriginal = await _leader.TryRenewAsync( + "token-1", later, TimeSpan.FromSeconds(30), cancellationToken); + Assert.False(renewedByOriginal); } [Fact] - public async Task TryRenewAsync_Should_ExtendTheLease_When_OwnerAndEpochStillMatch() + public async Task TryRenewAsync_Should_ExtendTheLease_When_TokenStillHolds() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var epoch = - await _leader.TryAcquireAsync(InstanceId, "owner-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); + await _leader.TryAcquireAsync("token-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); var justBeforeExpiry = acquiredAt + TimeSpan.FromSeconds(9); // act var renewed = await _leader.TryRenewAsync( - InstanceId, "owner-1", epoch!.Value, justBeforeExpiry, TimeSpan.FromSeconds(10), null, cancellationToken); + "token-1", justBeforeExpiry, TimeSpan.FromSeconds(10), cancellationToken); // assert Assert.True(renewed); var stolen = await _leader.TryAcquireAsync( - InstanceId, "owner-2", acquiredAt + TimeSpan.FromSeconds(11), TimeSpan.FromSeconds(10), cancellationToken); - Assert.Null(stolen); + "token-2", acquiredAt + TimeSpan.FromSeconds(11), TimeSpan.FromSeconds(10), cancellationToken); + Assert.False(stolen); } [Fact] - public async Task TryRenewAsync_Should_ReturnFalse_When_EpochNoLongerMatches() + public async Task TryRenewAsync_Should_ReturnFalse_When_TokenDoesNotHoldTheLease() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var staleEpoch = - await _leader.TryAcquireAsync(InstanceId, "owner-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); + await _leader.TryAcquireAsync("token-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); var later = acquiredAt + TimeSpan.FromSeconds(11); - await _leader.TryAcquireAsync(InstanceId, "owner-2", later, TimeSpan.FromSeconds(30), cancellationToken); + await _leader.TryAcquireAsync("token-2", later, TimeSpan.FromSeconds(30), cancellationToken); // act - var renewed = await _leader.TryRenewAsync( - InstanceId, "owner-1", staleEpoch!.Value, later, TimeSpan.FromSeconds(10), null, cancellationToken); + // the stale holder tries to renew after a new holder has taken over. + var renewed = await _leader.TryRenewAsync("token-1", later, TimeSpan.FromSeconds(10), cancellationToken); // assert Assert.False(renewed); @@ -129,57 +126,55 @@ public async Task TryRenewAsync_Should_ReturnFalse_When_LeaseHasAlreadyExpired() var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var epoch = - await _leader.TryAcquireAsync(InstanceId, "owner-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); + await _leader.TryAcquireAsync("token-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); var afterExpiry = acquiredAt + TimeSpan.FromSeconds(11); // act - var renewed = await _leader.TryRenewAsync( - InstanceId, "owner-1", epoch!.Value, afterExpiry, TimeSpan.FromSeconds(10), null, cancellationToken); + var renewed = await _leader.TryRenewAsync("token-1", afterExpiry, TimeSpan.FromSeconds(10), cancellationToken); // assert Assert.False(renewed); } [Fact] - public async Task TryReleaseAsync_Should_ExpireTheLeaseImmediately_When_OwnerAndEpochMatch() + public async Task TryReleaseAsync_Should_ExpireTheLeaseImmediately_When_TokenHolds() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - var epoch = await _leader.TryAcquireAsync(InstanceId, "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); + await _leader.TryAcquireAsync("token-1", now, TimeSpan.FromSeconds(30), cancellationToken); // act - var released = await _leader.TryReleaseAsync(InstanceId, "owner-1", epoch!.Value, now, cancellationToken); - var reacquiredEpoch = - await _leader.TryAcquireAsync(InstanceId, "owner-2", now, TimeSpan.FromSeconds(30), cancellationToken); + var released = await _leader.TryReleaseAsync("token-1", now, cancellationToken); + var reacquired = await _leader.TryAcquireAsync("token-2", now, TimeSpan.FromSeconds(30), cancellationToken); // assert Assert.True(released); - Assert.Equal(2, reacquiredEpoch); + Assert.True(reacquired); } [Fact] - public async Task TryReleaseAsync_Should_ReturnFalse_When_EpochDoesNotMatch() + public async Task TryReleaseAsync_Should_ReturnFalse_When_TokenDoesNotHold() { // arrange var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _leader.TryAcquireAsync(InstanceId, "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); + await _leader.TryAcquireAsync("token-1", now, TimeSpan.FromSeconds(30), cancellationToken); // act - var released = await _leader.TryReleaseAsync(InstanceId, "owner-1", 999, now, cancellationToken); + var released = await _leader.TryReleaseAsync("token-2", now, cancellationToken); // assert Assert.False(released); } [Fact] - public async Task TryAcquireAsync_Should_ElectExactlyOneLeader_When_SixConcurrentCallersRaceTheSameInstance() + public async Task TryAcquireAsync_Should_ElectExactlyOneHolder_When_SixDifferentTokensRaceTheSameLease() { - // arrange: separate connections (Pooling=False, matching production) racing the same instance. + // arrange + // separate connections (Pooling=False, matching production) racing with six distinct tokens. var cancellationToken = TestContext.Current.CancellationToken; await InitializeWorkspaceAsync(cancellationToken); var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); @@ -188,29 +183,11 @@ public async Task TryAcquireAsync_Should_ElectExactlyOneLeader_When_SixConcurren var results = await ConcurrentTestHarness.RunAsync( 6, i => new MailWakeDaemonLeaderStore(_fileSystem, _database) - .TryAcquireAsync(InstanceId, $"owner-{i}", now, TimeSpan.FromSeconds(30), cancellationToken)); - - // assert: exactly one caller became leader, with epoch 1. - var won = results.Where(epoch => epoch is not null).ToArray(); - Assert.Single(won); - Assert.Equal(1, won[0]); - } - - [Fact] - public async Task TryAcquireAsync_Should_ElectIndependentLeaders_When_InstanceIdsDiffer() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - - // act - var epochA = await _leader.TryAcquireAsync("instance-a", "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); - var epochB = await _leader.TryAcquireAsync("instance-b", "owner-1", now, TimeSpan.FromSeconds(30), cancellationToken); + .TryAcquireAsync($"token-{i}", now, TimeSpan.FromSeconds(30), cancellationToken)); - // assert: a live lease on one instance never blocks another. - Assert.Equal(1, epochA); - Assert.Equal(1, epochB); + // assert + // exactly one distinct token ever won, so two tokens never both lead. + Assert.Single(results, acquired => acquired); } private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/NitroInstanceIdProviderTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/NitroInstanceIdProviderTests.cs deleted file mode 100644 index f43262b34f9..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/NitroInstanceIdProviderTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System.Security.Cryptography; -using System.Text; -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Agents; - -/// -/// Tests machine-id hashing and creation -/// and reuse of a persisted fallback id. -/// -public sealed class NitroInstanceIdProviderTests : IDisposable -{ - private readonly DirectoryInfo _tempRoot; - private readonly string _globalConfigDirectory; - - public NitroInstanceIdProviderTests() - { - _tempRoot = Directory.CreateTempSubdirectory("nitro-instance-id-tests"); - _globalConfigDirectory = Path.Combine(_tempRoot.FullName, "nitro"); - } - - public void Dispose() => _tempRoot.Delete(recursive: true); - - [Fact] - public async Task GetIdAsync_Should_ReturnHashedMachineId_When_MachineIdReaderReturnsAValue() - { - // arrange - var fileSystem = new TestFileSystem(_tempRoot.FullName); - var provider = new NitroInstanceIdProvider(fileSystem, () => "fixed-machine-id"); - var expected = Convert.ToHexString( - SHA256.HashData(Encoding.UTF8.GetBytes("fixed-machine-id"))).ToLowerInvariant(); - - // act - var id = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - - // assert - Assert.Equal(expected, id); - Assert.False(fileSystem.DirectoryExists(_globalConfigDirectory)); - } - - [Fact] - public async Task GetIdAsync_Should_BeDeterministic_When_CalledTwiceWithTheSameMachineId() - { - // arrange - var fileSystem = new TestFileSystem(_tempRoot.FullName); - var provider = new NitroInstanceIdProvider(fileSystem, () => "fixed-machine-id"); - - // act - var first = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - var second = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - - // assert - Assert.Equal(first, second); - } - - [Fact] - public async Task GetIdAsync_Should_CreateAndPersistFallbackId_When_NoMachineIdCanBeRead() - { - // arrange - var fileSystem = new TestFileSystem(_tempRoot.FullName); - var provider = new NitroInstanceIdProvider(fileSystem, () => null); - - // act - var id = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - - // assert - var persisted = await File.ReadAllTextAsync( - Path.Combine(_globalConfigDirectory, "instance-id"), TestContext.Current.CancellationToken); - Assert.Equal(persisted.Trim(), id); - Assert.False(string.IsNullOrWhiteSpace(id)); - } - - [Fact] - public async Task GetIdAsync_Should_ReturnTheSameFallbackId_When_CalledAgainAfterCreating() - { - // arrange - var fileSystem = new TestFileSystem(_tempRoot.FullName); - var provider = new NitroInstanceIdProvider(fileSystem, () => null); - var first = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - - // act - var second = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - - // assert - Assert.Equal(first, second); - } - - /// - /// Tests reuse of a fallback id file that exists before the provider is called. - /// - [Fact] - public async Task GetIdAsync_Should_ReturnTheExistingId_When_FallbackFileAlreadyExists() - { - // arrange - var fileSystem = new TestFileSystem(_tempRoot.FullName); - Directory.CreateDirectory(_globalConfigDirectory); - await File.WriteAllTextAsync( - Path.Combine(_globalConfigDirectory, "instance-id"), - "winner-id", - TestContext.Current.CancellationToken); - var provider = new NitroInstanceIdProvider(fileSystem, () => null); - - // act - var id = await provider.GetIdAsync(_globalConfigDirectory, TestContext.Current.CancellationToken); - - // assert - Assert.Equal("winner-id", id); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/SessionPingGateStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/SessionPingGateStoreTests.cs deleted file mode 100644 index 7345a4acb32..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/SessionPingGateStoreTests.cs +++ /dev/null @@ -1,212 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Agents; - -/// -/// Exercises 's atomic claim-or-steal-expired -/// upsert directly against a real workspace database. -/// -public sealed class SessionPingGateStoreTests : IDisposable -{ - private static readonly AgentSessionGeneration s_generation = - new("claude-code", "session-1", "host-a"); - - private readonly DirectoryInfo _tempRoot; - private readonly string _workspaceDirectory; - private readonly TestFileSystem _fileSystem; - private readonly AgentDatabase _database; - private readonly SessionPingGateStore _gates; - - public SessionPingGateStoreTests() - { - _tempRoot = Directory.CreateTempSubdirectory("nitro-session-ping-gate-store-tests"); - _workspaceDirectory = AgentWorkspace.GetDirectory(_tempRoot.FullName); - Directory.CreateDirectory(_workspaceDirectory); - _fileSystem = new TestFileSystem(_tempRoot.FullName); - _database = new AgentDatabase(); - _gates = new SessionPingGateStore(_fileSystem, _database); - } - - public void Dispose() => _tempRoot.Delete(recursive: true); - - [Fact] - public async Task TryAcquireAsync_Should_ClaimTheGate_When_NoneIsHeld() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - - // act - var claimed = await _gates.TryAcquireAsync(s_generation, "attempt-1", now, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.True(claimed); - } - - [Fact] - public async Task TryAcquireAsync_Should_ReturnFalse_When_GateIsHeldAndUnexpired() - { - // arrange: mutual exclusion for one exact session generation. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", now, TimeSpan.FromSeconds(30), cancellationToken); - - // act - var claimed = await _gates.TryAcquireAsync(s_generation, "attempt-2", now, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.False(claimed); - } - - [Fact] - public async Task TryAcquireAsync_Should_AllowDifferentGenerations_When_SameSessionIdOnDifferentPid() - { - // arrange - // Use the same harness and session id on a different host. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", now, TimeSpan.FromSeconds(30), cancellationToken); - var otherGeneration = s_generation with { Host = "host-other" }; - - // act - var claimed = - await _gates.TryAcquireAsync(otherGeneration, "attempt-2", now, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.True(claimed); - } - - [Fact] - public async Task TryAcquireAsync_Should_StealAnExpiredGate() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", acquiredAt, TimeSpan.FromSeconds(30), cancellationToken); - - // act - var later = acquiredAt + TimeSpan.FromSeconds(31); - var claimed = await _gates.TryAcquireAsync(s_generation, "attempt-2", later, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.True(claimed); - } - - [Fact] - public async Task TryRenewAsync_Should_ExtendExpiry_When_AttemptIdStillHoldsTheGate() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); - var justBeforeExpiry = acquiredAt + TimeSpan.FromSeconds(9); - - // act - var renewed = await _gates.TryRenewAsync( - s_generation, "attempt-1", justBeforeExpiry, TimeSpan.FromSeconds(10), cancellationToken); - - // assert - Assert.True(renewed); - var stillHeld = await _gates.TryAcquireAsync( - s_generation, "attempt-2", acquiredAt + TimeSpan.FromSeconds(11), TimeSpan.FromSeconds(10), cancellationToken); - Assert.False(stillHeld); - } - - [Fact] - public async Task TryRenewAsync_Should_ReturnFalse_When_LeaseHasAlreadyExpired() - { - // arrange: a lost gate can never be renewed back to life. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var acquiredAt = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", acquiredAt, TimeSpan.FromSeconds(10), cancellationToken); - var afterExpiry = acquiredAt + TimeSpan.FromSeconds(11); - - // act - var renewed = - await _gates.TryRenewAsync(s_generation, "attempt-1", afterExpiry, TimeSpan.FromSeconds(10), cancellationToken); - - // assert - Assert.False(renewed); - } - - [Fact] - public async Task TryRenewAsync_Should_ReturnFalse_When_AttemptIdDoesNotMatch() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", now, TimeSpan.FromSeconds(30), cancellationToken); - - // act - var renewed = await _gates.TryRenewAsync(s_generation, "attempt-stale", now, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.False(renewed); - } - - [Fact] - public async Task ReleaseAsync_Should_FreeTheGate_When_AttemptIdMatches() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", now, TimeSpan.FromSeconds(30), cancellationToken); - - // act - await _gates.ReleaseAsync(s_generation, "attempt-1", cancellationToken); - var reclaimed = await _gates.TryAcquireAsync(s_generation, "attempt-2", now, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.True(reclaimed); - } - - [Fact] - public async Task ReleaseAsync_Should_BeANoOp_When_AttemptIdDoesNotMatch() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - await _gates.TryAcquireAsync(s_generation, "attempt-1", now, TimeSpan.FromSeconds(30), cancellationToken); - - // act - await _gates.ReleaseAsync(s_generation, "attempt-stale", cancellationToken); - var stillHeld = await _gates.TryAcquireAsync(s_generation, "attempt-2", now, TimeSpan.FromSeconds(30), cancellationToken); - - // assert - Assert.False(stillHeld); - } - - [Fact] - public async Task TryAcquireAsync_Should_ClaimExactlyOnce_When_SixConcurrentCallersRaceTheSameGeneration() - { - // arrange: separate connections racing the same generation, Pooling=False as in production. - var cancellationToken = TestContext.Current.CancellationToken; - await InitializeWorkspaceAsync(cancellationToken); - var now = new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero); - - // act - var results = await ConcurrentTestHarness.RunAsync( - 6, - i => new SessionPingGateStore(_fileSystem, _database) - .TryAcquireAsync(s_generation, $"attempt-{i}", now, TimeSpan.FromSeconds(30), cancellationToken)); - - // assert: exactly one caller claimed the gate. - Assert.Equal(1, results.Count(claimed => claimed)); - } - - private async Task InitializeWorkspaceAsync(CancellationToken cancellationToken) - { - await using (await _database.InitializeAsync(_workspaceDirectory, cancellationToken)) - { - } - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentDatabaseTests.InitializeAsync_Should_AddMailWakeAndAgentPingGateTables_When_ExistingVersionIsV6.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentDatabaseTests.InitializeAsync_Should_AddMailWakeAndAgentPingGateTables_When_ExistingVersionIsV6.md new file mode 100644 index 00000000000..a6d915cf288 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentDatabaseTests.InitializeAsync_Should_AddMailWakeAndAgentPingGateTables_When_ExistingVersionIsV6.md @@ -0,0 +1,54 @@ +# InitializeAsync_Should_AddMailWakeAndAgentPingGateTables_When_ExistingVersionIsV6 + +## Version + +```json +18 +``` + +## Tables + +```json +[ + "mail_wake_outbox", + "mail_wake_batches", + "mail_wake_targets", + "mail_wake_daemons", + "agent_ping_gates" +] +``` + +## Indexes + +```json +[ + "idx_mail_wake_outbox_due", + "idx_mail_wake_batches_one_active_per_actor", + "idx_mail_wake_batches_expires", + "idx_agent_ping_gates_expires" +] +``` + +## AgentCount + +```json +0 +``` + +## MessageCount + +```json +1 +``` + +## RecipientCount + +```json +1 +``` + +## LeaseCount + +```json +0 +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentDatabaseTests.InitializeAsync_Should_CreateAllSchemasAndStampCurrentVersion_When_DatabaseIsNew.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentDatabaseTests.InitializeAsync_Should_CreateAllSchemasAndStampCurrentVersion_When_DatabaseIsNew.md new file mode 100644 index 00000000000..247e9d5e004 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentDatabaseTests.InitializeAsync_Should_CreateAllSchemasAndStampCurrentVersion_When_DatabaseIsNew.md @@ -0,0 +1,64 @@ +# InitializeAsync_Should_CreateAllSchemasAndStampCurrentVersion_When_DatabaseIsNew + +## Version + +```json +18 +``` + +## Tables + +```json +[ + "tasks", + "messages", + "agents", + "ping_leases", + "agent_deliveries", + "agent_ping_gates", + "mail_wake_outbox", + "mail_wake_batches", + "mail_wake_targets", + "mail_wake_daemons" +] +``` + +## Indexes + +```json +[ + "idx_mail_wake_outbox_due", + "idx_mail_wake_batches_one_active_per_actor", + "idx_mail_wake_batches_expires", + "idx_agent_ping_gates_expires" +] +``` + +## AgentColumns + +```json +[ + "name", + "role", + "harness", + "harness_version", + "session_id", + "cwd", + "workspace_path", + "registered_at", + "started_at", + "last_seen_at", + "ended_at", + "deleted_at", + "endpoint_kind", + "endpoint_addr", + "endpoint_secret", + "block_budget_used", + "last_ping_at", + "last_ping_attempt", + "last_ping_result", + "last_ping_detail", + "announcement_pending", + "idle_push_armed" +] +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_ReleaseInProgressTaskAndRecordEvent_When_AgentHasAssignedTask.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_ReleaseInProgressTaskAndRecordEvent_When_AgentHasAssignedTask.md new file mode 100644 index 00000000000..e2244088596 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_ReleaseInProgressTaskAndRecordEvent_When_AgentHasAssignedTask.md @@ -0,0 +1,22 @@ +# DeleteAsync_Should_ReleaseInProgressTaskAndRecordEvent_When_AgentHasAssignedTask + +## Status + +```text +open +``` + +## Assignee + +```json +null +``` + +## EventTypes + +```json +[ + "assignee_changed", + "status_changed" +] +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_RemoveWakeAndPingSideRows_When_RowExists.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_RemoveWakeAndPingSideRows_When_RowExists.md new file mode 100644 index 00000000000..f881923db00 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_RemoveWakeAndPingSideRows_When_RowExists.md @@ -0,0 +1,31 @@ +# DeleteAsync_Should_RemoveWakeAndPingSideRows_When_RowExists + +## Deliveries + +```json +0 +``` + +## PingGates + +```json +0 +``` + +## Outbox + +```json +0 +``` + +## Batches + +```json +0 +``` + +## Targets + +```json +0 +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_StampAndClearTheRow_When_RowExists.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_StampAndClearTheRow_When_RowExists.md new file mode 100644 index 00000000000..e320df00169 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteAsync_Should_StampAndClearTheRow_When_RowExists.md @@ -0,0 +1,67 @@ +# DeleteAsync_Should_StampAndClearTheRow_When_RowExists + +## IsDeleted + +```json +true +``` + +## EndpointKind + +```text +none +``` + +## EndpointAddr + +```text + +``` + +## EndpointSecret + +```json +null +``` + +## LastPingAt + +```json +null +``` + +## LastPingAttempt + +```json +null +``` + +## LastPingResult + +```json +null +``` + +## LastPingDetail + +```json +null +``` + +## AnnouncementPending + +```json +false +``` + +## IdlePushArmed + +```json +false +``` + +## BlockBudgetUsed + +```json +0 +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteInactiveAsync_Should_DeleteOfflineAndIdleRows_When_Called.md b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteInactiveAsync_Should_DeleteOfflineAndIdleRows_When_Called.md new file mode 100644 index 00000000000..cfb3fd75919 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Services/Workspace/__snapshots__/AgentStoreTests.DeleteInactiveAsync_Should_DeleteOfflineAndIdleRows_When_Called.md @@ -0,0 +1,31 @@ +# DeleteInactiveAsync_Should_DeleteOfflineAndIdleRows_When_Called + +## DeletedCount + +```json +2 +``` + +## OnlineDeleted + +```json +false +``` + +## UnreachableDeleted + +```json +false +``` + +## IdleDeleted + +```json +true +``` + +## OfflineDeleted + +```json +true +``` diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentDetailModelTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentDetailModelTests.cs deleted file mode 100644 index 295f0705099..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentDetailModelTests.cs +++ /dev/null @@ -1,203 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Tasks; -using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tui.Agents; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -public sealed class AgentDetailModelTests -{ - private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - - private static AgentRecord Agent(string name, string role = "") - => new() - { - Name = name, - Role = role, - Client = "", - Implicit = false, - RegisteredAt = s_now, - LastSeenAt = s_now - }; - - private static AgentDetailModel CreateModel(FakeTaskStore taskStore, FakeMailStore mailStore) - => new(taskStore, mailStore); - - [Fact] - public async Task LoadAsync_Should_LoadBoundIdentity_FromTheParticipant() - { - // arrange - var participant = AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", agent: Agent("agent-a", role: "backend")); - var model = CreateModel(new FakeTaskStore(), new FakeMailStore()); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(new AgentSessionKey("claude-code", "s-a"), model.CurrentKey); - Assert.NotNull(model.Participant); - Assert.NotNull(model.Participant!.Agent); - Assert.Equal("backend", model.Participant!.Agent!.Role); - } - - [Fact] - public async Task LoadAsync_Should_LeaveAgentNull_When_TheSessionIsUnbound() - { - // arrange - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: null); - var model = CreateModel(new FakeTaskStore(), new FakeMailStore()); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(new AgentSessionKey("claude-code", "s-a"), model.CurrentKey); - Assert.NotNull(model.Participant); - Assert.Null(model.Participant!.Agent); - } - - [Fact] - public async Task LoadAsync_Should_OrderTasks_InProgressFirstThenOpenThenOthers() - { - // arrange - var taskStore = new FakeTaskStore(); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-open", status: TaskStates.Open, assignee: "agent-a")); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-deferred", status: TaskStates.Deferred, assignee: "agent-a")); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-progress", status: TaskStates.InProgress, assignee: "agent-a")); - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a"); - var model = CreateModel(taskStore, new FakeMailStore()); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(["a-progress", "a-open", "a-deferred"], model.Tasks.Select(t => t.Id)); - } - - [Fact] - public async Task LoadAsync_Should_OnlyIncludeTasksAssignedToTheBoundActor() - { - // arrange - var taskStore = new FakeTaskStore(); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-1", assignee: "agent-a")); - taskStore.Tasks.Add(TaskItemBuilder.Create("b-1", assignee: "agent-b")); - taskStore.Tasks.Add(TaskItemBuilder.Create("unassigned")); - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a"); - var model = CreateModel(taskStore, new FakeMailStore()); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(["a-1"], model.Tasks.Select(t => t.Id)); - } - - [Fact] - public async Task LoadAsync_Should_ExcludeClosedAndTombstoneTasks_ByDefault() - { - // arrange - var taskStore = new FakeTaskStore(); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-open", status: TaskStates.Open, assignee: "agent-a")); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-closed", status: TaskStates.Closed, assignee: "agent-a")); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-tombstone", status: TaskStates.Tombstone, assignee: "agent-a")); - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a"); - var model = CreateModel(taskStore, new FakeMailStore()); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(["a-open"], model.Tasks.Select(t => t.Id)); - } - - [Fact] - public async Task LoadAsync_Should_LoadSentMail_ThroughMailStore() - { - // arrange - var mailStore = new FakeMailStore(); - mailStore.Messages.Add(MailMessageBuilder.Create("m-1", sender: "agent-a")); - mailStore.Messages.Add(MailMessageBuilder.Create("m-2", sender: "agent-b")); - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a"); - var model = CreateModel(new FakeTaskStore(), mailStore); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(["m-1"], model.SentMail.Select(m => m.Id)); - } - - [Fact] - public async Task LoadAsync_Should_CapSentMail_AtTwenty() - { - // arrange - var mailStore = new FakeMailStore(); - - for (var i = 0; i < 25; i++) - { - mailStore.Messages.Add(MailMessageBuilder.Create( - $"m-{i:D2}", sender: "agent-a", createdAt: s_now.AddMinutes(i))); - } - - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a"); - var model = CreateModel(new FakeTaskStore(), mailStore); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Equal(20, model.SentMail.Count); - } - - [Fact] - public async Task LoadAsync_Should_LoadNoTasksOrMail_When_TheSessionIsUnbound() - { - // arrange - var taskStore = new FakeTaskStore(); - taskStore.Tasks.Add(TaskItemBuilder.Create("a-1", assignee: "agent-a")); - var mailStore = new FakeMailStore(); - mailStore.Messages.Add(MailMessageBuilder.Create("m-1", sender: "agent-a")); - var participant = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: null); - var model = CreateModel(taskStore, mailStore); - - // act - await model.LoadAsync(participant, CancellationToken.None); - - // assert - Assert.Empty(model.Tasks); - Assert.Empty(model.SentMail); - } - - [Fact] - public async Task LoadAsync_Should_ReplaceWhicheverParticipantWasPreviouslyLoaded() - { - // arrange - var participantA = AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a"); - var participantB = AgentSessionParticipantBuilder.Participant(sessionId: "s-b", agentName: "agent-b"); - var model = CreateModel(new FakeTaskStore(), new FakeMailStore()); - await model.LoadAsync(participantA, CancellationToken.None); - - // act - await model.LoadAsync(participantB, CancellationToken.None); - - // assert - Assert.Equal(new AgentSessionKey("claude-code", "s-b"), model.CurrentKey); - Assert.Equal("agent-b", model.Participant?.Session.AgentName); - } - - [Fact] - public void Clear_Should_ResetToUnloadedState() - { - // arrange - var model = CreateModel(new FakeTaskStore(), new FakeMailStore()); - - // act - model.Clear(); - - // assert - Assert.Null(model.CurrentKey); - Assert.Null(model.Participant); - Assert.Empty(model.Tasks); - Assert.Empty(model.SentMail); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentDetailViewTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentDetailViewTests.cs deleted file mode 100644 index f59fbbe3499..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentDetailViewTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Tui.Agents; -using Microsoft.Extensions.Time.Testing; -using Spectre.Console.Testing; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -public sealed class AgentDetailViewTests -{ - [Fact] - public async Task Render_Should_RenderTruncationMarker_When_ContentInteriorIsOneColumn() - { - // arrange - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var taskStore = new FakeTaskStore(); - taskStore.Tasks.Add(TaskItemBuilder.Create("t-1", assignee: "agent-a")); - var mailStore = new FakeMailStore(); - mailStore.Messages.Add(MailMessageBuilder.Create("m-1", sender: "agent-a", createdAt: now)); - var model = new AgentDetailModel(taskStore, mailStore); - await model.LoadAsync( - AgentSessionParticipantBuilder.Participant(agentName: "agent-a"), - CancellationToken.None); - var view = new AgentDetailView(model, new FakeTimeProvider(now)); - var console = new TestConsole().Width(5).Height(1_000); - - // act - console.Write(view.Render(width: 5, height: 1_000, focused: true)); - - // assert - Assert.Equal(2, console.Output.Count(c => c == 'โ€ฆ')); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentPopoverModelTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentPopoverModelTests.cs new file mode 100644 index 00000000000..a3d6f211a67 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentPopoverModelTests.cs @@ -0,0 +1,921 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; +using ChilliCream.Nitro.CommandLine.Tui.Agents; +using ChilliCream.Nitro.CommandLine.Tui.Input; +using ChilliCream.Nitro.CommandLine.Tui.Shell; +using Microsoft.Extensions.Time.Testing; +using Spectre.Console; +using Spectre.Console.Testing; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; + +/// +/// Exercises against fakes: loading the header and +/// participation sections, cursor navigation, the show-more list, the delete and copy +/// gestures, and tick-driven age recomputation. +/// +public sealed class AgentPopoverModelTests +{ + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private static ConsoleKeyInfo Key(ConsoleKey key, char ch = '\0') => new(ch, key, false, false, false); + + private static string RenderToText(AgentPopoverModel model, int width = 100, int height = 30) + { + var console = new TestConsole().Width(width); + console.Write(model.Render(width, height)); + return console.Output; + } + + private static string RenderToAnsiText(AgentPopoverModel model, int width = 100, int height = 30) + { + var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(width); + console.Write(model.Render(width, height)); + return console.Output; + } + + private static string RenderMarkupToAnsiText(string markupLine) + { + var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(200); + console.Write(new Markup(markupLine)); + return console.Output; + } + + private static AgentRow AddOnlineAgent(FakeAgentStore store, string sessionId) + => store.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = AgentSessionHarness.ClaudeCode, + SessionId = sessionId, + HarnessVersion = "1.0.0", + Cwd = "", + WorkspacePath = "", + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1" + }, + TestContext.Current.CancellationToken) + .GetAwaiter().GetResult().Row!; + + private static AgentRow LoginAgent(FakeAgentStore store) + => store.LoginAsync(TestContext.Current.CancellationToken).GetAwaiter().GetResult(); + + private static void EndSession(FakeAgentStore store, AgentRow agent) + => store.EndSessionAsync(agent.Harness!, agent.SessionId!, TestContext.Current.CancellationToken) + .GetAwaiter().GetResult(); + + private static AgentPopoverModel CreateModel( + string name, + FakeAgentStore agentStore, + FakeMailStore? mailStore = null, + FakeTaskStore? taskStore = null, + FakeMemoryStore? memoryStore = null, + TimeProvider? timeProvider = null) + => new( + name, + agentStore, + mailStore ?? new FakeMailStore(), + taskStore ?? new FakeTaskStore(), + memoryStore ?? new FakeMemoryStore(), + timeProvider ?? new FakeTimeProvider(s_now)); + + [Fact] + public void Render_Should_ShowTheHarnessAndSessionId_When_TheAgentIsAHookAgent() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var model = CreateModel(agent.Name, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("claude-code 1.0.0", text); + Assert.Contains("s-a", text); + } + + [Fact] + public void Render_Should_ShowDashesForHarnessAndSession_When_TheAgentIsLoginOnly() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = LoginAgent(agentStore); + var model = CreateModel(agent.Name, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Harness: -", text); + Assert.Contains("Session id: -", text); + } + + [Fact] + public void Render_Should_ShowTheEndedRow_When_TheAgentSessionHasEnded() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + EndSession(agentStore, agent); + var model = CreateModel(agent.Name, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Ended:", text); + } + + [Fact] + public void Render_Should_ShowNotFound_When_TheAgentCannotBeLoaded() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var model = CreateModel("nobody", agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Agent not found.", text); + } + + [Fact] + public void Render_Should_ShowSpacerLinesAndSectionTitles_When_ThereAreTwoItemsPerSection() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0), CreateMailSummary(1)] }; + var taskStore = new FakeTaskStore + { + ParticipationRows = [TaskItemBuilder.Create("a1", "First"), TaskItemBuilder.Create("a2", "Second")] + }; + var memoryStore = new FakeMemoryStore { ParticipationRows = [CreateMemoryEntry(0), CreateMemoryEntry(1)] }; + var model = CreateModel(agent.Name, agentStore, mailStore, taskStore, memoryStore); + model.Load(TestContext.Current.CancellationToken); + var console = new TestConsole().Width(100); + + // act + console.Write(model.Render(100, 30)); + + // assert + console.Output.MatchInlineSnapshot( + """ + + + + โ•ญโ”€ackbarโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ State: โ— Online โ”‚ + โ”‚ Role: - โ”‚ + โ”‚ Harness: claude-code 1.0.0 โ”‚ + โ”‚ Session id: s-a โ”‚ + โ”‚ Started: just now โ”‚ + โ”‚ Last Seen: just now โ”‚ + โ”‚ โ”‚ + โ”‚ Mail (last 10) โ”‚ + โ”‚ now Subject 0 felix -> oscar (1) โ”‚ + โ”‚ now Subject 1 felix -> oscar (1) โ”‚ + โ”‚ โ€บ show more โ”‚ + โ”‚ โ”‚ + โ”‚ Tickets (last 10) โ”‚ + โ”‚ a1 open First โ”‚ + โ”‚ a2 open Second โ”‚ + โ”‚ โ€บ show more โ”‚ + โ”‚ โ”‚ + โ”‚ Memory (last 10) โ”‚ + โ”‚ journal now Memory 0 โ”‚ + โ”‚ journal now Memory 1 โ”‚ + โ”‚ โ€บ show more โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + + + """); + } + + [Fact] + public void HandleKey_Should_SkipTheSpacerAndSectionTitle_When_JMovesFromMailShowMoreIntoTickets() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mail = new[] { CreateMailSummary(0), CreateMailSummary(1) }; + var tickets = new[] { TaskItemBuilder.Create("a1", "First"), TaskItemBuilder.Create("a2", "Second") }; + var memory = new[] { CreateMemoryEntry(0), CreateMemoryEntry(1) }; + var model = CreateModel( + agent.Name, + agentStore, + new FakeMailStore { ParticipationRows = mail }, + new FakeTaskStore { ParticipationRows = tickets }, + new FakeMemoryStore { ParticipationRows = memory }); + model.Load(TestContext.Current.CancellationToken); + var highlighted = AgentPopoverView.BuildLines( + agent, mail, tickets, memory, s_now, 200, (AgentPopoverSection.Tickets, false, 0)); + var unselected = AgentPopoverView.BuildLines( + agent, mail, tickets, memory, s_now, 200, (AgentPopoverSection.Mail, false, 0)); + var expectedHighlightAnsi = RenderMarkupToAnsiText(highlighted.Lines[highlighted.SelectedLineIndex]); + var expectedTitleAnsi = RenderMarkupToAnsiText( + unselected.Lines.First(line => Markup.Remove(line) == "Tickets (last 10)")); + + // act + MoveCursorDown(model, 3); + var output = RenderToAnsiText(model); + + // assert + Assert.Contains(expectedHighlightAnsi, output); + Assert.Contains(expectedTitleAnsi, output); + } + + [Fact] + public void HandleKey_Should_SkipTheSpacerAndSectionTitle_When_KMovesFromTicketsBackToMailShowMore() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mail = new[] { CreateMailSummary(0), CreateMailSummary(1) }; + var tickets = new[] { TaskItemBuilder.Create("a1", "First"), TaskItemBuilder.Create("a2", "Second") }; + var memory = new[] { CreateMemoryEntry(0), CreateMemoryEntry(1) }; + var model = CreateModel( + agent.Name, + agentStore, + new FakeMailStore { ParticipationRows = mail }, + new FakeTaskStore { ParticipationRows = tickets }, + new FakeMemoryStore { ParticipationRows = memory }); + model.Load(TestContext.Current.CancellationToken); + var highlighted = AgentPopoverView.BuildLines( + agent, mail, tickets, memory, s_now, 200, (AgentPopoverSection.Mail, true, -1)); + var expectedHighlightAnsi = RenderMarkupToAnsiText(highlighted.Lines[highlighted.SelectedLineIndex]); + + // act + MoveCursorDown(model, 3); + model.HandleKey(Key(ConsoleKey.K, 'k')); + var output = RenderToAnsiText(model); + + // assert + Assert.Contains(expectedHighlightAnsi, output); + } + + [Fact] + public void Render_Should_ShowExactlyTenMailRowsAndAShowMoreRow_When_ThereAreTwelveMailThreads() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore + { + ParticipationRows = [.. Enumerable.Range(0, 12).Select(CreateMailSummary)] + }; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + var rowCount = text.Split("Subject ").Length - 1; + + // assert + Assert.Equal(10, rowCount); + Assert.Contains("show more", text); + } + + [Fact] + public void HandleKey_Should_OpenTheFullMailList_When_EnterIsPressedOnTheShowMoreRow() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore + { + ParticipationRows = [CreateMailSummary(0), CreateMailSummary(1)] + }; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + model.HandleKey(Key(ConsoleKey.J, 'j')); + model.HandleKey(Key(ConsoleKey.J, 'j')); + + // act + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + Assert.Contains("Mail (2)", text); + Assert.Contains("Subject 0", text); + } + + [Fact] + public void HandleKey_Should_ReturnToTheSummary_When_EscapeIsPressedInTheFullList() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore + { + ParticipationRows = [CreateMailSummary(0), CreateMailSummary(1)] + }; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + model.HandleKey(Key(ConsoleKey.J, 'j')); + model.HandleKey(Key(ConsoleKey.J, 'j')); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + var result = model.HandleKey(Key(ConsoleKey.Escape)); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Harness:", text); + } + + [Fact] + public void HandleKey_Should_ReturnDeleteRequested_When_DIsPressed() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var model = CreateModel(agent.Name, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.D, 'd')); + + // assert + var request = Assert.IsType(result); + var delete = Assert.IsType(request.Payload); + Assert.Equal(agent.Name, delete.Name); + } + + [Fact] + public void HandleKey_Should_ReturnCopyRequestedWithTheAgentsOwnSessionId_When_YIsPressed() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var model = CreateModel(agent.Name, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Y, 'y')); + + // assert + var request = Assert.IsType(result); + var copy = Assert.IsType(request.Payload); + Assert.Equal((agent.Name, agent.SessionId), (copy.Name, copy.SessionId)); + } + + [Fact] + public void HandleKey_Should_OpenTheMailThreadDetail_When_EnterIsPressedOnAMailRow() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0)] }; + mailStore.Threads["t0"] = [CreateMailMessage("t0", "m1", "felix", "Subject 0", "Body text 0")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Body text 0", text); + Assert.Equal(AgentPopoverModel.DetailHints, model.Hints); + } + + [Fact] + public void HandleKey_Should_LeaveReadAtUntouched_When_OpeningAMailThreadFromTheSummary() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0)] }; + mailStore.Threads["t0"] = [CreateMailMessage("t0", "m1", "felix", "Subject 0", "Body text 0")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + + // act + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // assert + Assert.Equal(["t0"], mailStore.LoadedThreadIds); + Assert.False(mailStore.MarkReadCalled); + } + + [Fact] + public void HandleKey_Should_OpenTheTicketDetail_When_EnterIsPressedOnATicketRow() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var task = TaskItemBuilder.Create("a1", "Fix the thing"); + var taskStore = new FakeTaskStore { ParticipationRows = [task] }; + taskStore.Tasks[task.Id] = task; + var model = CreateModel(agent.Name, agentStore, taskStore: taskStore); + model.Load(TestContext.Current.CancellationToken); + + // act + // Mail has no rows, so cursor 1 is the ticket's first item. + MoveCursorDown(model, 1); + var result = model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Fix the thing", text); + } + + [Fact] + public void HandleKey_Should_OpenTheJournalMemoryDetail_When_EnterIsPressedOnAMemoryRow() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var memoryStore = new FakeMemoryStore { ParticipationRows = [CreateMemoryEntry(0)] }; + memoryStore.JournalEntries["j0"] = new MemoryJournalEntry + { + Id = "j0", + Body = "Journal body 0", + CreatedAt = s_now, + CreatedBy = "felix" + }; + var model = CreateModel(agent.Name, agentStore, memoryStore: memoryStore); + model.Load(TestContext.Current.CancellationToken); + + // act + // Mail and tickets have no rows, so cursor 2 is memory's first item. + MoveCursorDown(model, 2); + var result = model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Journal body 0", text); + } + + [Fact] + public void HandleKey_Should_RenderTheJournalEntryWithoutTheMemoryTabActionHint_When_EnterIsPressedOnAJournalRow() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var memoryStore = new FakeMemoryStore { ParticipationRows = [CreateMemoryEntry(0)] }; + memoryStore.JournalEntries["j0"] = new MemoryJournalEntry + { + Id = "j0", + Body = "Journal body 0", + CreatedAt = s_now, + CreatedBy = "felix" + }; + var model = CreateModel(agent.Name, agentStore, memoryStore: memoryStore); + model.Load(TestContext.Current.CancellationToken); + + // act + // Mail and tickets have no rows, so cursor 2 is memory's first item. + MoveCursorDown(model, 2); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + text.MatchInlineSnapshot( + """ + โ•ญโ”€j0โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ Created: 2026-01-01T00:00:00Z by felix โ”‚ + โ”‚ โ”‚ + โ”‚ Journal body 0 โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + """); + } + + [Fact] + public void HandleKey_Should_OpenTheCuratedMemoryDetail_When_TheSelectedMemoryRowIsCurated() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var memoryStore = new FakeMemoryStore + { + ParticipationRows = [new MemoryParticipationEntry(MemoryParticipationKind.Curated, "m0", "note", [], "Curated body 0", s_now)] + }; + memoryStore.CuratedRecords["m0"] = new MemoryRecord + { + Id = "m0", + Type = "note", + Tags = [], + Body = "Curated body 0", + CreatedAt = s_now, + UpdatedAt = s_now, + CreatedBy = "felix" + }; + var model = CreateModel(agent.Name, agentStore, memoryStore: memoryStore); + model.Load(TestContext.Current.CancellationToken); + + // act + MoveCursorDown(model, 2); + var result = model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Curated body 0", text); + } + + [Fact] + public void HandleKey_Should_OpenTheItemDetail_When_EnterIsPressedInsideTheFullList() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0), CreateMailSummary(1)] }; + mailStore.Threads["t0"] = [CreateMailMessage("t0", "m1", "felix", "Subject 0", "Body text 0")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + MoveCursorDown(model, 2); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + var result = model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Body text 0", text); + } + + [Fact] + public void HandleKey_Should_ReturnToTheSummaryWithCursorUnchanged_When_EscapeIsPressedInADetailOpenedFromTheSummary() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mail = new[] { CreateMailSummary(0), CreateMailSummary(1) }; + var mailStore = new FakeMailStore { ParticipationRows = mail }; + mailStore.Threads["t1"] = [CreateMailMessage("t1", "m2", "felix", "Subject 1", "Body text 1")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + MoveCursorDown(model, 1); + var expected = AgentPopoverView.BuildLines(agent, mail, [], [], s_now, 200, (AgentPopoverSection.Mail, false, 1)); + var expectedHighlightAnsi = RenderMarkupToAnsiText(expected.Lines[expected.SelectedLineIndex]); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + var result = model.HandleKey(Key(ConsoleKey.Escape)); + var output = RenderToAnsiText(model); + + // assert + Assert.Null(result); + Assert.Contains(expectedHighlightAnsi, output); + } + + [Fact] + public void HandleKey_Should_ReturnToTheFullList_When_EscapeIsPressedInADetailOpenedFromTheShowMoreList() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0), CreateMailSummary(1)] }; + mailStore.Threads["t0"] = [CreateMailMessage("t0", "m1", "felix", "Subject 0", "Body text 0")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + MoveCursorDown(model, 2); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + var result = model.HandleKey(Key(ConsoleKey.Escape)); + var text = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Contains("Mail (2)", text); + } + + [Fact] + public void HandleKey_Should_ReturnCopyItemRequestedWithTheThreadId_When_YIsPressedInAMailDetail() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0)] }; + mailStore.Threads["t0"] = [CreateMailMessage("t0", "m1", "felix", "Subject 0", "Body text 0")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + var result = model.HandleKey(Key(ConsoleKey.Y, 'y')); + + // assert + var request = Assert.IsType(result); + var copy = Assert.IsType(request.Payload); + Assert.Equal("t0", copy.Id); + } + + [Fact] + public void HandleKey_Should_ReturnCopyItemRequestedWithTheTaskId_When_YIsPressedInATicketDetail() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var task = TaskItemBuilder.Create("a1", "Fix the thing"); + var taskStore = new FakeTaskStore { ParticipationRows = [task] }; + taskStore.Tasks[task.Id] = task; + var model = CreateModel(agent.Name, agentStore, taskStore: taskStore); + model.Load(TestContext.Current.CancellationToken); + MoveCursorDown(model, 1); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + var result = model.HandleKey(Key(ConsoleKey.Y, 'y')); + + // assert + var request = Assert.IsType(result); + var copy = Assert.IsType(request.Payload); + Assert.Equal("a1", copy.Id); + } + + [Fact] + public void HandleKey_Should_ScrollTheDetailBody_When_JIsPressedInAMailDetail() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0)] }; + mailStore.Threads["t0"] = + [ + CreateMailMessage("t0", "m1", "felix", "Subject 0", string.Join('\n', Enumerable.Range(0, 40).Select(i => $"Line {i}"))) + ]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var before = RenderToText(model, height: 10); + + // act + for (var i = 0; i < 5; i++) + { + model.HandleKey(Key(ConsoleKey.J, 'j')); + } + + var after = RenderToText(model, height: 10); + + // assert + Assert.NotEqual(before, after); + } + + [Fact] + public void Hints_Should_ReturnDetailHints_When_ANestedDetailIsOpen() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0)] }; + mailStore.Threads["t0"] = [CreateMailMessage("t0", "m1", "felix", "Subject 0", "Body text 0")]; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore); + model.Load(TestContext.Current.CancellationToken); + + // act + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // assert + Assert.Equal(AgentPopoverModel.DetailHints, model.Hints); + } + + [Fact] + public void SummaryHints_Should_IncludeEnterOpen_When_Inspected() + { + // arrange + // act + var hints = AgentPopoverModel.SummaryHints; + + // assert + Assert.Contains(new KeyHint("enter", "open"), hints); + } + + [Fact] + public void ListHints_Should_IncludeEnterOpen_When_Inspected() + { + // arrange + // act + var hints = AgentPopoverModel.ListHints; + + // assert + Assert.Contains(new KeyHint("enter", "open"), hints); + } + + [Fact] + public void Render_Should_ShowTenRowsInTheSummaryAndAllTwentyFiveInEachShowMoreList_When_ThereAreTwentyFiveOfEachParticipationType() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore + { + ParticipationRows = [.. Enumerable.Range(0, 25).Select(CreateMailSummary)] + }; + var taskStore = new FakeTaskStore + { + ParticipationRows = [.. Enumerable.Range(0, 25).Select(i => TaskItemBuilder.Create($"a{i}", $"Ticket {i}"))] + }; + var memoryStore = new FakeMemoryStore + { + ParticipationRows = [.. Enumerable.Range(0, 25).Select(CreateMemoryEntry)] + }; + var model = CreateModel(agent.Name, agentStore, mailStore, taskStore, memoryStore); + model.Load(TestContext.Current.CancellationToken); + + // act + // height 100 keeps every section and its show-more row on screen; show-more rows sit at cursor 10, 21 and 32 + var summary = RenderToText(model, height: 100); + var summaryCounts = ( + Mail: summary.Split("Subject ").Length - 1, + Tickets: summary.Split("Ticket ").Length - 1, + Memory: summary.Split("journal now Memory ").Length - 1, + ShowMore: summary.Split("show more").Length - 1); + + MoveCursorDown(model, 10); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var mailListCount = RenderToText(model).Split("Subject ").Length - 1; + model.HandleKey(Key(ConsoleKey.Escape)); + + MoveCursorDown(model, 11); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var ticketListCount = RenderToText(model).Split("Ticket ").Length - 1; + model.HandleKey(Key(ConsoleKey.Escape)); + + MoveCursorDown(model, 11); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + var memoryListCount = RenderToText(model).Split("journal now Memory ").Length - 1; + + // assert + Assert.Equal((10, 10, 10, 3), summaryCounts); + Assert.Equal((25, 25, 25), (mailListCount, ticketListCount, memoryListCount)); + } + + [Fact] + public void HandleKey_Should_ReturnClosed_When_EscapeIsPressedAtTheSummaryLevel() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var model = CreateModel(agent.Name, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Escape)); + + // assert + Assert.IsType(result); + } + + [Fact] + public void Tick_Should_ReturnFalse_When_NoTimeHasPassed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var agent = AddOnlineAgent(agentStore, "s-a"); + var model = CreateModel(agent.Name, agentStore, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + + // act + var dirty = model.Tick(); + + // assert + Assert.False(dirty); + } + + [Fact] + public void Tick_Should_ReturnTrueAndUpdateTheLastSeenAge_When_TimeAdvances() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var agent = AddOnlineAgent(agentStore, "s-a"); + var model = CreateModel(agent.Name, agentStore, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + + // act + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = model.Tick(); + var text = RenderToText(model); + + // assert + Assert.True(dirty); + Assert.Contains("2m ago", text); + } + + [Fact] + public void Tick_Should_ReturnTrueAndUpdateTheMailRowAge_When_OnlyAMailThreadAgeChanges() + { + // arrange + // The agent's own LastSeen is already day-old, so only the mail thread's age moves. + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var agent = AddOnlineAgent(agentStore, "s-a"); + time.Advance(TimeSpan.FromDays(2)); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0) with { LastMessageAt = time.GetUtcNow() }] }; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + + // act + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = model.Tick(); + var text = RenderToText(model); + + // assert + Assert.True(dirty); + Assert.Contains("2m", text); + } + + [Fact] + public void Tick_Should_ReturnTrueAndUpdateTheFullListRowAge_When_TimeAdvancesWhileAShowMoreListIsOpen() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var agent = AddOnlineAgent(agentStore, "s-a"); + time.Advance(TimeSpan.FromDays(2)); + var mailStore = new FakeMailStore { ParticipationRows = [CreateMailSummary(0) with { LastMessageAt = time.GetUtcNow() }] }; + var model = CreateModel(agent.Name, agentStore, mailStore: mailStore, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + model.HandleKey(Key(ConsoleKey.J, 'j')); + model.HandleKey(Key(ConsoleKey.Enter, '\r')); + + // act + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = model.Tick(); + var text = RenderToText(model); + + // assert + Assert.True(dirty); + Assert.Contains("2m", text); + } + + private static void MoveCursorDown(AgentPopoverModel model, int times) + { + for (var i = 0; i < times; i++) + { + model.HandleKey(Key(ConsoleKey.J, 'j')); + } + } + + private static MemoryParticipationEntry CreateMemoryEntry(int index) => + new(MemoryParticipationKind.Journal, $"j{index}", null, [], $"Memory {index}", s_now); + + private static MailMessage CreateMailMessage(string threadId, string id, string sender, string subject, string body) => new() + { + Id = id, + ThreadId = threadId, + Sender = sender, + Subject = subject, + Body = body, + CreatedAt = s_now + }; + + private static MailThreadSummary CreateMailSummary(int index) => new() + { + ThreadId = $"t{index}", + Subject = $"Subject {index}", + MessageCount = 1, + LastMessageAt = s_now, + LastSender = "felix", + LastRecipients = ["oscar"], + BodyPreview = "", + UnreadCount = 0, + ArchivedCount = 0 + }; +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentPopoverViewTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentPopoverViewTests.cs new file mode 100644 index 00000000000..e215e66fd33 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentPopoverViewTests.cs @@ -0,0 +1,405 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; +using ChilliCream.Nitro.CommandLine.Tui.Agents; +using Spectre.Console; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; + +/// +/// Exercises 's pure formatting: the header block, the three +/// participation sections, and the individual mail, ticket, and memory row formats. +/// +public sealed class AgentPopoverViewTests +{ + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly (AgentPopoverSection Section, bool IsShowMore, int ItemIndex) s_noSelection = + (AgentPopoverSection.Memory, true, -1); + + private static AgentRow CreateRow( + string role = "", + string? harness = "claude-code", + string harnessVersion = "2.1.0", + string? sessionId = "session-a", + DateTimeOffset? lastSeenAt = null, + DateTimeOffset? endedAt = null) => new() + { + Name = "agent-a", + Role = role, + Harness = harness, + HarnessVersion = harnessVersion, + SessionId = sessionId, + Cwd = "", + WorkspacePath = "", + RegisteredAt = s_now, + StartedAt = s_now, + LastSeenAt = lastSeenAt ?? s_now, + EndedAt = endedAt, + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1", + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; + + private static MailThreadSummary CreateMailSummary( + string threadId, string subject, int unreadCount = 0) => new() + { + ThreadId = threadId, + Subject = subject, + MessageCount = 3, + LastMessageAt = s_now, + LastSender = "felix", + LastRecipients = ["oscar"], + BodyPreview = "", + UnreadCount = unreadCount, + ArchivedCount = 0 + }; + + private static string PlainText(AgentPopoverBuiltLines built) => + string.Join('\n', built.Lines.Select(Markup.Remove)); + + [Fact] + public void BuildLines_Should_ShowHarnessAndSessionId_When_TheAgentIsAHookAgent() + { + // arrange + var row = CreateRow(); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("Harness: claude-code 2.1.0", text); + Assert.Contains("Session id: session-a", text); + } + + [Fact] + public void BuildLines_Should_ShowDashesForHarnessAndSessionId_When_TheAgentIsLoginOnly() + { + // arrange + var row = CreateRow(harness: null, harnessVersion: "", sessionId: null); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("Harness: -", text); + Assert.Contains("Session id: -", text); + } + + [Fact] + public void BuildLines_Should_OmitTheVersion_When_HarnessVersionIsEmpty() + { + // arrange + var row = CreateRow(harnessVersion: ""); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("Harness: claude-code\n", text); + } + + [Fact] + public void BuildLines_Should_ShowIdle_When_LastSeenIsPastTheOnlineWindow() + { + // arrange + var row = CreateRow(lastSeenAt: s_now - AgentStateResolver.OnlineWindow - TimeSpan.FromMinutes(1)); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("State: โ— Idle", text); + } + + [Fact] + public void BuildLines_Should_ShowTheEndedRow_When_EndedAtIsSet() + { + // arrange + var row = CreateRow(endedAt: s_now.AddHours(-1)); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("Ended: 1h ago", text); + } + + [Fact] + public void BuildLines_Should_ShowJustNow_When_LastSeenIsFresh() + { + // arrange + var row = CreateRow(lastSeenAt: s_now); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("Last Seen: just now", text); + } + + [Fact] + public void BuildLines_Should_ShowARelativeAge_When_LastSeenIsMinutesOld() + { + // arrange + var row = CreateRow(lastSeenAt: s_now.AddMinutes(-26)); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("Last Seen: 26m ago", text); + } + + [Fact] + public void BuildLines_Should_ShowABareDate_When_LastSeenIsAtLeastAWeekOld() + { + // arrange + var lastSeenAt = s_now.AddDays(-8); + var row = CreateRow(lastSeenAt: lastSeenAt); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains($"Last Seen: {lastSeenAt.ToUniversalTime():yyyy-MM-dd}\n", text); + } + + [Fact] + public void BuildLines_Should_ShowEmptySectionMessages_When_ThereIsNoParticipation() + { + // arrange + var row = CreateRow(); + + // act + var built = AgentPopoverView.BuildLines(row, [], [], [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("No mail yet", text); + Assert.Contains("No tickets yet", text); + Assert.Contains("No memory yet", text); + } + + [Fact] + public void BuildLines_Should_ShowARowPerTicket_When_ThereAreThreeTickets() + { + // arrange + var row = CreateRow(); + var tickets = new[] + { + TaskItemBuilder.Create("a1", "First"), + TaskItemBuilder.Create("a2", "Second"), + TaskItemBuilder.Create("a3", "Third") + }; + + // act + var built = AgentPopoverView.BuildLines(row, [], tickets, [], s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + Assert.Contains("a1 open First", text); + Assert.Contains("a2 open Second", text); + Assert.Contains("a3 open Third", text); + } + + [Fact] + public void BuildLines_Should_ShowSpacerLinesAndSectionTitles_When_ThereAreTwoItemsPerSection() + { + // arrange + var row = CreateRow(); + var mail = new[] { CreateMailSummary("t1", "Ship it"), CreateMailSummary("t2", "Review PR") }; + var tickets = new[] + { + TaskItemBuilder.Create("a1", "First"), + TaskItemBuilder.Create("a2", "Second") + }; + var memory = new[] + { + new MemoryParticipationEntry(MemoryParticipationKind.Journal, "j1", null, [], "Note one.", s_now), + new MemoryParticipationEntry(MemoryParticipationKind.Journal, "j2", null, [], "Note two.", s_now) + }; + + // act + var built = AgentPopoverView.BuildLines(row, mail, tickets, memory, s_now, 80, s_noSelection); + var text = PlainText(built); + + // assert + text.MatchInlineSnapshot( + """ + + State: โ— Online + Role: - + Harness: claude-code 2.1.0 + Session id: session-a + Started: just now + Last Seen: just now + + Mail (last 10) + now Ship it felix -> oscar (3) + now Review PR felix -> oscar (3) + โ€บ show more + + Tickets (last 10) + a1 open First + a2 open Second + โ€บ show more + + Memory (last 10) + journal now Note one. + journal now Note two. + โ€บ show more + """); + } + + [Fact] + public void BuildLines_Should_MarkTheSelectedRowWithTheHighlightStyle_When_ItIsAMailRow() + { + // arrange + var row = CreateRow(); + var mail = new[] { CreateMailSummary("t1", "Subject") }; + var selected = (AgentPopoverSection.Mail, IsShowMore: false, ItemIndex: 0); + + // act + var built = AgentPopoverView.BuildLines(row, mail, [], [], s_now, 80, selected); + var mailLine = built.Lines[built.SelectedLineIndex]; + + // assert + Assert.Contains("Subject", Markup.Remove(mailLine)); + Assert.NotEqual(Markup.Remove(mailLine), mailLine); + } + + [Fact] + public void FormatMailRow_Should_ReturnPlainContent_When_TheThreadIsRead() + { + // arrange + var summary = CreateMailSummary("t1", "Ship it", unreadCount: 0); + + // act + var line = AgentPopoverView.FormatMailRow(summary, s_now, 80); + + // assert + Assert.Equal("now Ship it felix -> oscar (3)", line); + } + + [Fact] + public void FormatMailRow_Should_WrapInAStyleTag_When_TheThreadIsUnreadForTheAgent() + { + // arrange + var summary = CreateMailSummary("t1", "Ship it", unreadCount: 2); + + // act + var line = AgentPopoverView.FormatMailRow(summary, s_now, 80); + + // assert + Assert.StartsWith("[", line); + Assert.Equal("now Ship it felix -> oscar (3)", Markup.Remove(line)); + } + + [Fact] + public void FormatTicketRow_Should_ReturnPlainContent_When_TheTicketIsOpen() + { + // arrange + var task = TaskItemBuilder.Create("a1", "Fix it"); + + // act + var line = AgentPopoverView.FormatTicketRow(task, 80); + + // assert + Assert.Equal("a1 open Fix it", line); + } + + [Fact] + public void FormatTicketRow_Should_WrapInAStyleTag_When_TheTicketIsClosed() + { + // arrange + var task = TaskItemBuilder.Create("a1", "Fix it", TaskStates.Closed); + + // act + var line = AgentPopoverView.FormatTicketRow(task, 80); + + // assert + Assert.StartsWith("[", line); + Assert.Equal("a1 closed Fix it", Markup.Remove(line)); + } + + [Fact] + public void FormatTicketRow_Should_WrapInAStyleTag_When_TheTicketIsArchived() + { + // arrange + var task = TaskItemBuilder.Create("a1", "Fix it", TaskStates.Archived); + + // act + var line = AgentPopoverView.FormatTicketRow(task, 80); + + // assert + Assert.StartsWith("[", line); + Assert.Equal("a1 archived Fix it", Markup.Remove(line)); + } + + [Fact] + public void FormatMemoryRow_Should_IncludeTheType_When_TheEntryIsCurated() + { + // arrange + var entry = new MemoryParticipationEntry( + MemoryParticipationKind.Curated, "m1", "fact", [], "First line.\nSecond line.", s_now); + + // act + var line = AgentPopoverView.FormatMemoryRow(entry, s_now, 80); + + // assert + Assert.Equal("curated fact now First line.", line); + } + + [Fact] + public void FormatMemoryRow_Should_OmitTheType_When_TheEntryIsAJournalNote() + { + // arrange + var entry = new MemoryParticipationEntry(MemoryParticipationKind.Journal, "j1", null, [], "A note.", s_now); + + // act + var line = AgentPopoverView.FormatMemoryRow(entry, s_now, 80); + + // assert + Assert.Equal("journal now A note.", line); + } + + [Fact] + public void FormatMemoryRow_Should_TrimTheTrailingCarriageReturn_When_TheBodyUsesCrlfLineEndings() + { + // arrange + var entry = new MemoryParticipationEntry( + MemoryParticipationKind.Journal, "j1", null, [], "First line.\r\nSecond line.", s_now); + + // act + var line = AgentPopoverView.FormatMemoryRow(entry, s_now, 80); + + // assert + Assert.Equal("journal now First line.", line); + } + + [Fact] + public void Highlight_Should_WrapContentInTheSelectionStyle_When_Called() + { + // arrange + const string line = "plain text"; + + // act + var highlighted = AgentPopoverView.Highlight(line); + + // assert + Assert.StartsWith("[", highlighted); + Assert.Equal(line, Markup.Remove(highlighted)); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentRowBadgeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentRowBadgeTests.cs index 60e700d770d..d2fa9a7cb76 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentRowBadgeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentRowBadgeTests.cs @@ -8,102 +8,261 @@ public sealed class AgentRowBadgeTests { private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - [Theory] - [InlineData(false, false)] - [InlineData(true, false)] - [InlineData(false, true)] - [InlineData(true, true)] - public void Render_Should_FitNarrowWidth_When_SelectedOrImplicit(bool selected, bool implicitIdentity) + private static AgentRow CreateRow( + string name = "agent-a", + string role = "", + string? harness = "claude-code", + string? sessionId = "session-a", + DateTimeOffset? startedAt = null, + DateTimeOffset? lastSeenAt = null, + string endpointKind = AgentSessionEndpointKind.ClaudePeer, + DateTimeOffset? endedAt = null) => new() + { + Name = name, + Role = role, + Harness = harness, + HarnessVersion = "", + SessionId = sessionId, + Cwd = "", + WorkspacePath = "", + RegisteredAt = s_now, + StartedAt = startedAt ?? s_now, + LastSeenAt = lastSeenAt ?? s_now, + EndedAt = endedAt, + EndpointKind = endpointKind, + EndpointAddr = endpointKind == AgentSessionEndpointKind.None ? "" : "peer-1", + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; + + [Fact] + public void Render_Should_ReturnEmpty_When_MaxWidthIsZero() { // arrange - const int maxWidth = 11; - var agent = implicitIdentity - ? new AgentRecord - { - Name = "agent-a", - Role = "", - Client = "", - Implicit = true, - RegisteredAt = s_now, - LastSeenAt = s_now - } - : null; - var row = new AgentParticipantRow( - AgentSessionParticipantBuilder.Participant(agentName: "agent-a", role: "ๆผขโŒšโค๏ธ1๏ธโƒฃ", agent: agent), - Activity: null); + var row = CreateRow(); var widths = AgentRowBadge.ComputeWidths([row], s_now); // act - var line = AgentRowBadge.Render(row, s_now, selected, maxWidth, widths); + var line = AgentRowBadge.Render(row, s_now, selected: false, maxWidth: 0, widths); // assert - Assert.True(Markup.Remove(line).GetCellWidth() <= maxWidth); + Assert.Empty(line); } [Fact] - public void Render_Should_FitFixedColumns_When_RoleHasNoBudget() + public void Render_Should_ShowEveryColumn_When_MaxWidthFits() { // arrange - const int maxWidth = 47; - var row = new AgentParticipantRow( - AgentSessionParticipantBuilder.Participant(agentName: "agent-a"), - Activity: null); + const int maxWidth = 80; + var row = CreateRow(role: "implementer"); var widths = AgentRowBadge.ComputeWidths([row], s_now); // act var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); // assert - Assert.Equal(" agent-a โ— claude-code started now heard now", line); - Assert.Equal(maxWidth, line.GetCellWidth()); + Assert.Equal(" โ— agent-a implementer Claude Code just now just now ", line); } [Fact] - public void Render_Should_TruncateRoleByDisplayWidth_When_NormalWidthHasPartialRoleBudget() + public void Render_Should_ShowDashForRole_When_RoleIsEmpty() { // arrange - const int maxWidth = 55; - var row = new AgentParticipantRow( - AgentSessionParticipantBuilder.Participant(agentName: "agent-a", role: "ๆผข๐Ÿ˜€โค๏ธ1๏ธโƒฃtail"), - Activity: null); + const int maxWidth = 80; + var row = CreateRow(role: ""); var widths = AgentRowBadge.ComputeWidths([row], s_now); // act var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); // assert - Assert.Equal(" agent-a โ— claude-code ๆผข๐Ÿ˜€โค๏ธโ€ฆ started now heard now", line); - Assert.Equal(maxWidth, line.GetCellWidth()); + Assert.Equal(" โ— agent-a - Claude Code just now just now ", line); } [Fact] - public void Render_Should_ReturnEmpty_When_MaxWidthIsZero() + public void Render_Should_ShowDashForHarness_When_AgentIsLoginOnly() { // arrange - var row = new AgentParticipantRow(AgentSessionParticipantBuilder.Participant(agentName: "agent-a"), Activity: null); + const int maxWidth = 80; + var row = CreateRow(harness: null, sessionId: null, endpointKind: AgentSessionEndpointKind.None); var widths = AgentRowBadge.ComputeWidths([row], s_now); // act - var line = AgentRowBadge.Render(row, s_now, selected: false, maxWidth: 0, widths); + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); // assert - Assert.Empty(line); + Assert.Equal(" โ— agent-a - - just now just now ", line); + } + + [Fact] + public void Render_Should_DropStartedColumn_When_WidthIsTooNarrowForAllColumns() + { + // arrange + const int maxWidth = 65; + var row = CreateRow(role: "implementer"); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + Assert.Equal(" โ— agent-a implementer Claude Code just now ", line); + } + + [Fact] + public void Render_Should_DropHarnessColumn_When_WidthIsTooNarrowForHarnessAndStarted() + { + // arrange + const int maxWidth = 50; + var row = CreateRow(role: "implementer"); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + Assert.Equal(" โ— agent-a implementer just now ", line); + } + + [Fact] + public void Render_Should_TruncateRole_When_WidthIsTooNarrowForNameAndRole() + { + // arrange + const int maxWidth = 30; + var row = CreateRow(name: "a-long-agent-name", role: "implementer"); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + Assert.Equal(" โ— a-long-agent-name implโ€ฆ", line); + } + + [Fact] + public void Render_Should_ShowNameAndRoleOnly_When_WidthIsTooNarrowForLastSeen() + { + // arrange + const int maxWidth = 35; + var row = CreateRow(name: "agent-a", role: "implementer"); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + Assert.Equal(" โ— agent-a implementer ", line); + } + + [Fact] + public void RenderHeader_Should_ShowNameAndRoleOnly_When_WidthIsTooNarrowForLastSeen() + { + // arrange + const int maxWidth = 35; + var row = CreateRow(name: "agent-a", role: "implementer"); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var header = Markup.Remove(AgentRowBadge.RenderHeader(maxWidth, widths)); + + // assert + Assert.Equal(" NAME ROLE ", header); + } + + [Theory] + [InlineData(0, "just now")] + [InlineData(90, "1m ago")] + public void Render_Should_FormatLastSeen_When_AgeIsFreshOrMinutesOld(int elapsedSeconds, string expectedAge) + { + // arrange + var row = CreateRow(lastSeenAt: s_now.AddSeconds(-elapsedSeconds)); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth: 80, widths)); + + // assert + // The Last Seen column is padded to the "LAST SEEN" header's width, so a shorter age has trailing fill spaces. + Assert.EndsWith(expectedAge, line.TrimEnd()); + } + + [Fact] + public void Render_Should_FormatLastSeenAsBareDate_When_AgeIsAtLeastAWeekOld() + { + // arrange + var lastSeenAt = s_now.AddDays(-8); + var row = CreateRow(lastSeenAt: lastSeenAt); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth: 80, widths)); + + // assert + Assert.EndsWith(lastSeenAt.ToUniversalTime().ToString("yyyy-MM-dd"), line.TrimEnd()); + } + + [Fact] + public void RenderHeader_Should_AlignColumnsWithRow_When_WidthIsWide() + { + // arrange + const int maxWidth = 80; + var row = CreateRow(role: "implementer"); + var widths = AgentRowBadge.ComputeWidths([row], s_now); + + // act + var header = Markup.Remove(AgentRowBadge.RenderHeader(maxWidth, widths)); + var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + var nameOffset = header.IndexOf("NAME", StringComparison.Ordinal); + var roleOffset = header.IndexOf("ROLE", StringComparison.Ordinal); + var harnessOffset = header.IndexOf("HARNESS", StringComparison.Ordinal); + var startedOffset = header.IndexOf("STARTED", StringComparison.Ordinal); + var lastSeenOffset = header.IndexOf("LAST SEEN", StringComparison.Ordinal); + var columnsAtHeaderOffsets = ( + Name: line.Substring(nameOffset, 7), + Role: line.Substring(roleOffset, 11), + Harness: line.Substring(harnessOffset, 11), + Started: line.Substring(startedOffset, 8), + LastSeen: line.Substring(lastSeenOffset, 8)); + + // assert + Assert.Equal( + (Name: "agent-a", Role: "implementer", Harness: "Claude Code", Started: "just now", LastSeen: "just now"), + columnsAtHeaderOffsets); } [Fact] - public void Render_Should_KeepEveryColumn_When_MaxWidthFits() + public void RenderHeader_Should_DropTheSameColumnsAsRow_When_WidthIsNarrow() { // arrange - const int maxWidth = 120; - var row = new AgentParticipantRow( - AgentSessionParticipantBuilder.Participant(agentName: "agent-a", role: "developer"), - Activity: null); + const int maxWidth = 50; + var row = CreateRow(role: "implementer"); var widths = AgentRowBadge.ComputeWidths([row], s_now); // act + var header = Markup.Remove(AgentRowBadge.RenderHeader(maxWidth, widths)); var line = Markup.Remove(AgentRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + var actual = ( + HeaderHasRole: header.Contains("ROLE", StringComparison.Ordinal), + RowHasRole: line.Contains("implementer", StringComparison.Ordinal), + HeaderHasStarted: header.Contains("STARTED", StringComparison.Ordinal), + HeaderHasHarness: header.Contains("HARNESS", StringComparison.Ordinal), + RowHasHarness: line.Contains("Claude Code", StringComparison.Ordinal)); + + // assert + Assert.Equal((true, true, false, false, false), actual); + } + + [Fact] + public void PresenceStyle_Should_ReturnDistinctStyles_When_StateDiffers() + { + // arrange + var states = new[] { AgentState.Online, AgentState.Idle, AgentState.Unreachable, AgentState.Offline }; + + // act + var styles = states.Select(AgentRowBadge.PresenceStyle).ToArray(); // assert - Assert.Equal(" agent-a โ— claude-code developer started now heard now", line); + Assert.Equal(states.Length, styles.Distinct().Count()); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentSentMailRowBadgeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentSentMailRowBadgeTests.cs deleted file mode 100644 index ef8e8e01ff5..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentSentMailRowBadgeTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Tui.Agents; -using Spectre.Console; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -public sealed class AgentSentMailRowBadgeTests -{ - [Fact] - public void Render_Should_FitDisplayWidth_When_FixedPrefixExceedsMaxWidth() - { - // arrange - const int maxWidth = 1; - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var message = MailMessageBuilder.Create("m-1", createdAt: now); - - // act - var line = AgentSentMailRowBadge.Render(message, now, maxWidth); - - // assert - Assert.True(Markup.Remove(line).GetCellWidth() <= maxWidth); - Assert.Equal("โ€ฆ", Markup.Remove(line)); - } - - [Fact] - public void Render_Should_PreserveRecipientAllocation_When_SubjectAndRecipientOverflow() - { - // arrange - const int maxWidth = 19; - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var message = MailMessageBuilder.Create( - "m-1", - subject: "ABCDEFGHIJK", - createdAt: now, - recipients: [MailMessageBuilder.ToRecipient("abcdefghijk")]); - - // act - var line = AgentSentMailRowBadge.Render(message, now, maxWidth); - - // assert - Assert.Equal("now ABCDโ€ฆ -> abcdeโ€ฆ", line); - } - - [Fact] - public void Render_Should_FitDisplayWidth_When_SubjectAndRecipientsContainCjkAndEmoji() - { - // arrange - const int maxWidth = 24; - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var message = MailMessageBuilder.Create( - "m-1", - subject: "ๆผข๐Ÿ˜€ subject text", - createdAt: now, - recipients: [MailMessageBuilder.ToRecipient("ๆผข๐Ÿ˜€ recipient")]); - - // act - var line = AgentSentMailRowBadge.Render(message, now, maxWidth); - - // assert - Assert.True(Markup.Remove(line).GetCellWidth() <= maxWidth); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentSessionParticipantBuilder.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentSessionParticipantBuilder.cs deleted file mode 100644 index bd6334f2770..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentSessionParticipantBuilder.cs +++ /dev/null @@ -1,75 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// Builds and -/// instances with sensible defaults for agents mode and agent detail model -/// tests. -/// -internal static class AgentSessionParticipantBuilder -{ - private static readonly DateTimeOffset s_defaultNow = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - - public static AgentSessionRecord Session( - string sessionId = "s-1", - string harness = "claude-code", - string? agentName = null, - string role = "", - string harnessVersion = "", - string host = "host-a", - string cwd = "/work", - string workspacePath = "/work/.nitro/agents", - string endpointKind = "claude-peer", - string endpointAddr = "peer", - DateTimeOffset? startedAt = null, - DateTimeOffset? lastBeatAt = null) - => new() - { - Harness = harness, - SessionId = sessionId, - AgentName = agentName, - BindingKind = agentName is null ? AgentSessionBindingKind.None : AgentSessionBindingKind.Explicit, - Host = host, - Cwd = cwd, - WorkspacePath = workspacePath, - EndpointKind = endpointKind, - EndpointAddr = endpointAddr, - StartedAt = startedAt ?? s_defaultNow, - LastBeatAt = lastBeatAt ?? startedAt ?? s_defaultNow, - BlockBudgetUsed = 0, - Role = role, - HarnessVersion = harnessVersion - }; - - /// - /// Builds a participant with the given . When is - /// , the endpoint fields are cleared. - /// - public static AgentSessionParticipant Participant( - string sessionId = "s-1", - string? agentName = null, - string role = "", - string harness = "claude-code", - string harnessVersion = "", - string state = AgentSessionState.Online, - AgentRecord? agent = null, - DateTimeOffset? startedAt = null, - DateTimeOffset? lastBeatAt = null) - { - var unreachable = state == AgentSessionState.Unreachable; - - var session = Session( - sessionId: sessionId, - harness: harness, - agentName: agentName, - role: role, - harnessVersion: harnessVersion, - endpointKind: unreachable ? AgentSessionEndpointKind.None : AgentSessionEndpointKind.ClaudePeer, - endpointAddr: unreachable ? "" : "peer", - startedAt: startedAt, - lastBeatAt: lastBeatAt); - - return new AgentSessionParticipant(session, agent, state); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentsModeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentsModeTests.cs index cf0b97dcbc3..53cbde3178f 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentsModeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/AgentsModeTests.cs @@ -1,7 +1,7 @@ using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; using ChilliCream.Nitro.CommandLine.Tui.Agents; using ChilliCream.Nitro.CommandLine.Tui.Input; -using ChilliCream.Nitro.CommandLine.Tui.Theming; using Microsoft.Extensions.Time.Testing; using Spectre.Console; using Spectre.Console.Testing; @@ -14,35 +14,34 @@ public sealed class AgentsModeTests { private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - private static AgentRecord Agent( - string name, string role = "", string client = "", bool isImplicit = false) - => new() - { - Name = name, - Role = role, - Client = client, - Implicit = isImplicit, - RegisteredAt = s_now, - LastSeenAt = s_now - }; - + /// + /// Builds an , defaulting the mail, task, and memory stores the + /// agent detail popover needs when a test does not care about them. + /// private static AgentsMode CreateMode( - FakeAgentSessionRegistry sessionRegistry, FakeClaudeSessionActivityReader? activityReader = null) - => new( - new FakeTaskStore(), - new FakeMailStore(), - sessionRegistry, - activityReader ?? new FakeClaudeSessionActivityReader(), - new FakeTimeProvider(s_now)); + FakeAgentStore store, + FakeTimeProvider time, + FakeMailStore? mailStore = null, + FakeTaskStore? taskStore = null, + FakeMemoryStore? memoryStore = null) => + new( + store, + mailStore ?? new FakeMailStore(), + taskStore ?? new FakeTaskStore(), + memoryStore ?? new FakeMemoryStore(), + time); - private static AgentsMode CreateMode( - FakeAgentSessionRegistry sessionRegistry, FakeTaskStore taskStore, FakeMailStore mailStore) - => new( - taskStore, - mailStore, - sessionRegistry, - new FakeClaudeSessionActivityReader(), - new FakeTimeProvider(s_now)); + private static ConsoleKeyInfo Key(char c) => new(c, ConsoleKey.NoName, false, false, false); + + private static ConsoleKeyInfo CtrlKey(ConsoleKey key) => new('\0', key, false, false, true); + + private static void Type(AgentsMode mode, string text) + { + foreach (var c in text) + { + mode.HandleRawKey(Key(c)); + } + } private static string RenderToText(AgentsMode mode, int width = 100, int height = 24) { @@ -51,752 +50,634 @@ private static string RenderToText(AgentsMode mode, int width = 100, int height return console.Output; } - [Fact] - public void MoveSelection_Should_ClampAtLastRow_When_MovingDownPastEnd() + private static string RenderToAnsiText(AgentsMode mode, int width = 100, int height = 24) { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-b", agentName: "agent-b")); - var mode = CreateMode(sessions); - mode.OnEnter(); - - // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); - - // assert - Assert.Equal(1, mode.State.SelectedRow); + var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(width); + console.Write(mode.Render(width, height)); + return console.Output; } - [Fact] - public void MoveSelection_Should_ClampAtFirstRow_When_MovingUpPastStart() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - var mode = CreateMode(sessions); - mode.OnEnter(); - - // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Up)); + private static AgentRow AddOnlineAgent(FakeAgentStore store, string sessionId) + => store.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = AgentSessionHarness.ClaudeCode, + SessionId = sessionId, + HarnessVersion = "1.0.0", + Cwd = "", + WorkspacePath = "", + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1" + }, + TestContext.Current.CancellationToken) + .GetAwaiter().GetResult().Row!; - // assert - Assert.Equal(0, mode.State.SelectedRow); - } + private static AgentRow AddUnreachableAgent(FakeAgentStore store) + => store.LoginAsync(TestContext.Current.CancellationToken).GetAwaiter().GetResult(); - [Fact] - public void MoveSelectionToEdge_Should_SelectLastRow_When_Bottom() + private static AgentRow AddOfflineAgent(FakeAgentStore store, string sessionId) { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-b", agentName: "agent-b")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-c", agentName: "agent-c")); - var mode = CreateMode(sessions); - mode.OnEnter(); - - // act - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); - - // assert - Assert.Equal(2, mode.State.SelectedRow); + var row = AddOnlineAgent(store, sessionId); + store.EndSessionAsync(row.Harness!, row.SessionId!, TestContext.Current.CancellationToken) + .GetAwaiter().GetResult(); + return row; } - [Fact] - public void MoveSelectionToEdge_Should_SelectFirstRow_When_Top() + /// + /// Adds an idle agent: a valid endpoint, but a last-seen beat past the online window. + /// + private static AgentRow AddIdleAgent(FakeAgentStore store, string sessionId, FakeTimeProvider time) { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-b", agentName: "agent-b")); - var mode = CreateMode(sessions); - mode.OnEnter(); - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); - - // act - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Top)); - - // assert - Assert.Equal(0, mode.State.SelectedRow); + var row = AddOnlineAgent(store, sessionId); + time.Advance(AgentStateResolver.OnlineWindow + TimeSpan.FromMinutes(1)); + return row; } - [Fact] - public void Refresh_Should_PreserveSelection_ByHarnessAndSessionId_When_ReloadedListReorders() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add( - AgentSessionParticipantBuilder.Participant(sessionId: "s-bravo", agentName: "bravo")); - sessions.Participants.Add( - AgentSessionParticipantBuilder.Participant(sessionId: "s-charlie", agentName: "charlie")); - var mode = CreateMode(sessions); - mode.OnEnter(); - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); - Assert.Equal("s-charlie", mode.State.SelectedParticipant?.Participant.Session.SessionId); - - // act - // Insert a row before the selected session, preserving its harness and session id. - sessions.Participants.Insert( - 0, AgentSessionParticipantBuilder.Participant(sessionId: "s-alpha", agentName: "alpha")); - mode.Handle(new TuiMessage.RefreshRequested()); - - // assert - Assert.Equal("s-charlie", mode.State.SelectedParticipant?.Participant.Session.SessionId); - Assert.Equal(2, mode.State.SelectedRow); - } + private static void Touch(FakeAgentStore store, string name) + => store.TouchAsync(name, TestContext.Current.CancellationToken).GetAwaiter().GetResult(); - [Fact] - public void Refresh_Should_RemoveRow_When_TheSessionEndsOrIsReaped() + /// + /// Seeds an online agent last seen at exactly . + /// + private static AgentRow AddOnlineAgentSeenAt(FakeAgentStore store, string name, DateTimeOffset lastSeenAt) { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - var mode = CreateMode(sessions); - mode.OnEnter(); - Assert.Single(mode.State.Rows); - - // act - sessions.Participants.Clear(); - mode.Handle(new TuiMessage.RefreshRequested()); + var row = new AgentRow + { + Name = name, + Role = string.Empty, + Harness = AgentSessionHarness.ClaudeCode, + HarnessVersion = "1.0.0", + SessionId = $"session-{name}", + Cwd = string.Empty, + WorkspacePath = string.Empty, + RegisteredAt = lastSeenAt, + StartedAt = lastSeenAt, + LastSeenAt = lastSeenAt, + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1", + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; - // assert - Assert.Empty(mode.State.Rows); - Assert.Null(mode.State.SelectedParticipant); + store.Seed(row); + return row; } - [Fact] - public void Rows_Should_ShowTwoSeparateRows_When_TwoSessionsShareOneActor() + /// + /// Seeds an offline agent (its session already ended) last seen at exactly + /// . + /// + private static AgentRow AddOfflineAgentSeenAt(FakeAgentStore store, string name, DateTimeOffset lastSeenAt) { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-1", agentName: "bravo", harness: "claude-code")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-2", agentName: "bravo", harness: "codex")); - var mode = CreateMode(sessions); - - // act - mode.OnEnter(); + var row = new AgentRow + { + Name = name, + Role = string.Empty, + Harness = AgentSessionHarness.ClaudeCode, + HarnessVersion = "1.0.0", + SessionId = $"session-{name}", + Cwd = string.Empty, + WorkspacePath = string.Empty, + RegisteredAt = lastSeenAt, + StartedAt = lastSeenAt, + LastSeenAt = lastSeenAt, + EndedAt = lastSeenAt, + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1", + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; - // assert - Assert.Equal(2, mode.State.Rows.Count); - Assert.Equal( - ["s-1", "s-2"], - mode.State.Rows.Select(r => r.Participant.Session.SessionId)); - Assert.All(mode.State.Rows, r => Assert.Equal("bravo", r.Participant.Session.AgentName)); + store.Seed(row); + return row; } [Fact] - public void Refresh_Should_UpdateRoleInPlace_When_TheSameSessionIsPromoted_WithoutDuplicatingTheRow() + public void Render_Should_ListOnlineBeforeUnreachableBeforeOffline_When_AllThreeStatesArePresent() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add( - AgentSessionParticipantBuilder.Participant(sessionId: "s-1", agentName: "alpha", role: "")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var offline = AddOfflineAgent(store, "s-offline"); + var unreachable = AddUnreachableAgent(store); + var online = AddOnlineAgent(store, "s-online"); + var mode = CreateMode(store, time); mode.OnEnter(); - Assert.Single(mode.State.Rows); // act - sessions.Participants[0] = AgentSessionParticipantBuilder.Participant( - sessionId: "s-1", agentName: "alpha", role: "orchestrator"); - mode.Handle(new TuiMessage.RefreshRequested()); + var text = RenderToText(mode); // assert - var row = Assert.Single(mode.State.Rows); - Assert.Equal("orchestrator", row.Participant.Session.Role); + var onlineIndex = text.IndexOf(online.Name, StringComparison.Ordinal); + var unreachableIndex = text.IndexOf(unreachable.Name, StringComparison.Ordinal); + var offlineIndex = text.IndexOf(offline.Name, StringComparison.Ordinal); + Assert.True(onlineIndex >= 0 && unreachableIndex > onlineIndex && offlineIndex > unreachableIndex); } [Fact] - public void OpenSelected_Should_FocusDetailPane_And_ReturnEmpty() + public void Render_Should_ListIdleBetweenOnlineAndUnreachable_When_AllFourStatesArePresent() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var offline = AddOfflineAgent(store, "s-offline"); + var unreachable = AddUnreachableAgent(store); + var idle = AddIdleAgent(store, "s-idle", time); + var online = AddOnlineAgent(store, "s-online"); + var mode = CreateMode(store, time); mode.OnEnter(); // act - var messages = mode.Handle(new TuiMessage.OpenSelected()); + var text = RenderToText(mode); // assert - Assert.Empty(messages); - Assert.Equal(AgentsFocus.Detail, mode.State.Focus); + var onlineIndex = text.IndexOf(online.Name, StringComparison.Ordinal); + var idleIndex = text.IndexOf(idle.Name, StringComparison.Ordinal); + var unreachableIndex = text.IndexOf(unreachable.Name, StringComparison.Ordinal); + var offlineIndex = text.IndexOf(offline.Name, StringComparison.Ordinal); + Assert.True( + onlineIndex >= 0 && idleIndex > onlineIndex && unreachableIndex > idleIndex + && offlineIndex > unreachableIndex); } [Fact] - public void CopySelectedId_Should_ShowSessionIdInToast_When_ParticipantSelected() + public void Render_Should_ShowTheOnlinePresenceToken_When_AgentIsOnline() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-online"); + AddOfflineAgent(store, "s-offline"); + var mode = CreateMode(store, time); mode.OnEnter(); // act - var messages = mode.Handle(new TuiMessage.CopySelectedId()); + // Select the offline row first so the online row's bubble is not selection-highlighted. + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); + var text = RenderToAnsiText(mode); // assert - var toast = Assert.IsType(Assert.Single(messages)); - Assert.Equal("s-a", toast.Text); + AssertAnsiStylePrefixesText(text, "agents.list.presence.online", "โ—"); } [Fact] - public void CopySelectedId_Should_WarnNoSessionSelected_When_ListEmpty() + public void Render_Should_ShowTheOfflinePresenceToken_When_AgentIsOffline() { // arrange - var mode = CreateMode(new FakeAgentSessionRegistry()); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOfflineAgent(store, "s-offline"); + AddOnlineAgent(store, "s-online"); + var mode = CreateMode(store, time); mode.OnEnter(); // act - var messages = mode.Handle(new TuiMessage.CopySelectedId()); + // The default selection sits on the online row, sorted first, not on this one. + var text = RenderToAnsiText(mode); // assert - var toast = Assert.IsType(Assert.Single(messages)); - Assert.Equal(ToastStyle.Warn, toast.Style); + AssertAnsiStylePrefixesText(text, "agents.list.presence.offline", "โ—"); } [Fact] - public void Render_Should_IncludeActorRoleAndPanelTitle() + public void Render_Should_ShowTheUnreachablePresenceToken_When_AgentIsLoginOnly() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", role: "backend")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddUnreachableAgent(store); + AddOnlineAgent(store, "s-online"); + var mode = CreateMode(store, time); mode.OnEnter(); - var console = new TestConsole().Width(80).Height(20); // act - console.Write(mode.Render(80, 20)); + var text = RenderToAnsiText(mode); // assert - Assert.Contains("Agents (1)", console.Output); - Assert.Contains("agent-a", console.Output); - Assert.Contains("backend", console.Output); + AssertAnsiStylePrefixesText(text, "agents.list.presence.unreachable", "โ—"); } [Fact] - public void Render_Should_ShowUnboundLabel_When_TheSessionHasNoBoundActor() + public void Render_Should_ShowOnlineCountAndTotal_When_HeaderIsRendered() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: null)); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + AddOfflineAgent(store, "s-c"); + var mode = CreateMode(store, time); mode.OnEnter(); // act - var row = Assert.Single(RenderToText(mode, 100, 20).Split('\n'), l => l.Contains("started ")); + var text = RenderToText(mode); // assert - Assert.Contains(AgentParticipantRow.UnboundLabel, row); + Assert.Contains("Agents (2 online / 3)", text); } [Fact] - public void Render_Should_ShowDash_When_RoleEmpty() + public void Render_Should_ShowTheEmptyStateMessage_When_NoAgentsExist() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", harness: "claude-code")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var mode = CreateMode(store, time); mode.OnEnter(); // act - var text = RenderToText(mode, 120, 20); - var row = Assert.Single(text.Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); + var text = RenderToText(mode); // assert - Assert.Contains("claude-code -", row); + Assert.Contains("No agents yet.", text); } [Fact] - public void Render_Should_ShowHarness_In_ListRow() + public void Render_Should_KeepOnlyNameAndRole_When_WidthIsTooNarrowForEveryOtherColumn() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", role: "backend", harness: "codex")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var agent = AddOnlineAgent(store, "s-a"); + time.Advance(TimeSpan.FromMinutes(10)); + Touch(store, agent.Name); + var mode = CreateMode(store, time); mode.OnEnter(); + var wide = RenderToText(mode, width: 100); // act - var text = RenderToText(mode, 100, 20); - var row = Assert.Single(text.Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); + // At this width, Started, Harness and Last Seen all drop before Name or Role would. + var narrow = RenderToText(mode, width: 35); + var actual = ( + HasName: narrow.Contains(agent.Name, StringComparison.Ordinal), + HasHarness: narrow.Contains("Claude Code", StringComparison.Ordinal), + HasStartedAge: narrow.Contains("10m ago", StringComparison.Ordinal), + HasLastSeenAge: narrow.Contains("just now", StringComparison.Ordinal)); // assert - Assert.Contains("codex", row); + Assert.Contains("10m ago", wide); + Assert.Equal((true, false, false, false), actual); } [Fact] - public void Render_Should_ShowOnlineGlyph_When_TheSessionHasAnEndpoint() + public void Render_Should_ShowAnUpdatedAgeAndIdleBubble_When_TimeAdvancesPastTheOnlineWindowWithoutARefresh() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", state: AgentSessionState.Online)); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + var mode = CreateMode(store, time); mode.OnEnter(); + // Move off row 0 so its bubble is never selection-highlighted, before or after the tick. + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); + var initialText = RenderToText(mode); // act - var row = Assert.Single( - RenderToText(mode, 100, 20).Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); + // Advance the clock 31 minutes with no refresh in between. + time.Advance(TimeSpan.FromMinutes(31)); + var text = RenderToAnsiText(mode); // assert - Assert.Contains("agent-a โ— ", row); + Assert.Contains("just now", initialText); + Assert.Contains("31m ago", RenderToText(mode)); + AssertAnsiStylePrefixesText(text, "agents.list.presence.idle", "โ—"); } [Fact] - public void Render_Should_ShowUnreachableGlyph_When_TheSessionHasNoEndpoint() + public void Tick_Should_MoveTheSelectedAgentToTheIdleGroupByName_When_ItsOnlineWindowElapses() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", state: AgentSessionState.Unreachable)); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var stale = AddOnlineAgent(store, "s-a"); + time.Advance(TimeSpan.FromMinutes(25)); + var alreadyOffline = AddOfflineAgent(store, "s-off"); + time.Advance(TimeSpan.FromMinutes(4)); + var fresh = AddOnlineAgent(store, "s-c"); + var mode = CreateMode(store, time); mode.OnEnter(); + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); + Assert.Equal(stale.Name, mode.State.SelectedAgent?.Name); // act - var row = Assert.Single( - RenderToText(mode, 100, 20).Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); + // Only the stale agent's online window elapses; the other two keep their state. + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = mode.Tick(); + var text = RenderToText(mode); // assert - Assert.Contains("agent-a โ— ", row); + // The now-idle stale agent sorts ahead of the (still) offline group. + var freshIndex = text.IndexOf(fresh.Name, StringComparison.Ordinal); + var staleIndex = text.IndexOf(stale.Name, StringComparison.Ordinal); + var offlineIndex = text.IndexOf(alreadyOffline.Name, StringComparison.Ordinal); + Assert.True(dirty && freshIndex >= 0 && staleIndex > freshIndex && offlineIndex > staleIndex); + Assert.Equal(stale.Name, mode.State.SelectedAgent?.Name); } [Fact] - public void Render_Should_ShowUnobservableGlyph_When_TheSessionCannotBeVerified() + public void Rows_Should_OrderByNameAscending_When_TwoOnlineAgentsLastSeenFallInTheSameFiveMinuteWindow() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", state: AgentSessionState.Unobservable)); - var mode = CreateMode(sessions); - mode.OnEnter(); + // 10:01 and 10:04 share the 10:00 window + var windowStart = new DateTimeOffset(2026, 1, 1, 10, 0, 0, TimeSpan.Zero); + var time = new FakeTimeProvider(windowStart.AddMinutes(6)); + var store = new FakeAgentStore(time); + AddOnlineAgentSeenAt(store, "zed", windowStart.AddMinutes(4)); + AddOnlineAgentSeenAt(store, "ann", windowStart.AddMinutes(1)); + var mode = CreateMode(store, time); // act - var row = Assert.Single( - RenderToText(mode, 100, 20).Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); - - // assert: distinct from both the online and unreachable glyphs. - Assert.Contains("agent-a โ—Œ ", row); - } - - [Fact] - public void Render_Should_ShowRemoteGlyph_When_TheSessionIsOnAnotherInstance() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", state: AgentSessionState.Remote)); - var mode = CreateMode(sessions); mode.OnEnter(); - // act - var row = Assert.Single( - RenderToText(mode, 100, 20).Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); - // assert - Assert.Contains("agent-a โ—‡ ", row); + Assert.Collection( + mode.State.Rows, + row => Assert.Equal("ann", row.Name), + row => Assert.Equal("zed", row.Name)); } [Fact] - public void Render_Should_ShowActivityLetter_When_TheOnlineClaudeSessionHasKnownActivity() + public void Rows_Should_SortTheLaterWindowFirst_When_OneAgentsLastSeenCrossedTheNextFiveMinuteBoundary() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", state: AgentSessionState.Online)); - var activityReader = new FakeClaudeSessionActivityReader(); - activityReader.StatusBySessionId["s-a"] = "busy"; - var mode = CreateMode(sessions, activityReader); - mode.OnEnter(); + // 10:06 falls in the 10:05 window, 10:01 and 10:04 in the 10:00 window + var windowStart = new DateTimeOffset(2026, 1, 1, 10, 0, 0, TimeSpan.Zero); + var time = new FakeTimeProvider(windowStart.AddMinutes(7)); + var store = new FakeAgentStore(time); + AddOnlineAgentSeenAt(store, "zzz", windowStart.AddMinutes(1)); + AddOnlineAgentSeenAt(store, "yyy", windowStart.AddMinutes(4)); + AddOnlineAgentSeenAt(store, "aaa", windowStart.AddMinutes(6)); + var mode = CreateMode(store, time); // act - var row = Assert.Single( - RenderToText(mode, 100, 20).Split('\n'), l => l.Contains("agent-a") && l.Contains("started ")); - - // assert - Assert.Contains("agent-a โ—(b) ", row); - } - - [Fact] - public void Render_Should_ShowIdentitySection_When_TheSelectedSessionIsBound() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", agent: Agent("agent-a", client: "claude-code"))); - var mode = CreateMode(sessions); mode.OnEnter(); - // act - var text = RenderToText(mode); - // assert - Assert.Contains("Identity", text); - Assert.Contains("Name: agent-a", text); - Assert.Contains("Client: claude-code", text); + Assert.Equal("aaa", mode.State.Rows[0].Name); } [Fact] - public void Render_Should_OmitIdentityTasksAndSentMailSections_When_TheSelectedSessionIsUnbound() + public void Rows_Should_PlaceTwoLastSeenTimesInDifferentWindows_When_OneLandsRightBeforeAndOneRightAtTheBoundary() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: null)); - var mode = CreateMode(sessions); - mode.OnEnter(); + // 10:04:59 is in the 10:00 window, 10:05:00 starts the 10:05 window + var boundary = new DateTimeOffset(2026, 1, 1, 10, 5, 0, TimeSpan.Zero); + var time = new FakeTimeProvider(boundary.AddMinutes(1)); + var store = new FakeAgentStore(time); + AddOnlineAgentSeenAt(store, "b", boundary); + AddOnlineAgentSeenAt(store, "a", boundary - TimeSpan.FromSeconds(1)); + var mode = CreateMode(store, time); // act - var text = RenderToText(mode); - - // assert - Assert.Contains("Session", text); - Assert.Contains(AgentParticipantRow.UnboundLabel, text); - Assert.DoesNotContain("Identity", text); - Assert.DoesNotContain("Tasks", text); - Assert.DoesNotContain("Sent mail", text); - } - - [Fact] - public void Render_Should_ShowFullSessionIdAndHarnessVersion_In_DetailPane() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-full-session-id", agentName: "agent-a", harness: "claude-code", harnessVersion: "2.1.241")); - var mode = CreateMode(sessions); mode.OnEnter(); - // act - var text = RenderToText(mode); - // assert - Assert.Contains("Session id: s-full-session-id", text); - Assert.Contains("Harness: claude-code 2.1.241", text); + Assert.Equal("b", mode.State.Rows[0].Name); + Assert.Equal("a", mode.State.Rows[1].Name); } [Fact] - public void Render_Should_NotThrow_When_WidthOrHeightIsZero() + public void Rows_Should_KeepOnlineBeforeOffline_When_TheOfflineAgentsWindowIsLaterThanTheOnlineAgents() { // arrange - var mode = CreateMode(new FakeAgentSessionRegistry()); - mode.OnEnter(); + // The offline agent's window is later than the online agent's + var windowStart = new DateTimeOffset(2026, 1, 1, 10, 0, 0, TimeSpan.Zero); + var time = new FakeTimeProvider(windowStart.AddMinutes(20)); + var store = new FakeAgentStore(time); + var online = AddOnlineAgentSeenAt(store, "zzz", windowStart); + var offline = AddOfflineAgentSeenAt(store, "aaa", windowStart.AddMinutes(15)); + var mode = CreateMode(store, time); // act - var exception = Record.Exception(() => mode.Render(0, 0)); - - // assert - Assert.Null(exception); - } - - [Fact] - public void Render_Should_FitTheListContentBudget_When_RoleContainsCjkAndEmoji() - { - // arrange - const int terminalWidth = 30; - const int listContentWidth = 11; - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - agentName: "agent-a", role: "ๆผขโŒšโค๏ธ1๏ธโƒฃ a-very-long-mutable-role-value")); - var mode = CreateMode(sessions); mode.OnEnter(); - var row = mode.State.Rows[0]; - var widths = AgentRowBadge.ComputeWidths([row], s_now); - - // act - var output = RenderToText(mode, terminalWidth); - var line = AgentRowBadge.Render(row, s_now, selected: true, listContentWidth, widths); // assert - Assert.Contains("agent-a", output); - Assert.True(Markup.Remove(line).GetCellWidth() <= listContentWidth); + Assert.Equal(online.Name, mode.State.Rows[0].Name); + Assert.Equal(offline.Name, mode.State.Rows[1].Name); } [Fact] - public void Render_Should_ShowMoreBelowIndicator_When_ParticipantsExceedPanelHeight() + public void MoveSelection_Should_ClampAtLastRow_When_MovingDownPastEnd() { // arrange - var sessions = new FakeAgentSessionRegistry(); - for (var i = 1; i <= 15; i++) - { - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: $"s-{i:D2}", agentName: $"agent-{i:D2}")); - } - - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + var mode = CreateMode(store, time); mode.OnEnter(); - var console = new TestConsole().Width(80).Height(12); // act - console.Write(mode.Render(80, 12)); + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); // assert - Assert.Contains("more below", console.Output); - Assert.DoesNotContain("agent-15", console.Output); + Assert.Equal(1, mode.State.SelectedRow); } [Fact] - public void Render_Should_ShowMoreAboveIndicator_And_SelectedParticipant_When_MovedToBottom() + public void MoveSelectionToEdge_Should_SelectLastRow_When_Bottom() { // arrange - var sessions = new FakeAgentSessionRegistry(); - for (var i = 1; i <= 15; i++) - { - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: $"s-{i:D2}", agentName: $"agent-{i:D2}")); - } - - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + AddOnlineAgent(store, "s-c"); + var mode = CreateMode(store, time); mode.OnEnter(); - var console = new TestConsole().Width(80).Height(12); // act mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); - console.Write(mode.Render(80, 12)); - - // assert - Assert.Contains("more above", console.Output); - Assert.Contains("agent-15", console.Output); - } - - [Fact] - public void OnEnter_Should_LoadEveryParticipant_ThroughTheRegistry_InItsOwnOrder() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-z", agentName: "zeta")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "alpha")); - var mode = CreateMode(sessions); - - // act - mode.OnEnter(); // assert - Assert.Equal(["s-z", "s-a"], mode.State.Rows.Select(r => r.Participant.Session.SessionId)); + Assert.Equal(2, mode.State.SelectedRow); } [Fact] - public void Render_Should_ShowListAndDetailPanesSideBySide_When_ParticipantSelected() + public void CopySelectedId_Should_ReturnTheSessionId_When_TheSelectedAgentHasASession() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", role: "backend")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + var mode = CreateMode(store, time); mode.OnEnter(); // act - var text = RenderToText(mode); + var followUp = mode.Handle(new TuiMessage.CopySelectedId()); // assert - Assert.Contains("Agents (1)", text); - Assert.Contains("agent-a", text); - Assert.Contains("Session", text); - Assert.Contains("Role: backend", text); + var toast = Assert.Single(followUp); + var shown = Assert.IsType(toast); + Assert.Equal("s-a", shown.Text); } [Fact] - public void MoveSelection_Should_ReloadDetailPane_When_SelectionChanges() + public void CopySelectedId_Should_ReturnAHint_When_TheSelectedAgentIsLoginOnly() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-b", agentName: "agent-b")); - var taskStore = new FakeTaskStore(); - taskStore.Tasks.Add(TaskItemBuilder.Create("b-1", assignee: "agent-b")); - var mode = CreateMode(sessions, taskStore, new FakeMailStore()); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var agent = AddUnreachableAgent(store); + var mode = CreateMode(store, time); mode.OnEnter(); - Assert.DoesNotContain("b-1", RenderToText(mode)); // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); + var followUp = mode.Handle(new TuiMessage.CopySelectedId()); // assert - Assert.Contains("b-1", RenderToText(mode)); + var toast = Assert.Single(followUp); + var shown = Assert.IsType(toast); + Assert.Contains(agent.Name, shown.Text); } [Fact] - public void TogglePane_Should_FlipFocusBetweenListAndDetail() + public void SearchRequested_Should_OpenTheSearchForm_When_Requested() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var mode = CreateMode(store, time); mode.OnEnter(); - Assert.Equal(AgentsFocus.List, mode.State.Focus); // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Right)); + var followUp = mode.Handle(new TuiMessage.SearchRequested()); // assert - Assert.Equal(AgentsFocus.Detail, mode.State.Focus); - - // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Left)); - - // assert - Assert.Equal(AgentsFocus.List, mode.State.Focus); + Assert.Empty(followUp); + Assert.True(mode.IsInputCapturing); } [Fact] - public void Refresh_Should_ReloadDetailPane_For_SelectedParticipant() + public void SearchForm_Apply_Should_NarrowRowsByName_When_TextMatchesOneAgent() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - var taskStore = new FakeTaskStore(); - var mode = CreateMode(sessions, taskStore, new FakeMailStore()); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var first = AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + var mode = CreateMode(store, time); mode.OnEnter(); - Assert.DoesNotContain("a-1", RenderToText(mode)); + mode.Handle(new TuiMessage.SearchRequested()); + Type(mode, first.Name); // act - taskStore.Tasks.Add(TaskItemBuilder.Create("a-1", assignee: "agent-a")); - mode.Handle(new TuiMessage.RefreshRequested()); + mode.HandleRawKey(CtrlKey(ConsoleKey.S)); // assert - Assert.Contains("a-1", RenderToText(mode)); - } - - [Fact] - public void Refresh_Should_ClearDetailPane_When_ListEmpties() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", role: "backend")); - var mode = CreateMode(sessions); - mode.OnEnter(); - Assert.Contains("Role: backend", RenderToText(mode)); - - // act: the selected session ends before the next refresh. - sessions.Participants.Clear(); - mode.Handle(new TuiMessage.RefreshRequested()); - var text = RenderToText(mode); - - // assert - Assert.Contains("Agents (0)", text); - Assert.DoesNotContain("Role: backend", text); + Assert.False(mode.IsInputCapturing); + var row = Assert.Single(mode.State.Rows); + Assert.Equal(first.Name, row.Name); } [Fact] - public void Render_Should_AlignColumns_Across_Rows() + public void CountInactiveAgents_Should_CountOfflineAndIdleRows_When_ASearchFilterIsActive() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-1", agentName: "a", role: "backend")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-2", agentName: "longer-name", role: "qa")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOfflineAgent(store, "s-a"); + var idle = AddIdleAgent(store, "s-b", time); + AddOnlineAgent(store, "s-c"); + var mode = CreateMode(store, time); mode.OnEnter(); + mode.State.ApplySearch("no-agent-matches-this"); // act - var text = RenderToText(mode, 140, 24); - var rows = text.Split('\n').Where(l => l.Contains("started ") && l.Contains("heard ")).ToList(); - var shortNameRow = Assert.Single(rows, l => l.Contains("backend")); - var longNameRow = Assert.Single(rows, l => l.Contains("qa")); + var inactiveCount = mode.CountInactiveAgents(); // assert - Assert.Equal( - shortNameRow.IndexOf("backend", StringComparison.Ordinal), - longNameRow.IndexOf("qa", StringComparison.Ordinal)); - Assert.Equal( - shortNameRow.IndexOf("started ", StringComparison.Ordinal), - longNameRow.IndexOf("started ", StringComparison.Ordinal)); + Assert.Equal(2, inactiveCount); + Assert.Equal(AgentState.Idle, AgentStateResolver.Resolve(idle, time.GetUtcNow())); } [Fact] - public void Render_Should_ApplyAnsiStyling_ToActorAndHarnessTokens_InTheListRow() + public void Render_Should_ScrollRowsBelowTheHeaderBlock_When_MoreAgentsThanRowLinesExist() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-b", agentName: "agent-b", role: "backend", harness: "codex")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + AddOnlineAgent(store, "s-c"); + AddOnlineAgent(store, "s-d"); + AddOnlineAgent(store, "s-e"); + AddOnlineAgent(store, "s-f"); + var mode = CreateMode(store, time); mode.OnEnter(); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(80).Height(20); + var console = new TestConsole().Width(100); // act - console.Write(mode.Render(80, 20)); + console.Write(mode.Render(100, 10)); // assert - // The actor name immediately follows its style escape sequence. - var row = Assert.Single(console.Output.Split('\n'), l => l.Contains("agent-b")); - var style = ThemeTokens.GetStyle("agents.list.name"); - var styleConsole = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(1).Height(1); - styleConsole.Write(new Markup("x", style)); - var ansiPrefix = styleConsole.Output[..styleConsole.Output.IndexOf('x')]; - Assert.Contains(ansiPrefix + "agent-b", row); - AssertAnsiStyleApplied(row, "agents.list.harness"); + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Agents (6 online / 6)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ NAME ROLE HARNESS STARTED LAST SEEN โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > โ— ackbar - Claude Code just now just now โ”‚ + โ”‚ โ— ahsoka - Claude Code just now just now โ”‚ + โ”‚ โ— aladdin - Claude Code just now just now โ”‚ + โ”‚ โ— albus - Claude Code just now just now โ”‚ + โ”‚ 2 more below โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + """); } [Fact] - public void Render_Should_ApplyAnsiStyling_ToPerRoleToken_When_RoleHasADedicatedColor() + public void Render_Should_ShowHeaderRuleAndRows_When_ThreeAgentsArePresent() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-b", agentName: "agent-b", role: "orchestrator")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + AddOnlineAgent(store, "s-a"); + AddOnlineAgent(store, "s-b"); + AddOnlineAgent(store, "s-c"); + var mode = CreateMode(store, time); mode.OnEnter(); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(140).Height(20); + var console = new TestConsole().Width(100); // act - console.Write(mode.Render(140, 20)); + console.Write(mode.Render(100, 9)); // assert - Assert.NotEqual( - ThemeTokens.GetStyle("agents.list.role"), - ThemeTokens.GetStyle("agents.list.role.orchestrator")); - var row = Assert.Single(console.Output.Split('\n'), l => l.Contains("agent-b")); - AssertAnsiStyleApplied(row, "agents.list.role.orchestrator"); - } - - [Fact] - public void Render_Should_ApplyAnsiStyling_ToPerRoleToken_When_RoleIsResearcher() - { - // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-b", agentName: "agent-b", role: "researcher")); - var mode = CreateMode(sessions); - mode.OnEnter(); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(140).Height(20); + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Agents (3 online / 3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ NAME ROLE HARNESS STARTED LAST SEEN โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > โ— ackbar - Claude Code just now just now โ”‚ + โ”‚ โ— ahsoka - Claude Code just now just now โ”‚ + โ”‚ โ— aladdin - Claude Code just now just now โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - // act - console.Write(mode.Render(140, 20)); - - // assert: pin to agent-b's row rather than the whole frame. - Assert.Equal( - new Style(Color.Blue), - ThemeTokens.GetStyle("agents.list.role.researcher")); - var row = Assert.Single(console.Output.Split('\n'), l => l.Contains("agent-b")); - AssertAnsiStylePrefixesText(row, "agents.list.role.researcher", "researcher"); + """); } [Fact] - public void Render_Should_ApplyAnsiStyling_ToBaseRoleToken_When_RoleHasNoDedicatedColor() + public void RefreshRequested_Should_ReloadRowsFromTheStore_When_ANewAgentWasAdded() { // arrange - var sessions = new FakeAgentSessionRegistry(); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant(sessionId: "s-a", agentName: "agent-a")); - sessions.Participants.Add(AgentSessionParticipantBuilder.Participant( - sessionId: "s-b", agentName: "agent-b", role: "backend")); - var mode = CreateMode(sessions); + var time = new FakeTimeProvider(s_now); + var store = new FakeAgentStore(time); + var mode = CreateMode(store, time); mode.OnEnter(); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(140).Height(20); + Assert.Empty(mode.State.Rows); + AddOnlineAgent(store, "s-a"); // act - console.Write(mode.Render(140, 20)); + mode.Handle(new TuiMessage.RefreshRequested()); - // assert: pin to agent-b's row rather than the whole frame. - var row = Assert.Single(console.Output.Split('\n'), l => l.Contains("agent-b")); - AssertAnsiStyleApplied(row, "agents.list.role"); + // assert + Assert.Single(mode.State.Rows); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentRegistry.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentRegistry.cs deleted file mode 100644 index 20d684b2bbf..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentRegistry.cs +++ /dev/null @@ -1,49 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// An in-memory supporting and -/// . All other methods throw . -/// -internal sealed class FakeAgentRegistry : IAgentRegistry -{ - public List Agents { get; } = []; - - public Task AllocateAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> ListAsync( - string? role, - DateTimeOffset? staleBefore, - CancellationToken cancellationToken) - { - IEnumerable query = Agents; - - if (role is not null) - { - query = query.Where(a => a.Role == role); - } - - if (staleBefore is { } threshold) - { - query = query.Where(a => a.LastSeenAt < threshold); - } - - var result = query.OrderBy(a => a.Name, StringComparer.Ordinal).ToList(); - - return Task.FromResult>(result); - } - - public Task RegisterAsync(string name, string role, string client, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task TouchAsync(string name, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task GetAsync(string name, CancellationToken cancellationToken) - => Task.FromResult(Agents.FirstOrDefault(a => a.Name == name)); - - public Task EnsureImplicitAsync(string name, CancellationToken cancellationToken) - => throw new NotSupportedException(); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentSessionRegistry.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentSessionRegistry.cs deleted file mode 100644 index 54ac6191883..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentSessionRegistry.cs +++ /dev/null @@ -1,113 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// An in-memory supporting -/// and . All other methods throw . -/// -internal sealed class FakeAgentSessionRegistry : IAgentSessionRegistry -{ - public List Participants { get; } = []; - - /// - /// The rows returns, keyed - /// by agent name; an agent name with no entry gets an empty list. - /// - public Dictionary> LiveSessionsByAgentName { get; } = - new(StringComparer.Ordinal); - - public Task> ListParticipantsAsync(CancellationToken cancellationToken) - => Task.FromResult>(Participants); - - public Task> FindLiveClaimedByAgentNameAsync( - string agentName, CancellationToken cancellationToken) - => Task.FromResult(LiveSessionsByAgentName.TryGetValue(agentName, out var sessions) - ? sessions - : []); - - public Task> ListAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task StartAsync( - AgentSessionGeneration generation, - string cwd, - string workspacePath, - string endpointKind, - string endpointAddr, - string? envActor, - CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task ClaimAsync( - AgentSessionGeneration generation, string actor, bool forceRebind, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task EndAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> ReapAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task TouchAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task RecordHarnessVersionAsync( - AgentSessionGeneration generation, string harnessVersion, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task SetRoleAsync(AgentSessionGeneration generation, string role, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task RegisterAsync( - AgentSessionGeneration generation, - string actor, - string role, - string client, - bool forceRebind, - CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task FindBySessionIdAsync( - string harness, string host, string sessionId, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task FindByGenerationAsync( - AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task ResetBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task IncrementBlockBudgetAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task TryClaimPingCooldownAsync( - AgentSessionRecord session, - string attemptId, - DateTimeOffset now, - TimeSpan cooldown, - CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task WritePingResultAsync( - string harness, - string sessionId, - string attemptId, - string result, - string? detail, - CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task ArmAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task ClaimAnnouncementAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task RearmIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task ClaimIdlePushAsync(AgentSessionGeneration generation, CancellationToken cancellationToken) - => throw new NotSupportedException(); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentStore.cs new file mode 100644 index 00000000000..76b107935de --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeAgentStore.cs @@ -0,0 +1,460 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Workspace; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; + +/// +/// An in-memory backed by a plain list of rows, reproducing the +/// login, session, touch, role, and lookup contracts for tests that do not need a real +/// SQLite workspace. +/// +internal sealed class FakeAgentStore(TimeProvider timeProvider) : IAgentStore +{ + private readonly List _rows = []; + + public IReadOnlyList Rows => _rows; + + /// + /// Adds a row directly, bypassing the allocated-name contract, for tests that need + /// a deterministic agent name. + /// + public void Seed(AgentRow row) => _rows.Add(row); + + public Task LoginAsync(CancellationToken cancellationToken) + { + var now = timeProvider.GetUtcNow(); + + var row = new AgentRow + { + Name = AllocateName(), + Role = string.Empty, + Harness = null, + HarnessVersion = string.Empty, + SessionId = null, + Cwd = string.Empty, + WorkspacePath = string.Empty, + RegisteredAt = now, + StartedAt = now, + LastSeenAt = now, + EndpointKind = AgentSessionEndpointKind.None, + EndpointAddr = string.Empty, + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; + + _rows.Add(row); + + return Task.FromResult(row); + } + + public Task StartSessionAsync( + AgentSessionStartRequest request, CancellationToken cancellationToken) + { + EnsureAgentHarness(request.Harness); + + var now = timeProvider.GetUtcNow(); + var index = _rows.FindIndex(r => r.Harness == request.Harness && r.SessionId == request.SessionId); + + if (index >= 0) + { + var existing = _rows[index]; + + if (existing.IsDeleted) + { + return Task.FromResult(AgentSessionStartResult.Ignored); + } + + var reused = existing with + { + EndedAt = null, + HarnessVersion = request.HarnessVersion.Length == 0 + ? existing.HarnessVersion + : request.HarnessVersion, + Cwd = request.Cwd, + WorkspacePath = request.WorkspacePath, + EndpointKind = request.EndpointKind, + EndpointAddr = request.EndpointAddr, + EndpointSecret = request.EndpointSecret, + LastSeenAt = now + }; + + _rows[index] = reused; + + return Task.FromResult(AgentSessionStartResult.Reused(reused)); + } + + var minted = new AgentRow + { + Name = AllocateName(), + Role = string.Empty, + Harness = request.Harness, + HarnessVersion = request.HarnessVersion, + SessionId = request.SessionId, + Cwd = request.Cwd, + WorkspacePath = request.WorkspacePath, + RegisteredAt = now, + StartedAt = now, + LastSeenAt = now, + EndpointKind = request.EndpointKind, + EndpointAddr = request.EndpointAddr, + EndpointSecret = request.EndpointSecret, + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }; + + _rows.Add(minted); + + return Task.FromResult(AgentSessionStartResult.Minted(minted)); + } + + public Task TouchSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + { + EnsureAgentHarness(harness); + + var index = _rows.FindIndex(r => r.Harness == harness && r.SessionId == sessionId && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + _rows[index] = _rows[index] with { LastSeenAt = timeProvider.GetUtcNow() }; + + return Task.FromResult(true); + } + + public Task TouchAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + _rows[index] = _rows[index] with { LastSeenAt = timeProvider.GetUtcNow() }; + + return Task.FromResult(true); + } + + public Task EndSessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + { + EnsureAgentHarness(harness); + + var index = _rows.FindIndex(r => r.Harness == harness && r.SessionId == sessionId && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + _rows[index] = _rows[index] with { EndedAt = timeProvider.GetUtcNow() }; + + return Task.FromResult(true); + } + + public Task SetRoleAsync(string name, string role, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(null); + } + + var updated = _rows[index] with + { + Role = AgentRole.Normalize(role), + LastSeenAt = timeProvider.GetUtcNow() + }; + + _rows[index] = updated; + + return Task.FromResult(updated); + } + + public Task FindAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + + return Task.FromResult(_rows.FirstOrDefault(r => r.Name == normalizedName)); + } + + public Task FindBySessionAsync(string harness, string sessionId, CancellationToken cancellationToken) + { + EnsureAgentHarness(harness); + + return Task.FromResult(_rows.FirstOrDefault(r => r.Harness == harness && r.SessionId == sessionId)); + } + + public Task> ListAsync(CancellationToken cancellationToken) + => Task.FromResult>(_rows.Where(r => !r.IsDeleted).ToList()); + + public Task SetEndpointAsync( + string name, + string endpointKind, + string endpointAddr, + string? endpointSecret, + CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + var (kind, addr, secret) = EndpointAddress.Normalize( + _rows[index].Harness ?? string.Empty, endpointKind, endpointAddr, endpointSecret); + + _rows[index] = _rows[index] with + { + EndpointKind = kind, + EndpointAddr = addr, + EndpointSecret = secret + }; + + return Task.FromResult(true); + } + + public Task ResetBlockBudgetAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index >= 0) + { + _rows[index] = _rows[index] with { BlockBudgetUsed = 0 }; + } + + return Task.FromResult(0); + } + + public Task IncrementBlockBudgetAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(0); + } + + var updated = _rows[index] with { BlockBudgetUsed = _rows[index].BlockBudgetUsed + 1 }; + _rows[index] = updated; + + return Task.FromResult(updated.BlockBudgetUsed); + } + + public Task TryClaimPingCooldownAsync( + string name, TimeSpan cooldown, string attemptId, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + var now = timeProvider.GetUtcNow(); + var existing = _rows[index]; + + if (existing.LastPingAt is { } lastPingAt && lastPingAt > now - cooldown) + { + return Task.FromResult(false); + } + + _rows[index] = existing with + { + LastPingAt = now, + LastPingAttempt = attemptId, + LastPingResult = null, + LastPingDetail = null + }; + + return Task.FromResult(true); + } + + public Task WritePingResultAsync( + string name, string attemptId, string result, string? detail, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex( + r => r.Name == normalizedName && !r.IsDeleted && r.LastPingAttempt == attemptId); + + if (index >= 0) + { + _rows[index] = _rows[index] with { LastPingResult = result, LastPingDetail = detail }; + } + + return Task.CompletedTask; + } + + public Task ArmAnnouncementAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index >= 0) + { + _rows[index] = _rows[index] with { AnnouncementPending = true }; + } + + return Task.CompletedTask; + } + + public Task ClaimAnnouncementAsync(string name, CancellationToken cancellationToken) + => ClaimFlag(name, row => row.AnnouncementPending, (row, cleared) => row with { AnnouncementPending = cleared }); + + public Task IsAnnouncementPendingAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var row = _rows.FirstOrDefault(r => r.Name == normalizedName && !r.IsDeleted); + + return Task.FromResult(row?.AnnouncementPending ?? false); + } + + public Task RearmIdlePushAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index >= 0) + { + _rows[index] = _rows[index] with { IdlePushArmed = true }; + } + + return Task.CompletedTask; + } + + public Task ClaimIdlePushAsync(string name, CancellationToken cancellationToken) + => ClaimFlag(name, row => row.IdlePushArmed, (row, cleared) => row with { IdlePushArmed = cleared }); + + public Task RecordHarnessVersionAsync( + string name, string harnessVersion, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + _rows[index] = _rows[index] with { HarnessVersion = harnessVersion }; + + return Task.FromResult(true); + } + + public Task DeleteAsync(string name, CancellationToken cancellationToken) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0) + { + return Task.FromResult(false); + } + + _rows[index] = DeletedRow(_rows[index], timeProvider.GetUtcNow()); + + return Task.FromResult(true); + } + + public Task DeleteInactiveAsync(CancellationToken cancellationToken) + { + var now = timeProvider.GetUtcNow(); + var deletedCount = 0; + + for (var index = 0; index < _rows.Count; index++) + { + var row = _rows[index]; + var state = AgentStateResolver.Resolve(row, now); + + if (row.IsDeleted || (state != AgentState.Offline && state != AgentState.Idle)) + { + continue; + } + + _rows[index] = DeletedRow(row, now); + deletedCount++; + } + + return Task.FromResult(deletedCount); + } + + private static AgentRow DeletedRow(AgentRow row, DateTimeOffset now) => row with + { + DeletedAt = now, + EndpointKind = AgentSessionEndpointKind.None, + EndpointAddr = string.Empty, + EndpointSecret = null, + LastPingAt = null, + LastPingAttempt = null, + LastPingResult = null, + LastPingDetail = null, + AnnouncementPending = false, + IdlePushArmed = false, + BlockBudgetUsed = 0 + }; + + private Task ClaimFlag( + string name, Func read, Func write) + { + var normalizedName = MailAgentName.Normalize(name); + var index = _rows.FindIndex(r => r.Name == normalizedName && !r.IsDeleted); + + if (index < 0 || !read(_rows[index])) + { + return Task.FromResult(false); + } + + _rows[index] = write(_rows[index], false); + + return Task.FromResult(true); + } + + private static void EnsureAgentHarness(string harness) + { + if (!AgentSessionHarness.IsAgentHarness(harness)) + { + throw ThrowHelper.UnknownAgentHarness(harness); + } + } + + /// + /// Picks the first unused name from , then falls back to a + /// numeric suffix once the pool is exhausted. + /// + private string AllocateName() + { + var occupied = _rows.Select(r => r.Name).ToHashSet(StringComparer.Ordinal); + + foreach (var name in AgentNamePool.Names) + { + if (!occupied.Contains(name)) + { + return name; + } + } + + for (var suffix = 2; ; suffix++) + { + foreach (var name in AgentNamePool.Names) + { + var candidate = $"{name}-{suffix}"; + + if (!occupied.Contains(candidate)) + { + return candidate; + } + } + } + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeClaudeSessionActivityReader.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeClaudeSessionActivityReader.cs deleted file mode 100644 index 89a7f689d8d..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeClaudeSessionActivityReader.cs +++ /dev/null @@ -1,15 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Workspace; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// An in-memory returning the configured status -/// for a session id, or null when no status is configured. -/// -internal sealed class FakeClaudeSessionActivityReader : IClaudeSessionActivityReader -{ - public Dictionary StatusBySessionId { get; } = []; - - public string? GetStatus(string sessionId) - => StatusBySessionId.GetValueOrDefault(sessionId); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMailStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMailStore.cs index 9a2afc3f883..4721a13b2df 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMailStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMailStore.cs @@ -3,32 +3,51 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; /// -/// An in-memory supporting . -/// All other methods throw . +/// An exposing and +/// with configurable rows, for tests of the agent +/// detail popover's Mail section and its drilled-into thread view. Every other member +/// throws . /// internal sealed class FakeMailStore : IMailStore { - public List Messages { get; } = []; - - public Task> QuerySentAsync( - string sender, int? limit, CancellationToken cancellationToken) + /// + /// The rows returns, sliced to the + /// requested limit; empty by default. + /// + public IReadOnlyList ParticipationRows { get; set; } = []; + + /// + /// The messages returns, keyed by thread id; + /// empty by default. + /// + public Dictionary> Threads { get; } = []; + + /// + /// The agent and limit the last call + /// received, or null before one is made. + /// + public (string Agent, int? Limit)? LastParticipationQuery { get; private set; } + + /// + /// The thread ids passed to , in call order. + /// + public List LoadedThreadIds { get; } = []; + + /// + /// Whether was ever called. + /// + public bool MarkReadCalled { get; private set; } + + public Task> QueryParticipationThreadsAsync( + string agent, int? limit, CancellationToken cancellationToken) { - var ordered = Messages - .Where(m => m.Sender == sender) - .OrderByDescending(m => m.CreatedAt) - .ThenByDescending(m => m.Id, StringComparer.Ordinal) - .AsEnumerable(); - - if (limit is { } cap) - { - ordered = ordered.Take(cap); - } - - return Task.FromResult>(ordered.ToList()); + LastParticipationQuery = (agent, limit); + + return Task.FromResult>( + limit is { } max ? [.. ParticipationRows.Take(max)] : ParticipationRows); } - public string? FindWorkspaceDirectory() - => throw new NotSupportedException(); + public string? FindWorkspaceDirectory() => throw new NotSupportedException(); public Task InitializeWorkspaceAsync(string workspaceDirectory, CancellationToken cancellationToken) => throw new NotSupportedException(); @@ -47,16 +66,24 @@ public Task GetRequiredMessageAsync(string id, CancellationToken ca => throw new NotSupportedException(); public Task> GetThreadMessagesAsync(string threadId, CancellationToken cancellationToken) - => throw new NotSupportedException(); + { + LoadedThreadIds.Add(threadId); + + return Task.FromResult(Threads.GetValueOrDefault(threadId, [])); + } public Task> QueryInboxAsync(MailInboxFilter filter, CancellationToken cancellationToken) => throw new NotSupportedException(); - public Task> QueryWorkspaceMessagesAsync(MailWorkspaceFilter filter, CancellationToken cancellationToken) + public Task> QueryWorkspaceMessagesAsync( + MailWorkspaceFilter filter, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task MarkReadAsync(IReadOnlyList messageIds, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); + { + MarkReadCalled = true; + return Task.CompletedTask; + } public Task MarkUnreadAsync(IReadOnlyList messageIds, string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); @@ -74,7 +101,8 @@ public Task> QueryInboxThreadsAsync( public Task> QuerySentThreadsAsync(string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); - public Task> QueryWorkspaceThreadsAsync(string? agent, CancellationToken cancellationToken) + public Task> QueryWorkspaceThreadsAsync( + string? agent, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> SearchAsync(string actor, string text, CancellationToken cancellationToken) @@ -82,4 +110,8 @@ public Task> SearchAsync(string actor, string text, C public Task CountUnreadAsync(string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); + + public Task> QuerySentAsync( + string sender, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMemoryStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMemoryStore.cs new file mode 100644 index 00000000000..53d4d2ec306 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeMemoryStore.cs @@ -0,0 +1,90 @@ +using ChilliCream.Nitro.CommandLine.Services.Memory; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; + +/// +/// An exposing , +/// , and with configurable rows, for +/// tests of the agent detail popover's Memory section and its drilled-into detail view. Every +/// other member throws . +/// +internal sealed class FakeMemoryStore : IMemoryStore +{ + /// + /// The rows returns, sliced to the requested + /// limit; empty by default. + /// + public IReadOnlyList ParticipationRows { get; set; } = []; + + /// + /// The curated memories returns, keyed by id; empty by default. + /// + public Dictionary CuratedRecords { get; } = []; + + /// + /// The journal entries returns, keyed by id; empty by + /// default. + /// + public Dictionary JournalEntries { get; } = []; + + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => Task.FromResult>( + limit is { } max ? [.. ParticipationRows.Take(max)] : ParticipationRows); + + public string? FindWorkspaceDirectory() => throw new NotSupportedException(); + + public Task SaveAsync(MemoryRecordCreation creation, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task UpdateAsync(string id, MemoryRecordUpdate update, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task ForgetAsync(string id, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task FindAsync(string id, CancellationToken cancellationToken) + => Task.FromResult(CuratedRecords.TryGetValue(id, out var record) ? record : null); + + public Task GetRequiredAsync(string id, CancellationToken cancellationToken) + => CuratedRecords.TryGetValue(id, out var record) + ? Task.FromResult(record) + : throw new ExitException($"Memory '{id}' not found."); + + public Task> GetRecentCuratedAsync(int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task> SearchCuratedAsync( + string query, + IReadOnlyList tags, + string? type, + DateTimeOffset? since, + int? limit, + CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task LogAsync(MemoryJournalEntryCreation creation, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task FindJournalEntryAsync(string id, CancellationToken cancellationToken) + => Task.FromResult(JournalEntries.TryGetValue(id, out var entry) ? entry : null); + + public Task GetRequiredJournalEntryAsync(string id, CancellationToken cancellationToken) + => JournalEntries.TryGetValue(id, out var entry) + ? Task.FromResult(entry) + : throw new ExitException($"Journal entry '{id}' not found."); + + public Task> GetRecentJournalAsync(int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task> SearchJournalAsync( + string query, DateTimeOffset? since, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task> GetUnpromotedJournalEntriesAsync(CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public Task PromoteAsync( + string journalId, string type, IReadOnlyList tags, CancellationToken cancellationToken) + => throw new NotSupportedException(); +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeTaskStore.cs deleted file mode 100644 index 08f712a7162..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/FakeTaskStore.cs +++ /dev/null @@ -1,143 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Tasks; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// An in-memory supporting with status, -/// assignee, and limit filters. All other methods throw . -/// -internal sealed class FakeTaskStore : ITaskStore -{ - public List Tasks { get; } = []; - - public Task> QueryTasksAsync(TaskFilter filter, CancellationToken cancellationToken) - { - IEnumerable query = Tasks; - - if (filter.Statuses is { Length: > 0 } statuses) - { - query = query.Where(t => statuses.Contains(t.Status)); - } - else if (!filter.IncludeAll) - { - query = query.Where(t => !TaskStates.IsTerminal(t.Status)); - } - - if (filter.Unassigned) - { - query = query.Where(t => string.IsNullOrEmpty(t.Assignee)); - } - else if (filter.Assignee is { } assignee) - { - query = query.Where(t => t.Assignee == assignee); - } - - var result = query.ToList(); - - if (filter.Limit is { } limit) - { - result = result.Take(limit).ToList(); - } - - return Task.FromResult>(result); - } - - public string? FindWorkspaceDirectory() - => throw new NotSupportedException(); - - public Task GetTaskAsync(string id, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task GetRequiredTaskAsync(string id, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetLabelsAsync(string taskId, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetLabelCountsAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetCommentsAsync(string taskId, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetDependenciesAsync(string taskId, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetDependentsAsync(string taskId, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetDependencyEdgesAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task>> ComputeBlockedAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> GetEpicStatusesAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task CountTasksAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> CountTasksByAsync(TaskCountDimension dimension, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task GetStatsAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task GetConfigAsync(string key, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task SetConfigAsync(string key, string value, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> ListConfigAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task GetPrefixAsync(CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task InitializeWorkspaceAsync(string workspaceDirectory, string prefix, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task CreateTaskAsync(TaskCreation creation, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task UpdateTaskAsync(string id, TaskUpdate update, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> CloseTaskAsync(IReadOnlyList ids, string reason, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task ReopenTaskAsync(string id, string reason, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task DeferTaskAsync(string id, DateTimeOffset until, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task UndeferTaskAsync(string id, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task DeleteTaskAsync(string id, string reason, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> CloseEligibleEpicsAsync(string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task AddCommentAsync(string id, string text, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task> AddLabelAsync(string id, IReadOnlyList labels, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task RemoveLabelAsync(string id, string label, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task AddDependencyAsync(string id, string dependsOnId, string type, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task RemoveDependencyAsync(string id, string dependsOnId, string actor, CancellationToken cancellationToken) - => throw new NotSupportedException(); - - public Task EnsureWorkspaceAsync(string workspaceDirectory, CancellationToken cancellationToken) - => throw new NotSupportedException(); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/MailMessageBuilder.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/MailMessageBuilder.cs deleted file mode 100644 index 03f6040fb94..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/MailMessageBuilder.cs +++ /dev/null @@ -1,31 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// Builds and -/// instances with sensible defaults for agent detail model tests. -/// -internal static class MailMessageBuilder -{ - public static MailMessage Create( - string id, - string sender = "sender", - string subject = "Subject", - string body = "Body", - DateTimeOffset? createdAt = null, - IReadOnlyList? recipients = null) - => new() - { - Id = id, - ThreadId = id, - Sender = sender, - Subject = subject, - Body = body, - CreatedAt = createdAt ?? DateTimeOffset.UnixEpoch, - Recipients = recipients ?? [ToRecipient("recipient")] - }; - - public static MailRecipient ToRecipient(string name, int ordinal = 0) - => new() { Name = name, Kind = MailRecipientKinds.To, Ordinal = ordinal }; -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/TaskItemBuilder.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/TaskItemBuilder.cs deleted file mode 100644 index d783274a068..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Agents/TaskItemBuilder.cs +++ /dev/null @@ -1,33 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Tasks; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; - -/// -/// Builds instances with sensible defaults for agent -/// detail model tests. -/// -internal static class TaskItemBuilder -{ - public static TaskItem Create( - string id, - string status = TaskStates.Open, - int priority = TaskPriorities.Medium, - string type = TaskTypes.Task, - string? assignee = null, - DateTimeOffset? createdAt = null) - { - var created = createdAt ?? DateTimeOffset.UnixEpoch; - - return new TaskItem - { - Id = id, - Title = id, - Status = status, - Priority = priority, - Type = type, - Assignee = assignee, - CreatedAt = created, - UpdatedAt = created - }; - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardModeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardModeTests.cs index f8994393f50..58302b8c37c 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardModeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardModeTests.cs @@ -43,7 +43,10 @@ public void FocusColumn_Should_ClampAtFirstColumn_When_MovingLeftPastStart() public void FocusColumn_Should_ClampAtLastColumn_When_MovingRightPastEnd() { // arrange + // both columns need a task so neither is hidden by the empty-column rule var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); var mode = CreateMode(store, TwoColumnView()); mode.OnEnter(); @@ -302,6 +305,7 @@ public void Render_Should_IncludeColumnTitlesAndTaskBadges() // arrange var store = new FakeTaskStore(); store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); var mode = CreateMode(store, TwoColumnView()); mode.OnEnter(); var console = new TestConsole().Width(80).Height(20); @@ -311,10 +315,138 @@ public void Render_Should_IncludeColumnTitlesAndTaskBadges() // assert Assert.Contains("Open (1)", console.Output); - Assert.Contains("Closed (0)", console.Output); + Assert.Contains("Closed (1)", console.Output); Assert.Contains("a-1", console.Output); } + [Fact] + public void Render_Should_HideColumn_When_ColumnHasNoTasks() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + var mode = CreateMode(store, TwoColumnView()); + mode.OnEnter(); + var console = new TestConsole().Width(80).Height(6); + + // act + console.Write(mode.Render(80, 6)); + + // assert + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Open (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ TYPE PRIO ID TITLE โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > โ—‹ task P2 a-1 a-1 โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + """); + } + + [Fact] + public void Render_Should_ShareWidthAmongVisibleColumnsOnly_When_SomeColumnsAreEmpty() + { + // arrange + // Ready, In Progress and Closed each get one task; Blocked and Deferred stay empty + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.InProgress)); + store.Tasks.Add(TaskItemBuilder.Create("a-3", status: TaskStates.Closed)); + var mode = CreateMode(store, BoardView.Default); + mode.OnEnter(); + var console = new TestConsole().Width(90).Height(6); + + // act + console.Write(mode.Render(90, 6)); + + // assert + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Ready (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญโ”€In Progress (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญโ”€Closed (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚ + โ”‚ ID TITLE โ”‚โ”‚ ID TITLE โ”‚โ”‚ ID TITLE โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > โ—‹ a-1 a-1 โ”‚โ”‚ โ— a-2 a-2 โ”‚โ”‚ โœ“ a-3 a-3 โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + """); + } + + [Fact] + public void Render_Should_ShowEmptyBoardPanel_When_EveryColumnHasNoTasks() + { + // arrange + var store = new FakeTaskStore(); + var mode = CreateMode(store, BoardView.Default); + mode.OnEnter(); + var console = new TestConsole().Width(80).Height(6); + + // act + console.Write(mode.Render(80, 6)); + + // assert + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Board (0)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ No tasks yet. โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + """); + } + + [Fact] + public void FocusColumn_Should_SkipHiddenColumns_When_MovingRight() + { + // arrange + // Deferred sits between Open and Closed but has no tasks, so it must be skipped + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); + var view = new BoardView + { + Name = "Test", + Columns = + [ + new ColumnDefinition { Name = "Open", Statuses = [TaskStates.Open] }, + new ColumnDefinition { Name = "Deferred", Statuses = [TaskStates.Deferred] }, + new ColumnDefinition { Name = "Closed", Statuses = [TaskStates.Closed] } + ] + }; + var mode = CreateMode(store, view); + mode.OnEnter(); + + // act + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Right)); + + // assert + Assert.Equal(2, mode.State.FocusedColumnIndex); + Assert.Equal("a-2", mode.SelectedTaskId); + } + + [Fact] + public async Task Refresh_Should_MoveFocusToFirstVisibleColumn_When_FocusedColumnBecomesEmpty() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); + var mode = CreateMode(store, TwoColumnView()); + mode.OnEnter(); + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Right)); + Assert.Equal(1, mode.State.FocusedColumnIndex); + + // act + // the focused column's only task closes out of it + store.Tasks.RemoveAt(1); + await mode.State.RefreshAsync(CancellationToken.None); + + // assert + Assert.Equal(0, mode.State.FocusedColumnIndex); + } + [Fact] public void Render_Should_NotThrow_When_WidthOrHeightIsZero() { @@ -383,6 +515,7 @@ public void ToggleMaximize_Should_ShowOnlyFocusedColumn_When_Toggled() // arrange var store = new FakeTaskStore(); store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); var mode = CreateMode(store, TwoColumnView()); mode.OnEnter(); var console = new TestConsole().Width(80).Height(20); @@ -401,6 +534,8 @@ public void ToggleMaximize_Should_ShowNewlyFocusedColumn_When_FocusChangedWhileM { // arrange var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); var mode = CreateMode(store, TwoColumnView()); mode.OnEnter(); var console = new TestConsole().Width(80).Height(20); @@ -420,6 +555,8 @@ public void ToggleMaximize_Should_ReturnToGrid_When_ToggledTwice() { // arrange var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); var mode = CreateMode(store, TwoColumnView()); mode.OnEnter(); var console = new TestConsole().Width(80).Height(20); @@ -430,8 +567,8 @@ public void ToggleMaximize_Should_ReturnToGrid_When_ToggledTwice() console.Write(mode.Render(80, 20)); // assert - Assert.Contains("Open (0)", console.Output); - Assert.Contains("Closed (0)", console.Output); + Assert.Contains("Open (1)", console.Output); + Assert.Contains("Closed (1)", console.Output); } [Fact] @@ -452,21 +589,25 @@ public void Render_Should_ReClampViewport_When_ResizedSmaller_After_ScrollingDow mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); bigConsole.Write(mode.Render(80, 20)); - // act: shrink the frame drastically after scrolling to the bottom + // act + // shrink the frame drastically after scrolling to the bottom mode.OnResize(80, 4); var smallConsole = new TestConsole().Width(80).Height(4); var exception = Record.Exception(() => smallConsole.Write(mode.Render(80, 4))); // assert Assert.Null(exception); - Assert.Contains("t-30", smallConsole.Output); + var lines = TrimTrailingNewline(smallConsole.Output.Split('\n')); + Assert.Equal(4, lines.Length); } [Fact] public void Render_Should_NotThrow_When_WidthIsBelowColumnCount() { // arrange + // one task matching every column's filter keeps all five columns visible var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); var view = new BoardView { Name = "Many", @@ -557,6 +698,8 @@ public void Render_Should_FillRequestedHeight_When_Stacked() { // arrange var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); var mode = CreateMode(store, TwoColumnView()); mode.OnEnter(); var console = new TestConsole().Width(40).Height(24); @@ -572,6 +715,195 @@ public void Render_Should_FillRequestedHeight_When_Stacked() Assert.Contains('โ•ฐ', lines[^1]); } + [Fact] + public void Render_Should_ShowColumnTableHeader_When_ColumnHasTasks() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + var mode = CreateMode(store, TwoColumnView()); + mode.OnEnter(); + var console = new TestConsole().Width(100).Height(20); + + // act + console.Write(mode.Render(100, 20)); + + // assert + Assert.Contains("TYPE", console.Output); + Assert.Contains("PRIO", console.Output); + Assert.Contains("ID", console.Output); + Assert.Contains("TITLE", console.Output); + } + + [Fact] + public void Render_Should_ShowTrimmedHeaderAndMoreBelow_When_InteriorHeightExactlyFitsHeaderBlock() + { + // arrange + // a four-row interior trims the header block to make room for one row + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("t-1", status: TaskStates.Open, createdAt: s_now)); + store.Tasks.Add(TaskItemBuilder.Create("t-2", status: TaskStates.Open, createdAt: s_now.AddMinutes(1))); + store.Tasks.Add(TaskItemBuilder.Create("c-1", status: TaskStates.Closed)); + var mode = CreateMode(store, TwoColumnView()); + mode.OnEnter(); + mode.Handle(new TuiMessage.ToggleMaximize()); + var console = new TestConsole().Width(80).Height(6); + + // act + console.Write(mode.Render(80, 6)); + + // assert + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Open - 1/2 (2)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ TYPE PRIO ID TITLE โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ 2 more below โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + """); + } + + [Fact] + public void Render_Should_ShowTask_When_InteriorHeightAddsOneRowPastHeaderBlock() + { + // arrange + // one interior row past the header block fits the column's one task + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("t-1", status: TaskStates.Open)); + var mode = CreateMode(store, TwoColumnView()); + mode.OnEnter(); + mode.Handle(new TuiMessage.ToggleMaximize()); + var console = new TestConsole().Width(80).Height(7); + + // act + console.Write(mode.Render(80, 7)); + + // assert + Assert.Contains("t-1", console.Output); + } + + [Fact] + public void Render_Should_ShowFocusedTaskRow_When_StackedFiveColumnsAt33Rows() + { + // arrange + // one task per remaining column keeps all five columns visible + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("blocked-1", status: TaskStates.Open, createdAt: s_now)); + store.Blocked["blocked-1"] = ["blocker-1"]; + store.Tasks.Add(TaskItemBuilder.Create( + "blocked-2", status: TaskStates.Open, createdAt: s_now.AddMinutes(1))); + store.Blocked["blocked-2"] = ["blocker-1"]; + store.Tasks.Add(TaskItemBuilder.Create("deferred-1", status: TaskStates.Deferred)); + store.Tasks.Add(TaskItemBuilder.Create("ready-1", status: TaskStates.Open, createdAt: s_now.AddMinutes(2))); + store.Tasks.Add(TaskItemBuilder.Create("in-progress-1", status: TaskStates.InProgress)); + store.Tasks.Add(TaskItemBuilder.Create("closed-1", status: TaskStates.Closed, closedAt: s_now.AddDays(-1))); + var mode = CreateMode(store, BoardView.Default); + mode.OnEnter(); + var console = new TestConsole().Width(95).Height(33); + + // act + console.Write(mode.Render(95, 33)); + + // assert + var selectedLine = Array.Find( + console.Output.Split('\n'), line => line.Contains("blocked-1", StringComparison.Ordinal)); + Assert.NotNull(selectedLine); + selectedLine.MatchInlineSnapshot( + "โ”‚ > โ—‹ task P2 blocked-1 blocked-1 โ”‚"); + } + + [Fact] + public void Render_Should_ShowTaskTable_When_GridWithThreeTasks() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create( + "a-1", status: TaskStates.Open, priority: TaskPriorities.Critical, type: TaskTypes.Bug, + title: "Fix bug", createdAt: s_now)); + store.Tasks.Add(TaskItemBuilder.Create( + "a-2", status: TaskStates.InProgress, priority: TaskPriorities.Medium, type: TaskTypes.Feature, + title: "Add feature", createdAt: s_now.AddMinutes(1))); + store.Tasks.Add(TaskItemBuilder.Create( + "a-3", status: TaskStates.Open, priority: TaskPriorities.Low, type: TaskTypes.Docs, + title: "Write docs", createdAt: s_now.AddMinutes(2))); + var view = new BoardView + { + Name = "Test", + Columns = [new ColumnDefinition { Name = "Open", Statuses = [TaskStates.Open, TaskStates.InProgress] }] + }; + var mode = CreateMode(store, view); + mode.OnEnter(); + var console = new TestConsole().Width(60).Height(12); + + // act + console.Write(mode.Render(60, 12)); + + // assert + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Open (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ TYPE PRIO ID TITLE โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > โ—‹ bug P0 a-1 Fix bug โ”‚ + โ”‚ โ— feature P2 a-2 Add feature โ”‚ + โ”‚ โ—‹ docs P3 a-3 Write docs โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + """); + } + + [Fact] + public void Render_Should_ShowTaskTable_When_MaximizedWithThreeTasks() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create( + "a-1", status: TaskStates.Open, priority: TaskPriorities.Critical, type: TaskTypes.Bug, + title: "Fix bug", createdAt: s_now)); + store.Tasks.Add(TaskItemBuilder.Create( + "a-2", status: TaskStates.InProgress, priority: TaskPriorities.Medium, type: TaskTypes.Feature, + title: "Add feature", createdAt: s_now.AddMinutes(1))); + store.Tasks.Add(TaskItemBuilder.Create( + "a-3", status: TaskStates.Open, priority: TaskPriorities.Low, type: TaskTypes.Docs, + title: "Write docs", createdAt: s_now.AddMinutes(2))); + var view = new BoardView + { + Name = "Test", + Columns = [new ColumnDefinition { Name = "Open", Statuses = [TaskStates.Open, TaskStates.InProgress] }] + }; + var mode = CreateMode(store, view); + mode.OnEnter(); + mode.Handle(new TuiMessage.ToggleMaximize()); + var console = new TestConsole().Width(60).Height(12); + + // act + console.Write(mode.Render(60, 12)); + + // assert + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Open - 1/1 (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ TYPE PRIO ID TITLE โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > โ—‹ bug P0 a-1 Fix bug โ”‚ + โ”‚ โ— feature P2 a-2 Add feature โ”‚ + โ”‚ โ—‹ docs P3 a-3 Write docs โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + """); + } + /// /// Removes the last entry when it is empty; otherwise returns the supplied lines unchanged. /// diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardStateTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardStateTests.cs index 693095db7fa..4b045a1cf1e 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardStateTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardStateTests.cs @@ -113,4 +113,82 @@ public void FocusColumn_Should_ClampToValidColumnRange(int requested, int expect // assert Assert.Equal(expected, state.FocusedColumnIndex); } + + [Fact] + public async Task VisibleColumns_Should_ExcludeColumnsWithNoTasks_When_Refreshed() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + var state = new BoardState(TwoColumnView(), new BoardDataLoader(store, new FakeTimeProvider(s_now))); + + // act + await state.RefreshAsync(CancellationToken.None); + + // assert + Assert.Equal(["Open"], state.VisibleColumns.Select(c => c.Definition.Name)); + Assert.Equal([0], state.VisibleColumnIndices); + } + + [Fact] + public async Task FocusAdjacentVisibleColumn_Should_SkipColumn_When_ColumnHasNoTasks() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-3", status: TaskStates.Closed)); + var view = new BoardView + { + Name = "Test", + Columns = + [ + new ColumnDefinition { Name = "Open", Statuses = [TaskStates.Open] }, + new ColumnDefinition { Name = "Deferred", Statuses = [TaskStates.Deferred] }, + new ColumnDefinition { Name = "Closed", Statuses = [TaskStates.Closed] } + ] + }; + var state = new BoardState(view, new BoardDataLoader(store, new FakeTimeProvider(s_now))); + await state.RefreshAsync(CancellationToken.None); + + // act + // the middle column (Deferred) is empty and must be skipped + state.FocusAdjacentVisibleColumn(1); + + // assert + Assert.Equal(2, state.FocusedColumnIndex); + } + + [Fact] + public void FocusAdjacentVisibleColumn_Should_DoNothing_When_NoColumnIsVisible() + { + // arrange + var store = new FakeTaskStore(); + var state = new BoardState(TwoColumnView(), new BoardDataLoader(store, new FakeTimeProvider(s_now))); + + // act + state.FocusAdjacentVisibleColumn(1); + + // assert + Assert.Equal(0, state.FocusedColumnIndex); + } + + [Fact] + public async Task RefreshAsync_Should_MoveFocusToFirstVisibleColumn_When_FocusedColumnLosesItsLastTask() + { + // arrange + var store = new FakeTaskStore(); + store.Tasks.Add(TaskItemBuilder.Create("a-1", status: TaskStates.Open)); + store.Tasks.Add(TaskItemBuilder.Create("a-2", status: TaskStates.Closed)); + var state = new BoardState(TwoColumnView(), new BoardDataLoader(store, new FakeTimeProvider(s_now))); + await state.RefreshAsync(CancellationToken.None); + state.FocusColumn(1); + + // act + // the focused (Closed) column's only task disappears + store.Tasks.RemoveAt(1); + await state.RefreshAsync(CancellationToken.None); + + // assert + Assert.Equal(0, state.FocusedColumnIndex); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardTaskRowTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardTaskRowTests.cs new file mode 100644 index 00000000000..f4464e7d20a --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/BoardTaskRowTests.cs @@ -0,0 +1,203 @@ +using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Tui.Board; +using Spectre.Console; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Board; + +public sealed class BoardTaskRowTests +{ + private static TaskItem CreateTask( + string id = "hc-10-abc", + string title = "Fix bug", + string status = TaskStates.Open, + int priority = TaskPriorities.Medium, + string type = TaskTypes.Task) => TaskItemBuilder.Create(id, status, priority, type, title); + + [Fact] + public void Render_Should_ReturnEmpty_When_MaxWidthIsZero() + { + // arrange + var task = CreateTask(); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var line = BoardTaskRow.Render(task, selected: false, maxWidth: 0, widths); + + // assert + Assert.Empty(line); + } + + [Fact] + public void Render_Should_ShowEveryColumn_When_MaxWidthFits() + { + // arrange + const int maxWidth = 60; + var task = CreateTask(id: "hc-10-abc", title: "Fix bug", priority: TaskPriorities.Critical, type: TaskTypes.Bug); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + + // assert + Assert.Equal(" โ—‹ bug P0 hc-10-abc Fix bug", line.TrimEnd()); + } + + [Fact] + public void Render_Should_DropPriorityColumn_When_WidthIsTooNarrowForAllColumns() + { + // arrange + const int maxWidth = 30; + var task = CreateTask(priority: TaskPriorities.Critical, type: TaskTypes.Bug); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + + // assert + Assert.Equal(" โ—‹ bug hc-10-abc", line.TrimEnd()); + Assert.True(line.GetCellWidth() <= maxWidth); + } + + [Fact] + public void Render_Should_DropTypeColumn_When_WidthIsTooNarrowForTypeAndPriority() + { + // arrange + const int maxWidth = 20; + var task = CreateTask(id: "hc-10-abc", priority: TaskPriorities.Critical, type: TaskTypes.Bug); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + + // assert + Assert.Equal(" โ—‹ hc-10-abc Fโ€ฆ", line.TrimEnd()); + Assert.True(line.GetCellWidth() <= maxWidth); + } + + [Fact] + public void Render_Should_TruncateTitleWithEllipsis_When_TitleExceedsRemainingWidth() + { + // arrange + const int maxWidth = 40; + var task = CreateTask(id: "hc-10-abc", title: "A very long task title that will not fit"); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + + // assert + Assert.Contains("โ€ฆ", line); + Assert.True(line.GetCellWidth() <= maxWidth); + } + + [Fact] + public void RenderHeader_Should_AlignColumnsWithRow_When_WidthIsWide() + { + // arrange + const int maxWidth = 60; + var task = CreateTask(id: "hc-10-abc", title: "Fix bug", priority: TaskPriorities.Critical, type: TaskTypes.Bug); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var header = Markup.Remove(BoardTaskRow.RenderHeader(maxWidth, widths)); + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + var typeOffset = header.IndexOf("TYPE", StringComparison.Ordinal); + var prioOffset = header.IndexOf("PRIO", StringComparison.Ordinal); + var idOffset = header.IndexOf("ID", StringComparison.Ordinal); + var titleOffset = header.IndexOf("TITLE", StringComparison.Ordinal); + var columnsAtHeaderOffsets = ( + Type: line.Substring(typeOffset, widths.Type).TrimEnd(), + Prio: line.Substring(prioOffset, widths.Priority).Trim(), + Id: line.Substring(idOffset, widths.Id).TrimEnd(), + Title: line.Substring(titleOffset, 7)); + + // assert + Assert.Equal((Type: "bug", Prio: "P0", Id: "hc-10-abc", Title: "Fix bug"), columnsAtHeaderOffsets); + } + + [Fact] + public void RenderHeader_Should_DropTheSameColumnsAsRow_When_WidthIsNarrow() + { + // arrange + const int maxWidth = 30; + var task = CreateTask(priority: TaskPriorities.Critical, type: TaskTypes.Bug); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var header = Markup.Remove(BoardTaskRow.RenderHeader(maxWidth, widths)); + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + + // assert + Assert.Equal(" TYPE ID", header.TrimEnd()); + Assert.Equal(" โ—‹ bug hc-10-abc", line.TrimEnd()); + } + + [Fact] + public void RenderHeader_Should_DropTypeColumn_When_WidthIsTooNarrowForTypeAndPriority() + { + // arrange + const int maxWidth = 20; + var task = CreateTask(id: "hc-10-abc", priority: TaskPriorities.Critical, type: TaskTypes.Bug); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var header = Markup.Remove(BoardTaskRow.RenderHeader(maxWidth, widths)); + + // assert + Assert.Equal(" ID Tโ€ฆ", header.TrimEnd()); + } + + [Fact] + public void ComputeWidths_Should_WidenIdColumn_When_LongestIdExceedsMinimum() + { + // arrange + var rows = new[] { CreateTask(id: "hc-10-a"), CreateTask(id: "hc-10-a-very-long-id") }; + + // act + var widths = BoardTaskRow.ComputeWidths(rows); + + // assert + Assert.Equal("hc-10-a-very-long-id".Length, widths.Id); + } + + [Fact] + public void ComputeWidths_Should_UseMinimumOfEight_When_TypeIsShorterThanMinimum() + { + // arrange + var rows = new[] { CreateTask(type: TaskTypes.Bug) }; + + // act + var widths = BoardTaskRow.ComputeWidths(rows); + + // assert + Assert.Equal(8, widths.Type); + } + + [Fact] + public void Render_Should_ShowFullTypeName_When_TypeIsQuestion() + { + // arrange + const int maxWidth = 60; + var task = CreateTask(type: TaskTypes.Question); + var widths = BoardTaskRow.ComputeWidths([task]); + + // act + var line = Markup.Remove(BoardTaskRow.Render(task, selected: false, maxWidth: maxWidth, widths)); + + // assert + Assert.Contains("question", line); + } + + [Fact] + public void ComputeWidths_Should_WidenTypeColumn_When_CustomTypeExceedsMinimum() + { + // arrange + var rows = new[] { CreateTask(type: "documentation") }; + + // act + var widths = BoardTaskRow.ComputeWidths(rows); + + // assert + Assert.Equal("documentation".Length, widths.Type); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/FakeTaskStore.cs index 1debeef3f80..65f2bbc4c20 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/FakeTaskStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/FakeTaskStore.cs @@ -91,6 +91,10 @@ public Task>> ComputeBlockedAs public Task GetTaskAsync(string id, CancellationToken cancellationToken) => Task.FromResult(Tasks.FirstOrDefault(t => t.Id == id)); + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task> GetLabelsAsync(string taskId, CancellationToken cancellationToken) => Task.FromResult>(Labels.TryGetValue(taskId, out var labels) ? labels : []); @@ -201,6 +205,9 @@ public Task UndeferTaskAsync(string id, string actor, CancellationToke public Task DeleteTaskAsync(string id, string reason, string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task ReleaseAssigneeAsync(string agent, string reason, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task> CloseEligibleEpicsAsync(string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/TaskItemBuilder.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/TaskItemBuilder.cs index a9ed226c6d7..4dfd4f50cbd 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/TaskItemBuilder.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Board/TaskItemBuilder.cs @@ -13,6 +13,7 @@ public static TaskItem Create( string status = TaskStates.Open, int priority = TaskPriorities.Medium, string type = TaskTypes.Task, + string? title = null, string? assignee = null, DateTimeOffset? createdAt = null, DateTimeOffset? updatedAt = null, @@ -24,7 +25,7 @@ public static TaskItem Create( return new TaskItem { Id = id, - Title = id, + Title = title ?? id, Status = status, Priority = priority, Type = type, diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Details/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Details/FakeTaskStore.cs index a45ba938109..7f4f3c7f3f8 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Details/FakeTaskStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Details/FakeTaskStore.cs @@ -23,6 +23,10 @@ internal sealed class FakeTaskStore : ITaskStore public Task GetTaskAsync(string id, CancellationToken cancellationToken) => Task.FromResult(Tasks.GetValueOrDefault(id)); + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task> GetLabelsAsync(string taskId, CancellationToken cancellationToken) => Task.FromResult>(Labels.GetValueOrDefault(taskId) ?? []); @@ -106,6 +110,9 @@ public Task UndeferTaskAsync(string id, string actor, CancellationToke public Task DeleteTaskAsync(string id, string reason, string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task ReleaseAssigneeAsync(string agent, string reason, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task> CloseEligibleEpicsAsync(string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Editing/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Editing/FakeTaskStore.cs index 8d3f8752ba6..af8e013252d 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Editing/FakeTaskStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Editing/FakeTaskStore.cs @@ -97,6 +97,9 @@ public Task DeleteTaskAsync( return Task.FromResult(ResultTask); } + public Task ReleaseAssigneeAsync(string agent, string reason, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public string? FindWorkspaceDirectory() => throw new NotSupportedException(); public Task> QueryTasksAsync(TaskFilter filter, CancellationToken cancellationToken) @@ -105,6 +108,10 @@ public Task> QueryTasksAsync(TaskFilter filter, Cancella public Task GetTaskAsync(string id, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task GetRequiredTaskAsync(string id, CancellationToken cancellationToken) => throw new NotSupportedException(); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDataLoaderTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDataLoaderTests.cs index c4f770acc93..a72b29d1a28 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDataLoaderTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDataLoaderTests.cs @@ -7,219 +7,54 @@ public sealed class MailDataLoaderTests private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); [Fact] - public async Task LoadInboxAsync_Should_ExcludeArchived_When_FilterIsInbox() + public async Task LoadWorkspaceThreadsAsync_Should_ReturnEveryThread_When_AgentIsNull() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice", archivedAt: s_now)])); - var loader = new MailDataLoader(store); - - // act - var messages = await loader.LoadInboxAsync("alice", MailListFilter.Inbox, CancellationToken.None); - - // assert - Assert.Equal(["m-1"], messages.Select(m => m.Id)); - } - - [Fact] - public async Task LoadInboxAsync_Should_OnlyReturnUnread_When_FilterIsUnread() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice", readAt: s_now)])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var loader = new MailDataLoader(store); - - // act - var messages = await loader.LoadInboxAsync("alice", MailListFilter.Unread, CancellationToken.None); - - // assert - Assert.Equal(["m-2"], messages.Select(m => m.Id)); - } - - [Fact] - public async Task LoadInboxAsync_Should_OnlyReturnArchived_When_FilterIsArchived() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice", archivedAt: s_now)])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-1", sender: "bob", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); var loader = new MailDataLoader(store); // act - var messages = await loader.LoadInboxAsync("alice", MailListFilter.Archived, CancellationToken.None); + var threads = await loader.LoadWorkspaceThreadsAsync(agent: null, CancellationToken.None); // assert - Assert.Equal(["m-1"], messages.Select(m => m.Id)); + Assert.Equal(["t-1"], threads.Select(t => t.ThreadId)); } [Fact] - public async Task LoadInboxAsync_Should_ReturnNewestFirst() + public async Task LoadWorkspaceThreadsAsync_Should_NarrowToThreadsTheAgentSentOrReceived_When_AgentIsGiven() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-1", sender: "alice", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-2", sender: "carol", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("bob")])); var loader = new MailDataLoader(store); // act - var messages = await loader.LoadInboxAsync("alice", MailListFilter.Inbox, CancellationToken.None); + var threads = await loader.LoadWorkspaceThreadsAsync("alice", CancellationToken.None); // assert - Assert.Equal(["m-2", "m-1"], messages.Select(m => m.Id)); + Assert.Equal(["t-1"], threads.Select(t => t.ThreadId)); } [Fact] - public async Task LoadSentAsync_Should_ReturnMessagesTheActorSent_ExcludingReceivedMail() + public async Task LoadWorkspaceThreadsAsync_Should_ReturnNewestActivityFirst_When_MultipleThreadsExist() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var loader = new MailDataLoader(store); - - // act - var messages = await loader.LoadSentAsync("alice", CancellationToken.None); - - // assert - Assert.Equal(["m-1"], messages.Select(m => m.Id)); - } - - [Fact] - public async Task LoadSentAsync_Should_ReturnAnUnrepliedThreadRootMessage() - { - // arrange - // Alice sends to bob and has no recipient row on the message. - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", threadId: "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var loader = new MailDataLoader(store); - - // act - var inbox = await loader.LoadInboxAsync("alice", MailListFilter.Inbox, CancellationToken.None); - var sent = await loader.LoadSentAsync("alice", CancellationToken.None); - - // assert - Assert.Empty(inbox); - Assert.Equal(["m-1"], sent.Select(m => m.Id)); - } - - [Fact] - public async Task LoadAllAsync_Should_ReturnMessagesTheActorSentOrReceived() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "bob", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-3", sender: "bob", createdAt: s_now.AddMinutes(2), recipients: [MailMessageBuilder.ToRecipient("carol")])); - var loader = new MailDataLoader(store); - - // act - var messages = await loader.LoadAllAsync("alice", CancellationToken.None); - - // assert - Assert.Equal(["m-2", "m-1"], messages.Select(m => m.Id)); - } - - [Fact] - public async Task LoadWorkspaceAsync_Should_ReturnEveryMessage_IncludingBetweenTwoOtherAgents() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); - var loader = new MailDataLoader(store); - - // act - var inbox = await loader.LoadInboxAsync("alice", MailListFilter.Inbox, CancellationToken.None); - var sent = await loader.LoadSentAsync("alice", CancellationToken.None); - var all = await loader.LoadAllAsync("alice", CancellationToken.None); - var workspace = await loader.LoadWorkspaceAsync(agent: null, CancellationToken.None); - - // assert - Assert.Empty(inbox); - Assert.Empty(sent); - Assert.Empty(all); - Assert.Equal(["m-1"], workspace.Select(m => m.Id)); - } - - [Fact] - public async Task LoadWorkspaceAsync_Should_ReturnMessagesTheAgentSentOrReceived_When_AgentGiven() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-3", sender: "carol", createdAt: s_now.AddMinutes(2), recipients: [MailMessageBuilder.ToRecipient("bob")])); - var loader = new MailDataLoader(store); - - // act - var messages = await loader.LoadWorkspaceAsync("alice", CancellationToken.None); - - // assert - Assert.Equal(["m-2", "m-1"], messages.Select(m => m.Id)); - } - - [Fact] - public async Task LoadWorkspaceAsync_Should_ReturnMessageExactlyOnce_When_AgentIsOneOfSeveralCcRecipients() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "carol", - createdAt: s_now, - recipients: - [ - MailMessageBuilder.ToRecipient("bob"), - MailMessageBuilder.CcRecipient("alice", ordinal: 1), - MailMessageBuilder.CcRecipient("dave", ordinal: 2) - ])); - var loader = new MailDataLoader(store); - - // act - var messages = await loader.LoadWorkspaceAsync("alice", CancellationToken.None); - - // assert - Assert.Equal(["m-1"], messages.Select(m => m.Id)); - } - - [Fact] - public async Task LoadThreadAsync_Should_ReturnEveryMessageInTheThread_OldestFirst() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1))); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now)); + "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); store.Messages.Add(MailMessageBuilder.Create( - "m-3", threadId: "t-other", createdAt: s_now)); + "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); var loader = new MailDataLoader(store); // act - var messages = await loader.LoadThreadAsync("t-1", CancellationToken.None); + var threads = await loader.LoadWorkspaceThreadsAsync(agent: null, CancellationToken.None); // assert - Assert.Equal(["m-1", "m-2"], messages.Select(m => m.Id)); + Assert.Equal(["t-2", "t-1"], threads.Select(t => t.ThreadId)); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDetailViewTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDetailViewTests.cs index f9199d77799..8ce74b2f038 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDetailViewTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailDetailViewTests.cs @@ -9,106 +9,88 @@ public sealed class MailDetailViewTests { private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - private static async Task CreateStateWithMessageAsync(FakeMailStore store, string body = "Hello there.") - { - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - subject: "Status update", - body: body, - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice")])); - - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - - // Switch the selected thread to its single-message view. - state.ShowMessage(); - return state; - } - [Fact] - public async Task Render_Should_ShowSenderAndBody_When_MessageSelected() + public void RenderThread_Should_ShowSenderAndBody_When_OneMessageIsGiven() { // arrange - var store = new FakeMailStore(); - var state = await CreateStateWithMessageAsync(store); + var messages = new[] + { + MailMessageBuilder.Create("m-1", sender: "bob", subject: "Status update", body: "Hello there.", createdAt: s_now) + }; var view = new MailDetailView(); var console = new TestConsole().Width(80).Height(20); // act - console.Write(view.Render(state, 80, 20, focused: true)); + console.Write(view.RenderThread(messages, 80, 20, focused: true)); // assert - Assert.Contains("From: bob", console.Output); + Assert.Contains("Thread: Status update", console.Output); + Assert.Contains("bob", console.Output); Assert.Contains("Hello there.", console.Output); } [Fact] - public async Task Render_Should_ShowNoMessageSelected_When_MessagesListIsEmptyButLoaded() + public void RenderThread_Should_ShowNoMessages_When_ThreadIsEmpty() { // arrange - var store = new FakeMailStore(); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); var view = new MailDetailView(); var console = new TestConsole().Width(80).Height(20); // act - console.Write(view.Render(state, 80, 20, focused: true)); + console.Write(view.RenderThread([], 80, 20, focused: true)); // assert Assert.Contains("No messages.", console.Output); } [Fact] - public async Task Render_Should_ShowEveryMessageInTheThread_When_ViewModeIsThread() + public void RenderThread_Should_ShowEveryMessageOldestFirst_When_ThreadHasMultipleMessages() { // arrange - var store = new FakeMailStore(); - var state = await CreateStateWithMessageAsync(store); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", body: "Reply body.", threadId: "m-1", createdAt: s_now.AddMinutes(1))); - await state.ShowThreadAsync(CancellationToken.None); + var messages = new[] + { + MailMessageBuilder.Create("m-1", sender: "bob", body: "First.", createdAt: s_now), + MailMessageBuilder.Create("m-2", sender: "carol", body: "Second.", threadId: "m-1", createdAt: s_now.AddMinutes(1)) + }; var view = new MailDetailView(); var console = new TestConsole().Width(80).Height(20); // act - console.Write(view.Render(state, 80, 20, focused: true)); + console.Write(view.RenderThread(messages, 80, 20, focused: true)); // assert - Assert.Contains("bob", console.Output); - Assert.Contains("carol", console.Output); - Assert.Contains("Reply body.", console.Output); + var bobIndex = console.Output.IndexOf("bob", StringComparison.Ordinal); + var carolIndex = console.Output.IndexOf("carol", StringComparison.Ordinal); + Assert.True(bobIndex >= 0 && carolIndex > bobIndex); + Assert.Contains("First.", console.Output); + Assert.Contains("Second.", console.Output); } [Fact] - public async Task Render_Should_NotThrow_When_WidthOrHeightIsZero() + public void RenderThread_Should_NotThrow_When_WidthOrHeightIsZero() { // arrange - var store = new FakeMailStore(); - var state = await CreateStateWithMessageAsync(store); + var messages = new[] { MailMessageBuilder.Create("m-1", createdAt: s_now) }; var view = new MailDetailView(); // act - var exception = Record.Exception(() => view.Render(state, 0, 0, focused: true)); + var exception = Record.Exception(() => view.RenderThread(messages, 0, 0, focused: true)); // assert Assert.Null(exception); } [Fact] - public async Task Render_Should_WordWrapLongBody_WithoutClippingContent() + public void RenderThread_Should_WordWrapLongBody_When_BodyExceedsTheWidth() { // arrange - var store = new FakeMailStore(); var body = string.Join(" ", Enumerable.Repeat("word", 200)); - var state = await CreateStateWithMessageAsync(store, body); + var messages = new[] { MailMessageBuilder.Create("m-1", body: body, createdAt: s_now) }; var view = new MailDetailView(); var console = new TestConsole().Width(30).Height(40); // act - var exception = Record.Exception(() => console.Write(view.Render(state, 30, 40, focused: true))); + var exception = Record.Exception(() => console.Write(view.RenderThread(messages, 30, 40, focused: true))); // assert Assert.Null(exception); @@ -116,214 +98,57 @@ public async Task Render_Should_WordWrapLongBody_WithoutClippingContent() } [Fact] - public async Task Render_Should_ShowEachRecipientsOwnState_When_ReadStatesAreMixed() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - createdAt: s_now, - recipients: - [ - MailMessageBuilder.ToRecipient("orchestrator", ordinal: 0, readAt: s_now.AddHours(14).AddMinutes(2)), - MailMessageBuilder.ToRecipient("planner-1", ordinal: 1) - ])); - var state = new MailState("orchestrator", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view - var view = new MailDetailView(); - var console = new TestConsole().Width(80).Height(20); - - // act - console.Write(view.Render(state, 80, 20, focused: true)); - - // assert - Assert.Contains("orchestrator: read", console.Output); - Assert.Contains("planner-1: unread", console.Output); - } - - [Fact] - public async Task Render_Should_ShowArchivedMarker_When_RecipientHasArchived() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - createdAt: s_now, - recipients: - [ - MailMessageBuilder.ToRecipient("alice", readAt: s_now, archivedAt: s_now.AddMinutes(5)) - ])); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - // Use Workspace to include archived messages. - await state.SelectMailboxAsync(MailMailbox.Workspace, CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view - var view = new MailDetailView(); - var console = new TestConsole().Width(80).Height(20); - - // act - console.Write(view.Render(state, 80, 20, focused: true)); - - // assert - Assert.Contains("alice: read", console.Output); - Assert.Contains("archived", console.Output); - } - - [Fact] - public async Task Render_Should_ShowRecipientStatesAndNoSenderState_When_ActorSentTheMessage() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "alice", - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("bob")])); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - // Select Sent to display the message sent by alice. - await state.SelectMailboxAsync(MailMailbox.Sent, CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view - var view = new MailDetailView(); - var console = new TestConsole().Width(80).Height(20); - - // act - console.Write(view.Render(state, 80, 20, focused: true)); - - // assert - Assert.Contains("bob: unread", console.Output); - Assert.DoesNotContain("alice: unread", console.Output); - Assert.DoesNotContain("alice: read", console.Output); - } - - [Fact] - public async Task Render_Should_AttributeSenderAndRecipientClient_When_LookupHasNonEmptyEntries() + public void RenderThread_Should_AttributeEachSpeaker_When_HarnessLookupHasEntries() { // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view - var view = new MailDetailView(); - var console = new TestConsole().Width(80).Height(20); - var clientsByName = new Dictionary + var messages = new[] { - ["bob"] = "codex", - ["alice"] = "claude-code" + MailMessageBuilder.Create("m-1", sender: "bob", body: "Hello.", createdAt: s_now), + MailMessageBuilder.Create("m-2", sender: "carol", body: "Reply.", threadId: "m-1", createdAt: s_now.AddMinutes(1)) }; - - // act - console.Write(view.Render(state, 80, 20, focused: true, clientsByName)); - - // assert - Assert.Contains("From: bob (codex)", console.Output); - Assert.Contains("alice (claude-code): unread", console.Output); - } - - [Fact] - public async Task Render_Should_ShowNoAttribution_When_ClientIsEmptyOrAgentIsUnknownToTheLookup() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view var view = new MailDetailView(); var console = new TestConsole().Width(80).Height(20); - // Supply an empty client for bob and no lookup entry for alice. - var clientsByName = new Dictionary { ["bob"] = "" }; + var harnessesByName = new Dictionary { ["bob"] = "Codex", ["carol"] = "Claude Code" }; // act - console.Write(view.Render(state, 80, 20, focused: true, clientsByName)); + console.Write(view.RenderThread(messages, 80, 20, focused: true, harnessesByName)); // assert - Assert.Contains("From: bob", console.Output); - Assert.DoesNotContain("From: bob (", console.Output); - Assert.Contains("alice: unread", console.Output); - Assert.DoesNotContain("alice (", console.Output); + Assert.Contains("bob (Codex)", console.Output); + Assert.Contains("carol (Claude Code)", console.Output); } [Fact] - public async Task Render_Should_ShowBracketsLiterally_When_ClientContainsMarkupSyntax() + public void RenderThread_Should_ShowNoAttribution_When_HarnessIsEmptyOrLookupHasNoEntry() { // arrange - // Use a client name containing markup brackets. - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view + var messages = new[] { MailMessageBuilder.Create("m-1", sender: "bob", createdAt: s_now) }; var view = new MailDetailView(); var console = new TestConsole().Width(80).Height(20); - var clientsByName = new Dictionary { ["bob"] = "claude-opus-5[1m]" }; + var harnessesByName = new Dictionary { ["bob"] = "" }; // act - var exception = Record.Exception(() => console.Write(view.Render(state, 80, 20, focused: true, clientsByName))); + console.Write(view.RenderThread(messages, 80, 20, focused: true, harnessesByName)); + var actual = ( + HasName: console.Output.Contains("bob", StringComparison.Ordinal), + HasAttribution: console.Output.Contains("bob (", StringComparison.Ordinal)); // assert - Assert.Null(exception); - Assert.Contains("From: bob (claude-opus-5[1m])", console.Output); + Assert.Equal((true, false), actual); } [Fact] - public async Task Render_Should_AttributeEachSpeakerInTheThread_When_LookupHasEntries() + public void RenderThread_Should_StayWithinPaneHeight_When_ThreadHasManyMessages() { // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", body: "Hello.", createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", body: "Reply body.", threadId: "m-1", createdAt: s_now.AddMinutes(1))); - var state = new MailState("alice", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - await state.ShowThreadAsync(CancellationToken.None); - var view = new MailDetailView(); - var console = new TestConsole().Width(80).Height(20); - var clientsByName = new Dictionary { ["bob"] = "codex", ["carol"] = "claude-code" }; - - // act - console.Write(view.Render(state, 80, 20, focused: true, clientsByName)); - - // assert - Assert.Contains("bob (codex)", console.Output); - Assert.Contains("carol (claude-code)", console.Output); - } - - [Fact] - public async Task Render_Should_StayWithinPaneHeight_When_BroadcastHasManyRecipients() - { - // arrange - var store = new FakeMailStore(); - var recipients = Enumerable.Range(0, 20) - .Select(i => MailMessageBuilder.ToRecipient($"agent-{i}", ordinal: i)) + var messages = Enumerable.Range(0, 20) + .Select(i => MailMessageBuilder.Create($"m-{i}", threadId: "m-0", createdAt: s_now.AddMinutes(i))) .ToArray(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: recipients)); - var state = new MailState("agent-0", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); var view = new MailDetailView(); var console = new TestConsole().Width(80).Height(20); // act - var exception = Record.Exception(() => console.Write(view.Render(state, 80, 20, focused: true))); + var exception = Record.Exception(() => console.Write(view.RenderThread(messages, 80, 20, focused: true))); // assert Assert.Null(exception); @@ -332,47 +157,34 @@ public async Task Render_Should_StayWithinPaneHeight_When_BroadcastHasManyRecipi } [Fact] - public async Task Render_Should_ApplyAnsiStyling_ToFieldLabelToken() + public void RenderThread_Should_ApplyAnsiStyling_When_RenderingTheSpeakerHeader() { // arrange - var store = new FakeMailStore(); - var state = await CreateStateWithMessageAsync(store); + var messages = new[] { MailMessageBuilder.Create("m-1", sender: "bob", createdAt: s_now) }; var view = new MailDetailView(); var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(80).Height(20); // act - console.Write(view.Render(state, 80, 20, focused: true)); + console.Write(view.RenderThread(messages, 80, 20, focused: true)); // assert - AssertAnsiStylePrefixesText(console.Output, "detail.section.header", "From:"); + AssertAnsiStylePrefixesText(console.Output, "detail.section.header", "bob"); } [Fact] - public async Task Render_Should_ApplyAnsiStyling_ToRecipientStateTokens_ForUnreadAndRead() + public void ScrollDown_And_ScrollUp_Should_NotThrow_When_CalledBeforeAnyRender() { // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", - sender: "bob", - createdAt: s_now, - recipients: - [ - MailMessageBuilder.ToRecipient("orchestrator", ordinal: 0, readAt: s_now.AddHours(14).AddMinutes(2)), - MailMessageBuilder.ToRecipient("planner-1", ordinal: 1) - ])); - var state = new MailState("orchestrator", new MailDataLoader(store)); - await state.RefreshAsync(CancellationToken.None); - state.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view var view = new MailDetailView(); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(80).Height(20); // act - console.Write(view.Render(state, 80, 20, focused: true)); + var exception = Record.Exception(() => + { + view.ScrollDown(); + view.ScrollUp(); + }); // assert - AssertAnsiStylePrefixesText( - console.Output, "mail.detail.recipient.read", "orchestrator: read 2026-01-01 14:02"); - AssertAnsiStylePrefixesText(console.Output, "mail.detail.recipient.unread", "planner-1: unread"); + Assert.Null(exception); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailKeyMapTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailKeyMapTests.cs index 3670cf61ca2..2afee9313ec 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailKeyMapTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailKeyMapTests.cs @@ -7,7 +7,7 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; public sealed class MailKeyMapTests { [Fact] - public void CreateDefault_Should_MapJAndDownArrow_ToMoveCursorDown() + public void CreateDefault_Should_ReturnMoveCursorDown_When_JOrDownArrowIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); @@ -24,112 +24,101 @@ public void CreateDefault_Should_MapJAndDownArrow_ToMoveCursorDown() } [Fact] - public void CreateDefault_Should_MapEnter_ToOpenSelected() + public void CreateDefault_Should_ReturnMoveCursorUp_When_KOrUpArrowIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var enter = new KeyChord(ConsoleKey.Enter, ConsoleModifiers.None, '\r'); - - // act - var resolved = keyMap.TryResolve(enter, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapTab_ToMoveCursorRight() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var tab = new KeyChord(ConsoleKey.Tab, ConsoleModifiers.None, '\t'); + var k = new KeyChord(ConsoleKey.K, ConsoleModifiers.None, 'k'); + var up = new KeyChord(ConsoleKey.UpArrow, ConsoleModifiers.None, '\0'); // act - var resolved = keyMap.TryResolve(tab, out var message); + keyMap.TryResolve(k, out var kMessage); + keyMap.TryResolve(up, out var upMessage); // assert - Assert.True(resolved); - Assert.Equal(CursorDirection.Right, Assert.IsType(message).Direction); + Assert.Equal(CursorDirection.Up, Assert.IsType(kMessage).Direction); + Assert.Equal(CursorDirection.Up, Assert.IsType(upMessage).Direction); } [Fact] - public void CreateDefault_Should_MapF_ToCycleViewForward() + public void CreateDefault_Should_ReturnMoveToEdge_When_GOrShiftGIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var f = new KeyChord(ConsoleKey.F, ConsoleModifiers.None, 'f'); + var g = new KeyChord(ConsoleKey.G, ConsoleModifiers.None, 'g'); + var shiftG = new KeyChord(ConsoleKey.G, ConsoleModifiers.Shift, 'G'); // act - var resolved = keyMap.TryResolve(f, out var message); + keyMap.TryResolve(g, out var top); + keyMap.TryResolve(shiftG, out var bottom); // assert - Assert.True(resolved); - Assert.Equal(1, Assert.IsType(message).Delta); + Assert.Equal(EdgeTarget.Top, Assert.IsType(top).Edge); + Assert.Equal(EdgeTarget.Bottom, Assert.IsType(bottom).Edge); } [Fact] - public void CreateDefault_Should_MapShiftF_ToCycleViewBackward() + public void CreateDefault_Should_ReturnOpenSelected_When_EnterIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var shiftF = new KeyChord(ConsoleKey.F, ConsoleModifiers.Shift, 'F'); + var enter = new KeyChord(ConsoleKey.Enter, ConsoleModifiers.None, '\r'); // act - var resolved = keyMap.TryResolve(shiftF, out var message); + var resolved = keyMap.TryResolve(enter, out var message); // assert Assert.True(resolved); - Assert.Equal(-1, Assert.IsType(message).Delta); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapT_ToToggleMaximize() + public void CreateDefault_Should_ReturnAgentFilterPickerRequested_When_PIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var t = new KeyChord(ConsoleKey.T, ConsoleModifiers.None, 't'); + var p = new KeyChord(ConsoleKey.P, ConsoleModifiers.None, 'p'); // act - var resolved = keyMap.TryResolve(t, out var message); + var resolved = keyMap.TryResolve(p, out var message); // assert Assert.True(resolved); - Assert.IsType(message); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapU_ToToggleReadRequested() + public void CreateDefault_Should_ReturnSearchRequested_When_SlashIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var u = new KeyChord(ConsoleKey.U, ConsoleModifiers.None, 'u'); + var slash = new KeyChord(ConsoleKey.Oem2, ConsoleModifiers.None, '/'); // act - var resolved = keyMap.TryResolve(u, out var message); + var resolved = keyMap.TryResolve(slash, out var message); // assert Assert.True(resolved); - Assert.IsType(message); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapA_ToArchiveRequested() + public void CreateDefault_Should_ReturnCopySelectedId_When_YIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var a = new KeyChord(ConsoleKey.A, ConsoleModifiers.None, 'a'); + var y = new KeyChord(ConsoleKey.Y, ConsoleModifiers.None, 'y'); // act - var resolved = keyMap.TryResolve(a, out var message); + var resolved = keyMap.TryResolve(y, out var message); // assert Assert.True(resolved); - Assert.IsType(message); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapR_ToReplyRequested() + public void CreateDefault_Should_ReturnRefreshRequested_When_RIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); @@ -138,43 +127,13 @@ public void CreateDefault_Should_MapR_ToReplyRequested() // act var resolved = keyMap.TryResolve(r, out var message); - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapC_ToComposeRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var c = new KeyChord(ConsoleKey.C, ConsoleModifiers.None, 'c'); - - // act - var resolved = keyMap.TryResolve(c, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapShiftR_ToRefreshRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var shiftR = new KeyChord(ConsoleKey.R, ConsoleModifiers.Shift, 'R'); - - // act - var resolved = keyMap.TryResolve(shiftR, out var message); - // assert Assert.True(resolved); Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapQ_ToQuitRequested() + public void CreateDefault_Should_ReturnQuitRequested_When_QIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); @@ -189,11 +148,11 @@ public void CreateDefault_Should_MapQ_ToQuitRequested() } [Fact] - public void CreateDefault_Should_MapEscape_ToBack() + public void CreateDefault_Should_ReturnBack_When_EscapeIsResolved() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var escape = new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, ''); + var escape = new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, '\u001b'); // act var resolved = keyMap.TryResolve(escape, out var message); @@ -204,153 +163,41 @@ public void CreateDefault_Should_MapEscape_ToBack() } [Fact] - public void CreateDefault_Should_MapShiftI_ToSelectInboxRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var shiftI = new KeyChord(ConsoleKey.I, ConsoleModifiers.Shift, 'I'); - - // act - var resolved = keyMap.TryResolve(shiftI, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapShiftS_ToSelectSentRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var shiftS = new KeyChord(ConsoleKey.S, ConsoleModifiers.Shift, 'S'); - - // act - var resolved = keyMap.TryResolve(shiftS, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapShiftL_ToSelectAllMailRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var shiftL = new KeyChord(ConsoleKey.L, ConsoleModifiers.Shift, 'L'); - - // act - var resolved = keyMap.TryResolve(shiftL, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapShiftW_ToSelectWorkspaceMailRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var shiftW = new KeyChord(ConsoleKey.W, ConsoleModifiers.Shift, 'W'); - - // act - var resolved = keyMap.TryResolve(shiftW, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapP_ToAgentFilterPickerRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var p = new KeyChord(ConsoleKey.P, ConsoleModifiers.None, 'p'); - - // act - var resolved = keyMap.TryResolve(p, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_CarryADedicatedInboxHint_Separate_FromTheOtherMailboxJumps() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - - // act - var inboxHint = keyMap.Hints.Single(h => h.Key == "I"); - - // assert - Assert.Contains("inbox", inboxHint.Action, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain(keyMap.Hints, h => h.Key.Contains('I') && h.Key != "I"); - } - - [Fact] - public void CreateDefault_Should_NotBind_TaskOnlyGestures() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); - var e = new KeyChord(ConsoleKey.E, ConsoleModifiers.None, 'e'); - var t = new KeyChord(ConsoleKey.X, ConsoleModifiers.Shift, 'X'); - - // act - var eResolved = keyMap.TryResolve(e, out _); - var xResolved = keyMap.TryResolve(t, out _); - - // assert - Assert.False(eResolved); - Assert.False(xResolved); - } - - [Fact] - public void CreateDefault_Should_MapShiftT_ToToggleListModeRequested() + public void CreateDefault_Should_NotResolveWriteGestures_When_TheyMatchTheRetiredSplitPaneBoard() { // arrange var keyMap = MailKeyMap.CreateDefault(); + var u = new KeyChord(ConsoleKey.U, ConsoleModifiers.None, 'u'); + var a = new KeyChord(ConsoleKey.A, ConsoleModifiers.None, 'a'); + var c = new KeyChord(ConsoleKey.C, ConsoleModifiers.None, 'c'); var shiftV = new KeyChord(ConsoleKey.V, ConsoleModifiers.Shift, 'V'); - - // act - var resolved = keyMap.TryResolve(shiftV, out var message); - - // assert - Assert.True(resolved); - Assert.IsType(message); - } - - [Fact] - public void CreateDefault_Should_MapZ_ToFoldPrefixRequested() - { - // arrange - var keyMap = MailKeyMap.CreateDefault(); var z = new KeyChord(ConsoleKey.Z, ConsoleModifiers.None, 'z'); // act - var resolved = keyMap.TryResolve(z, out var message); + var uResolved = keyMap.TryResolve(u, out _); + var aResolved = keyMap.TryResolve(a, out _); + var cResolved = keyMap.TryResolve(c, out _); + var vResolved = keyMap.TryResolve(shiftV, out _); + var zResolved = keyMap.TryResolve(z, out _); // assert - Assert.True(resolved); - Assert.IsType(message); + Assert.False(uResolved); + Assert.False(aResolved); + Assert.False(cResolved); + Assert.False(vResolved); + Assert.False(zResolved); } [Fact] - public void CreateDefault_Should_KeepLowercaseT_Bound_ToToggleMaximize() + public void CreateDefault_Should_ListHintsInBindingOrder_When_KeyMapIsBuilt() { // arrange var keyMap = MailKeyMap.CreateDefault(); - var t = new KeyChord(ConsoleKey.T, ConsoleModifiers.None, 't'); // act - var resolved = keyMap.TryResolve(t, out var message); + var keys = keyMap.Hints.Select(h => h.Key).ToList(); // assert - Assert.True(resolved); - Assert.IsType(message); + Assert.Equal(["hjkl", "enter", "p", "/", "y", "r", "esc", "q"], keys); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeRealStoreTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeRealStoreTests.cs deleted file mode 100644 index f3c1a8d7357..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeRealStoreTests.cs +++ /dev/null @@ -1,219 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Mail; -using ChilliCream.Nitro.CommandLine.Services.Workspace; -using ChilliCream.Nitro.CommandLine.Tests.Commands; -using ChilliCream.Nitro.CommandLine.Tests.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Input; -using ChilliCream.Nitro.CommandLine.Tui.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Widgets.Form; -using Microsoft.Extensions.Time.Testing; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; - -/// -/// Exercises and its overlays against a real /SQLite -/// workspace. -/// -public sealed class MailModeRealStoreTests : IAsyncDisposable -{ - private readonly DirectoryInfo _tempRoot; - private readonly string _workingDirectory; - private readonly string _workspaceDirectory; - private readonly FakeTimeProvider _timeProvider; - private readonly AgentRegistry _registry; - private readonly MailStore _store; - - public MailModeRealStoreTests() - { - _tempRoot = Directory.CreateTempSubdirectory("nitro-mail-mode-tests"); - _workingDirectory = Path.Combine(_tempRoot.FullName, "acme"); - Directory.CreateDirectory(_workingDirectory); - _workspaceDirectory = AgentWorkspace.GetDirectory(_workingDirectory); - - _timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 12, 0, 0, TimeSpan.Zero)); - _registry = new AgentRegistry(new TestFileSystem(_workingDirectory), _timeProvider, new AgentDatabase()); - - _store = new MailStore( - new TestFileSystem(_workingDirectory), - _timeProvider, - new AgentDatabase(), - _registry, - new FixedInstanceIdProvider("host-1"), - new FixedGlobalConfigDirectoryProvider(_workingDirectory)); - } - - public async ValueTask DisposeAsync() - { - await Task.CompletedTask; - _tempRoot.Delete(recursive: true); - } - - private static ConsoleKeyInfo Key(char c) => new(c, ConsoleKey.NoName, false, false, false); - - private static ConsoleKeyInfo Key(ConsoleKey key) => new('\0', key, false, false, false); - - private static ConsoleKeyInfo CtrlKey(ConsoleKey key) => new('\0', key, false, false, true); - - private static void Type(MailMode mode, string text) - { - foreach (var c in text) - { - mode.HandleRawKey(Key(c)); - } - } - - private async Task InitAsync(CancellationToken cancellationToken) - { - Directory.CreateDirectory(_workspaceDirectory); - await _store.InitializeWorkspaceAsync(_workspaceDirectory, cancellationToken); - } - - private MailMode CreateMode(string actor) => new(_store, actor, _registry, _timeProvider); - - /// - /// Refreshes until a non- outcome toast - /// is returned. Cancels the wait after five seconds or when the supplied token is cancelled. - /// - private static async Task WaitForOutcomeToastAsync( - MailMode mode, CancellationToken cancellationToken) - { - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeoutCts.CancelAfter(TimeSpan.FromSeconds(5)); - - while (true) - { - var result = mode.Handle(new TuiMessage.RefreshRequested()); - - foreach (var message in result) - { - var toast = Assert.IsType(message); - - if (toast.Style != ToastStyle.Info) - { - return toast; - } - } - - await Task.Delay(5, timeoutCts.Token); - } - } - - [Fact] - public async Task OpenSelected_Should_MarkMessageRead_AgainstTheRealStore() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitAsync(cancellationToken); - await _registry.RegisterAsync("alice", role: "", client: "", cancellationToken); - await _registry.RegisterAsync("bob", role: "", client: "", cancellationToken); - var sent = await _store.SendMessageAsync( - new MailMessageCreation { Sender = "bob", Subject = "Hi", Body = "Body", To = ["alice"] }, - cancellationToken); - - var mode = CreateMode("alice"); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - - // act - mode.Handle(new TuiMessage.OpenSelected()); - - // assert - var reloaded = await _store.GetRequiredMessageAsync(sent.Id, cancellationToken); - var recipient = MailRecipientView.FindRecipient(reloaded, "alice"); - Assert.NotNull(recipient!.ReadAt); - } - - [Fact] - public async Task ArchiveConfirmation_Confirmed_Should_ArchiveMessage_AgainstTheRealStore() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - await InitAsync(cancellationToken); - await _registry.RegisterAsync("alice", role: "", client: "", cancellationToken); - await _registry.RegisterAsync("bob", role: "", client: "", cancellationToken); - var sent = await _store.SendMessageAsync( - new MailMessageCreation { Sender = "bob", Subject = "Hi", Body = "Body", To = ["alice"] }, - cancellationToken); - - var mode = CreateMode("alice"); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ArchiveRequested()); - - // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Success, Assert.IsType(toast).Style); - - var reloaded = await _store.GetRequiredMessageAsync(sent.Id, cancellationToken); - var recipient = MailRecipientView.FindRecipient(reloaded, "alice"); - Assert.NotNull(recipient!.ArchivedAt); - - var defaultInbox = await _store.QueryInboxAsync( - new MailInboxFilter { Actor = "alice" }, cancellationToken); - Assert.Empty(defaultInbox); - } - - [Fact] - public async Task ComposeForm_Submit_Should_CreateImplicitRow_When_RecipientIsUnknown() - { - // arrange - // Compose a message to an unregistered recipient. - var cancellationToken = TestContext.Current.CancellationToken; - await InitAsync(cancellationToken); - await _registry.RegisterAsync("alice", role: "", client: "", cancellationToken); - - var mode = CreateMode("alice"); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "ghost"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // act - await WaitForOutcomeToastAsync(mode, cancellationToken); - - // assert - var ghost = await _registry.GetAsync("ghost", cancellationToken); - Assert.True(ghost?.Implicit); - } - - [Fact] - public async Task ReplyForm_Submit_Should_ComputeTheSameRecipientSet_AsTheCliReplyCommand() - { - // arrange - // Seed matching threads for a direct reply and a reply built by the form. - var cancellationToken = TestContext.Current.CancellationToken; - await InitAsync(cancellationToken); - await _registry.RegisterAsync("alice", role: "", client: "", cancellationToken); - await _registry.RegisterAsync("bob", role: "", client: "", cancellationToken); - await _registry.RegisterAsync("carol", role: "", client: "", cancellationToken); - - var cliOriginal = await _store.SendMessageAsync( - new MailMessageCreation { Sender = "bob", Subject = "Plan", Body = "Body", To = ["alice"], Cc = ["carol"] }, - cancellationToken); - var tuiOriginal = await _store.SendMessageAsync( - new MailMessageCreation { Sender = "bob", Subject = "Plan", Body = "Body", To = ["alice"], Cc = ["carol"] }, - cancellationToken); - - // act - var cliReply = await _store.ReplyMessageAsync(cliOriginal.Id, "alice", "CLI reply", cancellationToken); - - var replyForm = new MailReplyForm(tuiOriginal); - var values = new Dictionary { [MailReplyForm.BodyFieldId] = new FormValue.Text("TUI reply") }; - var request = replyForm.BuildRequest(values, "alice"); - var tuiReply = await _store.ReplyMessageAsync( - request.InReplyToId, request.Actor, request.Body, MailWakePolicy.Enqueue, cancellationToken); - - // assert - var cliRecipientNames = cliReply.Recipients.Select(r => r.Name).OrderBy(n => n, StringComparer.Ordinal); - var tuiRecipientNames = tuiReply.Recipients.Select(r => r.Name).OrderBy(n => n, StringComparer.Ordinal); - Assert.Equal(cliRecipientNames, tuiRecipientNames); - Assert.Equal(["bob", "carol"], cliRecipientNames); - } -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeTests.cs index b2a9642f7cd..9fd5093a004 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailModeTests.cs @@ -1,17 +1,11 @@ -using System.Diagnostics; -using System.Threading.Channels; using ChilliCream.Nitro.CommandLine.Services.Workspace; using ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; using ChilliCream.Nitro.CommandLine.Tui.Input; using ChilliCream.Nitro.CommandLine.Tui.Mail; -using ChilliCream.Nitro.CommandLine.Tui.Runtime; using ChilliCream.Nitro.CommandLine.Tui.Shell; -using ChilliCream.Nitro.CommandLine.Tui.Theming; using Microsoft.Extensions.Time.Testing; -using Spectre.Console; using Spectre.Console.Testing; using CursorDirection = ChilliCream.Nitro.CommandLine.Tui.Input.CursorDirection; -using static ChilliCream.Nitro.CommandLine.Tests.Tui.AnsiAssertions; namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; @@ -19,29 +13,31 @@ public sealed class MailModeTests { private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - private static MailMode CreateMode( - FakeMailStore store, - string? actor = "alice", - FakeAgentRegistry? agentRegistry = null) - => new( - store, - actor, - agentRegistry ?? new FakeAgentRegistry(), - new FakeTimeProvider(s_now)); - - private static AgentRecord Agent(string name) => new() + private static MailMode CreateMode(FakeMailStore store, FakeAgentStore? agentStore = null) + => new(store, agentStore ?? new FakeAgentStore(new FakeTimeProvider(s_now)), new FakeTimeProvider(s_now)); + + private static AgentRow Agent(string name) => new() { Name = name, Role = "", - Client = "", - Implicit = false, + HarnessVersion = "", + Cwd = "", + WorkspacePath = "", RegisteredAt = s_now, - LastSeenAt = s_now + StartedAt = s_now, + LastSeenAt = s_now, + EndpointKind = AgentSessionEndpointKind.None, + EndpointAddr = "", + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false }; - private static void AddMessage(FakeMailStore store, string id, DateTimeOffset createdAt, string actor = "alice") + private static void AddThread( + FakeMailStore store, string threadId, string sender, string recipient, DateTimeOffset createdAt) => store.Messages.Add(MailMessageBuilder.Create( - id, createdAt: createdAt, recipients: [MailMessageBuilder.ToRecipient(actor)])); + threadId, sender: sender, threadId: threadId, createdAt: createdAt, + recipients: [MailMessageBuilder.ToRecipient(recipient)])); private static ConsoleKeyInfo Key(char c) => new(c, ConsoleKey.NoName, false, false, false); @@ -57,272 +53,156 @@ private static void Type(MailMode mode, string text) } } - [Fact] - public void MutatingGesture_Should_BeRefused_When_TheBoardHasNoIdentity() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store, actor: null); - mode.OnEnter(); - - // act - var followUp = mode.Handle(new TuiMessage.ToggleReadRequested()); - - // assert - var shown = Assert.IsType(Assert.Single(followUp)); - Assert.Equal(BoardIdentity.NoIdentityMessage, shown.Text); - Assert.Equal(ToastStyle.Warn, shown.Style); - } - - [Fact] - public void JumpToInbox_Should_BeRefused_And_StayOnWorkspace_When_TheBoardHasNoIdentity() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store, actor: null); - mode.OnEnter(); - - // act - var followUp = mode.Handle(new TuiMessage.SelectInboxRequested()); - - // assert - var shown = Assert.IsType(Assert.Single(followUp)); - Assert.Equal(BoardIdentity.NoIdentityMessage, shown.Text); - Assert.Equal(MailMailbox.Workspace, mode.State.Mailbox); - } - - [Fact] - public void Workspace_Should_ListEveryAgentsMail_When_TheBoardHasNoIdentity() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now, actor: "alice"); - AddMessage(store, "m-2", s_now.AddMinutes(1), actor: "bob"); - - // act - var mode = CreateMode(store, actor: null); - mode.OnEnter(); - - // assert - Assert.Equal(MailMailbox.Workspace, mode.State.Mailbox); - Assert.Equal(2, mode.State.Messages.Count); - Assert.Equal(0, mode.UnreadCount); - } - - [Fact] - public void MoveSelection_Should_ClampAtLastRow_When_MovingDownPastEnd() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now.AddMinutes(1)); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); - - // assert - Assert.Equal(1, mode.State.SelectedRow); - } - - [Fact] - public void MoveSelection_Should_ClampAtFirstRow_When_MovingUpPastStart() + private static string RenderToText(MailMode mode, int width = 100, int height = 24) { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Up)); - - // assert - Assert.Equal(0, mode.State.SelectedRow); + var console = new TestConsole().Width(width); + console.Write(mode.Render(width, height)); + return console.Output; } [Fact] - public void MoveToEdge_Should_SelectLastRow_When_Bottom() + public void Render_Should_ShowTheEmptyStateMessage_When_NoMailExists() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now.AddMinutes(1)); - AddMessage(store, "m-3", s_now.AddMinutes(2)); var mode = CreateMode(store); mode.OnEnter(); // act - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); + var text = RenderToText(mode); // assert - Assert.Equal(2, mode.State.SelectedRow); + Assert.Contains("No mail yet.", text); } [Fact] - public void MoveToEdge_Should_SelectFirstRow_When_Top() + public void Render_Should_ShowTheThreadCount_When_HeaderIsRendered() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now.AddMinutes(1)); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "bob", "alice", s_now.AddMinutes(1)); var mode = CreateMode(store); mode.OnEnter(); - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); // act - mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Top)); + var text = RenderToText(mode); // assert - Assert.Equal(0, mode.State.SelectedRow); + Assert.Contains("Mail (2)", text); } [Fact] - public void MoveCursor_Should_TogglePaneFocus_When_Left() + public void Render_Should_OrderThreadsByLastActivityDescending_When_ThreeThreadsExist() { // arrange var store = new FakeMailStore(); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(-2)); + AddThread(store, "t-3", "dave", "alice", s_now.AddMinutes(-1)); var mode = CreateMode(store); mode.OnEnter(); - Assert.Equal(MailFocus.List, mode.State.Focus); // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Left)); + var text = RenderToText(mode); // assert - Assert.Equal(MailFocus.Detail, mode.State.Focus); + var t1Index = text.IndexOf("bob", StringComparison.Ordinal); + var t3Index = text.IndexOf("dave", StringComparison.Ordinal); + var t2Index = text.IndexOf("carol", StringComparison.Ordinal); + Assert.True(t1Index >= 0 && t3Index > t1Index && t2Index > t3Index); } [Fact] - public void MoveCursor_Should_TogglePaneFocus_When_Right() + public void Render_Should_ShowHeaderRuleAndRows_When_ThreeThreadsArePresent() { // arrange var store = new FakeMailStore(); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(-2)); + AddThread(store, "t-3", "dave", "alice", s_now.AddMinutes(-1)); var mode = CreateMode(store); mode.OnEnter(); - Assert.Equal(MailFocus.List, mode.State.Focus); + var console = new TestConsole().Width(100); // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Right)); + console.Write(mode.Render(100, 9)); // assert - Assert.Equal(MailFocus.Detail, mode.State.Focus); - } - - [Fact] - public void OpenSelected_Should_FocusDetailPane() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - mode.Handle(new TuiMessage.OpenSelected()); + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Mail (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ SUBJECT FROM TO MESSAGES LAST ACTIVITY โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > Subject bob alice 1 just now โ”‚ + โ”‚ Subject dave alice 1 1m ago โ”‚ + โ”‚ Subject carol alice 1 2m ago โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - // assert - Assert.Equal(MailFocus.Detail, mode.State.Focus); + """); } [Fact] - public void RefreshRequested_Should_ReloadMessages() + public void MoveSelection_Should_ClampAtLastRow_When_MovingDownPastEnd() { // arrange var store = new FakeMailStore(); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(1)); var mode = CreateMode(store); mode.OnEnter(); - Assert.Empty(mode.State.Messages); // act - AddMessage(store, "m-1", s_now); - mode.Handle(new TuiMessage.RefreshRequested()); + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); + mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); // assert - Assert.Equal(["m-1"], mode.State.Messages.Select(m => m.Id)); + Assert.Equal(1, mode.State.SelectedRow); } [Fact] - public void CycleView_Should_AdvanceTheListFilter() + public void MoveSelectionToEdge_Should_SelectLastRow_When_Bottom() { // arrange var store = new FakeMailStore(); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(1)); + AddThread(store, "t-3", "dave", "alice", s_now.AddMinutes(2)); var mode = CreateMode(store); mode.OnEnter(); // act - mode.Handle(new TuiMessage.CycleView(1)); + mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); // assert - Assert.Equal(MailListFilter.Unread, mode.State.Filter); + Assert.Equal(2, mode.State.SelectedRow); } [Fact] - public void ToggleMaximize_Should_SwitchToThreadView_When_MessageSelected() + public void OpenSelected_Should_BeANoOp_When_AThreadIsSelected() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); + AddThread(store, "t-1", "bob", "alice", s_now); var mode = CreateMode(store); mode.OnEnter(); - // flip to Flat mode, so a message row (not a thread row) is selected - mode.State.ToggleListMode(); // act - var followUp = mode.Handle(new TuiMessage.ToggleMaximize()); + var followUp = mode.Handle(new TuiMessage.OpenSelected()); // assert Assert.Empty(followUp); - Assert.Equal(MailViewMode.Thread, mode.State.ViewMode); - } - - [Fact] - public void ToggleMaximize_Should_ShowWarningToast_When_NoMessageSelected() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - var followUp = mode.Handle(new TuiMessage.ToggleMaximize()); - - // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Warn, shown.Style); - } - - [Fact] - public void ToggleMaximize_Should_SwitchBackToMessageView_When_AlreadyShowingThread() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - // flip to Flat mode first, so the arrange toggle is the one that enters Thread view - mode.State.ToggleListMode(); - mode.Handle(new TuiMessage.ToggleMaximize()); - - // act - mode.Handle(new TuiMessage.ToggleMaximize()); - - // assert - Assert.Equal(MailViewMode.Message, mode.State.ViewMode); + Assert.Equal(0, mode.State.SelectedRow); } [Fact] - public void CopySelectedId_Should_ShowInfoToast_When_MessageSelected() + public void CopySelectedId_Should_ReturnTheThreadId_When_AThreadIsSelected() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); + AddThread(store, "t-1", "bob", "alice", s_now); var mode = CreateMode(store); mode.OnEnter(); @@ -332,12 +212,11 @@ public void CopySelectedId_Should_ShowInfoToast_When_MessageSelected() // assert var toast = Assert.Single(followUp); var shown = Assert.IsType(toast); - Assert.Equal("m-1", shown.Text); - Assert.Equal(ToastStyle.Info, shown.Style); + Assert.Equal("t-1", shown.Text); } [Fact] - public void CopySelectedId_Should_ShowWarningToast_When_NoMessageSelected() + public void CopySelectedId_Should_ReturnAWarning_When_NoThreadIsSelected() { // arrange var store = new FakeMailStore(); @@ -354,195 +233,139 @@ public void CopySelectedId_Should_ShowWarningToast_When_NoMessageSelected() } [Fact] - public void Render_Should_IncludeListHeaderAndBadges() + public void TryCreatePopover_Should_ReturnNull_When_NoThreadIsSelected() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); var mode = CreateMode(store); mode.OnEnter(); - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("Workspace (1)", console.Output); - Assert.Contains("From", console.Output); - Assert.Contains("Subject", console.Output); - Assert.Contains("sender", console.Output); - } - - [Fact] - public void Render_Should_AttributeSenderClient_InTheDetailPane_When_SenderHasOne() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob") with { Client = "codex" }); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.State.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("From: bob (codex)", console.Output); - } - - [Fact] - public void OnEnter_Should_NotThrow_When_RegistryHasCaseVariantDuplicateNames() - { - // arrange - // a registry can hold "bob" and "Bob" side by side; the case-insensitive lookup must not throw - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob") with { Client = "codex" }); - registry.Agents.Add(Agent("Bob") with { Client = "claude-code" }); - var mode = CreateMode(store, agentRegistry: registry); // act - var exception = Record.Exception(mode.OnEnter); + var popover = mode.TryCreatePopover(); // assert - Assert.Null(exception); + Assert.Null(popover); } [Fact] - public void Render_Should_ShowNoAttribution_InTheDetailPane_When_SenderHasNoRegisteredClient() + public void TryCreatePopover_Should_ReturnAPopoverForTheSelectedThread_When_AThreadIsSelected() { // arrange var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store, agentRegistry: new FakeAgentRegistry()); + AddThread(store, "t-1", "bob", "alice", s_now); + var mode = CreateMode(store); mode.OnEnter(); - mode.State.ShowMessage(); // Threads mode defaults a single-message thread's row to Thread view - var console = new TestConsole().Width(100).Height(20); // act - console.Write(mode.Render(100, 20)); + var popover = mode.TryCreatePopover(); + popover?.Load(TestContext.Current.CancellationToken); + var console = new TestConsole().Width(100); + console.Write(popover!.Render(100, 30)); // assert - Assert.Contains("From: bob", console.Output); - Assert.DoesNotContain("From: bob (", console.Output); + Assert.NotNull(popover); + Assert.Contains("Participants: alice, bob", console.Output); } [Fact] - public void Render_Should_NotThrow_When_WidthOrHeightIsZero() + public void HandleKey_Should_MoveTheModeSelectionToTheNextThread_When_DownArrowIsPressedOnThePopover() { // arrange + // threads sort by last activity descending, so t-2 lands at row 0 and t-1 at row 1 var store = new FakeMailStore(); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(1)); var mode = CreateMode(store); mode.OnEnter(); + var popover = mode.TryCreatePopover(); + popover!.Load(TestContext.Current.CancellationToken); // act - var exception = Record.Exception(() => mode.Render(0, 0)); - - // assert - Assert.Null(exception); - } - - [Fact] - public void OnEnter_Should_DefaultToWorkspaceMailbox() - { - // arrange - // Workspace shows every agent's mail, unlike Inbox which would show only alice's - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now, actor: "bob"); - var mode = CreateMode(store, actor: "alice"); - - // act - mode.OnEnter(); + popover.HandleKey(Key(ConsoleKey.DownArrow)); + var console = new TestConsole().Width(100); + console.Write(popover.Render(100, 30)); // assert - Assert.Equal(MailMailbox.Workspace, mode.State.Mailbox); - Assert.Equal(["m-2", "m-1"], mode.State.Messages.Select(m => m.Id)); + Assert.Equal(1, mode.State.SelectedRow); + Assert.Contains("Participants: alice, bob", console.Output); } [Fact] - public void OnEnter_Should_LoadTheActorsInbox_When_InboxIsSelected() + public void HandleKey_Should_LeaveTheModeSelectionUnchanged_When_UpArrowIsPressedOnThePopoverAtTheFirstThread() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now, actor: "bob"); - var mode = CreateMode(store, actor: "alice"); + AddThread(store, "t-1", "bob", "alice", s_now); + var mode = CreateMode(store); mode.OnEnter(); + var popover = mode.TryCreatePopover(); + popover!.Load(TestContext.Current.CancellationToken); // act - mode.Handle(new TuiMessage.SelectInboxRequested()); + var result = popover.HandleKey(Key(ConsoleKey.UpArrow)); // assert - Assert.Equal(["m-1"], mode.State.Messages.Select(m => m.Id)); + Assert.Null(result); + Assert.Equal(0, mode.State.SelectedRow); } [Fact] - public void OpenSelected_Should_MarkMessageRead_When_MessageIsUnread() + public void HandleKey_Should_LeaveTheModeSelectionOnTheThreadReached_When_EscapeIsPressedOnThePopoverAfterMovingDown() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(1)); var mode = CreateMode(store); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only + var popover = mode.TryCreatePopover(); + popover!.Load(TestContext.Current.CancellationToken); + popover.HandleKey(Key(ConsoleKey.DownArrow)); // act - mode.Handle(new TuiMessage.OpenSelected()); + var result = popover.HandleKey(Key(ConsoleKey.Escape)); // assert - var recipient = MailRecipientView.FindRecipient(store.Messages[0], "alice"); - Assert.NotNull(recipient!.ReadAt); + Assert.IsType(result); + Assert.Equal(1, mode.State.SelectedRow); } [Fact] - public void ToggleReadRequested_Should_MarkRead_And_ShowSuccessToast_When_MessageIsUnread() + public void HandlePopoverRequest_Should_ReturnACopyToast_When_TheThreadPopoverRequestsACopy() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only + var request = new PopoverResult.Request(new MailThreadPopoverRequest.CopyRequested("t-1")); // act - var followUp = mode.Handle(new TuiMessage.ToggleReadRequested()); + var followUp = mode.HandlePopoverRequest(request); // assert var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Success, Assert.IsType(toast).Style); - var recipient = MailRecipientView.FindRecipient(store.Messages[0], "alice"); - Assert.NotNull(recipient!.ReadAt); + var shown = Assert.IsType(toast); + Assert.Equal(("t-1", ToastStyle.Info), (shown.Text, shown.Style)); } [Fact] - public void ToggleReadRequested_Should_MarkUnread_When_MessageIsRead() + public void RefreshRequested_Should_ReloadThreadsFromTheStore_When_ANewThreadWasAdded() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); var mode = CreateMode(store); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ToggleReadRequested()); + Assert.Empty(mode.State.Threads); + AddThread(store, "t-1", "bob", "alice", s_now); // act - mode.Handle(new TuiMessage.ToggleReadRequested()); + mode.Handle(new TuiMessage.RefreshRequested()); // assert - var recipient = MailRecipientView.FindRecipient(store.Messages[0], "alice"); - Assert.Null(recipient!.ReadAt); + Assert.Single(mode.State.Threads); } [Fact] - public void ToggleReadRequested_Should_ShowWarnToast_When_NoMessageSelected() + public void SearchRequested_Should_OpenTheSearchForm_When_Requested() { // arrange var store = new FakeMailStore(); @@ -550,1457 +373,203 @@ public void ToggleReadRequested_Should_ShowWarnToast_When_NoMessageSelected() mode.OnEnter(); // act - var followUp = mode.Handle(new TuiMessage.ToggleReadRequested()); + var followUp = mode.Handle(new TuiMessage.SearchRequested()); // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); + Assert.Empty(followUp); + Assert.True(mode.IsInputCapturing); } [Fact] - public void ArchiveRequested_Should_OpenConfirmation_Without_ArchivingYet() + public void SearchForm_Apply_Should_NarrowThreadsBySubject_When_TextMatchesOneThread() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); + store.Messages.Add(MailMessageBuilder.Create( + "t-1", subject: "Status update", threadId: "t-1", createdAt: s_now, + recipients: [MailMessageBuilder.ToRecipient("alice")])); + store.Messages.Add(MailMessageBuilder.Create( + "t-2", subject: "Lunch plans", threadId: "t-2", createdAt: s_now.AddMinutes(1), + recipients: [MailMessageBuilder.ToRecipient("alice")])); var mode = CreateMode(store); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only + mode.Handle(new TuiMessage.SearchRequested()); + Type(mode, "status"); // act - var followUp = mode.Handle(new TuiMessage.ArchiveRequested()); + mode.HandleRawKey(CtrlKey(ConsoleKey.S)); // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - Assert.Null(MailRecipientView.FindRecipient(store.Messages[0], "alice")!.ArchivedAt); + Assert.False(mode.IsInputCapturing); + var thread = Assert.Single(mode.State.Threads); + Assert.Equal("t-1", thread.ThreadId); } [Fact] - public void ArchiveRequested_Should_ShowWarnToast_When_NoMessageSelected() + public void SearchForm_Cancel_Should_LeaveThreadsUnfiltered_When_FormIsCancelled() { // arrange var store = new FakeMailStore(); + AddThread(store, "t-1", "bob", "alice", s_now); + AddThread(store, "t-2", "carol", "alice", s_now.AddMinutes(1)); var mode = CreateMode(store); mode.OnEnter(); + mode.Handle(new TuiMessage.SearchRequested()); + Type(mode, "no-match"); // act - var followUp = mode.Handle(new TuiMessage.ArchiveRequested()); + mode.HandleRawKey(Key(ConsoleKey.Escape)); // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); + Assert.False(mode.IsInputCapturing); + Assert.Equal(2, mode.State.Threads.Count); } [Fact] - public void ArchiveConfirmation_Confirmed_Should_ArchiveMessage_And_RemoveItFromTheDefaultInboxList() + public void AgentFilterPickerRequested_Should_ListAgentsByName_When_StoreReturnsThemOutOfOrder() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + agentStore.Seed(Agent("zeta")); + agentStore.Seed(Agent("alpha")); + agentStore.Seed(Agent("mike")); + var mode = CreateMode(store, agentStore); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ArchiveRequested()); + mode.Handle(new TuiMessage.AgentFilterPickerRequested()); + var console = new TestConsole().Width(70).Height(6); // act - // Enter confirms from the dialog's initially focused, empty reason field - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); + console.Write(mode.Render(70, 6)); // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Success, Assert.IsType(toast).Style); - Assert.False(mode.IsInputCapturing); - Assert.Empty(mode.State.Messages); + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Filter by agentโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ (o) All agents โ”‚ + โ”‚ ( ) alpha โ”‚ + โ”‚ ( ) mike โ”‚ + โ”‚ ( ) zeta โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + """); } [Fact] - public void ArchiveConfirmation_Cancelled_Should_LeaveTheMessageAndListUntouched() + public void AgentFilterPicker_Applied_Should_NarrowThreads_ToThreadsTheAgentSentOrReceived_When_AnAgentIsSelected() { // arrange var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); + AddThread(store, "t-1", "bob", "carol", s_now); + AddThread(store, "t-2", "dave", "erin", s_now.AddMinutes(1)); + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + agentStore.Seed(Agent("bob")); + var mode = CreateMode(store, agentStore); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ArchiveRequested()); + mode.Handle(new TuiMessage.AgentFilterPickerRequested()); // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); + // move down from "All agents" to "bob", then apply + mode.HandleRawKey(Key(ConsoleKey.DownArrow)); + var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); // assert Assert.Empty(followUp); Assert.False(mode.IsInputCapturing); - Assert.Null(MailRecipientView.FindRecipient(store.Messages[0], "alice")!.ArchivedAt); - Assert.Equal(["m-1"], mode.State.Messages.Select(m => m.Id)); + Assert.Equal("bob", mode.State.AgentFilter); + Assert.Equal(["t-1"], mode.State.Threads.Select(t => t.ThreadId)); } [Fact] - public void ComposeRequested_Should_OpenComposeForm() + public void AgentFilterPicker_Applied_AllAgents_Should_RestoreEveryThread_When_AllAgentsIsSelected() { // arrange var store = new FakeMailStore(); - var mode = CreateMode(store); + AddThread(store, "t-1", "bob", "carol", s_now); + AddThread(store, "t-2", "dave", "erin", s_now.AddMinutes(1)); + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + agentStore.Seed(Agent("bob")); + var mode = CreateMode(store, agentStore); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only + mode.Handle(new TuiMessage.AgentFilterPickerRequested()); + mode.HandleRawKey(Key(ConsoleKey.DownArrow)); + mode.HandleRawKey(Key(ConsoleKey.Enter)); + Assert.Equal(["t-1"], mode.State.Threads.Select(t => t.ThreadId)); // act - var followUp = mode.Handle(new TuiMessage.ComposeRequested()); + // reopen the picker (pre-selected on "bob") and move back up to "All agents", then apply + mode.Handle(new TuiMessage.AgentFilterPickerRequested()); + mode.HandleRawKey(Key(ConsoleKey.UpArrow)); + var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); // assert Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); + Assert.Null(mode.State.AgentFilter); + Assert.Equal(["t-2", "t-1"], mode.State.Threads.Select(t => t.ThreadId)); } [Fact] - public void ComposeForm_Submit_Should_ShowSendingToast_Immediately_And_CloseTheForm() + public void AgentFilterPicker_Cancelled_Should_LeaveTheFilterUnchanged_When_PickerIsCancelled() { // arrange - // the submit key's synchronous return is only ever the immediate "Sending" toast, never the outcome var store = new FakeMailStore(); - var mode = CreateMode(store); + AddThread(store, "t-1", "bob", "carol", s_now); + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + agentStore.Seed(Agent("bob")); + var mode = CreateMode(store, agentStore); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "All good."); + var threadsBeforeCancel = mode.State.Threads.Select(t => t.ThreadId).ToList(); + mode.Handle(new TuiMessage.AgentFilterPickerRequested()); + mode.HandleRawKey(Key(ConsoleKey.DownArrow)); // act - var followUp = mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Info, shown.Style); + Assert.Empty(followUp); Assert.False(mode.IsInputCapturing); + Assert.Null(mode.State.AgentFilter); + Assert.Equal(threadsBeforeCancel, mode.State.Threads.Select(t => t.ThreadId)); } [Fact] - public async Task ComposeForm_Submit_Should_ShowErrorToast_And_WriteNothing_When_StoreRejectsTheWrite() + public void Render_Should_ShowTheSelectedAgentInTheHeader_When_AgentFilterIsSet() { // arrange - // A comma passes the nonempty To-field check but produces no recipient names. - var cancellationToken = TestContext.Current.CancellationToken; var store = new FakeMailStore(); - var mode = CreateMode(store); + AddThread(store, "t-1", "bob", "carol", s_now); + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + agentStore.Seed(Agent("bob")); + var mode = CreateMode(store, agentStore); mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, ","); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + mode.Handle(new TuiMessage.AgentFilterPickerRequested()); + mode.HandleRawKey(Key(ConsoleKey.DownArrow)); + mode.HandleRawKey(Key(ConsoleKey.Enter)); // act - var toast = await WaitForOutcomeToastAsync(mode, cancellationToken); + var text = RenderToText(mode); // assert - Assert.Equal(ToastStyle.Error, toast.Style); - Assert.Empty(store.Messages); - Assert.True(mode.IsInputCapturing); - var console = new TestConsole().Width(100).Height(20); - console.Write(mode.Render(100, 20)); - Assert.Contains("Status", console.Output); + Assert.Contains("Mail: bob (1)", text); } [Fact] - public async Task ReplyForm_Submit_Should_ShowErrorToast_And_ReopenTheForm_When_StoreRejectsTheWrite() + public void Render_Should_DropToColumn_When_WidthIsTooNarrowForEveryColumn() { // arrange - // the replied-to message is removed from the store between opening the form and submitting it - var cancellationToken = TestContext.Current.CancellationToken; var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.State.SelectedRow = 0; - mode.Handle(new TuiMessage.ReplyRequested()); - Type(mode, "On it."); - store.Messages.Clear(); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // act - var toast = await WaitForOutcomeToastAsync(mode, cancellationToken); - - // assert - Assert.Equal(ToastStyle.Error, toast.Style); - Assert.Empty(store.Messages); - Assert.True(mode.IsInputCapturing); - var console = new TestConsole().Width(100).Height(20); - console.Write(mode.Render(100, 20)); - Assert.Contains("On it.", console.Output); - } - - [Fact] - public async Task ComposeForm_Submit_Should_RefuseADuplicateSubmit_While_TheFirstIsStillInFlight() - { - // arrange - // the second compose is submitted while the first send's store write is still gated open - var cancellationToken = TestContext.Current.CancellationToken; - var store = new FakeMailStore { SendGate = new TaskCompletionSource() }; - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "First"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - await WaitUntilAsync(() => store.SendGateEntered, cancellationToken); - - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "carol"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Second"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - - // act - var followUp = mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); - Assert.True(mode.IsInputCapturing); - Assert.Empty(store.Messages); // the first write is still held open - - // Release the first write and wait for completion. - store.SendGate!.SetResult(); - await WaitForOutcomeToastAsync(mode, cancellationToken); - Assert.Single(store.Messages); - } - - [Fact] - public async Task CreateQuitGate_Should_ReportPendingCount_While_ASendIsStillInFlight_And_ClearAfterwards() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var store = new FakeMailStore { SendGate = new TaskCompletionSource() }; - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - await WaitUntilAsync(() => store.SendGateEntered, cancellationToken); - - var gate = mode.CreateQuitGate(); - - // act - // bounded drain while the store write is still gated open - var reportWhilePending = await gate(TimeSpan.FromMilliseconds(50), cancellationToken); - - // assert - Assert.Equal(1, reportWhilePending.PendingCount); - Assert.Equal(0, reportWhilePending.OutcomeUnknownCount); - Assert.True(reportWhilePending.HasUnresolvedWork); - - // cleanup - // release the gate and resume accepting, then confirm the effect drains cleanly - store.SendGate!.SetResult(); - await WaitForOutcomeToastAsync(mode, cancellationToken); - mode.ResumeSendAcceptance(); - } - - [Fact] - public async Task CreateQuitGate_Should_LeaveTheStashedToastForTheNextHandle_AfterACancelledQuit() - { - // arrange - // a cancelled second confirmation resuming the live TUI must still show the send's toast once it lands - var cancellationToken = TestContext.Current.CancellationToken; - var store = new FakeMailStore { SendGate = new TaskCompletionSource() }; - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - await WaitUntilAsync(() => store.SendGateEntered, cancellationToken); - var report = await mode.CreateQuitGate()(TimeSpan.FromMilliseconds(50), cancellationToken); - Assert.True(report.HasUnresolvedWork); // the second confirmation the shell would show - - // act - // the user declines the second confirmation, and the held send then lands - mode.ResumeSendAcceptance(); - store.SendGate!.SetResult(); - - // assert - var toast = await WaitForOutcomeToastAsync(mode, cancellationToken); - Assert.Equal(ToastStyle.Success, toast.Style); - Assert.Contains("Sent", toast.Text, StringComparison.Ordinal); - } - - [Fact] - public async Task ComposeForm_Submit_Should_ShowOutcomeUnknownToast_Without_AssertingNotStored_When_TheSendEffectFaults() - { - // arrange - // a non-ExitException from the store write reaches the send effect as Faulted, an unknown outcome - var cancellationToken = TestContext.Current.CancellationToken; - var store = new FakeMailStore { SendFault = new InvalidOperationException("boom") }; - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // act - var toast = await WaitForOutcomeToastAsync(mode, cancellationToken); - - // assert - Assert.Equal(ToastStyle.Error, toast.Style); - Assert.Equal("Sending did not complete. The message's outcome is unknown.", toast.Text); - Assert.Empty(store.Messages); - } - - /// - /// Refreshes until a non- outcome toast - /// is returned. Cancels the wait after five seconds or when the supplied token is cancelled. - /// - private static async Task WaitForOutcomeToastAsync( - MailMode mode, CancellationToken cancellationToken) - { - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeoutCts.CancelAfter(TimeSpan.FromSeconds(5)); - - while (true) - { - var result = mode.Handle(new TuiMessage.RefreshRequested()); - - foreach (var message in result) - { - var toast = Assert.IsType(message); - - if (toast.Style != ToastStyle.Info) - { - return toast; - } - } - - await Task.Delay(5, timeoutCts.Token); - } - } - - private static async Task WaitUntilAsync(Func condition, CancellationToken cancellationToken) - { - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeoutCts.CancelAfter(TimeSpan.FromSeconds(5)); - - while (!condition()) - { - await Task.Delay(5, timeoutCts.Token); - } - } - - [Fact] - public async Task ShieldPendingSendsAsync_Should_LetACommittedWriteLand_When_TheEffectTokenIsCancelled() - { - // arrange - // the store commit is gated open when the effect token cancels; the write itself is never cancelled - var cancellationToken = TestContext.Current.CancellationToken; - var gate = new TaskCompletionSource(); - var store = new FakeMailStore { SendGate = gate }; - using var effectCts = new CancellationTokenSource(); - var mode = new MailMode( - store, - "alice", - new FakeAgentRegistry(), - new FakeTimeProvider(s_now), - effectCts.Token); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - await WaitUntilAsync(() => store.SendGateEntered, cancellationToken); - - // act - await effectCts.CancelAsync(); - var shieldTask = mode.ShieldPendingSendsAsync(TimeSpan.FromSeconds(2), cancellationToken); - Assert.False(shieldTask.IsCompleted); // the shield waits for the committed write already in flight - gate.SetResult(); - await shieldTask; - - // assert - Assert.Single(store.Messages); - } - - [Fact] - public async Task ShieldPendingSendsAsync_Should_ReturnWithinTheBound_When_TheWriteHasNotLanded() - { - // arrange - // the gate is never released before the bound elapses - var cancellationToken = TestContext.Current.CancellationToken; - var gate = new TaskCompletionSource(); - var store = new FakeMailStore { SendGate = gate }; - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // act - var stopwatch = Stopwatch.StartNew(); - await mode.ShieldPendingSendsAsync(TimeSpan.FromMilliseconds(200), cancellationToken); - stopwatch.Stop(); - - // assert - Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(2)); - Assert.Empty(store.Messages); - - // cleanup - // release the gate so the still-running write can finish - gate.SetResult(); - } - - [Fact] - public async Task RunSendEffectEventsAsync_Should_EmitAnEffectCompletedEvent_ThatHandleDrainsIntoTheOutcomeToast() - { - // arrange - // Run the send-effect event source and submit a message. - var cancellationToken = TestContext.Current.CancellationToken; - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - var channel = Channel.CreateUnbounded(); - using var eventSourceCts = new CancellationTokenSource(); - var eventSourceTask = mode.RunSendEffectEventsAsync(channel.Writer, eventSourceCts.Token); - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Status"); - mode.HandleRawKey(Key(ConsoleKey.Tab)); - Type(mode, "Body"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // act - // Handle completion events until a non-Info toast appears. - using var readCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - readCts.CancelAfter(TimeSpan.FromSeconds(5)); - TuiMessage.ShowToast? toast = null; - - while (toast is null) - { - var effectEvent = await channel.Reader.ReadAsync(readCts.Token); - Assert.IsType(effectEvent); - var followUp = mode.Handle(new TuiMessage.EffectCompleted()); - - foreach (var message in followUp) - { - var shown = Assert.IsType(message); - - if (shown.Style != ToastStyle.Info) - { - toast = shown; - } - } - } - - await eventSourceCts.CancelAsync(); - await eventSourceTask; - - // assert - Assert.Equal(ToastStyle.Success, toast.Style); - Assert.Contains("Sent", toast.Text, StringComparison.Ordinal); - } - - [Fact] - public void ComposeForm_Cancel_Should_CloseImmediately_When_NotDirty() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - - // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // assert - Assert.Empty(followUp); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void ComposeForm_Cancel_Should_OpenDiscardConfirmation_When_Dirty() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - - // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - } - - [Fact] - public void ComposeForm_DiscardConfirmed_Should_CloseTheForm() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); - - // assert - Assert.Empty(followUp); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void ComposeForm_DiscardCancelled_Should_ReturnToTheFormWithItsValuesIntact() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ComposeRequested()); - Type(mode, "bob"); - mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - Assert.Empty(store.Messages); - } - - [Fact] - public void SelectSentRequested_Should_SwitchToSentMailboxAndLoadTheActorsSentMessages() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - Assert.Empty(mode.State.Messages); // alice is not a recipient of m-1 - - // act - var followUp = mode.Handle(new TuiMessage.SelectSentRequested()); - - // assert - Assert.Empty(followUp); - Assert.Equal(MailMailbox.Sent, mode.State.Mailbox); - Assert.Equal(["m-1"], mode.State.Messages.Select(m => m.Id)); - } - - [Fact] - public void Render_Should_ShowTheMailboxName_NotTheFilterName_When_MailboxIsNotInbox() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectSentRequested()); - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("Sent (1)", console.Output); - } - - [Fact] - public void Render_Should_ShowTheFilterName_When_MailboxIsInboxAndListModeIsThreads() - { - // arrange - // the filter name must stay visible in Threads mode too, not just Flat - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.CycleView(1)); // Inbox -> Unread - Assert.Equal(MailListMode.Threads, mode.State.ListMode); - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("Unread", console.Output); - } - - [Fact] - public async Task CycleView_Should_HideFullyReadThreads_When_MailboxIsInboxAndListModeIsThreads() - { - // arrange - // m-1's thread is unread for alice; m-2's thread is already read for her - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - await mode.State.RefreshAsync(CancellationToken.None); - await store.MarkReadAsync(["m-2"], "alice", CancellationToken.None); - - // act - mode.Handle(new TuiMessage.CycleView(1)); // Inbox -> Unread - - // assert - Assert.Equal(["t-1"], mode.State.Threads.Select(t => t.ThreadId)); - } - - [Fact] - public void Render_Should_ShowTheFilterName_When_MailboxIsInboxAndListModeIsFlat() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.ToggleListModeRequested()); // Threads -> Flat - mode.Handle(new TuiMessage.CycleView(1)); // Inbox -> Unread - Assert.Equal(MailListMode.Flat, mode.State.ListMode); - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("Unread", console.Output); - } - - [Fact] - public void ToggleReadRequested_Should_ShowWarnToast_NotAnError_When_ActorIsNotARecipient_InSentMailbox() - { - // arrange - // alice sent m-1 to bob, so alice has no recipient row on it and the store would reject the write - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectSentRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ToggleReadRequested()); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); - } - - [Fact] - public void ArchiveRequested_Should_ShowWarnToast_NotAnError_When_ActorIsNotARecipient_InSentMailbox() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectSentRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ArchiveRequested()); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void ToggleReadRequested_Should_Succeed_When_TheSentMessageIsSelfAddressed() - { - // arrange - // alice addressed the message to herself, so a recipient row exists and the write goes through - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectSentRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ToggleReadRequested()); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Success, Assert.IsType(toast).Style); - } - - [Fact] - public void ReplyRequested_Should_StillOpenTheReplyForm_ForTheActorsOwnSentMessage() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectSentRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ReplyRequested()); - - // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - } - - [Fact] - public void ReplyRequested_Should_ShowWarnToast_When_NoMessageSelected() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - var followUp = mode.Handle(new TuiMessage.ReplyRequested()); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); - } - - [Fact] - public async Task ReplyForm_Submit_Should_SendReply_And_ShowSuccessToast() - { - // arrange - var cancellationToken = TestContext.Current.CancellationToken; - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); // sender defaults to "sender", to "alice" - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - mode.Handle(new TuiMessage.ReplyRequested()); - Type(mode, "On it."); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); - - // act - var toast = await WaitForOutcomeToastAsync(mode, cancellationToken); - - // assert - Assert.Equal(ToastStyle.Success, toast.Style); - Assert.False(mode.IsInputCapturing); - Assert.Contains(store.Messages, m => m.InReplyTo == "m-1" && m.Body == "On it."); - } - - [Fact] - public void ToggleReadRequested_Should_ShowReadOnlyToast_And_NotMutate_When_MailboxIsWorkspace() - { - // arrange - // alice is a genuine recipient of m-1, but Workspace refuses the write regardless of recipient status - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ToggleReadRequested()); - - // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Warn, shown.Style); - Assert.Contains("read-only", shown.Text, StringComparison.OrdinalIgnoreCase); - Assert.Null(MailRecipientView.FindRecipient(store.Messages[0], "alice")!.ReadAt); - } - - [Fact] - public void OpenSelected_Should_NotMarkRead_When_MailboxIsWorkspace() - { - // arrange - // alice is an unread recipient of m-1, but Workspace must stay inert regardless - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.OpenSelected()); - - // assert - Assert.Empty(followUp); - Assert.Null(MailRecipientView.FindRecipient(store.Messages[0], "alice")!.ReadAt); - - // act - // flip back to List, then Right again, which must stay inert too - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Left)); - var moveFollowUp = mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Right)); - - // assert - Assert.Empty(moveFollowUp); - Assert.Null(MailRecipientView.FindRecipient(store.Messages[0], "alice")!.ReadAt); - } - - [Fact] - public void ArchiveRequested_Should_ShowReadOnlyToast_And_NotOpenDialog_When_MailboxIsWorkspace() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ArchiveRequested()); - - // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Warn, shown.Style); - Assert.False(mode.IsInputCapturing); - Assert.Null(MailRecipientView.FindRecipient(store.Messages[0], "alice")!.ArchivedAt); - } - - [Fact] - public void ComposeRequested_Should_ShowReadOnlyToast_And_NotOpenForm_When_MailboxIsWorkspace() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ComposeRequested()); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void ReplyRequested_Should_ShowReadOnlyToast_And_NotOpenForm_When_MailboxIsWorkspace_EvenForTheActorsOwnThread() - { - // arrange - // alice sent m-1, but Workspace refuses the reply regardless of the actor's own participation - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.ReplyRequested()); - - // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void Render_Should_CarryTwoRedundantWorkspaceIndicators_When_MailboxIsWorkspace() - { - // arrange - // the header names the mailbox, and the list pane's border token is distinct from other mailboxes - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("Workspace (1)", console.Output); - Assert.NotEqual( - ThemeTokens.GetStyle("board.column.border"), - ThemeTokens.GetStyle(MailMode.ResolveListBorderToken(MailMailbox.Workspace, focused: true))); - Assert.NotEqual( - ThemeTokens.GetStyle("board.column.border.focused"), - ThemeTokens.GetStyle(MailMode.ResolveListBorderToken(MailMailbox.Workspace, focused: true))); - - // assert - var borderStyle = ThemeTokens.GetStyle(MailMode.ResolveListBorderToken(MailMailbox.Workspace, focused: true)); - var styleConsole = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(1).Height(1); - styleConsole.Write(new Markup("x", borderStyle)); - var ansiPrefix = styleConsole.Output[..styleConsole.Output.IndexOf('x')]; - Assert.Contains(ansiPrefix, console.Output); - } - - [Fact] - public void ResolveListBorderToken_Should_UseThePlainBoardTokens_When_MailboxIsNotWorkspace() - { - // act & assert - Assert.Equal("board.column.border", MailMode.ResolveListBorderToken(MailMailbox.Inbox, focused: false)); - Assert.Equal("board.column.border.focused", MailMode.ResolveListBorderToken(MailMailbox.Sent, focused: true)); - } - - [Fact] - public void SuppressedGlobalHints_Should_BeEmpty_When_MailboxIsNotWorkspace() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace (the default) is read-only - - // act & assert - // outside Workspace, u/a/r/c stay live and their footer hints stay visible - Assert.Empty(mode.SuppressedGlobalHints); - } - - [Fact] - public void SuppressedGlobalHints_Should_HideToggleReadArchiveReplyAndCompose_When_MailboxIsWorkspace() - { - // arrange - // the same four gestures refused with a toast in Workspace must also have their footer hints hidden - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var suppressed = mode.SuppressedGlobalHints; - - // assert - Assert.Equal( - [ - MailKeyMap.ToggleReadHint, - MailKeyMap.ArchiveHint, - MailKeyMap.ReplyHint, - MailKeyMap.ComposeHint - ], - suppressed); - } - - [Fact] - public void AgentFilterPickerRequested_Should_ShowWarnToast_When_MailboxIsNotWorkspace() - { - // arrange - var store = new FakeMailStore(); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectInboxRequested()); // Workspace is the default mailbox - - // act - var followUp = mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - - // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Warn, shown.Style); - Assert.Contains("Workspace", shown.Text); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void AgentFilterPickerRequested_Should_OpenPicker_When_MailboxIsWorkspace() - { - // arrange - var store = new FakeMailStore(); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - - // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - } - - [Fact] - public void AgentFilterPickerRequested_Should_ShowClientNextToName_When_AgentHasOne() - { - // arrange - var store = new FakeMailStore(); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob") with { Client = "codex" }); - registry.Agents.Add(Agent("carol")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("bob (codex)", console.Output); - Assert.Contains("carol", console.Output); - Assert.DoesNotContain("carol (", console.Output); - } - - [Fact] - public void AgentFilterPicker_Applied_Should_NarrowWorkspaceMessages_ToMessagesTheAgentSentOrReceived() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("bob")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-3", sender: "carol", createdAt: s_now.AddMinutes(2), recipients: [MailMessageBuilder.ToRecipient("dave")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - - // act - // move down from "All agents" to "bob", then apply - mode.HandleRawKey(Key(ConsoleKey.DownArrow)); - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); - - // assert - Assert.Empty(followUp); - Assert.False(mode.IsInputCapturing); - Assert.Equal("bob", mode.State.AgentFilter); - Assert.Equal(["m-2", "m-1"], mode.State.Messages.Select(m => m.Id)); - } - - [Fact] - public void AgentFilterPicker_Applied_AllAgents_Should_RestoreTheFullWorkspaceStream() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("dave")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - mode.HandleRawKey(Key(ConsoleKey.DownArrow)); - mode.HandleRawKey(Key(ConsoleKey.Enter)); - Assert.Equal(["m-1"], mode.State.Messages.Select(m => m.Id)); - - // act - // reopen the picker (pre-selected on "bob") and move back up to "All agents", then apply - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - mode.HandleRawKey(Key(ConsoleKey.UpArrow)); - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); - - // assert - Assert.Empty(followUp); - Assert.Null(mode.State.AgentFilter); - Assert.Equal(["m-2", "m-1"], mode.State.Messages.Select(m => m.Id)); - } - - [Fact] - public void AgentFilterPicker_Cancelled_Should_LeaveTheFilterUnchanged() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - var messagesBeforeCancel = mode.State.Messages.Select(m => m.Id).ToList(); - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - mode.HandleRawKey(Key(ConsoleKey.DownArrow)); - - // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // assert - Assert.Empty(followUp); - Assert.False(mode.IsInputCapturing); - Assert.Null(mode.State.AgentFilter); - Assert.Equal(messagesBeforeCancel, mode.State.Messages.Select(m => m.Id)); - } - - [Fact] - public void Render_Should_ShowTheSelectedAgentInTheHeader_When_AgentFilterIsSetInWorkspace() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - mode.HandleRawKey(Key(ConsoleKey.DownArrow)); - mode.HandleRawKey(Key(ConsoleKey.Enter)); - var console = new TestConsole().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - Assert.Contains("Workspace: bob (1)", console.Output); - } - - [Fact] - public void SelectInboxRequested_Should_ClearAgentFilter_When_LeavingWorkspace() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var registry = new FakeAgentRegistry(); - registry.Agents.Add(Agent("bob")); - var mode = CreateMode(store, agentRegistry: registry); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - mode.Handle(new TuiMessage.AgentFilterPickerRequested()); - mode.HandleRawKey(Key(ConsoleKey.DownArrow)); - mode.HandleRawKey(Key(ConsoleKey.Enter)); - Assert.Equal("bob", mode.State.AgentFilter); - - // act - // leave Workspace for Inbox, then come back - mode.Handle(new TuiMessage.SelectInboxRequested()); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - - // assert - Assert.Null(mode.State.AgentFilter); - } - - [Fact] - public void Render_Should_ApplyAnsiStyling_ToRowGlyphFromToAndAgeTokens_When_MessageReceived() - { - // arrange - // two messages so at least one row is unselected; a selected row merges its color with the highlight - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now.AddMinutes(1)); - var mode = CreateMode(store); - mode.OnEnter(); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - AssertAnsiStyleApplied(console.Output, "mail.row.glyph.direct"); - AssertAnsiStyleApplied(console.Output, "mail.row.from"); - AssertAnsiStyleApplied(console.Output, "mail.row.to"); - AssertAnsiStyleApplied(console.Output, "mail.row.age"); - } - - [Fact] - public void Render_Should_ApplyFromMeToken_NotThePlainFromToken_When_ActorSentTheMessage() - { - // arrange - // two sent messages so at least one row is unselected; alice's own name in From gets the from-me token - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "alice", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("bob")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectSentRequested()); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - AssertAnsiStyleApplied(console.Output, "mail.row.from.me"); - AssertAnsiStyleApplied(console.Output, "mail.row.glyph.from-me"); - } - - [Fact] - public void Render_Should_ApplyAnsiStyling_ToWorkspaceHeaderText_When_MailboxIsWorkspace() - { - // arrange - // Spectre paints a panel's header with its BorderStyle, so the header sits inside the border's own styled run - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.SelectWorkspaceMailRequested()); - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(100).Height(20); - - // act - console.Write(mode.Render(100, 20)); - - // assert - var borderToken = MailMode.ResolveListBorderToken(MailMailbox.Workspace, focused: true); - var style = ThemeTokens.GetStyle(borderToken); - var styleConsole = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(1).Height(1); - styleConsole.Write(new Markup("x", style)); - var ansiPrefix = styleConsole.Output[..styleConsole.Output.IndexOf('x')]; - - var ansiIndex = console.Output.IndexOf(ansiPrefix, StringComparison.Ordinal); - var textIndex = console.Output.IndexOf("Workspace (1)", StringComparison.Ordinal); - Assert.True(ansiIndex >= 0, "Expected the Workspace border/header ANSI sequence to appear."); - Assert.True(textIndex > ansiIndex, "Expected the header text to follow the styled run."); - var runStart = ansiIndex + ansiPrefix.Length; - Assert.Equal(-1, console.Output.IndexOf('\u001b', runStart, textIndex - runStart)); - } - - [Fact] - public void ToggleListModeRequested_Should_SwitchBetweenThreadsAndFlatListMode() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - Assert.Equal(MailListMode.Threads, mode.State.ListMode); - - // act - mode.Handle(new TuiMessage.ToggleListModeRequested()); - - // assert - Assert.Equal(MailListMode.Flat, mode.State.ListMode); - - // act again - mode.Handle(new TuiMessage.ToggleListModeRequested()); - - // assert - Assert.Equal(MailListMode.Threads, mode.State.ListMode); - } - - [Fact] - public void FoldPrefixRequested_Should_EnterCapturingState() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - var followUp = mode.Handle(new TuiMessage.FoldPrefixRequested()); - - // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - } - - [Fact] - public void FoldPrefixRequested_Should_ShowWarnToast_When_ListModeIsFlat() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - mode.Handle(new TuiMessage.ToggleListModeRequested()); - - // act - var followUp = mode.Handle(new TuiMessage.FoldPrefixRequested()); - - // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Warn, shown.Style); - Assert.False(mode.IsInputCapturing); - } - - [Fact] - public void FoldPrefixThenO_Should_ExpandTheSelectedThread() - { - // arrange - // a two-message thread so expanding is observable as an extra row - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store); - mode.OnEnter(); - Assert.Single(mode.State.Rows); // one collapsed thread row - - // act - // z then o (open/expand) - mode.Handle(new TuiMessage.FoldPrefixRequested()); - mode.HandleRawKey(Key('o')); - - // assert - Assert.False(mode.IsInputCapturing); - Assert.Equal(3, mode.State.Rows.Count); // thread row + its two messages - } - - [Fact] - public void FoldPrefixThenC_Should_CollapseAnExpandedThread() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store); - mode.OnEnter(); - mode.State.ExpandThread("t-1"); - Assert.Equal(3, mode.State.Rows.Count); - - // act - // z then c (close/collapse) - mode.Handle(new TuiMessage.FoldPrefixRequested()); - mode.HandleRawKey(Key('c')); - - // assert - Assert.Single(mode.State.Rows); - } - - [Fact] - public void FoldPrefixThenA_Should_ToggleTheSelectedThread() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - // z then a (toggle) twice - mode.Handle(new TuiMessage.FoldPrefixRequested()); - mode.HandleRawKey(Key('a')); - Assert.Equal(3, mode.State.Rows.Count); - - mode.Handle(new TuiMessage.FoldPrefixRequested()); - mode.HandleRawKey(Key('a')); - - // assert - Assert.Single(mode.State.Rows); - } - - [Fact] - public void FoldPrefixThenShiftRAndShiftM_Should_ExpandAndCollapseEveryThread() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - AddMessage(store, "m-2", s_now.AddMinutes(1)); - var mode = CreateMode(store); - mode.OnEnter(); - Assert.Equal(2, mode.State.Rows.Count); // two collapsed singleton threads - - // act - // z then Shift+R (unfold all) - mode.Handle(new TuiMessage.FoldPrefixRequested()); - mode.HandleRawKey(new ConsoleKeyInfo('R', ConsoleKey.R, shift: true, alt: false, control: false)); - - // assert - Assert.Equal(4, mode.State.Rows.Count); - var threadRows = mode.State.Rows.OfType().ToList(); - Assert.Equal(2, threadRows.Count); - Assert.All(threadRows, row => Assert.True(row.Expanded)); - - // act - // z then Shift+M (fold all) - mode.Handle(new TuiMessage.FoldPrefixRequested()); - mode.HandleRawKey(new ConsoleKeyInfo('M', ConsoleKey.M, shift: true, alt: false, control: false)); - - // assert - Assert.All(mode.State.Rows, row => Assert.False(((MailListRow.Thread)row).Expanded)); - } - - [Fact] - public void FoldPrefixThenUnrecognizedKey_Should_CancelWithNoAction() - { - // arrange - var store = new FakeMailStore(); - AddMessage(store, "m-1", s_now); - var mode = CreateMode(store); - mode.OnEnter(); - - // act - // z then Escape, an unrecognized second key that shows no error toast - mode.Handle(new TuiMessage.FoldPrefixRequested()); - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); - - // assert - Assert.Empty(followUp); - Assert.False(mode.IsInputCapturing); - Assert.Single(mode.State.Rows); - } - - [Fact] - public void Render_Should_ShowUnreadToMeHighlight_InWorkspace_ForAMessageAddressedToTheActor_And_NotForAThirdPartyMessage() - { - // arrange - // m-1 is unread and addressed to alice; m-2 is unread between two other agents and never addresses her - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("dave")])); + AddThread(store, "t-1", "bob", "alice", s_now); var mode = CreateMode(store); mode.OnEnter(); - Assert.Equal(MailMailbox.Workspace, mode.State.Mailbox); - var console = new TestConsole().Width(100).Height(20); + var wide = RenderToText(mode, width: 100); // act - console.Write(mode.Render(100, 20)); + var narrow = RenderToText(mode, width: 74); + var actual = ( + WideHasTo: wide.Contains("alice", StringComparison.Ordinal), + NarrowHasTo: narrow.Contains("alice", StringComparison.Ordinal), + NarrowHasFrom: narrow.Contains("bob", StringComparison.Ordinal)); // assert - var markerCount = console.Output.Split('\u25cf').Length - 1; - Assert.Equal(1, markerCount); + Assert.Equal((true, false, true), actual); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailStateTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailStateTests.cs index 0d3afe06c38..3bf117cc9be 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailStateTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailStateTests.cs @@ -6,368 +6,71 @@ public sealed class MailStateTests { private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - private static MailState CreateState(FakeMailStore store, string actor = "alice") - => new(actor, new MailDataLoader(store)); + private static MailState CreateState(FakeMailStore store) => new(new MailDataLoader(store)); [Fact] - public async Task RefreshAsync_Should_LoadInboxForTheCurrentFilter() + public async Task RefreshAsync_Should_LoadEveryWorkspaceThread_When_StoreHasThreads() { // arrange var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - - // act - await state.RefreshAsync(CancellationToken.None); - - // assert - Assert.Equal(["m-1"], state.Messages.Select(m => m.Id)); - } - - [Fact] - public async Task RefreshAsync_Should_KeepSelectedRowOnSameMessage_When_MessageStillPresentAfterReorder() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); - state.SelectedRow = 1; // m-1, currently the older/last row - - // act - // a newer message pushes m-1 to a different row on refresh - store.Messages.Add(MailMessageBuilder.Create( - "m-3", createdAt: s_now.AddMinutes(2), recipients: [MailMessageBuilder.ToRecipient("alice")])); - await state.RefreshAsync(CancellationToken.None); - - // assert - Assert.Equal(["m-3", "m-2", "m-1"], state.Messages.Select(m => m.Id)); - Assert.Equal(2, state.SelectedRow); - Assert.Equal("m-1", state.SelectedMessage?.Id); - } - - [Fact] - public async Task RefreshAsync_Should_ClampSelectedRow_When_SelectedMessageNoLongerPresent() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); - state.SelectedRow = 0; // m-2, newest first - - // act - // m-2 is removed from the store entirely - store.Messages.RemoveAt(1); - await state.RefreshAsync(CancellationToken.None); - - // assert - Assert.Equal(["m-1"], state.Messages.Select(m => m.Id)); - Assert.Equal(0, state.SelectedRow); - } - - [Fact] - public async Task CycleFilterAsync_Should_AdvanceThroughFiltersAndWrap() - { - // arrange - var store = new FakeMailStore(); - var state = CreateState(store); - Assert.Equal(MailListFilter.Inbox, state.Filter); - - // act & assert - // Inbox -> Unread -> Archived -> Inbox - await state.CycleFilterAsync(1, CancellationToken.None); - Assert.Equal(MailListFilter.Unread, state.Filter); - - await state.CycleFilterAsync(1, CancellationToken.None); - Assert.Equal(MailListFilter.Archived, state.Filter); - - await state.CycleFilterAsync(1, CancellationToken.None); - Assert.Equal(MailListFilter.Inbox, state.Filter); - } - - [Fact] - public async Task CycleFilterAsync_Should_WrapBackward_When_DeltaIsNegative() - { - // arrange - var store = new FakeMailStore(); - var state = CreateState(store); - - // act - await state.CycleFilterAsync(-1, CancellationToken.None); - - // assert - Assert.Equal(MailListFilter.Archived, state.Filter); - } - - [Fact] - public async Task RefreshAsync_Should_HideFullyReadThreads_When_MailboxIsInboxAndFilterIsUnread() - { - // arrange - // t-1's only message is unread for alice; t-2's only message is already read for her - var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - Assert.Equal(["t-2", "t-1"], state.Threads.Select(t => t.ThreadId)); - - await store.MarkReadAsync(["m-2"], "alice", CancellationToken.None); - - // act - await state.CycleFilterAsync(1, CancellationToken.None); // Inbox -> Unread - - // assert - Assert.Equal(MailListFilter.Unread, state.Filter); - Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); - } - - [Fact] - public async Task RefreshAsync_Should_ExcludeFullyArchivedThreads_When_MailboxIsInboxAndFilterIsInbox() - { - // arrange - // t-1's only message to alice is archived for her; t-2's is not - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice", archivedAt: s_now)])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); // act - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - - // assert - Assert.Equal(MailListFilter.Inbox, state.Filter); - Assert.Equal(["t-2"], state.Threads.Select(t => t.ThreadId)); - } - - [Fact] - public async Task RefreshAsync_Should_ShowOnlyArchivedThreads_When_MailboxIsInboxAndFilterIsArchived() - { - // arrange - // t-1's only message to alice is archived for her; t-2's is not - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice", archivedAt: s_now)])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - - // act - await state.CycleFilterAsync(1, CancellationToken.None); // Inbox -> Unread - await state.CycleFilterAsync(1, CancellationToken.None); // Unread -> Archived + await state.RefreshAsync(CancellationToken.None); // assert - Assert.Equal(MailListFilter.Archived, state.Filter); Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); } [Fact] - public async Task SelectMailboxAsync_Should_SwitchMailboxAndLoadFromItsOwnStoreMethod() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - Assert.Empty(state.Messages); // alice is not a recipient of m-1, so the Inbox is empty - - // act - await state.SelectMailboxAsync(MailMailbox.Sent, CancellationToken.None); - - // assert - Assert.Equal(MailMailbox.Sent, state.Mailbox); - Assert.Equal(["m-1"], state.Messages.Select(m => m.Id)); - } - - [Fact] - public async Task SelectMailboxAsync_Should_ResetSelectedRowToTop() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - state.SelectedRow = 1; - - // act - // Switch from Inbox to Workspace. - await state.SelectMailboxAsync(MailMailbox.Workspace, CancellationToken.None); - - // assert - Assert.Equal(0, state.SelectedRow); - } - - [Fact] - public async Task SelectMailboxAsync_Should_BeNoOp_When_MailboxIsAlreadyActive() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - state.SelectedRow = 1; - - // act - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - - // assert - Assert.Equal(MailMailbox.Inbox, state.Mailbox); - Assert.Equal(1, state.SelectedRow); - } - - [Fact] - public async Task ShowThreadAsync_Should_LoadSelectedMessagesThread() + public async Task RefreshAsync_Should_OrderNewestActivityFirst_When_MultipleThreadsExist() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1))); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); - - // act - var opened = await state.ShowThreadAsync(CancellationToken.None); - - // assert - Assert.True(opened); - Assert.Equal(MailViewMode.Thread, state.ViewMode); - Assert.Equal(["m-1", "m-2"], state.ThreadMessages.Select(m => m.Id)); - } - - [Fact] - public async Task ShowThreadAsync_Should_ReturnFalse_When_NoMessageSelected() - { - // arrange - var store = new FakeMailStore(); + "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); // act - var opened = await state.ShowThreadAsync(CancellationToken.None); - - // assert - Assert.False(opened); - Assert.Equal(MailViewMode.Message, state.ViewMode); - } - - [Fact] - public async Task ShowMessage_Should_ClearThreadMessagesAndSwitchBack() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); await state.RefreshAsync(CancellationToken.None); - await state.ShowThreadAsync(CancellationToken.None); - - // act - state.ShowMessage(); // assert - Assert.Equal(MailViewMode.Message, state.ViewMode); - Assert.Empty(state.ThreadMessages); + Assert.Equal(["t-2", "t-1"], state.Threads.Select(t => t.ThreadId)); } [Fact] - public async Task RefreshAsync_Should_PreserveAManualThreadOverride_When_TheSelectedMessageRowSurvivesTheRefresh() + public async Task RefreshAsync_Should_KeepSelectedRowOnSameThread_When_ThreadStillPresentAfterReorder() { // arrange - // Flat mode selects a MessageRow (default view Message); ShowThreadAsync overrides it to Thread var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); - state.ToggleListMode(); // Threads -> Flat - Assert.Equal(MailListMode.Flat, state.ListMode); - Assert.Equal(MailViewMode.Message, state.ViewMode); // MessageRow's own default - - var opened = await state.ShowThreadAsync(CancellationToken.None); - Assert.True(opened); - Assert.Equal(MailViewMode.Thread, state.ViewMode); - - // act - // the same message row survives the reload by identity - await state.RefreshAsync(CancellationToken.None); - - // assert - Assert.Equal(MailViewMode.Thread, state.ViewMode); - } - - [Fact] - public async Task RefreshAsync_Should_PreserveAManualMessageOverride_When_TheSelectedThreadRowSurvivesTheRefresh() - { - // arrange - // Threads mode (the default) selects a thread row (default view Thread); ShowMessage overrides it to Message - var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); await state.RefreshAsync(CancellationToken.None); - Assert.Equal(MailViewMode.Thread, state.ViewMode); // Thread row's own default - - state.ShowMessage(); - Assert.Equal(MailViewMode.Message, state.ViewMode); + state.SelectedRow = 1; // t-1, currently the older/last row // act - // the same thread row survives the reload by identity - await state.RefreshAsync(CancellationToken.None); - - // assert - Assert.Equal(MailViewMode.Message, state.ViewMode); - } - - [Fact] - public async Task SelectedRow_Should_ResolveTheRowsOwnDefaultViewMode_When_MovingToADifferentThreadRow() - { - // arrange - // two single-message threads in Threads mode; the first thread row's default is overridden to Message - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + // a newer message pushes t-1 to a different row on refresh store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); + "m-3", threadId: "t-3", createdAt: s_now.AddMinutes(2), recipients: [MailMessageBuilder.ToRecipient("alice")])); await state.RefreshAsync(CancellationToken.None); - state.ShowMessage(); - Assert.Equal(MailViewMode.Message, state.ViewMode); - - // act - // a genuine selection change to the other thread row - state.SelectedRow = 1; // assert - Assert.Equal(MailViewMode.Thread, state.ViewMode); + Assert.Equal(["t-3", "t-2", "t-1"], state.Threads.Select(t => t.ThreadId)); + Assert.Equal(2, state.SelectedRow); + Assert.Equal("t-1", state.SelectedThread?.ThreadId); } [Fact] - public async Task SelectedRow_Should_ResolveTheRowsOwnDefaultViewMode_When_MovingToADifferentMessageRow() + public async Task RefreshAsync_Should_ClampSelectedRow_When_SelectedThreadNoLongerPresent() { // arrange - // two messages in Flat mode; the first message row's default is overridden to Thread var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); @@ -375,314 +78,142 @@ public async Task SelectedRow_Should_ResolveTheRowsOwnDefaultViewMode_When_Movin "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); await state.RefreshAsync(CancellationToken.None); - state.ToggleListMode(); // Threads -> Flat - var opened = await state.ShowThreadAsync(CancellationToken.None); - Assert.True(opened); - Assert.Equal(MailViewMode.Thread, state.ViewMode); + state.SelectedRow = 0; // t-2, newest first // act - // a genuine selection change to the other message row - state.SelectedRow = 1; - - // assert - Assert.Equal(MailViewMode.Message, state.ViewMode); - } - - [Fact] - public async Task RefreshAsync_Should_RefreshThreadMessagesContent_When_ViewModeIsThread_AndTheSelectionSurvives() - { - // arrange - // a thread row's own Thread default is active, so ThreadMessages is populated from the start - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); - Assert.Equal(MailViewMode.Thread, state.ViewMode); - Assert.Equal(["m-1"], state.ThreadMessages.Select(m => m.Id)); - - // act - // Add a reply to the selected thread, then refresh. - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1))); + // t-2's only message is removed from the store entirely + store.Messages.RemoveAt(1); await state.RefreshAsync(CancellationToken.None); // assert - Assert.Equal(["m-1", "m-2"], state.ThreadMessages.Select(m => m.Id)); - Assert.Equal("m-2", state.SelectedMessage?.Id); + Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); + Assert.Equal(0, state.SelectedRow); } [Fact] - public async Task SelectAgentFilterAsync_Should_NarrowWorkspaceMessages_ToTheGivenAgent() + public async Task SelectAgentFilterAsync_Should_NarrowToThreadsTheAgentSentOrReceived_When_AgentIsGiven() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); + "m-1", sender: "alice", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("bob")])); + "m-2", sender: "carol", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("dave")])); var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); // already the default Workspace mailbox - Assert.Equal(["m-2", "m-1"], state.Messages.Select(m => m.Id)); + await state.RefreshAsync(CancellationToken.None); // act await state.SelectAgentFilterAsync("alice", CancellationToken.None); // assert Assert.Equal("alice", state.AgentFilter); - Assert.Equal(["m-1"], state.Messages.Select(m => m.Id)); - } - - [Fact] - public async Task SelectAgentFilterAsync_Should_ResetSelectedRowToTop() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "alice", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("bob")])); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); // already the default Workspace mailbox - state.SelectedRow = 1; - - // act - await state.SelectAgentFilterAsync("alice", CancellationToken.None); - - // assert + Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); Assert.Equal(0, state.SelectedRow); } [Fact] - public async Task SelectAgentFilterAsync_Should_RestoreTheFullWorkspaceStream_When_AgentIsNull() + public async Task SelectAgentFilterAsync_Should_RestoreEveryThread_When_FilterIsClearedToNull() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); + "m-1", sender: "alice", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", sender: "carol", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("bob")])); + "m-2", sender: "carol", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("dave")])); var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Workspace, CancellationToken.None); + await state.RefreshAsync(CancellationToken.None); await state.SelectAgentFilterAsync("alice", CancellationToken.None); - Assert.Equal(["m-1"], state.Messages.Select(m => m.Id)); // act await state.SelectAgentFilterAsync(null, CancellationToken.None); // assert Assert.Null(state.AgentFilter); - Assert.Equal(["m-2", "m-1"], state.Messages.Select(m => m.Id)); - } - - [Fact] - public async Task SelectMailboxAsync_Should_ClearAgentFilter_When_LeavingWorkspace() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Workspace, CancellationToken.None); - await state.SelectAgentFilterAsync("alice", CancellationToken.None); - Assert.Equal("alice", state.AgentFilter); - - // act - // leave Workspace for Sent, then come back - await state.SelectMailboxAsync(MailMailbox.Sent, CancellationToken.None); - await state.SelectMailboxAsync(MailMailbox.Workspace, CancellationToken.None); - - // assert - Assert.Null(state.AgentFilter); - Assert.Equal(["m-1"], state.Messages.Select(m => m.Id)); // unfiltered again - } - - [Fact] - public void SelectedMessage_Should_ReturnNull_When_MessagesIsEmpty() - { - // arrange - var store = new FakeMailStore(); - var state = CreateState(store); - - // act & assert - Assert.Null(state.SelectedMessage); - } - - [Fact] - public void MailState_Should_DefaultToWorkspaceMailboxAndThreadsListMode() - { - // arrange & act - var state = CreateState(new FakeMailStore()); - - // assert - Assert.Equal(MailMailbox.Workspace, state.Mailbox); - Assert.Equal(MailListMode.Threads, state.ListMode); - } - - [Fact] - public async Task RefreshAsync_Should_PopulateThreadRollups_ForTheCurrentMailbox() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - - // act - await state.RefreshAsync(CancellationToken.None); - - // assert - Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); - Assert.Equal(2, state.Threads[0].MessageCount); - var row = Assert.Single(state.Rows); - var thread = Assert.IsType(row); - Assert.False(thread.Expanded); + Assert.Equal(["t-2", "t-1"], state.Threads.Select(t => t.ThreadId)); } [Fact] - public async Task ExpandThread_Should_InsertTheThreadsMessages_AsIndentedRowsAfterIt() + public async Task ApplySearch_Should_NarrowToThreadsMatchingSubject_When_TextMatchesOneThread() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-1", subject: "Status update", threadId: "t-1", createdAt: s_now, + recipients: [MailMessageBuilder.ToRecipient("alice")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-2", subject: "Lunch plans", threadId: "t-2", createdAt: s_now.AddMinutes(1), + recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); await state.RefreshAsync(CancellationToken.None); // act - state.ExpandThread("t-1"); + state.ApplySearch("status"); // assert - Assert.Equal(3, state.Rows.Count); - var threadRow = Assert.IsType(state.Rows[0]); - Assert.True(threadRow.Expanded); - var first = Assert.IsType(state.Rows[1]); - var second = Assert.IsType(state.Rows[2]); - Assert.True(first.ThreadChild); - Assert.True(second.ThreadChild); - Assert.Equal("m-1", first.Message.Id); - Assert.Equal("m-2", second.Message.Id); + Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); + Assert.Equal(0, state.SelectedRow); } [Fact] - public async Task CollapseThread_Should_RemoveTheIndentedChildRows() + public async Task ApplySearch_Should_MatchLastSenderAndLastRecipients_When_TextMatchesEither() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-1", sender: "bob", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-1", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-2", sender: "dave", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("erin")])); var state = CreateState(store); await state.RefreshAsync(CancellationToken.None); - state.ExpandThread("t-1"); // act - state.CollapseThread("t-1"); + state.ApplySearch("carol"); // assert - var row = Assert.Single(state.Rows); - var thread = Assert.IsType(row); - Assert.False(thread.Expanded); - } - - [Fact] - public async Task ToggleThreadFold_Should_AlternateBetweenExpandedAndCollapsed() - { - // arrange - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.RefreshAsync(CancellationToken.None); - - // act & assert - state.ToggleThreadFold("t-1"); - Assert.Equal(2, state.Rows.Count); // thread row + its one message - - state.ToggleThreadFold("t-1"); - Assert.Single(state.Rows); + Assert.Equal(["t-1"], state.Threads.Select(t => t.ThreadId)); } [Fact] - public async Task ExpandAllThreads_And_CollapseAllThreads_Should_ActOnEveryThread() + public async Task ApplySearch_Should_ShowEveryThread_When_TextIsCleared() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-1", subject: "Status update", threadId: "t-1", createdAt: s_now, + recipients: [MailMessageBuilder.ToRecipient("alice")])); store.Messages.Add(MailMessageBuilder.Create( - "m-2", threadId: "t-2", createdAt: s_now.AddMinutes(1), recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-2", subject: "Lunch plans", threadId: "t-2", createdAt: s_now.AddMinutes(1), + recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); await state.RefreshAsync(CancellationToken.None); + state.ApplySearch("status"); // act - state.ExpandAllThreads(); + state.ApplySearch(""); // assert - Assert.Equal(4, state.Rows.Count); - - // act - state.CollapseAllThreads(); - - // assert - Assert.Equal(2, state.Rows.Count); - Assert.All(state.Rows, row => Assert.False(((MailListRow.Thread)row).Expanded)); + Assert.Equal(["t-2", "t-1"], state.Threads.Select(t => t.ThreadId)); } [Fact] - public async Task IsThreadUnreadToMe_Should_UseTheRollupsUnreadCount_OutsideWorkspace() + public async Task TotalCount_Should_IgnoreTheSearchFilter_When_SearchIsActive() { // arrange var store = new FakeMailStore(); store.Messages.Add(MailMessageBuilder.Create( - "m-1", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); - var state = CreateState(store); - await state.SelectMailboxAsync(MailMailbox.Inbox, CancellationToken.None); - - // act & assert - Assert.True(state.IsThreadUnreadToMe(state.Threads[0])); - - await store.MarkReadAsync(["m-1"], "alice", CancellationToken.None); - await state.RefreshAsync(CancellationToken.None); - Assert.False(state.IsThreadUnreadToMe(state.Threads[0])); - } - - [Fact] - public async Task IsThreadUnreadToMe_Should_BeTrue_InWorkspace_When_UnreadAndAddressedToTheActor() - { - // arrange - // already the default Workspace mailbox - var store = new FakeMailStore(); + "m-1", subject: "Status update", threadId: "t-1", createdAt: s_now, + recipients: [MailMessageBuilder.ToRecipient("alice")])); store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")])); + "m-2", subject: "Lunch plans", threadId: "t-2", createdAt: s_now.AddMinutes(1), + recipients: [MailMessageBuilder.ToRecipient("alice")])); var state = CreateState(store); - - // act await state.RefreshAsync(CancellationToken.None); - // assert - Assert.True(state.IsThreadUnreadToMe(state.Threads[0])); - } - - [Fact] - public async Task IsThreadUnreadToMe_Should_BeFalse_InWorkspace_ForAnUnreadThreadBetweenTwoOtherAgents() - { - // arrange - // bob and carol's thread never addresses alice, so it must never render as unread-to-me for her - var store = new FakeMailStore(); - store.Messages.Add(MailMessageBuilder.Create( - "m-1", sender: "bob", threadId: "t-1", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("carol")])); - var state = CreateState(store); - // act - await state.RefreshAsync(CancellationToken.None); + state.ApplySearch("status"); // assert - Assert.False(state.IsThreadUnreadToMe(state.Threads[0])); + Assert.Single(state.Threads); + Assert.Equal(2, state.TotalCount); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailTableTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailTableTests.cs index 1056943d917..8ccfd29cfba 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailTableTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailTableTests.cs @@ -1,9 +1,6 @@ -using System.Globalization; using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Tui.Mail; using Spectre.Console; -using Spectre.Console.Testing; -using static ChilliCream.Nitro.CommandLine.Tests.Tui.AnsiAssertions; namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; @@ -16,9 +13,7 @@ private static MailThreadSummary Thread( string subject = "Status update", string lastSender = "bob", IReadOnlyList? lastRecipients = null, - string bodyPreview = "Body preview text", int messageCount = 1, - int? unreadCount = null, DateTimeOffset? lastMessageAt = null) => new() { @@ -28,596 +23,242 @@ private static MailThreadSummary Thread( LastMessageAt = lastMessageAt ?? s_now, LastSender = lastSender, LastRecipients = lastRecipients ?? ["alice"], - BodyPreview = bodyPreview, - UnreadCount = unreadCount, + BodyPreview = "Body preview text", + UnreadCount = null, ArchivedCount = null }; - private static void AssertRendersWithoutError(string markup) - { - var console = new TestConsole().Width(200); - var exception = Record.Exception(() => console.Write(new Markup(markup))); - Assert.Null(exception); - } - - /// - /// Renders through without ANSI styling - /// and removes trailing line breaks. - /// - private static string RenderPlain(string markup) - { - var console = new TestConsole().Width(300); - console.Write(new Markup(markup)); - return console.Output.TrimEnd('\r', '\n'); - } - - /// - /// Renders through with true-color ANSI styling. - /// - private static string RenderAnsi(string markup) - { - var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(300); - console.Write(new Markup(markup)); - return console.Output; - } - - /// - /// An independent, test-only terminal-cell-width measurement: 2 cells for CJK ideographs and - /// the emoji block used by these tests' fixtures, 1 otherwise. - /// - private static int MeasureCellWidth(string value) - => value.EnumerateRunes().Sum(rune => rune.Value switch - { - >= 0x4E00 and <= 0x9FFF => 2, // CJK unified ideographs - >= 0x1F300 and <= 0x1FAFF => 2, // emoji blocks - _ => 1 - }); - - private static int MeasureEmojiPresentationWidth(string value) - { - var width = 0; - var elements = StringInfo.GetTextElementEnumerator(value); - - while (elements.MoveNext()) - { - width += (string)elements.Current switch - { - "โŒš" or "โค๏ธ" or "1๏ธโƒฃ" => 2, - _ => 1 - }; - } - - return width; - } - - /// - /// True when contains a UTF-16 surrogate half with no matching - /// partner. - /// - private static bool ContainsLoneSurrogate(string value) - { - for (var i = 0; i < value.Length; i++) - { - if (char.IsHighSurrogate(value[i])) - { - if (i + 1 >= value.Length || !char.IsLowSurrogate(value[i + 1])) - { - return true; - } - - i++; - } - else if (char.IsLowSurrogate(value[i])) - { - return true; - } - } - - return false; - } - - [Fact] - public void ComputeColumns_Should_SplitElasticRemainder_BetweenSubjectAndPreview() - { - // act - var columns = MailTable.ComputeColumns(100, showCount: false); - - // assert - Assert.Equal(20, columns.SubjectWidth); - Assert.Equal(30, columns.PreviewWidth); - Assert.False(columns.ShowCount); - } - - [Fact] - public void ComputeColumns_Should_ReserveTheCountColumn_When_ShowCountIsTrue() - { - // act - var columns = MailTable.ComputeColumns(100, showCount: true); - - // assert - Assert.True(columns.ShowCount); - Assert.Equal(17, columns.SubjectWidth); - Assert.Equal(27, columns.PreviewWidth); - } - - [Fact] - public void ComputeColumns_Should_DegradeToZero_Not_Negative_When_WidthIsNarrow() - { - // act - var columns = MailTable.ComputeColumns(10, showCount: true); - - // assert - Assert.True(columns.SubjectWidth >= 0); - Assert.True(columns.PreviewWidth >= 0); - } - - [Fact] - public void RenderHeading_Should_ContainEveryColumnLabel() - { - // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); - - // act - var heading = MailTable.RenderHeading(columns); - - // assert - Assert.Contains("From", heading); - Assert.Contains("To", heading); - Assert.Contains("Subject", heading); - Assert.Contains("Preview", heading); - Assert.Contains("Age", heading); - Assert.Contains("#", heading); - AssertRendersWithoutError(heading); - } - - [Fact] - public void RenderHeading_Should_OmitCountLabel_When_ShowCountIsFalse() - { - // arrange - var columns = MailTable.ComputeColumns(120, showCount: false); - - // act - var heading = MailTable.RenderHeading(columns); - - // assert - Assert.DoesNotContain("#", heading); - } - - [Fact] - public void RenderThreadRow_Should_ContainFromToSubjectPreviewAndAge() - { - // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); - var thread = Thread(subject: "Status update", lastSender: "bob", lastRecipients: ["alice"], bodyPreview: "hi there"); - - // act - var line = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - - // assert - Assert.Contains("bob", line); - Assert.Contains("alice", line); - Assert.Contains("Status update", line); - Assert.Contains("hi there", line); - Assert.Contains("now", line); - AssertRendersWithoutError(line); - } - - [Fact] - public void RenderThreadRow_Should_ShowMessageCount_When_ShowCountIsTrue() - { - // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); - var thread = Thread(messageCount: 7); - - // act - var line = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - - // assert - Assert.Contains("(7)", line); - } - [Fact] - public void RenderThreadRow_Should_UseExpandedFoldGlyph_When_Expanded() + public void Render_Should_ReturnEmpty_When_MaxWidthIsZero() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var collapsed = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - var expanded = MailTable.RenderThreadRow(thread, expanded: true, unreadToMe: false, selected: false, "alice", s_now, columns); + var line = MailTable.Render(thread, s_now, selected: false, maxWidth: 0, widths); // assert - Assert.Contains("โ–ธ", collapsed); - Assert.Contains("โ–พ", expanded); + Assert.Empty(line); } [Fact] - public void RenderThreadRow_Should_ApplyUnreadToMeToken_When_UnreadToMeIsTrue() + public void Render_Should_ShowEveryColumn_When_MaxWidthFits() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); + const int maxWidth = 90; var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var unread = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: true, selected: false, "alice", s_now, columns); - var read = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth, widths)); // assert - Assert.Contains("โ—", unread); - Assert.DoesNotContain("โ—", read); - Assert.NotEqual(unread, read); + var expected = " " + + "Status update".PadRight(widths.Subject) + + " " + "bob".PadRight(widths.From) + + " " + "alice".PadRight(widths.To) + + " " + "1".PadLeft(widths.Messages) + + " " + "just now".PadRight(widths.LastActivity); + Assert.Equal(expected, line); } [Fact] - public void RenderThreadRow_Should_Highlight_When_Selected() + public void Render_Should_ShowFirstRecipientPlusOverflowCount_When_ThreadHasMultipleRecipients() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); - var thread = Thread(); + const int maxWidth = 90; + var thread = Thread(lastRecipients: ["alice", "carol", "dave"]); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var selected = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: true, "alice", s_now, columns); - var unselected = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth, widths)); // assert - Assert.Contains(">", selected); - Assert.NotEqual(selected, unselected); - AssertRendersWithoutError(selected); + Assert.Contains("alice+2", line); } [Fact] - public void RenderThreadRow_Should_EscapeMarkupCharacters_InSubjectAndPreview() + public void Render_Should_RightAlignMessageCount_When_ColumnIsWiderThanTheDigits() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); - var thread = Thread(subject: "[URGENT] fix this", bodyPreview: "see [here]"); + const int maxWidth = 90; + var thread = Thread(messageCount: 1); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var line = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); + var header = Markup.Remove(MailTable.RenderHeader(maxWidth, widths)); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth, widths)); + var messagesOffset = header.IndexOf("MESSAGES", StringComparison.Ordinal); // assert - AssertRendersWithoutError(line); + Assert.Equal("1".PadLeft(widths.Messages), line.Substring(messagesOffset, widths.Messages)); } - [Fact] - public void RenderThreadRow_Should_ApplyAnsiStyling_ToGlyphPeerAndAgeTokens_When_ActorIsDirectRecipient() + [Theory] + [InlineData(0, "just now")] + [InlineData(90, "1m ago")] + public void Render_Should_FormatLastActivity_When_AgeIsFreshOrMinutesOld(int elapsedSeconds, string expectedAge) { // arrange - // bob's last message addresses alice alone, so the thread gets the direct relationship glyph - var columns = MailTable.ComputeColumns(120, showCount: true); - var thread = Thread(lastSender: "bob", lastRecipients: ["alice"]); + var thread = Thread(lastMessageAt: s_now.AddSeconds(-elapsedSeconds)); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var line = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - var output = RenderAnsi(line); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth: 80, widths)); // assert - AssertAnsiStyleApplied(output, "mail.row.glyph.direct"); - AssertAnsiStylePrefixesText(output, "mail.row.to", "alice"); - AssertAnsiStylePrefixesText(output, "mail.row.age", "now"); - AssertAnsiStyleApplied(output, "mail.row.from"); + Assert.EndsWith(expectedAge, line.TrimEnd()); } [Fact] - public void RenderThreadRow_Should_ApplyFromMeTokens_When_ActorSentTheThread() + public void Render_Should_FormatLastActivityAsBareDate_When_ActivityIsAtLeastAWeekOld() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); - var thread = Thread(lastSender: "alice", lastRecipients: ["bob"]); + var lastMessageAt = s_now.AddDays(-8); + var thread = Thread(lastMessageAt: lastMessageAt); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var line = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - var output = RenderAnsi(line); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth: 80, widths)); // assert - AssertAnsiStylePrefixesText(output, "mail.row.glyph.from-me", "F"); - AssertAnsiStylePrefixesText(output, "mail.row.from.me", "alice"); + Assert.EndsWith(lastMessageAt.ToUniversalTime().ToString("yyyy-MM-dd"), line.TrimEnd()); } [Fact] - public void RenderThreadRow_Should_ApplyAnsiStyling_ToUnreadToMeMarker_When_UnreadToMeIsTrue() + public void Render_Should_DropToColumn_When_WidthIsTooNarrowForAllColumns() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); + var wide = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth: 90, widths)); // act - var line = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: true, selected: false, "alice", s_now, columns); - var output = RenderAnsi(line); - - // assert - AssertAnsiStyleApplied(output, "mail.row.unread-to-me"); - } - - [Fact] - public void RenderMessageRow_Should_ContainFromToSubjectAndAge() - { - // arrange - var columns = MailTable.ComputeColumns(120, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", - sender: "bob", - subject: "Status update", - body: "hi there, this is the body", - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient("alice")]); - - // act - var line = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns); - - // assert - Assert.Contains("bob", line); - Assert.Contains("alice", line); - Assert.Contains("Status update", line); - Assert.Contains("hi there", line); - AssertRendersWithoutError(line); - } - - [Fact] - public void RenderMessageRow_Should_UseThreadMembershipGlyph_NotRelationshipGlyph_When_ThreadChild() - { - // arrange - // the actor sent the message, but as an expanded thread child it shows thread-membership vocabulary instead - var columns = MailTable.ComputeColumns(120, showCount: true); - var message = MailMessageBuilder.Create( - "m-1", sender: "alice", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("bob")]); - - // act - var childRow = MailTable.RenderMessageRow(message, threadChild: true, unreadToMe: false, selected: false, "alice", s_now, columns); - var flatRow = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns); + var narrowMaxWidth = widths.Subject + 3 + widths.From + 4 + widths.Messages + 4 + widths.LastActivity + 4; + var narrow = Markup.Remove(MailTable.Render(thread, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + WideHasTo: wide.Contains("alice", StringComparison.Ordinal), + NarrowHasTo: narrow.Contains("alice", StringComparison.Ordinal), + NarrowHasFrom: narrow.Contains("bob", StringComparison.Ordinal)); // assert - Assert.Contains("โ””", childRow); - Assert.DoesNotContain("โ””", flatRow); - Assert.Contains("F", flatRow); + Assert.Equal((true, false, true), actual); } [Fact] - public void RenderMessageRow_Should_ApplyUnreadToMeToken_When_UnreadToMeIsTrue() + public void Render_Should_DropFromColumn_When_WidthIsTooNarrowForToAndFrom() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")]); + var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); + var narrowMaxWidth = widths.Subject + 3 + widths.Messages + 4 + widths.LastActivity + 4; // act - var unread = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: true, selected: false, "alice", s_now, columns); - var read = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns); + var narrow = Markup.Remove(MailTable.Render(thread, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + HasTo: narrow.Contains("alice", StringComparison.Ordinal), + HasFrom: narrow.Contains("bob", StringComparison.Ordinal), + HasActivity: narrow.Contains("just now", StringComparison.Ordinal)); // assert - Assert.Contains("โ—", unread); - Assert.DoesNotContain("โ—", read); + Assert.Equal((false, false, true), actual); } [Fact] - public void RenderMessageRow_Should_ApplyAnsiStyling_ToGlyphPeerPreviewAndAgeTokens_When_ActorIsDirectRecipient() + public void Render_Should_KeepSubjectAndLastActivity_When_WidthIsTooNarrowForEveryOtherColumn() { // arrange - // bob addresses alice alone, so the message gets the direct relationship glyph - var columns = MailTable.ComputeColumns(120, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", sender: "bob", body: "hi", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")]); + var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); + var narrowMaxWidth = widths.Subject + 3 + widths.LastActivity + 4; // act - var line = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns); - var output = RenderAnsi(line); + var narrow = Markup.Remove(MailTable.Render(thread, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + HasSubject: narrow.Contains("Status update", StringComparison.Ordinal), + HasActivity: narrow.Contains("just now", StringComparison.Ordinal), + HasFrom: narrow.Contains("bob", StringComparison.Ordinal), + HasTo: narrow.Contains("alice", StringComparison.Ordinal)); // assert - AssertAnsiStyleApplied(output, "mail.row.glyph.direct"); - AssertAnsiStylePrefixesText(output, "mail.row.to", "alice"); - AssertAnsiStylePrefixesText(output, "mail.row.preview", "hi"); - AssertAnsiStylePrefixesText(output, "mail.row.age", "now"); + Assert.Equal((true, true, false, false), actual); } [Fact] - public void RenderMessageRow_Should_ApplyAnsiStyling_ToUnreadToMeMarker_When_UnreadToMeIsTrue() + public void Render_Should_TruncateSubject_When_WidthIsTooNarrowForEveryColumn() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", sender: "bob", createdAt: s_now, recipients: [MailMessageBuilder.ToRecipient("alice")]); + const int maxWidth = 20; + var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var line = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: true, selected: false, "alice", s_now, columns); - var output = RenderAnsi(line); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth, widths)); // assert - AssertAnsiStyleApplied(output, "mail.row.unread-to-me"); + Assert.True(line.GetCellWidth() <= maxWidth); } [Fact] - public void RenderMessageRow_Should_LeaveTheCountColumnBlank_When_FlatRowInThreadedColumns() + public void RenderHeader_Should_AlignColumnsWithRow_When_WidthIsWide() { // arrange - // a flat-mode row rendered with Threads-mode columns must not print a stray count - var columns = MailTable.ComputeColumns(120, showCount: true); - var message = MailMessageBuilder.Create("m-1", createdAt: s_now); + const int maxWidth = 90; + var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); // act - var line = MailTable.RenderMessageRow(message, threadChild: false, unreadToMe: false, selected: false, "actor", s_now, columns); + var header = Markup.Remove(MailTable.RenderHeader(maxWidth, widths)); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, maxWidth, widths)); + var subjectOffset = header.IndexOf("SUBJECT", StringComparison.Ordinal); + var fromOffset = header.IndexOf("FROM", StringComparison.Ordinal); + var toOffset = header.IndexOf("TO", StringComparison.Ordinal); // assert - Assert.DoesNotContain("(", line); + Assert.Equal("Status update", line.Substring(subjectOffset, 13)); + Assert.Equal("bob", line.Substring(fromOffset, 3)); + Assert.Equal("alice", line.Substring(toOffset, 5)); } [Fact] - public void RenderThreadRow_And_RenderMessageRow_Should_BeDeterministic() + public void RenderHeader_Should_DropTheSameColumnsAsRow_When_WidthIsNarrow() { // arrange - var columns = MailTable.ComputeColumns(120, showCount: true); var thread = Thread(); + var widths = MailTable.ComputeWidths([thread], s_now); + var narrowMaxWidth = widths.Subject + 3 + widths.From + 4 + widths.Messages + 4 + widths.LastActivity + 4; // act - var first = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - var second = MailTable.RenderThreadRow(thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns); - - // assert - Assert.Equal(first, second); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void RenderHeading_And_RenderThreadRow_Should_AlignColumnStarts_AtTheSameIndex(bool showCount) - { - // arrange - // a width wide enough that Subject/Preview stay above zero, so every column has a start index - const int contentWidth = 100; - var columns = MailTable.ComputeColumns(contentWidth, showCount); - var thread = Thread( - subject: new string('S', 40), - lastSender: new string('F', columns.FromWidth), - lastRecipients: [new string('T', columns.ToWidth)], - bodyPreview: new string('P', 40)); - - var offsetFrom = columns.PrefixWidth; - var offsetTo = offsetFrom + columns.FromWidth + 1; - var offsetSubject = offsetTo + columns.ToWidth + 1; - var offsetPreview = offsetSubject + columns.SubjectWidth + 1; - var offsetAge = offsetPreview + columns.PreviewWidth + 1; - - // act - var heading = RenderPlain(MailTable.RenderHeading(columns)); - var row = RenderPlain(MailTable.RenderThreadRow( - thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns)); - - // assert - Assert.Equal(offsetFrom, heading.IndexOf("From", StringComparison.Ordinal)); - Assert.Equal(offsetFrom, row.IndexOf(new string('F', columns.FromWidth), StringComparison.Ordinal)); - Assert.Equal(offsetTo, heading.IndexOf("To", StringComparison.Ordinal)); - Assert.Equal(offsetTo, row.IndexOf(new string('T', columns.ToWidth), StringComparison.Ordinal)); - Assert.Equal(offsetSubject, heading.IndexOf("Subject", StringComparison.Ordinal)); - Assert.Equal(offsetSubject, row.IndexOf(new string('S', 4), StringComparison.Ordinal)); - Assert.Equal(offsetPreview, heading.IndexOf("Preview", StringComparison.Ordinal)); - Assert.Equal(offsetPreview, row.IndexOf(new string('P', 4), StringComparison.Ordinal)); - Assert.Equal(offsetAge, heading.IndexOf("Age", StringComparison.Ordinal)); - - // assert - Assert.Equal(contentWidth, row.Length); - Assert.True(heading.Length <= contentWidth); - } - - [Theory] - [InlineData(50, false)] // elastic 0 - [InlineData(51, false)] // elastic 1 - [InlineData(52, false)] // elastic 2 - [InlineData(56, true)] // elastic 0 - [InlineData(57, true)] // elastic 1 - [InlineData(58, true)] // elastic 2 - public void RenderHeading_And_RenderThreadRow_Should_NeverExceedContentWidth_When_ElasticIsNearZero( - int contentWidth, bool showCount) - { - // arrange - var columns = MailTable.ComputeColumns(contentWidth, showCount); - var thread = Thread(subject: new string('S', 40), bodyPreview: new string('P', 40)); - - // act - var heading = RenderPlain(MailTable.RenderHeading(columns)); - var row = RenderPlain(MailTable.RenderThreadRow( - thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns)); + var header = Markup.Remove(MailTable.RenderHeader(narrowMaxWidth, widths)); + var line = Markup.Remove(MailTable.Render(thread, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + HeaderHasTo: header.Contains("TO", StringComparison.Ordinal), + RowHasTo: line.Contains("alice", StringComparison.Ordinal), + HeaderHasFrom: header.Contains("FROM", StringComparison.Ordinal), + RowHasFrom: line.Contains("bob", StringComparison.Ordinal)); // assert - Assert.True(heading.Length <= contentWidth, $"heading length {heading.Length} exceeded {contentWidth}."); - Assert.True(row.Length <= contentWidth, $"row length {row.Length} exceeded {contentWidth}."); + Assert.Equal((false, false, true, true), actual); } [Fact] - public void RenderThreadRow_Should_FitContentWidth_InTerminalCells_When_EveryColumnHoldsWideCjkCharacters() + public void RenderRule_Should_ReturnEmpty_When_MaxWidthIsZero() { - // arrange - // Fill sender, recipients, subject, and preview with two-cell CJK characters. - const int contentWidth = 80; - var columns = MailTable.ComputeColumns(contentWidth, showCount: true); - var thread = Thread( - subject: new string('ไปถ', 60), - lastSender: new string('ๅ', 60), - lastRecipients: [new string('ๅฎ›', 60)], - bodyPreview: new string('ๆ–‡', 60)); - // act - var row = RenderPlain(MailTable.RenderThreadRow( - thread, expanded: false, unreadToMe: false, selected: false, "alice", s_now, columns)); + var rule = MailTable.RenderRule(0); // assert - Assert.Equal(contentWidth, MeasureCellWidth(row)); + Assert.Empty(rule); } [Fact] - public void RenderMessageRow_Should_FitContentWidth_InTerminalCells_When_EveryColumnHoldsEmojiCharacters() - { - // arrange - // Fill sender, recipients, subject, and body with two-cell emoji. - const int contentWidth = 80; - var columns = MailTable.ComputeColumns(contentWidth, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", - sender: string.Concat(Enumerable.Repeat("๐ŸŽˆ", 60)), - subject: string.Concat(Enumerable.Repeat("๐ŸŽ‰", 60)), - body: string.Concat(Enumerable.Repeat("๐ŸŽŠ", 60)), - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient(string.Concat(Enumerable.Repeat("๐ŸŽ", 60)))]); - - // act - var row = RenderPlain(MailTable.RenderMessageRow( - message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns)); - - // assert - Assert.Equal(contentWidth, MeasureCellWidth(row)); - } - - [Theory] - [InlineData("โŒš")] - [InlineData("โค๏ธ")] - [InlineData("1๏ธโƒฃ")] - public void RenderMessageRow_Should_FitContentWidth_When_ContentUsesEmojiPresentation(string emoji) - { - // arrange - const int contentWidth = 80; - var columns = MailTable.ComputeColumns(contentWidth, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", - sender: string.Concat(Enumerable.Repeat(emoji, 60)), - subject: string.Concat(Enumerable.Repeat(emoji, 60)), - body: string.Concat(Enumerable.Repeat(emoji, 60)), - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient(string.Concat(Enumerable.Repeat(emoji, 60)))]); - - // act - var row = RenderPlain(MailTable.RenderMessageRow( - message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns)); - - // assert - Assert.Equal(contentWidth, MeasureEmojiPresentationWidth(row)); - } - - [Theory] - [InlineData(20)] - [InlineData(21)] - [InlineData(22)] - [InlineData(35)] - [InlineData(36)] - [InlineData(50)] - [InlineData(51)] - public void RenderMessageRow_Should_NeverEmitALoneSurrogate_When_TruncatingEmojiContent(int contentWidth) + public void RenderRule_Should_FillTheGivenWidth_When_WidthIsPositive() { - // arrange - // Vary the available width while keeping the emoji content fixed. - var columns = MailTable.ComputeColumns(contentWidth, showCount: false); - var message = MailMessageBuilder.Create( - "m-1", - sender: string.Concat(Enumerable.Repeat("๐ŸŽˆ", 40)), - subject: string.Concat(Enumerable.Repeat("๐ŸŽ‰", 40)), - body: string.Concat(Enumerable.Repeat("๐ŸŽŠ", 40)), - createdAt: s_now, - recipients: [MailMessageBuilder.ToRecipient(string.Concat(Enumerable.Repeat("๐ŸŽ", 40)))]); - // act - var row = MailTable.RenderMessageRow( - message, threadChild: false, unreadToMe: false, selected: false, "alice", s_now, columns); + var rule = Markup.Remove(MailTable.RenderRule(20)); // assert - Assert.False(ContainsLoneSurrogate(row)); - Assert.False(ContainsLoneSurrogate(RenderPlain(row))); + Assert.Equal(new string('โ”€', 20), rule); } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailThreadPopoverTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailThreadPopoverTests.cs new file mode 100644 index 00000000000..846381752e3 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/MailThreadPopoverTests.cs @@ -0,0 +1,444 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; +using ChilliCream.Nitro.CommandLine.Tui.Mail; +using ChilliCream.Nitro.CommandLine.Tui.Shell; +using Microsoft.Extensions.Time.Testing; +using Spectre.Console; +using Spectre.Console.Testing; +using static ChilliCream.Nitro.CommandLine.Tests.Tui.AnsiAssertions; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; + +/// +/// Exercises against fakes: loading and rendering a +/// thread's header and messages, harness attribution, scrolling, the copy-id gesture, and +/// tick-driven age recomputation. +/// +public sealed class MailThreadPopoverModelTests +{ + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private static ConsoleKeyInfo Key(ConsoleKey key, char ch = '\0', bool shift = false) => + new(ch, key, shift, false, false); + + private static string RenderToText(MailThreadPopoverModel model, int width = 100, int height = 30) + { + var console = new TestConsole().Width(width); + console.Write(model.Render(width, height)); + return console.Output; + } + + private static string RenderToAnsiText(MailThreadPopoverModel model, int width = 100, int height = 30) + { + var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(width); + console.Write(model.Render(width, height)); + return console.Output; + } + + private static MailThreadPopoverModel CreateModel( + string threadId, + FakeMailStore mailStore, + FakeAgentStore? agentStore = null, + TimeProvider? timeProvider = null, + Func? moveSelection = null) + => new( + threadId, + mailStore, + agentStore ?? new FakeAgentStore(new FakeTimeProvider(s_now)), + timeProvider ?? new FakeTimeProvider(s_now), + moveSelection ?? (_ => null)); + + private static MailMessage CreateMessage( + string id, + string threadId, + string sender, + string subject, + string body, + DateTimeOffset createdAt, + IReadOnlyList? recipients = null) + => MailMessageBuilder.Create( + id, sender: sender, subject: subject, body: body, threadId: threadId, createdAt: createdAt, + recipients: recipients ?? [MailMessageBuilder.ToRecipient("alice")]); + + private static void SeedAgentWithHarness(FakeAgentStore store, string name, string harness) => store.Seed(new AgentRow + { + Name = name, + Role = "", + Harness = harness, + HarnessVersion = "1.0.0", + SessionId = $"s-{name}", + Cwd = "", + WorkspacePath = "", + RegisteredAt = s_now, + StartedAt = s_now, + LastSeenAt = s_now, + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1", + BlockBudgetUsed = 0, + AnnouncementPending = false, + IdlePushArmed = false + }); + + [Fact] + public void Render_Should_ShowTheSubjectAsTheTitle_When_ThreadIsLoaded() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Status update", "Hello.", s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Status update", text); + } + + [Fact] + public void Render_Should_ShowTheSubjectLiterally_When_TheSubjectContainsBrackets() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "[Fusion] Add x", "Hello.", s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("[Fusion] Add x", text); + } + + [Fact] + public void Render_Should_ShowParticipantsMessageCountAndAges_When_ThreadHasThreeMessages() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage( + "m1", "t1", "bob", "Status update", "First.", s_now, + [MailMessageBuilder.ToRecipient("alice"), MailMessageBuilder.CcRecipient("carol")])); + store.Messages.Add(CreateMessage("m2", "t1", "alice", "Status update", "Second.", s_now.AddMinutes(1))); + store.Messages.Add(CreateMessage("m3", "t1", "bob", "Status update", "Third.", s_now.AddMinutes(2))); + var time = new FakeTimeProvider(s_now.AddMinutes(2)); + var model = CreateModel("t1", store, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Participants: alice, bob, carol", text); + Assert.Contains("Messages: 3", text); + Assert.Contains("Started: 2m", text); + Assert.Contains("Last activity: now", text); + } + + [Fact] + public void Render_Should_ShowEveryMessageOldestFirstWithSpeakerRecipientsAndBody_When_ThreadHasThreeMessages() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage( + "m1", "t1", "bob", "Status update", "First message.", s_now, + [MailMessageBuilder.ToRecipient("alice"), MailMessageBuilder.CcRecipient("carol")])); + store.Messages.Add(CreateMessage("m2", "t1", "alice", "Status update", "Second message.", s_now.AddMinutes(1))); + store.Messages.Add(CreateMessage("m3", "t1", "bob", "Status update", "Third message.", s_now.AddMinutes(2))); + var model = CreateModel("t1", store, timeProvider: new FakeTimeProvider(s_now)); + model.Load(TestContext.Current.CancellationToken); + var console = new TestConsole().Width(100); + + // act + console.Write(model.Render(100, 30)); + + // assert + console.Output.MatchInlineSnapshot( + """ + + + + โ•ญโ”€Status updateโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ Participants: alice, bob, carol โ”‚ + โ”‚ Messages: 3 โ”‚ + โ”‚ Started: now โ”‚ + โ”‚ Last activity: now โ”‚ + โ”‚ โ”‚ + โ”‚ bob ยท now โ”‚ + โ”‚ To: alice โ”‚ + โ”‚ Cc: carol โ”‚ + โ”‚ First message. โ”‚ + โ”‚ โ”‚ + โ”‚ alice ยท now โ”‚ + โ”‚ To: alice โ”‚ + โ”‚ Second message. โ”‚ + โ”‚ โ”‚ + โ”‚ bob ยท now โ”‚ + โ”‚ To: alice โ”‚ + โ”‚ Third message. โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + + + """); + } + + [Fact] + public void Render_Should_AttributeTheSenderWithItsHarness_When_TheSenderHasAKnownHarness() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + SeedAgentWithHarness(agentStore, "bob", AgentSessionHarness.ClaudeCode); + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store, agentStore); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("bob (Claude Code)", text); + } + + [Fact] + public void Render_Should_ShowTheSenderAlone_When_NoAgentRowExists() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + var actual = ( + HasName: text.Contains("bob", StringComparison.Ordinal), + HasAttribution: text.Contains("bob (", StringComparison.Ordinal)); + + // assert + Assert.Equal((true, false), actual); + } + + [Fact] + public void Render_Should_ApplyTheSectionTitleStyle_When_RenderingTheSpeakerLine() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + + // act + var output = RenderToAnsiText(model); + + // assert + AssertAnsiStylePrefixesText(output, "detail.section.header", "bob"); + } + + [Fact] + public void Load_Should_NotMarkAnyMessageRead_When_TheThreadHasAnUnreadMessage() + { + // arrange + var store = new FakeMailStore(); + var recipient = MailMessageBuilder.ToRecipient("alice"); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now, [recipient])); + var model = CreateModel("t1", store); + + // act + model.Load(TestContext.Current.CancellationToken); + + // assert + var stored = Assert.Single(store.Messages); + Assert.Null(Assert.Single(stored.Recipients).ReadAt); + } + + [Fact] + public void HandleKey_Should_ScrollTheBody_When_PageDownIsPressedRepeatedly() + { + // arrange + var store = new FakeMailStore(); + var body = string.Join('\n', Enumerable.Range(0, 40).Select(i => $"Line {i}")); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", body, s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + var before = RenderToText(model, height: 10); + + // act + for (var i = 0; i < 5; i++) + { + model.HandleKey(Key(ConsoleKey.PageDown)); + } + + var after = RenderToText(model, height: 10); + + // assert + Assert.NotEqual(before, after); + } + + [Fact] + public void HandleKey_Should_MoveToTheNextThreadAndReload_When_DownArrowIsPressed() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "First subject", "First.", s_now)); + store.Messages.Add(CreateMessage("m2", "t2", "bob", "Second subject", "Second.", s_now)); + var next = new MailThreadSummary + { + ThreadId = "t2", + Subject = "Second subject", + MessageCount = 1, + LastMessageAt = s_now, + LastSender = "bob", + LastRecipients = [], + BodyPreview = "Second.", + UnreadCount = null, + ArchivedCount = null + }; + var model = CreateModel("t1", store, moveSelection: delta => delta == 1 ? next : null); + model.Load(TestContext.Current.CancellationToken); + + // act + model.HandleKey(Key(ConsoleKey.DownArrow)); + var text = RenderToText(model); + + // assert + Assert.Contains("Second subject", text); + } + + [Fact] + public void HandleKey_Should_DoNothing_When_UpArrowIsPressedAtTheFirstThread() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store, moveSelection: _ => null); + model.Load(TestContext.Current.CancellationToken); + var before = RenderToText(model); + + // act + var result = model.HandleKey(Key(ConsoleKey.UpArrow)); + var after = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Equal(before, after); + } + + [Fact] + public void HandleKey_Should_JumpToTheBottomAndBackToTheTop_When_ShiftGThenGArePressed() + { + // arrange + var store = new FakeMailStore(); + var body = string.Join('\n', Enumerable.Range(0, 40).Select(i => $"Line {i}")); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", body, s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + var top = RenderToText(model, height: 10); + + // act + model.HandleKey(Key(ConsoleKey.G, 'G', shift: true)); + var bottom = RenderToText(model, height: 10); + model.HandleKey(Key(ConsoleKey.G, 'g')); + var backAtTop = RenderToText(model, height: 10); + + // assert + Assert.NotEqual(top, bottom); + Assert.Equal(top, backAtTop); + } + + [Fact] + public void HandleKey_Should_ReturnCopyRequestedWithTheThreadId_When_YIsPressed() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Y, 'y')); + + // assert + var request = Assert.IsType(result); + var copy = Assert.IsType(request.Payload); + Assert.Equal("t1", copy.ThreadId); + } + + [Fact] + public void HandleKey_Should_ReturnClosed_When_EscapeIsPressed() + { + // arrange + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Escape)); + + // assert + Assert.IsType(result); + } + + [Fact] + public void Tick_Should_ReturnFalse_When_NoTimeHasPassed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + + // act + var dirty = model.Tick(); + + // assert + Assert.False(dirty); + } + + [Fact] + public void Tick_Should_ReturnTrueAndUpdateTheAges_When_TimeAdvances() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = new FakeMailStore(); + store.Messages.Add(CreateMessage("m1", "t1", "bob", "Subject", "Body.", s_now)); + var model = CreateModel("t1", store, timeProvider: time); + model.Load(TestContext.Current.CancellationToken); + + // act + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = model.Tick(); + var text = RenderToText(model); + + // assert + Assert.True(dirty); + Assert.Contains("Started: 2m", text); + } + + [Fact] + public void DefaultHints_Should_ListMovePageScrollCopyIdAndClose_When_Inspected() + { + // arrange + // act + var hints = MailThreadPopoverModel.DefaultHints; + + // assert + Assert.Equal( + [ + new("up/down", "prev/next"), + new("pgup/pgdn", "scroll"), + new("y", "copy id"), + new("esc", "close") + ], + hints); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/ThrowingActorWakeDispatcher.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/ThrowingActorWakeDispatcher.cs deleted file mode 100644 index ccfaffec2cd..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Mail/ThrowingActorWakeDispatcher.cs +++ /dev/null @@ -1,12 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Notify; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; - -/// -/// An whose always throws. -/// -internal sealed class ThrowingActorWakeDispatcher : IActorWakeDispatcher -{ - public Task DispatchAsync(string actor, DateTimeOffset deadline, CancellationToken cancellationToken) - => throw new InvalidOperationException("Dispatch failed."); -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryEntryPopoverTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryEntryPopoverTests.cs new file mode 100644 index 00000000000..74f1783d757 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryEntryPopoverTests.cs @@ -0,0 +1,452 @@ +using ChilliCream.Nitro.CommandLine.Services.Memory; +using ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; +using ChilliCream.Nitro.CommandLine.Tui.Memory; +using ChilliCream.Nitro.CommandLine.Tui.Shell; +using Microsoft.Extensions.Time.Testing; +using Spectre.Console.Testing; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Memory; + +/// +/// Exercises against a : +/// loading and rendering a curated memory's and a journal entry's header fields, scrolling, +/// the copy-id gesture, and tick-driven age recomputation. +/// +public sealed class MemoryEntryPopoverModelTests +{ + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private static ConsoleKeyInfo Key(ConsoleKey key, char ch = '\0', bool shift = false) => + new(ch, key, shift, false, false); + + private static string RenderToText(MemoryEntryPopoverModel model, int width = 100, int height = 30) + { + var console = new TestConsole().Width(width); + console.Write(model.Render(width, height)); + return console.Output; + } + + private static MemoryEntryPopoverModel CreateModel( + string id, + MemoryCollectionFilter kind, + FakeMemoryStore store, + TimeProvider? timeProvider = null, + Func? moveSelection = null) + => new(id, kind, store, timeProvider ?? new FakeTimeProvider(s_now), moveSelection ?? (_ => null)); + + private static MemoryRecord CreateCuratedRecord( + string id = "mem-1", + string type = "fact", + IReadOnlyList? tags = null, + string body = "Body text.", + DateTimeOffset? createdAt = null, + DateTimeOffset? updatedAt = null, + string createdBy = "bob", + string? promotedFrom = null) => new() + { + Id = id, + Type = type, + Tags = tags ?? [], + Body = body, + CreatedAt = createdAt ?? s_now, + UpdatedAt = updatedAt ?? createdAt ?? s_now, + CreatedBy = createdBy, + PromotedFrom = promotedFrom + }; + + private static MemoryJournalEntry CreateJournalEntry( + string id = "jrn-1", string body = "Journal body.", DateTimeOffset? createdAt = null, string createdBy = "bob") + => new() { Id = id, Body = body, CreatedAt = createdAt ?? s_now, CreatedBy = createdBy }; + + [Fact] + public void Render_Should_ShowTheEntryIdAsTheTitle_When_ACuratedMemoryIsLoaded() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("mem-1", text); + } + + [Fact] + public void Render_Should_ShowCuratedHeaderFields_When_ACuratedMemoryIsLoaded() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord( + type: "decision", tags: ["ops", "infra"], createdAt: s_now, updatedAt: s_now.AddMinutes(5)); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store, new FakeTimeProvider(s_now.AddMinutes(5))); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Kind: curated", text); + Assert.Contains("Type: decision", text); + Assert.Contains("Tags: ops, infra", text); + Assert.Contains("Created: 5m ago by bob", text); + Assert.Contains("Updated: just now", text); + } + + [Fact] + public void Render_Should_ShowADashForTags_When_TheCuratedMemoryHasNoTags() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(tags: []); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Tags: -", text); + } + + [Fact] + public void Render_Should_HideUpdated_When_ItMatchesCreated() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(createdAt: s_now, updatedAt: s_now); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + var actual = ( + HasCreated: text.Contains("Created:", StringComparison.Ordinal), + HasUpdated: text.Contains("Updated:", StringComparison.Ordinal)); + + // assert + Assert.Equal((true, false), actual); + } + + [Fact] + public void Render_Should_ShowPromotedFrom_When_TheCuratedMemoryWasPromoted() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(promotedFrom: "jrn-9"); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Promoted from: jrn-9", text); + } + + [Fact] + public void Render_Should_ShowJournalHeaderFieldsAndBody_When_AJournalEntryIsLoaded() + { + // arrange + var store = new FakeMemoryStore(); + store.JournalEntries["jrn-1"] = CreateJournalEntry(body: "Follow up needed.", createdAt: s_now, createdBy: "alice"); + var model = CreateModel("jrn-1", MemoryCollectionFilter.Journal, store, new FakeTimeProvider(s_now)); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("Kind: journal", text); + Assert.Contains("Created: just now by alice", text); + Assert.Contains("Follow up needed.", text); + } + + [Fact] + public void Render_Should_ShowTheFullPopoverLayout_When_ACuratedMemoryIsLoaded() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord( + type: "fact", tags: ["ops"], body: "Restart the worker on failure.", createdAt: s_now, createdBy: "bob"); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store, new FakeTimeProvider(s_now)); + model.Load(TestContext.Current.CancellationToken); + var console = new TestConsole().Width(100); + + // act + console.Write(model.Render(100, 30)); + + // assert + console.Output.MatchInlineSnapshot( + """ + + + + โ•ญโ”€mem-1โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ Kind: curated โ”‚ + โ”‚ Type: fact โ”‚ + โ”‚ Tags: ops โ”‚ + โ”‚ Created: just now by bob โ”‚ + โ”‚ โ”‚ + โ”‚ Restart the worker on failure. โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + + + """); + } + + [Fact] + public void Render_Should_ShowTheFullPopoverLayout_When_AJournalEntryIsLoaded() + { + // arrange + var store = new FakeMemoryStore(); + store.JournalEntries["jrn-1"] = CreateJournalEntry(body: "Follow up needed.", createdAt: s_now, createdBy: "alice"); + var model = CreateModel("jrn-1", MemoryCollectionFilter.Journal, store, new FakeTimeProvider(s_now)); + model.Load(TestContext.Current.CancellationToken); + var console = new TestConsole().Width(100); + + // act + console.Write(model.Render(100, 30)); + + // assert + console.Output.MatchInlineSnapshot( + """ + + + + โ•ญโ”€jrn-1โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ Kind: journal โ”‚ + โ”‚ Created: just now by alice โ”‚ + โ”‚ โ”‚ + โ”‚ Follow up needed. โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + + + """); + } + + [Fact] + public void Render_Should_ShowTheMissingState_When_TheEntryNoLongerExists() + { + // arrange + var store = new FakeMemoryStore(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var text = RenderToText(model); + + // assert + Assert.Contains("This entry no longer exists.", text); + } + + [Fact] + public void HandleKey_Should_ScrollTheBody_When_PageDownIsPressedRepeatedly() + { + // arrange + var store = new FakeMemoryStore(); + var body = string.Join('\n', Enumerable.Range(0, 40).Select(i => $"Line {i}")); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(body: body); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + var before = RenderToText(model, height: 10); + + // act + for (var i = 0; i < 5; i++) + { + model.HandleKey(Key(ConsoleKey.PageDown)); + } + + var after = RenderToText(model, height: 10); + + // assert + Assert.NotEqual(before, after); + } + + [Fact] + public void HandleKey_Should_MoveToTheNextRowAndReload_When_DownArrowIsPressed() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + store.CuratedRecords["mem-2"] = CreateCuratedRecord(id: "mem-2", body: "Second entry."); + var next = new MemoryRow(MemoryCollectionFilter.Curated, "mem-2", "fact", [], "Second entry.", s_now); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store, moveSelection: delta => delta == 1 ? next : null); + model.Load(TestContext.Current.CancellationToken); + + // act + model.HandleKey(Key(ConsoleKey.DownArrow)); + var text = RenderToText(model); + + // assert + Assert.Contains("mem-2", text); + } + + [Fact] + public void HandleKey_Should_DoNothing_When_UpArrowIsPressedAtTheFirstRow() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store, moveSelection: _ => null); + model.Load(TestContext.Current.CancellationToken); + var before = RenderToText(model); + + // act + var result = model.HandleKey(Key(ConsoleKey.UpArrow)); + var after = RenderToText(model); + + // assert + Assert.Null(result); + Assert.Equal(before, after); + } + + [Fact] + public void HandleKey_Should_JumpToTheBottomAndBackToTheTop_When_ShiftGThenGArePressed() + { + // arrange + var store = new FakeMemoryStore(); + var body = string.Join('\n', Enumerable.Range(0, 40).Select(i => $"Line {i}")); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(body: body); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + var top = RenderToText(model, height: 10); + + // act + model.HandleKey(Key(ConsoleKey.G, 'G', shift: true)); + var bottom = RenderToText(model, height: 10); + model.HandleKey(Key(ConsoleKey.G, 'g')); + var backAtTop = RenderToText(model, height: 10); + + // assert + Assert.NotEqual(top, bottom); + Assert.Equal(top, backAtTop); + } + + [Fact] + public void HandleKey_Should_ReturnCopyRequestedWithTheEntryId_When_YIsPressed() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Y, 'y')); + + // assert + var request = Assert.IsType(result); + var copy = Assert.IsType(request.Payload); + Assert.Equal("mem-1", copy.EntryId); + } + + [Fact] + public void HandleKey_Should_ReturnClosed_When_EscapeIsPressed() + { + // arrange + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store); + model.Load(TestContext.Current.CancellationToken); + + // act + var result = model.HandleKey(Key(ConsoleKey.Escape)); + + // assert + Assert.IsType(result); + } + + [Fact] + public void Tick_Should_ReturnFalse_When_NoTimeHasPassed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store, time); + model.Load(TestContext.Current.CancellationToken); + + // act + var dirty = model.Tick(); + + // assert + Assert.False(dirty); + } + + [Fact] + public void Tick_Should_ReturnTrueAndUpdateTheAges_When_TimeAdvances() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = new FakeMemoryStore(); + store.CuratedRecords["mem-1"] = CreateCuratedRecord(); + var model = CreateModel("mem-1", MemoryCollectionFilter.Curated, store, time); + model.Load(TestContext.Current.CancellationToken); + + // act + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = model.Tick(); + var text = RenderToText(model); + + // assert + Assert.True(dirty); + Assert.Contains("Created: 2m ago by bob", text); + } + + [Fact] + public void DefaultHints_Should_ListMovePageScrollCopyIdAndClose_When_Inspected() + { + // arrange + // act + var hints = MemoryEntryPopoverModel.DefaultHints; + + // assert + Assert.Equal( + [ + new("up/down", "prev/next"), + new("pgup/pgdn", "scroll"), + new("y", "copy id"), + new("esc", "close") + ], + hints); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryJournalRowBadgeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryJournalRowBadgeTests.cs deleted file mode 100644 index 51e6e38d366..00000000000 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryJournalRowBadgeTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -using ChilliCream.Nitro.CommandLine.Services.Memory; -using ChilliCream.Nitro.CommandLine.Tui.Memory; -using Spectre.Console; - -namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Memory; - -public sealed class MemoryJournalRowBadgeTests -{ - [Fact] - public void Render_Should_FitDisplayWidth_When_PreviewContainsCjkAndEmoji() - { - // arrange - const int maxWidth = 21; - var entry = CreateEntry("๐Ÿ˜€ๆผข preview"); - var widths = MemoryJournalRowBadge.ComputeWidths([entry]); - - // act - var line = MemoryJournalRowBadge.Render(entry, selected: false, maxWidth, widths); - var plainText = Markup.Remove(line); - - // assert - Assert.Equal(" 2026-01-01 00:00 โ€ฆ", plainText); - Assert.True(plainText.GetCellWidth() <= maxWidth); - } - - [Fact] - public void Render_Should_FitFixedColumns_When_MaxWidthMatchesTheirDisplayWidth() - { - // arrange - const int maxWidth = 19; - var entry = CreateEntry("Preview"); - var widths = MemoryJournalRowBadge.ComputeWidths([entry]); - - // act - var line = MemoryJournalRowBadge.Render(entry, selected: false, maxWidth, widths); - var plainText = Markup.Remove(line); - - // assert - Assert.Equal(" 2026-01-01 00:00 ", plainText); - Assert.Equal(maxWidth, plainText.GetCellWidth()); - } - - [Fact] - public void Render_Should_FitWithinOneColumn_When_Selected() - { - // arrange - var entry = CreateEntry("๐Ÿ˜€ preview"); - var widths = MemoryJournalRowBadge.ComputeWidths([entry]); - - // act - var line = MemoryJournalRowBadge.Render(entry, selected: true, maxWidth: 1, widths); - var plainText = Markup.Remove(line); - - // assert - Assert.Equal(">", plainText); - } - - [Fact] - public void Render_Should_PreserveNormalOutput_When_ItFits() - { - // arrange - var entry = CreateEntry("Preview"); - var widths = MemoryJournalRowBadge.ComputeWidths([entry]); - - // act - var line = MemoryJournalRowBadge.Render(entry, selected: false, maxWidth: 80, widths); - - // assert - Assert.Equal(" 2026-01-01 00:00 Preview", Markup.Remove(line)); - } - - private static MemoryJournalEntry CreateEntry(string body) => new() - { - Id = "j-1", - Body = body, - CreatedAt = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), - CreatedBy = "test-agent" - }; -} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryKeyMapTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryKeyMapTests.cs index 48eeeeb32c1..83ffe4df5a6 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryKeyMapTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryKeyMapTests.cs @@ -7,7 +7,7 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Memory; public sealed class MemoryKeyMapTests { [Fact] - public void CreateDefault_Should_MapJAndDownArrow_ToMoveCursorDown() + public void CreateDefault_Should_ReturnMoveCursorDown_When_JOrDownArrowIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); @@ -24,50 +24,71 @@ public void CreateDefault_Should_MapJAndDownArrow_ToMoveCursorDown() } [Fact] - public void CreateDefault_Should_MapF_ToCycleView() + public void CreateDefault_Should_ReturnMoveCursorUp_When_KOrUpArrowIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); - var f = new KeyChord(ConsoleKey.F, ConsoleModifiers.None, 'f'); + var k = new KeyChord(ConsoleKey.K, ConsoleModifiers.None, 'k'); + var up = new KeyChord(ConsoleKey.UpArrow, ConsoleModifiers.None, '\0'); // act - var resolved = keyMap.TryResolve(f, out var message); + keyMap.TryResolve(k, out var kMessage); + keyMap.TryResolve(up, out var upMessage); + + // assert + Assert.Equal(CursorDirection.Up, Assert.IsType(kMessage).Direction); + Assert.Equal(CursorDirection.Up, Assert.IsType(upMessage).Direction); + } + + [Fact] + public void CreateDefault_Should_ReturnMoveToEdge_When_GOrShiftGIsResolved() + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + var g = new KeyChord(ConsoleKey.G, ConsoleModifiers.None, 'g'); + var shiftG = new KeyChord(ConsoleKey.G, ConsoleModifiers.Shift, 'G'); + + // act + keyMap.TryResolve(g, out var top); + keyMap.TryResolve(shiftG, out var bottom); + + // assert + Assert.Equal(EdgeTarget.Top, Assert.IsType(top).Edge); + Assert.Equal(EdgeTarget.Bottom, Assert.IsType(bottom).Edge); + } + + [Fact] + public void CreateDefault_Should_ReturnOpenSelected_When_EnterIsResolved() + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + var enter = new KeyChord(ConsoleKey.Enter, ConsoleModifiers.None, '\r'); + + // act + var resolved = keyMap.TryResolve(enter, out var message); // assert Assert.True(resolved); - Assert.IsType(message); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_NotMapSOrAdvertiseScope() + public void CreateDefault_Should_ReturnCycleView_When_FIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); - var s = new KeyChord(ConsoleKey.S, ConsoleModifiers.None, 's'); + var f = new KeyChord(ConsoleKey.F, ConsoleModifiers.None, 'f'); // act - var resolved = keyMap.TryResolve(s, out _); + var resolved = keyMap.TryResolve(f, out var message); // assert - Assert.False(resolved); - Assert.Equal( - [ - new KeyHint("hjkl", "move"), - new KeyHint("tab", "switch pane"), - new KeyHint("enter", "focus detail"), - new KeyHint("f", "curated/journal"), - new KeyHint("/", "search"), - new KeyHint("p", "promote"), - new KeyHint("d", "forget"), - new KeyHint("y", "copy id"), - new KeyHint("esc", "back"), - new KeyHint("q", "quit") - ], - keyMap.Hints); + Assert.True(resolved); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapSlash_ToSearchRequested() + public void CreateDefault_Should_ReturnSearchRequested_When_SlashIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); @@ -82,42 +103,42 @@ public void CreateDefault_Should_MapSlash_ToSearchRequested() } [Fact] - public void CreateDefault_Should_MapP_ToPromoteRequested() + public void CreateDefault_Should_ReturnCopySelectedId_When_YIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); - var p = new KeyChord(ConsoleKey.P, ConsoleModifiers.None, 'p'); + var y = new KeyChord(ConsoleKey.Y, ConsoleModifiers.None, 'y'); // act - var resolved = keyMap.TryResolve(p, out var message); + var resolved = keyMap.TryResolve(y, out var message); // assert Assert.True(resolved); - Assert.IsType(message); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapD_ToForgetRequested() + public void CreateDefault_Should_ReturnRefreshRequested_When_RIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); - var d = new KeyChord(ConsoleKey.D, ConsoleModifiers.None, 'd'); + var r = new KeyChord(ConsoleKey.R, ConsoleModifiers.None, 'r'); // act - var resolved = keyMap.TryResolve(d, out var message); + var resolved = keyMap.TryResolve(r, out var message); // assert Assert.True(resolved); - Assert.IsType(message); + Assert.IsType(message); } [Fact] - public void CreateDefault_Should_MapQAndCtrlC_ToQuitRequested() + public void CreateDefault_Should_ReturnQuitRequested_When_QOrCtrlCIsResolved() { // arrange var keyMap = MemoryKeyMap.CreateDefault(); var q = new KeyChord(ConsoleKey.Q, ConsoleModifiers.None, 'q'); - var ctrlC = new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, ''); + var ctrlC = new KeyChord(ConsoleKey.C, ConsoleModifiers.Control, '\u0003'); // act keyMap.TryResolve(q, out var qMessage); @@ -127,4 +148,49 @@ public void CreateDefault_Should_MapQAndCtrlC_ToQuitRequested() Assert.IsType(qMessage); Assert.IsType(ctrlCMessage); } + + [Fact] + public void CreateDefault_Should_ReturnBack_When_EscapeIsResolved() + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + var escape = new KeyChord(ConsoleKey.Escape, ConsoleModifiers.None, '\u001b'); + + // act + var resolved = keyMap.TryResolve(escape, out var message); + + // assert + Assert.True(resolved); + Assert.IsType(message); + } + + [Fact] + public void CreateDefault_Should_NotResolvePromoteOrForget_When_TheyMatchTheRetiredSplitPaneBoard() + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + var p = new KeyChord(ConsoleKey.P, ConsoleModifiers.None, 'p'); + var d = new KeyChord(ConsoleKey.D, ConsoleModifiers.None, 'd'); + + // act + var pResolved = keyMap.TryResolve(p, out _); + var dResolved = keyMap.TryResolve(d, out _); + + // assert + Assert.False(pResolved); + Assert.False(dResolved); + } + + [Fact] + public void CreateDefault_Should_ListHintsInBindingOrder_When_KeyMapIsBuilt() + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + + // act + var keys = keyMap.Hints.Select(h => h.Key).ToList(); + + // assert + Assert.Equal(["hjkl", "enter", "f", "/", "y", "r", "esc", "q"], keys); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryModeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryModeTests.cs index 527d1ca2997..9563aacd0a0 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryModeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryModeTests.cs @@ -10,7 +10,7 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Memory; /// -/// Exercises and its overlays against a real . +/// Exercises against a real . /// public sealed class MemoryModeTests : MemoryTestBase { @@ -36,12 +36,19 @@ private static void Type(MemoryMode mode, string text) } } - private MemoryMode CreateMode(Func? hasIdentity = null) - => new(_store, TimeProvider, hasIdentity ?? (static () => true)); + private MemoryMode CreateMode() => new(_store, TimeProvider); - private Task SaveAsync(string text = "Some text.", string type = "fact") + private static string RenderToText(MemoryMode mode, int width = 100, int height = 24) + { + var console = new TestConsole().Width(width); + console.Write(mode.Render(width, height)); + return console.Output; + } + + private Task SaveAsync( + string text = "Some text.", string type = "fact", IReadOnlyList? tags = null) => _store.SaveAsync( - new MemoryRecordCreation { Text = text, Type = type, Actor = "test-agent" }, + new MemoryRecordCreation { Text = text, Type = type, Tags = tags ?? [], Actor = "test-agent" }, TestContext.Current.CancellationToken); private Task LogAsync(string text = "Journal note.") @@ -50,19 +57,105 @@ private Task LogAsync(string text = "Journal note.") TestContext.Current.CancellationToken); [Fact] - public async Task OnEnter_Should_LoadCuratedMemories() + public void Render_Should_ShowTheEmptyStateMessage_When_NoMemoryExists() + { + // arrange + var mode = CreateMode(); + mode.OnEnter(); + + // act + var text = RenderToText(mode); + + // assert + Assert.Contains("No memory yet.", text, StringComparison.Ordinal); + } + + [Fact] + public void Render_Should_ShowTheLoadError_When_TheStoreRejectsTheRead() + { + // arrange + // a store over a directory that has no agent workspace + var noWorkspaceDirectory = Path.Combine(Path.GetDirectoryName(WorkingDirectory)!, "no-workspace"); + Directory.CreateDirectory(noWorkspaceDirectory); + var storeWithNoWorkspace = new MemoryStore(new TestFileSystem(noWorkspaceDirectory), TimeProvider, new AgentDatabase()); + var mode = new MemoryMode(storeWithNoWorkspace, TimeProvider); + mode.OnEnter(); + + // act + var text = RenderToText(mode); + + // assert + Assert.Contains("No agent workspace found", text, StringComparison.Ordinal); + } + + [Fact] + public async Task Render_Should_ShowTheRowCount_When_HeaderIsRendered() { // arrange await SaveAsync("First."); + await LogAsync("Note one."); var mode = CreateMode(); + mode.OnEnter(); // act + var text = RenderToText(mode); + + // assert + Assert.Contains("Memory (2)", text, StringComparison.Ordinal); + } + + [Fact] + public async Task Render_Should_OrderRowsByTimeDescending_When_CuratedAndJournalRowsExist() + { + // arrange + await SaveAsync("Oldest curated.", type: "alpha"); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + await LogAsync("Middle journal."); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + await SaveAsync("Newest curated.", type: "omega"); + var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.RefreshRequested()); + + // act + var text = RenderToText(mode); + + // assert + var newestIndex = text.IndexOf("omega", StringComparison.Ordinal); + var middleIndex = text.IndexOf("journal", StringComparison.Ordinal); + var oldestIndex = text.IndexOf("alpha", StringComparison.Ordinal); + Assert.True(newestIndex >= 0 && middleIndex > newestIndex && oldestIndex > middleIndex); + } + + [Fact] + public async Task Render_Should_ShowHeaderRuleAndRows_When_TwoCuratedAndOneJournalRowsArePresent() + { + // arrange + await SaveAsync("Ops runbook.", type: "fact", tags: ["ops"]); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + await SaveAsync("Deploy notes.", type: "decision"); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + await LogAsync("Follow up needed."); + var mode = CreateMode(); + mode.OnEnter(); + var console = new TestConsole().Width(100); + + // act + console.Write(mode.Render(100, 9)); // assert - Assert.Single(mode.State.CuratedRecords); - Assert.Equal(MemoryCollectionFilter.Curated, mode.State.Collection); + console.Output.MatchInlineSnapshot( + """ + โ•ญโ”€Memory (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ โ”‚ + โ”‚ KIND TYPE TAGS AGE โ”‚ + โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ + โ”‚ > journal - - just now โ”‚ + โ”‚ curated decision - 1m ago โ”‚ + โ”‚ curated fact ops 2m ago โ”‚ + โ”‚ โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + + """); } [Fact] @@ -77,407 +170,387 @@ public async Task MoveSelection_Should_ClampAtLastRow_When_MovingDownPastEnd() // act mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Down)); // assert Assert.Equal(1, mode.State.SelectedRow); } [Fact] - public void MoveCursor_Should_TogglePaneFocus_When_Left() + public async Task MoveSelectionToEdge_Should_SelectLastRow_When_Bottom() { // arrange + await SaveAsync("First."); + await SaveAsync("Second."); + await SaveAsync("Third."); var mode = CreateMode(); mode.OnEnter(); - Assert.Equal(MemoryFocus.List, mode.State.Focus); // act - mode.Handle(new TuiMessage.MoveCursor(CursorDirection.Left)); + mode.Handle(new TuiMessage.MoveToEdge(EdgeTarget.Bottom)); // assert - Assert.Equal(MemoryFocus.Detail, mode.State.Focus); + Assert.Equal(2, mode.State.SelectedRow); } [Fact] - public async Task CycleView_Should_SwitchToTheJournalCollection() + public async Task OpenSelected_Should_BeANoOp_When_ARowIsSelected() { // arrange - await LogAsync("Note one."); + await SaveAsync("First."); var mode = CreateMode(); mode.OnEnter(); // act - mode.Handle(new TuiMessage.CycleView(1)); + var followUp = mode.Handle(new TuiMessage.OpenSelected()); // assert - Assert.Equal(MemoryCollectionFilter.Journal, mode.State.Collection); - Assert.Single(mode.State.JournalEntries); + Assert.Empty(followUp); + Assert.Equal(0, mode.State.SelectedRow); } [Fact] - public async Task RefreshRequested_Should_ReloadMemories() + public void OpenSelected_Should_ReturnAWarning_When_NoRowIsSelected() { // arrange var mode = CreateMode(); mode.OnEnter(); - Assert.Empty(mode.State.CuratedRecords); // act - await SaveAsync("New memory."); - mode.Handle(new TuiMessage.RefreshRequested()); + var followUp = mode.Handle(new TuiMessage.OpenSelected()); // assert - Assert.Single(mode.State.CuratedRecords); + var toast = Assert.Single(followUp); + var shown = Assert.IsType(toast); + Assert.Equal(ToastStyle.Warn, shown.Style); } [Fact] - public async Task CopySelectedId_Should_ShowInfoToast_When_ItemSelected() + public void TryCreatePopover_Should_ReturnNull_When_NoRowIsSelected() { // arrange - var saved = await SaveAsync("First."); var mode = CreateMode(); mode.OnEnter(); // act - var followUp = mode.Handle(new TuiMessage.CopySelectedId()); + var popover = mode.TryCreatePopover(); // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(saved.Id, shown.Text); - Assert.Equal(ToastStyle.Info, shown.Style); + Assert.Null(popover); } [Fact] - public void CopySelectedId_Should_ShowWarningToast_When_NoItemSelected() + public async Task TryCreatePopover_Should_ReturnAPopoverForTheSelectedRow_When_ARowIsSelected() { // arrange + var saved = await SaveAsync("First."); var mode = CreateMode(); mode.OnEnter(); // act - var followUp = mode.Handle(new TuiMessage.CopySelectedId()); + var popover = mode.TryCreatePopover(); + popover?.Load(TestContext.Current.CancellationToken); + var console = new TestConsole().Width(100); + console.Write(popover!.Render(100, 30)); // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); + Assert.NotNull(popover); + Assert.Contains(saved.Id, console.Output); } [Fact] - public async Task ForgetRequested_Should_RefuseWithoutDeleting_When_IdentityIsUnavailable() + public async Task HandleKey_Should_MoveTheModeSelectionToTheNextRow_When_DownArrowIsPressedOnThePopover() { // arrange - var saved = await SaveAsync("First."); - var mode = new MemoryMode(_store, TimeProvider); + // rows sort by time descending, so "Second." lands at row 0 and "First." at row 1 + var first = await SaveAsync("First."); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + await SaveAsync("Second."); + var mode = CreateMode(); mode.OnEnter(); + var popover = mode.TryCreatePopover(); + popover!.Load(TestContext.Current.CancellationToken); // act - var followUp = mode.Handle(new TuiMessage.ForgetRequested()); + popover.HandleKey(Key(ConsoleKey.DownArrow)); + var console = new TestConsole().Width(100); + console.Write(popover.Render(100, 30)); // assert - var shown = Assert.IsType(Assert.Single(followUp)); - Assert.Equal((BoardIdentity.NoIdentityMessage, ToastStyle.Warn), (shown.Text, shown.Style)); - Assert.False(mode.IsInputCapturing); - Assert.NotNull(await _store.FindAsync(saved.Id, TestContext.Current.CancellationToken)); + Assert.Equal(1, mode.State.SelectedRow); + Assert.Contains(first.Id, console.Output); } [Fact] - public async Task ForgetConfirmation_Should_RefuseWithoutDeleting_When_IdentityIsRemoved() + public async Task HandleKey_Should_LeaveTheModeSelectionUnchanged_When_UpArrowIsPressedOnThePopoverAtTheFirstRow() { // arrange - var saved = await SaveAsync("First."); - var hasIdentity = true; - var mode = CreateMode(() => hasIdentity); + await SaveAsync("First."); + var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.ForgetRequested()); - hasIdentity = false; + var popover = mode.TryCreatePopover(); + popover!.Load(TestContext.Current.CancellationToken); // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); + var result = popover.HandleKey(Key(ConsoleKey.UpArrow)); // assert - var shown = Assert.IsType(Assert.Single(followUp)); - Assert.Equal((BoardIdentity.NoIdentityMessage, ToastStyle.Warn), (shown.Text, shown.Style)); - Assert.True(mode.IsInputCapturing); - Assert.NotNull(await _store.FindAsync(saved.Id, TestContext.Current.CancellationToken)); + Assert.Null(result); + Assert.Equal(0, mode.State.SelectedRow); } [Fact] - public async Task ForgetRequested_Should_OpenConfirmation_When_IdentityIsAvailable() + public async Task HandleKey_Should_LeaveTheModeSelectionOnTheRowReached_When_EscapeIsPressedOnThePopoverAfterMovingDown() { // arrange - var saved = await SaveAsync("First."); - var mode = CreateMode(static () => true); + await SaveAsync("First."); + TimeProvider.Advance(TimeSpan.FromMinutes(1)); + await SaveAsync("Second."); + var mode = CreateMode(); mode.OnEnter(); + var popover = mode.TryCreatePopover(); + popover!.Load(TestContext.Current.CancellationToken); + popover.HandleKey(Key(ConsoleKey.DownArrow)); // act - var followUp = mode.Handle(new TuiMessage.ForgetRequested()); + var result = popover.HandleKey(Key(ConsoleKey.Escape)); // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); - var stillThere = await _store.FindAsync(saved.Id, TestContext.Current.CancellationToken); - Assert.NotNull(stillThere); + Assert.IsType(result); + Assert.Equal(1, mode.State.SelectedRow); } [Fact] - public void ForgetRequested_Should_ShowWarnToast_When_NoCuratedMemorySelected() + public void HandlePopoverRequest_Should_ReturnACopyToast_When_TheEntryPopoverRequestsACopy() { // arrange var mode = CreateMode(); - mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); + var request = new PopoverResult.Request(new MemoryEntryPopoverRequest.CopyRequested("mem-1")); // act - var followUp = mode.Handle(new TuiMessage.ForgetRequested()); + var followUp = mode.HandlePopoverRequest(request); // assert var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); + var shown = Assert.IsType(toast); + Assert.Equal(("mem-1", ToastStyle.Info), (shown.Text, shown.Style)); } [Fact] - public async Task ForgetConfirmation_Confirmed_Should_DeleteMemory_And_RemoveItFromTheList() + public async Task CopySelectedId_Should_ReturnTheRowId_When_ARowIsSelected() { // arrange var saved = await SaveAsync("First."); var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.ForgetRequested()); // act - // Confirm with the reason field empty. - var followUp = mode.HandleRawKey(Key(ConsoleKey.Enter)); + var followUp = mode.Handle(new TuiMessage.CopySelectedId()); // assert var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Success, Assert.IsType(toast).Style); - Assert.False(mode.IsInputCapturing); - Assert.Empty(mode.State.CuratedRecords); - var deleted = await _store.FindAsync(saved.Id, TestContext.Current.CancellationToken); - Assert.Null(deleted); + var shown = Assert.IsType(toast); + Assert.Equal(saved.Id, shown.Text); } [Fact] - public async Task ForgetConfirmation_Cancelled_Should_LeaveTheMemoryUntouched() + public void CopySelectedId_Should_ReturnAWarning_When_NoRowIsSelected() { // arrange - var saved = await SaveAsync("First."); var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.ForgetRequested()); // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); + var followUp = mode.Handle(new TuiMessage.CopySelectedId()); // assert - Assert.Empty(followUp); - Assert.False(mode.IsInputCapturing); - Assert.Single(mode.State.CuratedRecords); - var stillThere = await _store.FindAsync(saved.Id, TestContext.Current.CancellationToken); - Assert.NotNull(stillThere); + var toast = Assert.Single(followUp); + var shown = Assert.IsType(toast); + Assert.Equal(ToastStyle.Warn, shown.Style); } [Fact] - public void PromoteRequested_Should_ShowWarnToast_When_NoJournalEntrySelected() + public async Task RefreshRequested_Should_ReloadRowsFromTheStore_When_ANewMemoryWasAdded() { // arrange var mode = CreateMode(); mode.OnEnter(); + Assert.Empty(mode.State.Rows); + await SaveAsync("New memory."); // act - var followUp = mode.Handle(new TuiMessage.PromoteRequested()); + mode.Handle(new TuiMessage.RefreshRequested()); // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Warn, Assert.IsType(toast).Style); + Assert.Single(mode.State.Rows); } [Fact] - public async Task PromoteRequested_Should_RefuseWithoutOpening_When_IdentityIsUnavailable() + public async Task CycleView_Should_NarrowToCuratedOnly_When_PressedOnceFromAll() { // arrange + await SaveAsync("First."); await LogAsync("Note one."); - var mode = new MemoryMode(_store, TimeProvider); + var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); // act - var followUp = mode.Handle(new TuiMessage.PromoteRequested()); + mode.Handle(new TuiMessage.CycleView(1)); // assert - var shown = Assert.IsType(Assert.Single(followUp)); - Assert.Equal((BoardIdentity.NoIdentityMessage, ToastStyle.Warn), (shown.Text, shown.Style)); - Assert.False(mode.IsInputCapturing); - Assert.Empty(mode.State.CuratedRecords); + Assert.Equal(MemoryCollectionFilter.Curated, mode.State.Filter); + var row = Assert.Single(mode.State.Rows); + Assert.Equal(MemoryCollectionFilter.Curated, row.Kind); } [Fact] - public async Task PromoteSubmission_Should_RefuseWithoutWriting_When_IdentityIsRemoved() + public async Task CycleView_Should_NarrowToJournalOnly_When_PressedTwiceFromAll() { // arrange - var entry = await LogAsync("Note one."); - var hasIdentity = true; - var mode = CreateMode(() => hasIdentity); + await SaveAsync("First."); + await LogAsync("Note one."); + var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); - mode.Handle(new TuiMessage.PromoteRequested()); - Type(mode, "decision"); - hasIdentity = false; // act - var followUp = mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + mode.Handle(new TuiMessage.CycleView(1)); + mode.Handle(new TuiMessage.CycleView(1)); // assert - var shown = Assert.IsType(Assert.Single(followUp)); - Assert.Equal((BoardIdentity.NoIdentityMessage, ToastStyle.Warn), (shown.Text, shown.Style)); - Assert.True(mode.IsInputCapturing); - Assert.Null(await _store.FindAsync(MemoryPromotedId.Derive(entry.Id), TestContext.Current.CancellationToken)); + Assert.Equal(MemoryCollectionFilter.Journal, mode.State.Filter); + var row = Assert.Single(mode.State.Rows); + Assert.Equal(MemoryCollectionFilter.Journal, row.Kind); } [Fact] - public async Task PromoteRequested_Should_OpenForm_When_IdentityIsAvailable() + public async Task CycleView_Should_ReturnToAll_When_PressedThreeTimes() { // arrange + await SaveAsync("First."); await LogAsync("Note one."); - var mode = CreateMode(static () => true); + var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); // act - var followUp = mode.Handle(new TuiMessage.PromoteRequested()); + mode.Handle(new TuiMessage.CycleView(1)); + mode.Handle(new TuiMessage.CycleView(1)); + mode.Handle(new TuiMessage.CycleView(1)); // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); + Assert.Equal(MemoryCollectionFilter.All, mode.State.Filter); + Assert.Equal(2, mode.State.Rows.Count); } [Fact] - public async Task PromoteForm_Submit_Should_PromoteJournalEntry_And_ShowSuccessToast() + public async Task SearchRequested_Should_OpenTheSearchForm_When_Requested() { // arrange - var entry = await LogAsync("Note one."); + await SaveAsync("First."); var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); - mode.Handle(new TuiMessage.PromoteRequested()); - Type(mode, "decision"); // act - var followUp = mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + var followUp = mode.Handle(new TuiMessage.SearchRequested()); // assert - var toast = Assert.Single(followUp); - Assert.Equal(ToastStyle.Success, Assert.IsType(toast).Style); - Assert.False(mode.IsInputCapturing); - - var curatedId = MemoryPromotedId.Derive(entry.Id); - var promoted = await _store.FindAsync(curatedId, TestContext.Current.CancellationToken); - Assert.NotNull(promoted); - Assert.Equal("decision", promoted!.Type); + Assert.Empty(followUp); + Assert.True(mode.IsInputCapturing); } [Fact] - public async Task PromoteForm_Submit_Should_ReportAlreadyPromoted_When_TheJournalEntryWasPromotedBefore() + public async Task SearchForm_Apply_Should_NarrowRowsByTag_When_TagTermIsUsed() { // arrange - // Promote the journal entry before opening the tab. - var entry = await LogAsync("Note one."); - await _store.PromoteAsync(entry.Id, "fact", [], TestContext.Current.CancellationToken); - + await SaveAsync("Deploy checklist."); + await SaveAsync("Ops note.", tags: ["ops"]); var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); - mode.Handle(new TuiMessage.PromoteRequested()); - Type(mode, "decision"); + mode.Handle(new TuiMessage.SearchRequested()); + Type(mode, "tag:ops"); // act - var followUp = mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + mode.HandleRawKey(CtrlKey(ConsoleKey.S)); // assert - var toast = Assert.Single(followUp); - var shown = Assert.IsType(toast); - Assert.Equal(ToastStyle.Success, shown.Style); - Assert.Contains("already promoted", shown.Text, StringComparison.OrdinalIgnoreCase); + Assert.False(mode.IsInputCapturing); + var row = Assert.Single(mode.State.Rows); + Assert.Equal("Ops note.", row.Body); } [Fact] - public async Task PromoteForm_Cancel_Should_CloseImmediately_When_NotDirty() + public async Task SearchForm_Apply_Should_NarrowCuratedAndJournalRows_When_FreeTextIsUsed() { // arrange - await LogAsync("Note."); + await SaveAsync("Deploy checklist for staging."); + await LogAsync("Deploy failed overnight."); + await LogAsync("Unrelated note."); var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); - mode.Handle(new TuiMessage.PromoteRequested()); + mode.Handle(new TuiMessage.SearchRequested()); + Type(mode, "deploy"); // act - var followUp = mode.HandleRawKey(Key(ConsoleKey.Escape)); + mode.HandleRawKey(CtrlKey(ConsoleKey.S)); // assert - Assert.Empty(followUp); Assert.False(mode.IsInputCapturing); + Assert.Equal(2, mode.State.Rows.Count); } [Fact] - public async Task SearchRequested_Should_OpenSearchForm() + public async Task SearchForm_Cancel_Should_LeaveRowsUnfiltered_When_FormIsCancelled() { // arrange await SaveAsync("First."); + await SaveAsync("Second."); var mode = CreateMode(); mode.OnEnter(); + mode.Handle(new TuiMessage.SearchRequested()); + Type(mode, "no-match"); // act - var followUp = mode.Handle(new TuiMessage.SearchRequested()); + mode.HandleRawKey(Key(ConsoleKey.Escape)); // assert - Assert.Empty(followUp); - Assert.True(mode.IsInputCapturing); + Assert.False(mode.IsInputCapturing); + Assert.Equal(2, mode.State.Rows.Count); } [Fact] - public async Task SearchForm_Apply_Should_NarrowTheListByTag() + public async Task Render_Should_ShowFilteredSuffix_When_SearchTextIsSet() { // arrange await SaveAsync("Deploy checklist."); - await _store.SaveAsync( - new MemoryRecordCreation { Text = "Ops note.", Type = "fact", Tags = ["ops"], Actor = "test-agent" }, - TestContext.Current.CancellationToken); var mode = CreateMode(); mode.OnEnter(); mode.Handle(new TuiMessage.SearchRequested()); - Assert.Equal(2, mode.State.CuratedRecords.Count); - Type(mode, "tag:ops"); + Type(mode, "deploy"); + mode.HandleRawKey(CtrlKey(ConsoleKey.S)); // act - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + var text = RenderToText(mode); // assert - Assert.False(mode.IsInputCapturing); - var record = Assert.Single(mode.State.CuratedRecords); - Assert.Contains("ops", record.Tags); + Assert.Contains("Memory (1) (filtered)", text, StringComparison.Ordinal); } [Fact] - public async Task SearchForm_Apply_Should_ShowTypeTagIgnoredMarker_When_JournalCollectionSearchedWithType() + public async Task Render_Should_DropTypeColumn_When_WidthIsTooNarrowForEveryColumn() { // arrange - // Apply a type qualifier while viewing the journal. - await LogAsync("Note one."); + await SaveAsync("Deploy checklist.", tags: ["ops"]); var mode = CreateMode(); mode.OnEnter(); - mode.Handle(new TuiMessage.CycleView(1)); - mode.Handle(new TuiMessage.SearchRequested()); - Type(mode, "type:decision"); - mode.HandleRawKey(CtrlKey(ConsoleKey.S)); + var wide = RenderToText(mode, width: 100); // act - var console = new TestConsole().Width(100); - console.Write(mode.Render(100, 24)); - var text = console.Output; + var narrow = RenderToText(mode, width: 35); + var actual = ( + WideHasType: wide.Contains("fact", StringComparison.Ordinal), + NarrowHasType: narrow.Contains("fact", StringComparison.Ordinal), + NarrowHasKind: narrow.Contains("curated", StringComparison.Ordinal)); // assert - Assert.Contains("(type/tag ignored)", text); + Assert.Equal((true, false, true), actual); } [Fact] diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryRowBadgeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryRowBadgeTests.cs index c2f7cca18ac..c46c4918f65 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryRowBadgeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Memory/MemoryRowBadgeTests.cs @@ -1,4 +1,3 @@ -using ChilliCream.Nitro.CommandLine.Services.Memory; using ChilliCream.Nitro.CommandLine.Tui.Memory; using Spectre.Console; @@ -6,81 +5,244 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Memory; public sealed class MemoryRowBadgeTests { + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private static MemoryRow CuratedRow( + string id = "m-1", + string type = "fact", + IReadOnlyList? tags = null, + string body = "Body.", + DateTimeOffset? time = null) + => new(MemoryCollectionFilter.Curated, id, type, tags ?? [], body, time ?? s_now); + + private static MemoryRow JournalRow( + string id = "j-1", string body = "Body.", DateTimeOffset? time = null) + => new(MemoryCollectionFilter.Journal, id, Type: null, Tags: [], body, time ?? s_now); + + /// + /// The Tags column's width for a single-row : whatever + /// leaves after the prefix, Kind, Type, Age, and their gutters. + /// + private static int TagsWidth(MemoryRowBadge.Widths widths, int maxWidth) + => maxWidth - 3 - (widths.Kind + widths.Type + widths.Age + 3 * 4); + + [Fact] + public void Render_Should_ReturnEmpty_When_MaxWidthIsZero() + { + // arrange + var row = CuratedRow(); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + + // act + var line = MemoryRowBadge.Render(row, s_now, selected: false, maxWidth: 0, widths); + + // assert + Assert.Empty(line); + } + + [Fact] + public void Render_Should_ShowEveryColumn_When_MaxWidthFits() + { + // arrange + const int maxWidth = 80; + var row = CuratedRow(type: "fact", tags: ["ops"]); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + var expected = " " + + "curated".PadRight(widths.Kind) + + " " + "fact".PadRight(widths.Type) + + " " + "ops".PadRight(TagsWidth(widths, maxWidth)) + + " " + "just now".PadRight(widths.Age); + Assert.Equal(expected, line); + } + + [Fact] + public void Render_Should_ShowDashForTypeAndKindJournal_When_RowIsJournal() + { + // arrange + const int maxWidth = 80; + var row = JournalRow(); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + var expected = " " + + "journal".PadRight(widths.Kind) + + " " + "-".PadRight(widths.Type) + + " " + "-".PadRight(TagsWidth(widths, maxWidth)) + + " " + "just now".PadRight(widths.Age); + Assert.Equal(expected, line); + } + + [Fact] + public void Render_Should_ShowDashForTags_When_TagsIsEmpty() + { + // arrange + const int maxWidth = 80; + var row = CuratedRow(tags: []); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + + // assert + var expected = " " + + "curated".PadRight(widths.Kind) + + " " + "fact".PadRight(widths.Type) + + " " + "-".PadRight(TagsWidth(widths, maxWidth)) + + " " + "just now".PadRight(widths.Age); + Assert.Equal(expected, line); + } + + [Theory] + [InlineData(0, "just now")] + [InlineData(90, "1m ago")] + public void Render_Should_FormatAge_When_AgeIsFreshOrMinutesOld(int elapsedSeconds, string expectedAge) + { + // arrange + var row = CuratedRow(time: s_now.AddSeconds(-elapsedSeconds)); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth: 80, widths)); + + // assert + Assert.Contains(expectedAge, line, StringComparison.Ordinal); + } + + [Fact] + public void Render_Should_FormatAgeAsBareDate_When_RowIsAtLeastAWeekOld() + { + // arrange + var time = s_now.AddDays(-8); + var row = CuratedRow(time: time); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + + // act + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth: 80, widths)); + + // assert + Assert.Contains(time.ToUniversalTime().ToString("yyyy-MM-dd"), line, StringComparison.Ordinal); + } + [Fact] - public void Render_Should_FitDisplayWidth_When_TagsContainCjkAndEmoji() + public void Render_Should_DropTypeColumn_When_WidthIsTooNarrowForEveryColumn() { // arrange - const int maxWidth = 13; - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var record = CreateRecord(type: "fact", tags: ["๐Ÿ˜€ๆผข"]); - var widths = MemoryRowBadge.ComputeWidths([record], now); + var row = CuratedRow(tags: ["ops"]); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + var wide = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth: 80, widths)); + var narrowMaxWidth = widths.Kind + 3 + widths.Age + 4; // act - var line = MemoryRowBadge.Render(record, now, selected: false, maxWidth, widths); - var plainText = Markup.Remove(line); + var narrow = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + WideHasType: wide.Contains("fact", StringComparison.Ordinal), + NarrowHasType: narrow.Contains("fact", StringComparison.Ordinal), + NarrowHasKind: narrow.Contains("curated", StringComparison.Ordinal), + NarrowHasAge: narrow.Contains("just now", StringComparison.Ordinal)); // assert - Assert.Equal(" fact โ€ฆ now", plainText); - Assert.True(plainText.GetCellWidth() <= maxWidth); + Assert.Equal((true, false, true, true), actual); } [Fact] - public void Render_Should_FitFixedColumns_When_MaxWidthMatchesTheirDisplayWidth() + public void Render_Should_DropAgeColumn_When_WidthIsTooNarrowForTypeAndAge() { // arrange - const int maxWidth = 11; - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var record = CreateRecord(type: "ๆผข๐Ÿ˜€", tags: ["tag"]); - var widths = MemoryRowBadge.ComputeWidths([record], now); + var row = CuratedRow(tags: ["ops"]); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + var narrowMaxWidth = widths.Kind + 3; // act - var line = MemoryRowBadge.Render(record, now, selected: false, maxWidth, widths); - var plainText = Markup.Remove(line); + var narrow = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + HasKind: narrow.Contains("curated", StringComparison.Ordinal), + HasType: narrow.Contains("fact", StringComparison.Ordinal), + HasAge: narrow.Contains("just now", StringComparison.Ordinal)); // assert - Assert.Equal(" ๆผข๐Ÿ˜€ now", plainText); - Assert.Equal(maxWidth, plainText.GetCellWidth()); + Assert.Equal((true, false, false), actual); } [Fact] - public void Render_Should_FitWithinOneColumn_When_Selected() + public void Render_Should_TruncateTags_When_WidthLeavesNoRoomForTheFullList() { // arrange - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var record = CreateRecord(type: "๐Ÿ˜€", tags: ["ๆผข"]); - var widths = MemoryRowBadge.ComputeWidths([record], now); + var row = CuratedRow(tags: ["deploy", "staging", "rollback", "database"]); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + var narrowMaxWidth = widths.Kind + 3 + widths.Type + 4 + widths.Age + 4 + 10; // act - var line = MemoryRowBadge.Render(record, now, selected: true, maxWidth: 1, widths); - var plainText = Markup.Remove(line); + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, narrowMaxWidth, widths)); // assert - Assert.Equal(">", plainText); + Assert.Contains('โ€ฆ', line); } [Fact] - public void Render_Should_PreserveNormalOutput_When_ItFits() + public void RenderHeader_Should_AlignColumnsWithRow_When_WidthIsWide() { // arrange - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); - var record = CreateRecord(type: "fact", tags: ["ops"]); - var widths = MemoryRowBadge.ComputeWidths([record], now); + const int maxWidth = 80; + var row = CuratedRow(); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); // act - var line = MemoryRowBadge.Render(record, now, selected: false, maxWidth: 80, widths); + var header = Markup.Remove(MemoryRowBadge.RenderHeader(maxWidth, widths)); + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, maxWidth, widths)); + var kindOffset = header.IndexOf("KIND", StringComparison.Ordinal); + var typeOffset = header.IndexOf("TYPE", StringComparison.Ordinal); // assert - Assert.Equal(" fact ops now", Markup.Remove(line)); + Assert.Equal("curated", line.Substring(kindOffset, 7)); + Assert.Equal("fact", line.Substring(typeOffset, 4)); } - private static MemoryRecord CreateRecord(string type, IReadOnlyList tags) => new() + [Fact] + public void RenderHeader_Should_DropTheSameColumnAsRow_When_WidthIsNarrow() { - Id = "m-1", - Type = type, - Tags = tags, - Body = "Body.", - CreatedAt = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), - UpdatedAt = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), - CreatedBy = "test-agent" - }; + // arrange + var row = CuratedRow(tags: ["ops"]); + var widths = MemoryRowBadge.ComputeWidths([row], s_now); + var narrowMaxWidth = widths.Kind + 3 + widths.Age + 4; + + // act + var header = Markup.Remove(MemoryRowBadge.RenderHeader(narrowMaxWidth, widths)); + var line = Markup.Remove(MemoryRowBadge.Render(row, s_now, selected: false, narrowMaxWidth, widths)); + var actual = ( + HeaderHasType: header.Contains("TYPE", StringComparison.Ordinal), + RowHasType: line.Contains("fact", StringComparison.Ordinal), + HeaderHasAge: header.Contains("AGE", StringComparison.Ordinal), + RowHasAge: line.Contains("just now", StringComparison.Ordinal)); + + // assert + Assert.Equal((false, false, true, true), actual); + } + + [Fact] + public void RenderRule_Should_ReturnEmpty_When_MaxWidthIsZero() + { + // act + var rule = MemoryRowBadge.RenderRule(0); + + // assert + Assert.Empty(rule); + } + + [Fact] + public void RenderRule_Should_FillTheGivenWidth_When_WidthIsPositive() + { + // act + var rule = Markup.Remove(MemoryRowBadge.RenderRule(20)); + + // assert + Assert.Equal(new string('โ”€', 20), rule); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Search/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Search/FakeTaskStore.cs index 1df42956e07..3573c2a8f42 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Search/FakeTaskStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Search/FakeTaskStore.cs @@ -116,6 +116,10 @@ public Task>> ComputeBlockedAs public Task GetTaskAsync(string id, CancellationToken cancellationToken) => Task.FromResult(Tasks.FirstOrDefault(t => t.Id == id)); + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task GetRequiredTaskAsync(string id, CancellationToken cancellationToken) => throw new NotSupportedException(); @@ -189,6 +193,9 @@ public Task UndeferTaskAsync(string id, string actor, CancellationToke public Task DeleteTaskAsync(string id, string reason, string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task ReleaseAssigneeAsync(string agent, string reason, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task> CloseEligibleEpicsAsync(string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/FakeTaskStore.cs index 10a1ed828c5..03101fc88dc 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/FakeTaskStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/FakeTaskStore.cs @@ -39,6 +39,12 @@ internal sealed class FakeTaskStore : ITaskStore public TaskCreationResult CreationResult { get; set; } = new() { Id = "a1" }; + /// + /// The rows returns, sliced to the requested + /// limit; empty by default. + /// + public IReadOnlyList ParticipationRows { get; set; } = []; + public Task> QueryTasksAsync(TaskFilter filter, CancellationToken cancellationToken) => Task.FromResult>([.. Tasks.Values]); @@ -48,6 +54,11 @@ public Task> GetDependencyEdgesAsync(CancellationT public Task GetTaskAsync(string id, CancellationToken cancellationToken) => Task.FromResult(Tasks.GetValueOrDefault(id)); + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => Task.FromResult>( + limit is { } max ? [.. ParticipationRows.Take(max)] : ParticipationRows); + public Task> GetLabelsAsync(string taskId, CancellationToken cancellationToken) => Task.FromResult>(Labels.GetValueOrDefault(taskId) ?? []); @@ -79,6 +90,9 @@ public Task DeleteTaskAsync(string id, string reason, string actor, Ca return Task.FromResult(task); } + public Task ReleaseAssigneeAsync(string agent, string reason, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task UpdateTaskAsync(string id, TaskUpdate update, CancellationToken cancellationToken) { UpdatedId = id; diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TabSwitchKeysTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TabSwitchKeysTests.cs index 1d93d523537..14d3f6b20b4 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TabSwitchKeysTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TabSwitchKeysTests.cs @@ -1,5 +1,6 @@ using ChilliCream.Nitro.CommandLine.Tui.Input; using ChilliCream.Nitro.CommandLine.Tui.Mail; +using ChilliCream.Nitro.CommandLine.Tui.Memory; using ChilliCream.Nitro.CommandLine.Tui.Shell; namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; @@ -118,6 +119,23 @@ public void Resolve_Should_NotCollide_WithTheMailKeyMap() Assert.False(nextBound); } + [Fact] + public void Resolve_Should_ReturnFalse_When_BracketChordsAreResolvedAgainstTheMemoryKeyMap() + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + var previous = new KeyChord(ConsoleKey.Oem4, ConsoleModifiers.None, '['); + var next = new KeyChord(ConsoleKey.Oem6, ConsoleModifiers.None, ']'); + + // act + var previousBound = keyMap.TryResolve(previous, out _); + var nextBound = keyMap.TryResolve(next, out _); + + // assert + Assert.False(previousBound); + Assert.False(nextBound); + } + private static TuiTab Tab(string title, char mnemonic) => new(title, mnemonic, new FakeTuiMode(), new KeyDispatcher(KeyMap.CreateDefaultGlobal())); @@ -210,4 +228,21 @@ public void ResolveMnemonic_Should_NotCollide_WithTheMailKeyMap(char mnemonic) // assert Assert.False(bound); } + + [Theory] + [InlineData('T')] + [InlineData('M')] + [InlineData('A')] + public void ResolveMnemonic_Should_ReturnFalse_When_ShiftMnemonicIsResolvedAgainstTheMemoryKeyMap(char mnemonic) + { + // arrange + var keyMap = MemoryKeyMap.CreateDefault(); + var chord = new KeyChord(ConsoleKey.A, ConsoleModifiers.Shift, mnemonic); + + // act + var bound = keyMap.TryResolve(chord, out _); + + // assert + Assert.False(bound); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellQuitGateTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellQuitGateTests.cs index c92b5f4b4cb..f797c2535d2 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellQuitGateTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellQuitGateTests.cs @@ -24,7 +24,13 @@ private static ConsoleKeyInfo KeyInfo(char keyChar, ConsoleKey key) => private static readonly TimeSpan s_shortDrainBound = TimeSpan.FromMilliseconds(200); private static TuiShell CreateShell(FakeTuiMode mode, params TuiQuitGate[] quitGates) => - new(new KeyDispatcher(KeyMap.CreateDefaultGlobal()), mode, 80, 24, quitGates: quitGates); + new( + new KeyDispatcher(KeyMap.CreateDefaultGlobal()), + mode, + 80, + 24, + agentStore: new Agents.FakeAgentStore(TimeProvider.System), + quitGates: quitGates); private static TuiShell CreateShell(FakeTuiMode mode, TimeSpan quitGateDrainBound, params TuiQuitGate[] quitGates) => new( @@ -32,6 +38,7 @@ private static TuiShell CreateShell(FakeTuiMode mode, TimeSpan quitGateDrainBoun mode, 80, 24, + agentStore: new Agents.FakeAgentStore(TimeProvider.System), quitGates: quitGates, quitGateDrainBound: quitGateDrainBound); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTabsTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTabsTests.cs index b2216569517..8a2f9a01a4e 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTabsTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTabsTests.cs @@ -1,13 +1,17 @@ +using ChilliCream.Nitro.CommandLine.Services.Memory; using ChilliCream.Nitro.CommandLine.Services.Tasks; using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Memory; using ChilliCream.Nitro.CommandLine.Tests.Tui.Mail; using ChilliCream.Nitro.CommandLine.Tui.Agents; using ChilliCream.Nitro.CommandLine.Tui.Board; using ChilliCream.Nitro.CommandLine.Tui.Input; using ChilliCream.Nitro.CommandLine.Tui.Mail; +using ChilliCream.Nitro.CommandLine.Tui.Memory; using ChilliCream.Nitro.CommandLine.Tui.Runtime; using ChilliCream.Nitro.CommandLine.Tui.Search; using ChilliCream.Nitro.CommandLine.Tui.Shell; +using Microsoft.Extensions.Time.Testing; using Spectre.Console.Testing; namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; @@ -22,6 +26,8 @@ namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; /// public sealed class TuiShellTabsTests { + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static ConsoleKeyInfo KeyInfo(char keyChar, ConsoleKey key, ConsoleModifiers modifiers = ConsoleModifiers.None) => new( keyChar, @@ -46,25 +52,60 @@ private static TuiTab CreateMailTab(string title, ITuiMode mode, char mnemonic = private static TuiTab CreateAgentsTab(string title, ITuiMode mode, char mnemonic = 'A') => new(title, mnemonic, mode, new KeyDispatcher(KeyMap.CreateDefaultGlobal())); - private static AgentRecord Agent(string name, string role = "") => new() + private static TuiTab CreateMemoryTab(string title, ITuiMode mode, char mnemonic = 'e') => + new(title, mnemonic, mode, new KeyDispatcher(MemoryKeyMap.CreateDefault())); + + private static void LoginAgent(Agents.FakeAgentStore store) + => store.LoginAsync(TestContext.Current.CancellationToken).GetAwaiter().GetResult(); + + /// + /// A real over a freshly initialized workspace in its own + /// temporary directory, returned in for the caller to delete. + /// + private static MemoryStore CreateMemoryStore(TimeProvider time, out DirectoryInfo root) { - Name = name, - Role = role, - Client = "", - Implicit = false, - RegisteredAt = DateTimeOffset.UnixEpoch, - LastSeenAt = DateTimeOffset.UnixEpoch - }; + root = Directory.CreateTempSubdirectory("nitro-shell-memory-tests"); + var workspaceDirectory = AgentWorkspace.GetDirectory(root.FullName); + Directory.CreateDirectory(workspaceDirectory); + + using var connection = new AgentDatabase() + .InitializeAsync(workspaceDirectory, CancellationToken.None) + .GetAwaiter() + .GetResult(); + + return new MemoryStore(new TestFileSystem(root.FullName), time, new AgentDatabase()); + } + + private static MemoryRecord SaveMemory(MemoryStore store, string text) => store.SaveAsync( + new MemoryRecordCreation { Text = text, Type = "fact", Actor = "test-agent" }, + TestContext.Current.CancellationToken).GetAwaiter().GetResult(); + + private static void LogMemory(MemoryStore store, string text) => store.LogAsync( + new MemoryJournalEntryCreation { Text = text, Actor = "test-agent" }, + TestContext.Current.CancellationToken).GetAwaiter().GetResult(); + + private static void UpdateMemoryBody(MemoryStore store, string id, string text) => store.UpdateAsync( + id, + new MemoryRecordUpdate { Text = text, TextGiven = true }, + TestContext.Current.CancellationToken).GetAwaiter().GetResult(); + + private static void ForgetMemory(MemoryStore store, string id) => store.ForgetAsync( + id, TestContext.Current.CancellationToken).GetAwaiter().GetResult(); [Fact] - public void Constructor_Should_CallOnEnter_OnEveryHostedTab_NotOnlyTheActiveOne() + public void Constructor_Should_CallOnEnter_When_EveryHostedTabIsConstructed() { // arrange var tab1Mode = new FakeTuiMode(); var tab2Mode = new FakeTuiMode(); + var time = new FakeTimeProvider(s_now); // act - _ = new TuiShell([CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], 80, 24); + _ = new TuiShell( + [CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // assert Assert.True(tab1Mode.EnterCalled); @@ -75,8 +116,12 @@ public void Constructor_Should_CallOnEnter_OnEveryHostedTab_NotOnlyTheActiveOne( public void Render_Should_ShowATabStrip_WithEveryTabsTitle_When_MoreThanOneTabIsHosted() { // arrange + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( - [CreateTasksTab("Tasks", new FakeTuiMode()), CreateMailTab("Mail", new FakeTuiMode())], 80, 24); + [CreateTasksTab("Tasks", new FakeTuiMode()), CreateMailTab("Mail", new FakeTuiMode())], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // act var text = RenderToText(shell); @@ -87,9 +132,10 @@ public void Render_Should_ShowATabStrip_WithEveryTabsTitle_When_MoreThanOneTabIs } [Fact] - public void Render_Should_BracketEachTabsMnemonic_InBothActiveAndInactiveState() + public void Render_Should_BracketEachTabsMnemonic_When_TabsAreActiveOrInactive() { // arrange + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [ CreateTasksTab("Tasks", new FakeTuiMode()), @@ -97,7 +143,8 @@ public void Render_Should_BracketEachTabsMnemonic_InBothActiveAndInactiveState() CreateAgentsTab("Agents", new FakeTuiMode()) ], 80, - 24); + 24, + agentStore: new Agents.FakeAgentStore(time)); // act var text = RenderToText(shell); @@ -115,6 +162,7 @@ public void Handle_Should_JumpToTheMnemonicsTab_When_ShiftPlusItsLetterIsPressed var tasksMode = new FakeTuiMode(); var mailMode = new FakeTuiMode(); var agentsMode = new FakeTuiMode(); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [ CreateTasksTab("Tasks", tasksMode), @@ -122,23 +170,27 @@ public void Handle_Should_JumpToTheMnemonicsTab_When_ShiftPlusItsLetterIsPressed CreateAgentsTab("Agents", agentsMode) ], 80, - 24); + 24, + agentStore: new Agents.FakeAgentStore(time)); - // act: Shift+A jumps straight from the (active) tasks tab to agents. + // act + // Shift+A jumps straight from the (active) tasks tab to agents. var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('A', ConsoleKey.A, ConsoleModifiers.Shift))); // assert Assert.True(dirty); Assert.Single(agentsMode.ResizeCalls); - // act: Shift+M jumps from agents straight to mail, skipping tasks. + // act + // Shift+M jumps from agents straight to mail, skipping tasks. shell.Handle(new TuiEvent.KeyEvent(KeyInfo('M', ConsoleKey.M, ConsoleModifiers.Shift))); // assert Assert.Single(mailMode.ResizeCalls); Assert.Empty(tasksMode.ResizeCalls); - // act: Shift+T jumps back to tasks. + // act + // Shift+T jumps back to tasks. shell.Handle(new TuiEvent.KeyEvent(KeyInfo('T', ConsoleKey.T, ConsoleModifiers.Shift))); // assert @@ -150,8 +202,12 @@ public void Handle_Should_DoNothing_When_ShiftPlusLetterMatchesTheAlreadyActiveT { // arrange var tasksMode = new FakeTuiMode(); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( - [CreateTasksTab("Tasks", tasksMode), CreateMailTab("Mail", new FakeTuiMode())], 80, 24); + [CreateTasksTab("Tasks", tasksMode), CreateMailTab("Mail", new FakeTuiMode())], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // act var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('T', ConsoleKey.T, ConsoleModifiers.Shift))); @@ -166,6 +222,7 @@ public void Handle_Should_StillReachTheModeKey_When_ItsLowercaseCounterpartIsNot { // arrange var tasksMode = new FakeTuiMode(); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [ CreateTasksTab("Tasks", tasksMode), @@ -173,7 +230,8 @@ public void Handle_Should_StillReachTheModeKey_When_ItsLowercaseCounterpartIsNot CreateAgentsTab("Agents", new FakeTuiMode()) ], 80, - 24); + 24, + agentStore: new Agents.FakeAgentStore(time)); // act shell.Handle(new TuiEvent.KeyEvent(KeyInfo('r', ConsoleKey.R))); @@ -187,7 +245,12 @@ public void Handle_Should_ReserveOneExtraRow_ForTheTabStrip_When_MultipleTabsHos { // arrange var mode = new FakeTuiMode(); - var shell = new TuiShell([CreateTasksTab("Tasks", mode), CreateMailTab("Mail", new FakeTuiMode())], 80, 24); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", mode), CreateMailTab("Mail", new FakeTuiMode())], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // act shell.Handle(new TuiEvent.ResizeEvent(100, 30)); @@ -197,12 +260,17 @@ public void Handle_Should_ReserveOneExtraRow_ForTheTabStrip_When_MultipleTabsHos } [Fact] - public void Handle_Should_RouteKeysOnlyToTheActiveTabsDispatcherAndMode() + public void Handle_Should_RouteKeysOnlyToTheActiveTabsDispatcherAndMode_When_AKeyIsPressed() { // arrange var tasksMode = new FakeTuiMode(); var mailMode = new FakeTuiMode(); - var shell = new TuiShell([CreateTasksTab("Tasks", tasksMode), CreateMailTab("Mail", mailMode)], 80, 24); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", tasksMode), CreateMailTab("Mail", mailMode)], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // act shell.Handle(new TuiEvent.KeyEvent(KeyInfo('r', ConsoleKey.R))); @@ -211,13 +279,14 @@ public void Handle_Should_RouteKeysOnlyToTheActiveTabsDispatcherAndMode() Assert.Contains(tasksMode.HandledMessages, m => m is TuiMessage.RefreshRequested); Assert.Empty(mailMode.HandledMessages); - // act: switch to the mail tab and press 'r' again. + // act + // Switch to the mail tab, where 'p' resolves through the Mail key map instead. shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); tasksMode.HandledMessages.Clear(); - shell.Handle(new TuiEvent.KeyEvent(KeyInfo('r', ConsoleKey.R))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('p', ConsoleKey.P))); // assert - Assert.Contains(mailMode.HandledMessages, m => m is TuiMessage.ReplyRequested); + Assert.Contains(mailMode.HandledMessages, m => m is TuiMessage.AgentFilterPickerRequested); Assert.Empty(tasksMode.HandledMessages); } @@ -227,15 +296,22 @@ public void Handle_Should_WrapAround_When_SwitchingPastTheLastOrFirstTab() // arrange var tab1Mode = new FakeTuiMode(); var tab2Mode = new FakeTuiMode(); - var shell = new TuiShell([CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], 80, 24); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); - // act: '[' from the first tab wraps to the last. + // act + // '[' from the first tab wraps to the last. shell.Handle(new TuiEvent.KeyEvent(KeyInfo('[', ConsoleKey.Oem4))); // assert Assert.Single(tab2Mode.ResizeCalls); - // act: ']' from the last tab wraps back to the first. + // act + // ']' from the last tab wraps back to the first. shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); // assert @@ -248,7 +324,12 @@ public void Handle_Should_SwitchTab_When_TheKeyCarriesNoConsoleKey() // arrange var tab1Mode = new FakeTuiMode(); var tab2Mode = new FakeTuiMode(); - var shell = new TuiShell([CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], 80, 24); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // act shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.None))); @@ -262,13 +343,20 @@ public void Constructor_Should_Throw_When_TasksTabIndexIsOutOfRange() { // arrange var tabs = new[] { CreateTasksTab("Tasks", new FakeTuiMode()), CreateMailTab("Mail", new FakeTuiMode()) }; + var time = new FakeTimeProvider(s_now); - // act & assert - Assert.Throws(() => new TuiShell(tabs, 80, 24, tasksTabIndex: 2)); + // act + // assert + Assert.Throws(() => new TuiShell( + tabs, + 80, + 24, + agentStore: new Agents.FakeAgentStore(time), + tasksTabIndex: 2)); } [Fact] - public void HandleDataChanged_Should_NotRouteAnInactiveTabsFollowUp_ToTheActiveTab() + public void HandleDataChanged_Should_NotRouteAnInactiveTabsFollowUpToTheActiveTab_When_DataChanges() { // arrange // The inactive mail mode returns a toast when refreshed. @@ -278,7 +366,12 @@ public void HandleDataChanged_Should_NotRouteAnInactiveTabsFollowUp_ToTheActiveT { HandleResult = message => message is TuiMessage.RefreshRequested ? [mailFollowUp] : [] }; - var shell = new TuiShell([CreateTasksTab("Tasks", tasksMode), CreateMailTab("Mail", mailMode)], 80, 24); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", tasksMode), CreateMailTab("Mail", mailMode)], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); tasksMode.HandledMessages.Clear(); mailMode.HandledMessages.Clear(); @@ -303,10 +396,12 @@ public void Handle_Should_NotSwitchTab_When_ATaskOverlayIsCapturingInput() }; var board = new BoardMode(new BoardDataLoader(store, TimeProvider.System), [view]); var otherMode = new FakeTuiMode(); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [CreateTasksTab("Tasks", board), CreateTasksTab("Other", otherMode, mnemonic: 'O')], 80, 24, + agentStore: new Agents.FakeAgentStore(time), tasksTabIndex: 0, store: store, actor: "tester"); @@ -324,7 +419,7 @@ public void Handle_Should_NotSwitchTab_When_ATaskOverlayIsCapturingInput() } [Fact] - public void Handle_Should_SwitchTab_Again_OnceTheOverlayThatBlockedItCloses() + public void Handle_Should_SwitchTab_When_TheOverlayThatBlockedItCloses() { // arrange var store = new FakeTaskStore(); @@ -336,16 +431,19 @@ public void Handle_Should_SwitchTab_Again_OnceTheOverlayThatBlockedItCloses() }; var board = new BoardMode(new BoardDataLoader(store, TimeProvider.System), [view]); var otherMode = new FakeTuiMode(); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [CreateTasksTab("Tasks", board), CreateTasksTab("Other", otherMode, mnemonic: 'O')], 80, 24, + agentStore: new Agents.FakeAgentStore(time), tasksTabIndex: 0, store: store, actor: "tester"); shell.Handle(new TuiEvent.KeyEvent(KeyInfo('e', ConsoleKey.E))); - // act: Escape closes the (non-dirty) editor, then ']' switches tabs. + // act + // Escape closes the (non-dirty) editor, then ']' switches tabs. shell.Handle(new TuiEvent.KeyEvent(KeyInfo('', ConsoleKey.Escape))); shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); @@ -359,7 +457,12 @@ public void Handle_Should_RefreshEveryTabsActiveMode_When_DataChangedEventFires( // arrange var tab1Mode = new FakeTuiMode(); var tab2Mode = new FakeTuiMode(); - var shell = new TuiShell([CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], 80, 24); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", tab1Mode), CreateMailTab("Mail", tab2Mode)], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); // act var dirty = shell.Handle(new TuiEvent.DataChangedEvent()); @@ -371,90 +474,560 @@ public void Handle_Should_RefreshEveryTabsActiveMode_When_DataChangedEventFires( } [Fact] - public void Render_Should_ShowTheMailTabsUnreadBadge_RefreshedOnDataChanged() + public void Render_Should_ShowTheMailTabsThreadCount_When_MailTabIsSelected() { // arrange var mailStore = new FakeMailStore(); mailStore.Messages.Add(MailMessageBuilder.Create("m1")); - var mailMode = new MailMode( - mailStore, - "actor", - new Agents.FakeAgentRegistry()); - var mailTab = new TuiTab( - () => mailMode.UnreadCount > 0 ? $"Mail ({mailMode.UnreadCount})" : "Mail", - mnemonic: 'M', - mailMode, - new KeyDispatcher(MailKeyMap.CreateDefault())); - var shell = new TuiShell([CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], 80, 24); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(new FakeTimeProvider(s_now))); + var mailTab = new TuiTab("Mail", mnemonic: 'M', mailMode, new KeyDispatcher(MailKeyMap.CreateDefault())); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); + + // act + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); // assert - Assert.Contains("[M]ail (1)", RenderToText(shell)); + Assert.Contains("Mail (1)", RenderToText(shell)); + } + + [Fact] + public void Render_Should_UpdateTheMailTabsThreadCount_When_DataChangedEventArrives() + { + // arrange + var mailStore = new FakeMailStore(); + mailStore.Messages.Add(MailMessageBuilder.Create("m1")); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(new FakeTimeProvider(s_now))); + var mailTab = new TuiTab("Mail", mnemonic: 'M', mailMode, new KeyDispatcher(MailKeyMap.CreateDefault())); + var time = new FakeTimeProvider(s_now); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); // act - mailStore.Messages.Add(MailMessageBuilder.Create("m2")); + mailStore.Messages.Add(MailMessageBuilder.Create("m2", threadId: "m2")); shell.Handle(new TuiEvent.DataChangedEvent()); // assert - Assert.Contains("[M]ail (2)", RenderToText(shell)); + Assert.Contains("Mail (2)", RenderToText(shell)); } [Fact] - public async Task HandleDataChanged_Should_ShowTheMailTabsSendOutcomeToast_When_TheTasksTabIsActive() + public void Handle_Should_NarrowMailTabToPickedAgent_When_AgentFilterPickerAppliedThroughTheShell() { // arrange - var testToken = TestContext.Current.CancellationToken; var mailStore = new FakeMailStore(); - var mailMode = new MailMode( - mailStore, - "alice", - new Agents.FakeAgentRegistry()); - var shell = new TuiShell([CreateTasksTab("Tasks", new FakeTuiMode()), CreateMailTab("Mail", mailMode)], 80, 24); - mailMode.Handle(new TuiMessage.SelectInboxRequested()); - mailMode.Handle(new TuiMessage.ComposeRequested()); - - foreach (var c in "bob") + var time = new FakeTimeProvider(s_now); + var agentStore = new Agents.FakeAgentStore(time); + LoginAgent(agentStore); + var agentName = agentStore.Rows[0].Name; + mailStore.Messages.Add(MailMessageBuilder.Create("m1", sender: agentName, threadId: "t-1")); + mailStore.Messages.Add(MailMessageBuilder.Create("m2", sender: "outsider", threadId: "t-2")); + var mailMode = new MailMode(mailStore, agentStore, time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 80, + 24, + agentStore: agentStore); + + // act + // Switch to the Mail tab, open the agent picker, move to the seeded agent, and apply it. + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('p', ConsoleKey.P))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\0', ConsoleKey.DownArrow))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + Assert.Contains($"Mail: {agentName} (1)", RenderToText(shell)); + } + + [Fact] + public void Handle_Should_NarrowMailTabRows_When_SearchSubmittedThroughTheShell() + { + // arrange + var mailStore = new FakeMailStore(); + mailStore.Messages.Add(MailMessageBuilder.Create( + "m1", sender: "alice", subject: "Status update", threadId: "t-1")); + mailStore.Messages.Add(MailMessageBuilder.Create( + "m2", sender: "bob", subject: "Lunch plans", threadId: "t-2")); + var time = new FakeTimeProvider(s_now); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(time), time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); + + // act + // Switch to the Mail tab, open search, type a subject fragment, and submit with the save chord. + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('/', ConsoleKey.Oem2))); + + foreach (var c in "status") { - mailMode.HandleRawKey(KeyInfo(c, ConsoleKey.NoName)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(c, ConsoleKey.NoName))); } - mailMode.HandleRawKey(KeyInfo('\0', ConsoleKey.Tab)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('s', ConsoleKey.S, ConsoleModifiers.Control))); + + // assert + Assert.Collection(mailMode.State.Threads, t => Assert.Equal("Status update", t.Subject)); + Assert.Contains("Status update", RenderToText(shell)); + } - foreach (var c in "Status") + [Fact] + public void Handle_Should_OpenTheMailThreadPopover_When_EnterIsPressedWithAThreadSelected() + { + // arrange + var mailStore = new FakeMailStore(); + mailStore.Messages.Add(MailMessageBuilder.Create( + "m1", sender: "alice", subject: "Status update", threadId: "t-1", + recipients: [MailMessageBuilder.ToRecipient("bob")])); + var time = new FakeTimeProvider(s_now); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(time), time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains("Status update", rendered); + Assert.Contains("Participants:", rendered); + } + + [Fact] + public void Handle_Should_ShowTheThreadIdToast_When_YIsPressedInTheMailThreadPopover() + { + // arrange + var mailStore = new FakeMailStore(); + mailStore.Messages.Add(MailMessageBuilder.Create("m1", threadId: "t-1")); + var time = new FakeTimeProvider(s_now); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(time), time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('y', ConsoleKey.Y))); + var rendered = RenderToText(shell, width: 100); + + // assert + var statusLine = rendered.TrimEnd().Split('\n')[^1].Trim(); + Assert.Equal("i t-1", statusLine); + } + + [Fact] + public void Handle_Should_CloseTheMailThreadPopover_When_EscapeIsPressed() + { + // arrange + var mailStore = new FakeMailStore(); + mailStore.Messages.Add(MailMessageBuilder.Create( + "m1", subject: "Status update", threadId: "t-1")); + var time = new FakeTimeProvider(s_now); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(time), time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\u001b', ConsoleKey.Escape))); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains("enter open", rendered); + Assert.Contains("SUBJECT", rendered); + Assert.Contains("Status update", rendered); + } + + [Fact] + public void Handle_Should_ReloadTheMailThreadPopover_When_ADataChangedEventArrives() + { + // arrange + var mailStore = new FakeMailStore(); + mailStore.Messages.Add(MailMessageBuilder.Create( + "m1", body: "Original body", threadId: "t-1", createdAt: s_now)); + var time = new FakeTimeProvider(s_now); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(time), time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + mailStore.Messages.Add(MailMessageBuilder.Create( + "m2", body: "Distinctnewbody", threadId: "t-1", createdAt: s_now.AddMinutes(1))); + var dirty = shell.Handle(new TuiEvent.DataChangedEvent()); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains("Distinctnewbody", rendered); + } + + [Fact] + public void Handle_Should_ShowNoThreadSelectedToast_When_EnterIsPressedOnAnEmptyMailTab() + { + // arrange + var mailStore = new FakeMailStore(); + var time = new FakeTimeProvider(s_now); + var mailMode = new MailMode(mailStore, new Agents.FakeAgentStore(time), time); + var mailTab = CreateMailTab("Mail", mailMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), mailTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + Assert.True(dirty); + Assert.Contains("No thread selected.", RenderToText(shell, width: 100)); + } + + [Fact] + public void Handle_Should_ShowTheMemoryTabsHeaderRowAndCount_When_ShiftEIsPressed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try { - mailMode.HandleRawKey(KeyInfo(c, ConsoleKey.NoName)); + SaveMemory(store, "Ops note."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); + + // act + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + + // assert + var rendered = RenderToText(shell); + Assert.Contains("Memory (1)", rendered); + Assert.Contains("KIND", rendered); + Assert.Contains("TAGS", rendered); } + finally + { + root.Delete(recursive: true); + } + } - mailMode.HandleRawKey(KeyInfo('\0', ConsoleKey.Tab)); + [Fact] + public void Handle_Should_NarrowMemoryTabToCurated_When_FIsPressedAfterSwitchingWithShiftE() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); - foreach (var c in "Body") + try { - mailMode.HandleRawKey(KeyInfo(c, ConsoleKey.NoName)); + SaveMemory(store, "Ops note."); + LogMemory(store, "Follow up needed."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + + // act + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('f', ConsoleKey.F))); + + // assert + Assert.Contains("Curated (1)", RenderToText(shell)); + Assert.Equal(MemoryCollectionFilter.Curated, memoryMode.State.Filter); } + finally + { + root.Delete(recursive: true); + } + } - mailMode.HandleRawKey(KeyInfo('\0', ConsoleKey.S, ConsoleModifiers.Control)); - - // act - // Expire the current toast before each refresh until the terminal toast renders. - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(testToken); - timeoutCts.CancelAfter(TimeSpan.FromSeconds(5)); - var dirty = false; - var rendered = RenderToText(shell); + [Fact] + public void Handle_Should_NarrowMemoryTabRows_When_SearchSubmittedThroughTheShell() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); - while (!rendered.Contains("Sent", StringComparison.Ordinal)) + try { - shell.Handle(new TuiEvent.TickEvent(DateTimeOffset.UtcNow + Toaster.s_duration)); - dirty = shell.Handle(new TuiEvent.DataChangedEvent()); - rendered = RenderToText(shell); - - if (!rendered.Contains("Sent", StringComparison.Ordinal)) + SaveMemory(store, "Deploy note."); + SaveMemory(store, "Lunch plan."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 80, + 24, + agentStore: new Agents.FakeAgentStore(time)); + + // act + // Switch to the Memory tab, open search, type a body fragment, and submit with the save chord. + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('/', ConsoleKey.Oem2))); + + foreach (var c in "deploy") { - await Task.Delay(5, timeoutCts.Token); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo(c, ConsoleKey.NoName))); } + + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('s', ConsoleKey.S, ConsoleModifiers.Control))); + + // assert + Assert.Collection(memoryMode.State.Rows, r => Assert.Equal("Deploy note.", r.Body)); + Assert.Contains("Memory (1) (filtered)", RenderToText(shell)); + } + finally + { + root.Delete(recursive: true); } + } - // assert - Assert.True(dirty); - Assert.Contains("Sent", rendered); + [Fact] + public void Handle_Should_OpenTheMemoryEntryPopover_When_EnterIsPressedWithARowSelected() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try + { + var saved = SaveMemory(store, "Restart the worker on failure."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains(saved.Id, rendered); + Assert.Contains("Kind: curated", rendered); + } + finally + { + root.Delete(recursive: true); + } + } + + [Fact] + public void Handle_Should_ShowTheEntryIdToast_When_YIsPressedInTheMemoryEntryPopover() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try + { + var saved = SaveMemory(store, "Ops note."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('y', ConsoleKey.Y))); + var rendered = RenderToText(shell, width: 100); + + // assert + var statusLine = rendered.TrimEnd().Split('\n')[^1].Trim(); + Assert.Equal($"i {saved.Id}", statusLine); + } + finally + { + root.Delete(recursive: true); + } + } + + [Fact] + public void Handle_Should_CloseTheMemoryEntryPopover_When_EscapeIsPressed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try + { + SaveMemory(store, "Ops note."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\u001b', ConsoleKey.Escape))); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains("KIND", rendered); + Assert.Contains("curated", rendered); + } + finally + { + root.Delete(recursive: true); + } + } + + [Fact] + public void Handle_Should_ReloadTheMemoryEntryPopover_When_ADataChangedEventArrives() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try + { + var saved = SaveMemory(store, "Original body."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + UpdateMemoryBody(store, saved.Id, "Distinctnewbody"); + var dirty = shell.Handle(new TuiEvent.DataChangedEvent()); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains("Distinctnewbody", rendered); + } + finally + { + root.Delete(recursive: true); + } + } + + [Fact] + public void Handle_Should_ShowTheMissingState_When_TheOpenMemoryEntryIsForgotten() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try + { + var saved = SaveMemory(store, "Original body."); + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + ForgetMemory(store, saved.Id); + var dirty = shell.Handle(new TuiEvent.DataChangedEvent()); + var rendered = RenderToText(shell, width: 100); + + // assert + Assert.True(dirty); + Assert.Contains("This entry no longer exists.", rendered); + } + finally + { + root.Delete(recursive: true); + } + } + + [Fact] + public void Handle_Should_ShowNoItemSelectedToast_When_EnterIsPressedOnAnEmptyMemoryTab() + { + // arrange + var time = new FakeTimeProvider(s_now); + var store = CreateMemoryStore(time, out var root); + + try + { + var memoryMode = new MemoryMode(store, time); + var memoryTab = CreateMemoryTab("Memory", memoryMode); + var shell = new TuiShell( + [CreateTasksTab("Tasks", new FakeTuiMode()), memoryTab], + 100, + 24, + agentStore: new Agents.FakeAgentStore(time)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('E', ConsoleKey.E, ConsoleModifiers.Shift))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + Assert.True(dirty); + Assert.Contains("No item selected.", RenderToText(shell, width: 100)); + } + finally + { + root.Delete(recursive: true); + } } [Fact] @@ -469,10 +1042,12 @@ public void Handle_Should_OpenTaskDetail_When_EnterPressedOnBoardSelection_Throu Columns = [new ColumnDefinition { Name = "Open", Statuses = [TaskStates.Open] }] }; var board = new BoardMode(new BoardDataLoader(store, TimeProvider.System), [view]); + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [CreateTasksTab("Tasks", board), CreateTasksTab("Other", new FakeTuiMode(), mnemonic: 'O')], 80, 24, + agentStore: new Agents.FakeAgentStore(time), tasksTabIndex: 0, store: store, actor: "tester"); @@ -487,69 +1062,58 @@ public void Handle_Should_OpenTaskDetail_When_EnterPressedOnBoardSelection_Throu } [Fact] - public void Handle_Should_AlwaysShowSelectedAgentDetail_WithoutOpeningAnything_ThroughATabbedShell() + public void Handle_Should_OpenTheAgentPopover_When_EnterIsPressed_ThroughATabbedShell() { // arrange - var sessions = new Agents.FakeAgentSessionRegistry(); - sessions.Participants.Add( - Agents.AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a", role: "backend", agent: Agent("agent-a", role: "backend"))); - var taskStore = new FakeTaskStore(); - var mailStore = new Agents.FakeMailStore(); + var time = new FakeTimeProvider(s_now); + var agentStore = new Agents.FakeAgentStore(time); + LoginAgent(agentStore); var agentsMode = new AgentsMode( - taskStore, - mailStore, - sessions, - new Agents.FakeClaudeSessionActivityReader()); + agentStore, new Agents.FakeMailStore(), new FakeTaskStore(), new Agents.FakeMemoryStore(), time); var shell = new TuiShell( [CreateAgentsTab("Agents", agentsMode)], 100, 24, + agentStore: agentStore, tasksTabIndex: 0, - store: taskStore); - Assert.Contains("backend", RenderToText(shell, width: 100)); + store: new FakeTaskStore()); + var agentName = agentsMode.State.Rows[0].Name; // act - // Enter focuses the already-visible detail pane instead of pushing a full-screen mode. var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); // assert var rendered = RenderToText(shell, width: 100); Assert.True(dirty); - Assert.Equal(AgentsFocus.Detail, agentsMode.State.Focus); - Assert.Contains("agent-a", rendered); - Assert.Contains("backend", rendered); + Assert.Equal(0, agentsMode.State.SelectedRow); + Assert.Contains(agentName, rendered); + Assert.Contains("Harness:", rendered); } [Fact] public void Handle_Should_LeaveAgentsListSelectionUntouched_When_EscapePressed() { // arrange - var sessions = new Agents.FakeAgentSessionRegistry(); - sessions.Participants.Add( - Agents.AgentSessionParticipantBuilder.Participant( - sessionId: "s-a", agentName: "agent-a")); - var taskStore = new FakeTaskStore(); - var mailStore = new Agents.FakeMailStore(); + var time = new FakeTimeProvider(s_now); + var agentStore = new Agents.FakeAgentStore(time); + LoginAgent(agentStore); var agentsMode = new AgentsMode( - taskStore, - mailStore, - sessions, - new Agents.FakeClaudeSessionActivityReader()); + agentStore, new Agents.FakeMailStore(), new FakeTaskStore(), new Agents.FakeMemoryStore(), time); var shell = new TuiShell( [CreateAgentsTab("Agents", agentsMode)], 80, 24, - tasksTabIndex: 0, - store: taskStore); + agentStore: agentStore, + tasksTabIndex: 0); + var agentName = Assert.Single(agentsMode.State.Rows).Name; // act var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\x1b', ConsoleKey.Escape))); // assert Assert.True(dirty); - Assert.Equal("agent-a", agentsMode.State.SelectedParticipant?.Participant.Session.AgentName); - Assert.Contains("Agents (1)", RenderToText(shell)); + Assert.Equal(agentName, agentsMode.State.SelectedAgent?.Name); + Assert.Contains("Agents (0 online / 1)", RenderToText(shell)); } [Fact] @@ -559,39 +1123,46 @@ public void TaskOverlayGesture_Should_DoNothing_When_TheTasksTabIsNotActive() var store = new FakeTaskStore(); store.Tasks["a"] = TaskItemBuilder.Create("a"); var otherMode = new FakeTuiMode { SelectedTaskId = "a" }; + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [CreateTasksTab("Tasks", new FakeTuiMode()), CreateTasksTab("Other", otherMode, mnemonic: 'O')], 80, 24, + agentStore: new Agents.FakeAgentStore(time), tasksTabIndex: 0, store: store, actor: "tester"); shell.Handle(new TuiEvent.KeyEvent(KeyInfo(']', ConsoleKey.Oem6))); - // act: 'e' would open the task editor on the tasks tab. + // act + // 'e' would open the task editor on the tasks tab. shell.Handle(new TuiEvent.KeyEvent(KeyInfo('e', ConsoleKey.E))); - // assert: no editor opened on the (non-tasks) active tab. + // assert + // No editor opened on the (non-tasks) active tab. Assert.DoesNotContain("Edit Task", RenderToText(shell)); } [Fact] - public void Handle_Should_PreserveEachTabsNavigationStack_AcrossTabSwitches_AndKeepBackWithinTheTab() + public void Handle_Should_PreserveEachTabsNavigationStack_When_SwitchingTabs() { // arrange var store = new FakeTaskStore(); var searchMode = new SearchMode(store); var board = new FakeTuiMode { RenderText = "board" }; + var time = new FakeTimeProvider(s_now); var shell = new TuiShell( [CreateTasksTab("Tasks", board), CreateTasksTab("Other", new FakeTuiMode { RenderText = "other" }, mnemonic: 'O')], 80, 24, + agentStore: new Agents.FakeAgentStore(time), tasksTabIndex: 0, searchMode: searchMode, store: store, actor: "tester"); - // act: enter search from the tasks tab's board root. + // act + // Enter search from the tasks tab's board root. shell.Handle(new TuiEvent.KeyEvent(KeyInfo('/', ConsoleKey.Oem2))); Assert.Contains("Results", RenderToText(shell)); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTests.cs index a826d402973..b082fcd5257 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Shell/TuiShellTests.cs @@ -1,18 +1,26 @@ +using ChilliCream.Nitro.CommandLine.Services.Mail; using ChilliCream.Nitro.CommandLine.Services.Tasks; +using ChilliCream.Nitro.CommandLine.Services.Workspace; +using ChilliCream.Nitro.CommandLine.Tests.Tui.Agents; +using ChilliCream.Nitro.CommandLine.Tui.Agents; using ChilliCream.Nitro.CommandLine.Tui.Board; using ChilliCream.Nitro.CommandLine.Tui.Input; using ChilliCream.Nitro.CommandLine.Tui.Runtime; using ChilliCream.Nitro.CommandLine.Tui.Search; using ChilliCream.Nitro.CommandLine.Tui.Shell; using ChilliCream.Nitro.CommandLine.Tui.Tree; +using Microsoft.Extensions.Time.Testing; using Spectre.Console; using Spectre.Console.Testing; using CursorDirection = ChilliCream.Nitro.CommandLine.Tui.Input.CursorDirection; +using static ChilliCream.Nitro.CommandLine.Tests.Tui.AnsiAssertions; namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Shell; public sealed class TuiShellTests { + private static readonly DateTimeOffset s_now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static ConsoleKeyInfo KeyInfo(char keyChar, ConsoleKey key, ConsoleModifiers modifiers = ConsoleModifiers.None) => new( keyChar, @@ -22,7 +30,13 @@ private static ConsoleKeyInfo KeyInfo(char keyChar, ConsoleKey key, ConsoleModif modifiers.HasFlag(ConsoleModifiers.Control)); private static TuiShell CreateShell(FakeTuiMode mode, int width = 80, int height = 24, string? actor = null) => - new(new KeyDispatcher(KeyMap.CreateDefaultGlobal()), mode, width, height, actor: actor); + new( + new KeyDispatcher(KeyMap.CreateDefaultGlobal()), + mode, + width, + height, + agentStore: new FakeAgentStore(TimeProvider.System), + actor: actor); private static TuiShell CreateShellWithModes( ITuiMode initialMode, @@ -38,9 +52,10 @@ private static TuiShell CreateShellWithModes( initialMode, 80, 24, - searchMode, - treeView, - store, + agentStore: new FakeAgentStore(TimeProvider.System), + searchMode: searchMode, + treeView: treeView, + store: store, actor: "tester"); } @@ -58,6 +73,83 @@ private static string RenderToText(TuiShell shell, int width) return console.Output; } + private static string RenderToAnsiText(TuiShell shell, int width = 80) + { + var console = new TestConsole().Colors(ColorSystem.TrueColor).EmitAnsiSequences().Width(width); + console.Write(shell.Render()); + return console.Output; + } + + /// + /// Builds an Agents-tab shell around a freshly built , defaulting + /// the mail, task, and memory stores the agent detail popover needs when a test does not + /// care about them. + /// + private static TuiShell CreateAgentsShell( + out AgentsMode mode, + FakeAgentStore agentStore, + TimeProvider? timeProvider = null, + FakeMailStore? mailStore = null, + FakeTaskStore? taskStore = null, + FakeMemoryStore? memoryStore = null, + int width = 80) + { + var resolvedTaskStore = taskStore ?? new FakeTaskStore(); + mode = new AgentsMode( + agentStore, + mailStore ?? new FakeMailStore(), + resolvedTaskStore, + memoryStore ?? new FakeMemoryStore(), + timeProvider ?? TimeProvider.System); + + return new TuiShell( + new KeyDispatcher(KeyMap.CreateDefaultGlobal()), + mode, + width, + 24, + agentStore: agentStore, + store: resolvedTaskStore); + } + + private static AgentRow AddOnlineAgent(FakeAgentStore store, string sessionId) + => store.StartSessionAsync( + new AgentSessionStartRequest + { + Harness = AgentSessionHarness.ClaudeCode, + SessionId = sessionId, + HarnessVersion = "1.0.0", + Cwd = "", + WorkspacePath = "", + EndpointKind = AgentSessionEndpointKind.ClaudePeer, + EndpointAddr = "peer-1" + }, + TestContext.Current.CancellationToken) + .GetAwaiter().GetResult().Row!; + + private static AgentRow AddOfflineAgent(FakeAgentStore store, string sessionId) + { + var row = AddOnlineAgent(store, sessionId); + store.EndSessionAsync(row.Harness!, row.SessionId!, TestContext.Current.CancellationToken) + .GetAwaiter().GetResult(); + return row; + } + + private static void DeleteAgent(FakeAgentStore store, string name) + => store.DeleteAsync(name, TestContext.Current.CancellationToken).GetAwaiter().GetResult(); + + private static MailThreadSummary CreateMailSummary(DateTimeOffset lastMessageAt) => new() + { + ThreadId = "t1", + Subject = "New thread", + MessageCount = 1, + LastMessageAt = lastMessageAt, + LastSender = "felix", + LastRecipients = ["oscar"], + BodyPreview = "", + UnreadCount = 0, + ArchivedCount = 0 + }; + [Fact] public void Constructor_Should_CallOnEnter_OnActiveMode() { @@ -1308,4 +1400,339 @@ public void Render_Should_OmitActorIdentity_When_HintsAlreadyFillTheRow() Assert.Contains("move", text); Assert.DoesNotContain("someone", text); } + + [Fact] + public void Render_Should_ShowOnlyTheAgentsTabsOwnFooterHints_When_TheAgentsTabIsActive() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell(out _, agentStore, new FakeTimeProvider(s_now), width: 120); + + // act + var text = RenderToText(shell, 120); + + // assert + // None of the Tasks tab's zoom, edit, back, or quit hints leak in via the global table. + Assert.Contains( + "hjkl move enter open d delete D delete offline y copy id r refresh / search", + text); + } + + [Fact] + public void Handle_Should_OpenTheAgentDeleteDialog_When_DIsPressedWithAnAgentSelected() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell(out _, agentStore, new FakeTimeProvider(s_now)); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('d', ConsoleKey.D))); + + // assert + Assert.True(dirty); + Assert.Contains($"Delete agent '{agent.Name}'", RenderToText(shell)); + } + + [Fact] + public void Handle_Should_ShowToast_When_DIsPressedWithNoAgentSelected() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var shell = CreateAgentsShell(out _, agentStore, new FakeTimeProvider(s_now)); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('d', ConsoleKey.D))); + + // assert + Assert.True(dirty); + Assert.Contains("No agent selected.", RenderToText(shell)); + } + + [Fact] + public void Handle_Should_DeleteTheAgentAndRefresh_When_TheDeleteDialogIsConfirmed() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + var agent = AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell(out var mode, agentStore, new FakeTimeProvider(s_now)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('d', ConsoleKey.D))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + var rendered = RenderToText(shell); + Assert.True(dirty); + Assert.Empty(mode.State.Rows); + Assert.Contains($"Deleted agent '{agent.Name}'", rendered); + } + + [Fact] + public void Handle_Should_OpenTheDeleteOfflineDialogWithTheCount_When_ShiftDIsPressed() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + AddOfflineAgent(agentStore, "s-a"); + AddOfflineAgent(agentStore, "s-b"); + AddOnlineAgent(agentStore, "s-c"); + var shell = CreateAgentsShell(out _, agentStore, new FakeTimeProvider(s_now)); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('D', ConsoleKey.D, ConsoleModifiers.Shift))); + + // assert + Assert.True(dirty); + Assert.Contains("Delete 2 offline or idle agents?", RenderToText(shell)); + } + + [Fact] + public void Handle_Should_ShowToast_When_ShiftDIsPressedWithNoOfflineAgents() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell(out _, agentStore, new FakeTimeProvider(s_now)); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('D', ConsoleKey.D, ConsoleModifiers.Shift))); + + // assert + Assert.True(dirty); + Assert.Contains("No offline or idle agents to delete.", RenderToText(shell)); + } + + [Fact] + public void Handle_Should_DeleteEveryOfflineAgentAndRefresh_When_TheDeleteOfflineDialogIsConfirmed() + { + // arrange + var agentStore = new FakeAgentStore(new FakeTimeProvider(s_now)); + AddOfflineAgent(agentStore, "s-a"); + AddOfflineAgent(agentStore, "s-b"); + var online = AddOnlineAgent(agentStore, "s-c"); + var shell = CreateAgentsShell(out var mode, agentStore, new FakeTimeProvider(s_now)); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('D', ConsoleKey.D, ConsoleModifiers.Shift))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + var rendered = RenderToText(shell); + Assert.True(dirty); + var remaining = Assert.Single(mode.State.Rows); + Assert.Equal(online.Name, remaining.Name); + Assert.Contains("Deleted 2 offline or idle agents.", rendered); + } + + [Fact] + public void Handle_Should_DeleteEveryIdleAgentAndRefresh_When_TheDeleteOfflineDialogIsConfirmed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + AddOnlineAgent(agentStore, "s-a"); + time.Advance(AgentStateResolver.OnlineWindow + TimeSpan.FromMinutes(1)); + var online = AddOnlineAgent(agentStore, "s-b"); + var shell = CreateAgentsShell(out var mode, agentStore, time); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('D', ConsoleKey.D, ConsoleModifiers.Shift))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + var rendered = RenderToText(shell); + Assert.True(dirty); + var remaining = Assert.Single(mode.State.Rows); + Assert.Equal(online.Name, remaining.Name); + Assert.Contains("Deleted 1 offline or idle agents.", rendered); + } + + [Fact] + public void Handle_Should_ReportDirtyAndShowTheIdleBubble_When_ATickAdvancesPastTheOnlineWindow() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + AddOnlineAgent(agentStore, "s-a"); + AddOnlineAgent(agentStore, "s-b"); + var shell = CreateAgentsShell(out _, agentStore, time); + // Move off row 0 so its bubble is never selection-highlighted, before or after the tick. + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('j', ConsoleKey.J))); + AssertAnsiStylePrefixesText(RenderToAnsiText(shell), "agents.list.presence.online", "โ—"); + + // act + time.Advance(TimeSpan.FromMinutes(31)); + var dirty = shell.Handle(new TuiEvent.TickEvent(time.GetUtcNow())); + var rendered = RenderToAnsiText(shell); + + // assert + Assert.True(dirty); + AssertAnsiStylePrefixesText(rendered, "agents.list.presence.idle", "โ—"); + Assert.Contains("31m ago", rendered); + } + + [Fact] + public void Handle_Should_ReturnFalse_When_ATickHasNoTimeAdvance() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell(out _, agentStore, time); + + // act + var dirty = shell.Handle(new TuiEvent.TickEvent(time.GetUtcNow())); + + // assert + Assert.False(dirty); + } + + [Fact] + public void Handle_Should_OpenTheAgentPopover_When_EnterIsPressedWithAnAgentSelected() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var agent = AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell( + out _, agentStore, time, new FakeMailStore(), new FakeTaskStore(), new FakeMemoryStore()); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + Assert.True(dirty); + Assert.Contains(agent.Name, RenderToText(shell, 100)); + Assert.Contains("Harness:", RenderToText(shell, 100)); + } + + [Fact] + public void Handle_Should_ShowToast_When_EnterIsPressedWithNoAgentSelected() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var shell = CreateAgentsShell( + out _, agentStore, time, new FakeMailStore(), new FakeTaskStore(), new FakeMemoryStore()); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // assert + Assert.True(dirty); + Assert.Contains("No agent selected.", RenderToText(shell, 100)); + } + + [Fact] + public void Handle_Should_CopyThePopoversOwnAgentSessionId_When_YIsPressedAfterTheTableSelectionMovesToAnotherAgent() + { + // arrange + // deleting the popover agent moves the table selection to the only other agent + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var first = AddOnlineAgent(agentStore, "s-a"); + var second = AddOnlineAgent(agentStore, "s-b"); + var shell = CreateAgentsShell( + out var mode, agentStore, time, new FakeMailStore(), new FakeTaskStore(), new FakeMemoryStore()); + var popoverAgent = mode.State.SelectedAgent!; + var otherAgent = popoverAgent.Name == first.Name ? second : first; + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + DeleteAgent(agentStore, popoverAgent.Name); + shell.Handle(new TuiEvent.DataChangedEvent()); + + // act + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('y', ConsoleKey.Y))); + var rendered = RenderToText(shell, 100); + + // assert + Assert.Equal(otherAgent.Name, mode.State.SelectedAgent?.Name); + var statusLine = rendered.TrimEnd().Split('\n')[^1].Trim(); + Assert.Equal($"i {popoverAgent.SessionId}", statusLine); + } + + [Fact] + public void Handle_Should_CloseThePopoverToTheTable_When_DeleteFromThePopoverIsConfirmed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + var agent = AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell( + out var mode, agentStore, time, new FakeMailStore(), new FakeTaskStore(), new FakeMemoryStore()); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('d', ConsoleKey.D))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + var rendered = RenderToText(shell, 100); + + // assert + Assert.True(dirty); + Assert.Empty(mode.State.Rows); + Assert.Contains($"Deleted agent '{agent.Name}'", rendered); + Assert.Contains("Agents (0 online / 0)", rendered); + } + + [Fact] + public void Handle_Should_CloseThePopover_When_EscapeIsPressed() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell( + out _, agentStore, time, new FakeMailStore(), new FakeTaskStore(), new FakeMemoryStore()); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + var dirty = shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\u001b', ConsoleKey.Escape))); + var rendered = RenderToText(shell, 100); + + // assert + Assert.True(dirty); + Assert.Contains("hjkl move", rendered); + } + + [Fact] + public void Handle_Should_MarkDirtyAndRedrawThePopoverAges_When_ATickEventArrivesWithThePopoverOpen() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + AddOnlineAgent(agentStore, "s-a"); + var shell = CreateAgentsShell( + out _, agentStore, time, new FakeMailStore(), new FakeTaskStore(), new FakeMemoryStore()); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + time.Advance(TimeSpan.FromMinutes(2)); + var dirty = shell.Handle(new TuiEvent.TickEvent(time.GetUtcNow())); + var rendered = RenderToText(shell, 100); + + // assert + Assert.True(dirty); + Assert.Contains("2m ago", rendered); + } + + [Fact] + public void Handle_Should_ReloadThePopover_When_ADataChangedEventArrives() + { + // arrange + var time = new FakeTimeProvider(s_now); + var agentStore = new FakeAgentStore(time); + AddOnlineAgent(agentStore, "s-a"); + var mailStore = new FakeMailStore(); + var shell = CreateAgentsShell(out _, agentStore, time, mailStore, new FakeTaskStore(), new FakeMemoryStore()); + shell.Handle(new TuiEvent.KeyEvent(KeyInfo('\r', ConsoleKey.Enter))); + + // act + mailStore.ParticipationRows = [CreateMailSummary(time.GetUtcNow())]; + var dirty = shell.Handle(new TuiEvent.DataChangedEvent()); + var rendered = RenderToText(shell, 100); + + // assert + Assert.True(dirty); + Assert.Contains("New thread", rendered); + } } diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Tree/FakeTaskStore.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Tree/FakeTaskStore.cs index c45e87ab63c..ff5a9dc57d6 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Tree/FakeTaskStore.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Tree/FakeTaskStore.cs @@ -39,6 +39,10 @@ public Task> GetDependencyEdgesAsync( public Task GetTaskAsync(string id, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> QueryParticipationAsync( + string agent, int? limit, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task GetRequiredTaskAsync(string id, CancellationToken cancellationToken) => throw new NotSupportedException(); @@ -108,6 +112,9 @@ public Task UndeferTaskAsync(string id, string actor, CancellationToke public Task DeleteTaskAsync(string id, string reason, string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task ReleaseAssigneeAsync(string agent, string reason, CancellationToken cancellationToken) + => throw new NotSupportedException(); + public Task> CloseEligibleEpicsAsync(string actor, CancellationToken cancellationToken) => throw new NotSupportedException(); diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TableRendererTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TableRendererTests.cs new file mode 100644 index 00000000000..f333c1626d5 --- /dev/null +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TableRendererTests.cs @@ -0,0 +1,225 @@ +using ChilliCream.Nitro.CommandLine.Tui.Widgets; + +namespace ChilliCream.Nitro.CommandLine.Tests.Tui.Widgets; + +public sealed class TableRendererTests +{ + // ROLE drops first (priority 0), then AGE (priority 1); NAME has no drop priority so it is + // never dropped. With the four-space gutter, all three need 19 columns, NAME+AGE need 11, + // and NAME alone needs 4. + private static readonly IReadOnlyList s_columns = + [ + new TableColumnSpec("NAME", MinWidth: 4), + new TableColumnSpec("ROLE", MinWidth: 4, DropPriority: 0), + new TableColumnSpec("AGE", MinWidth: 3, DropPriority: 1, Alignment: ColumnAlignment.Right) + ]; + + [Fact] + public void ComputeWidths_Should_UseMinimumWidth_When_TitlesAndValuesAreShort() + { + // arrange + IReadOnlyList> rows = [["a", "b", "1"]]; + + // act + var widths = TableLayout.ComputeWidths(s_columns, rows); + + // assert + Assert.Equal([4, 4, 3], widths); + } + + [Fact] + public void ComputeWidths_Should_GrowToLongestValue_When_ARowIsWiderThanMinimum() + { + // arrange + IReadOnlyList> rows = [["a-very-long-name", "b", "1"]]; + + // act + var widths = TableLayout.ComputeWidths(s_columns, rows); + + // assert + Assert.Equal(16, widths[0]); + } + + [Fact] + public void ComputeWidths_Should_IgnoreRowValues_When_ColumnHasAFixedWidth() + { + // arrange + IReadOnlyList columns = [new TableColumnSpec("X", MinWidth: 1, FixedWidth: 5)]; + IReadOnlyList> rows = [["a-value-much-wider-than-five"]]; + + // act + var widths = TableLayout.ComputeWidths(columns, rows); + + // assert + Assert.Equal(5, widths[0]); + } + + [Fact] + public void Plan_Should_ShowEveryColumn_When_BudgetFitsThemAll() + { + // arrange + int[] widths = [4, 4, 3]; + + // act + var layout = TableLayout.Plan(budget: 19, s_columns, widths); + + // assert + Assert.Equal([true, true, true], layout.Select(c => c.Visible)); + } + + [Fact] + public void Plan_Should_DropLowestPriorityColumnFirst_When_BudgetIsTooNarrow() + { + // arrange + // NAME(4) + gutter(4) + AGE(3) fits in 11, but not with ROLE(4) + gutter too. + int[] widths = [4, 4, 3]; + + // act + var layout = TableLayout.Plan(budget: 15, s_columns, widths); + + // assert + Assert.Equal([true, false, true], layout.Select(c => c.Visible)); + } + + [Fact] + public void Plan_Should_KeepDroppingByPriority_When_BudgetStaysTooNarrow() + { + // arrange + int[] widths = [4, 4, 3]; + + // act + var layout = TableLayout.Plan(budget: 8, s_columns, widths); + + // assert + Assert.Equal([true, false, false], layout.Select(c => c.Visible)); + } + + [Fact] + public void Plan_Should_NeverDropAColumnWithoutDropPriority_When_BudgetIsExtremelyNarrow() + { + // arrange + int[] widths = [4, 4, 3]; + + // act + var layout = TableLayout.Plan(budget: 1, s_columns, widths); + + // assert + Assert.True(layout[0].Visible); + } + + [Fact] + public void Plan_Should_TruncateTheFirstVisibleColumn_When_EvenNeverDroppedColumnsDoNotFit() + { + // arrange + int[] widths = [4, 4, 3]; + + // act + var layout = TableLayout.Plan(budget: 1, s_columns, widths); + + // assert + Assert.Equal(1, layout[0].Width); + } + + [Fact] + public void RenderRow_Should_JoinVisibleCellsWithGutter_When_AllColumnsFit() + { + // arrange + var layout = TableLayout.Plan(budget: 19, s_columns, [4, 4, 3]); + TableCellSpec[] cells = [new("Ann", "bold"), new("Lead", ""), new("2m", "")]; + + // act + var line = TableRenderer.RenderRow("> ", new TableCellSpec("*"), cells, s_columns, layout); + + // assert + line.MatchInlineSnapshot("> * [bold]Ann [/] Lead 2m"); + } + + [Fact] + public void RenderRow_Should_SkipHiddenColumns_When_LayoutMarksThemInvisible() + { + // arrange + var layout = TableLayout.Plan(budget: 5, s_columns, [4, 4, 3]); + TableCellSpec[] cells = [new("Ann"), new("Lead"), new("2m")]; + + // act + var line = TableRenderer.RenderRow(" ", new TableCellSpec(" "), cells, s_columns, layout); + + // assert + line.MatchInlineSnapshot(" Ann "); + } + + [Fact] + public void RenderRow_Should_RightAlignAndPad_When_ColumnAlignmentIsRight() + { + // arrange + var layout = TableLayout.Plan(budget: 19, s_columns, [4, 4, 3]); + TableCellSpec[] cells = [new("Ann"), new("Lead"), new("2m")]; + + // act + var line = TableRenderer.RenderRow(" ", new TableCellSpec(" "), cells, s_columns, layout); + + // assert + Assert.EndsWith(" 2m", line); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void RenderRule_Should_ReturnEmpty_When_WidthIsNotPositive(int width) + { + // act + var rule = TableRenderer.RenderRule(width, "grey"); + + // assert + Assert.Equal(string.Empty, rule); + } + + [Fact] + public void RenderRule_Should_FillWidthWithRuleGlyphs_When_WidthIsPositive() + { + // act + var rule = TableRenderer.RenderRule(5, "grey"); + + // assert + rule.MatchInlineSnapshot("[grey]โ”€โ”€โ”€โ”€โ”€[/]"); + } + + [Fact] + public void RenderTopBlock_Should_EmitBlankHeaderRule_When_ThreeLinesFit() + { + // arrange + var lines = new List(); + var layout = TableLayout.Plan(budget: 19, s_columns, [4, 4, 3]); + + // act + TableRenderer.RenderTopBlock( + lines, lineCount: 3, width: 19, " ", new TableCellSpec(" "), s_columns, layout, "bold", "grey"); + + // assert + lines.MatchInlineSnapshots( + [ + " ", + " [bold]NAME[/] [bold]ROLE[/] [bold]AGE[/]", + "[grey]โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€[/]" + ]); + } + + [Fact] + public void RenderTopBlock_Should_DropTrailingLines_When_FewerLinesFit() + { + // arrange + var lines = new List(); + var layout = TableLayout.Plan(budget: 19, s_columns, [4, 4, 3]); + + // act + TableRenderer.RenderTopBlock( + lines, lineCount: 2, width: 19, " ", new TableCellSpec(" "), s_columns, layout, "bold", "grey"); + + // assert + lines.MatchInlineSnapshots( + [ + " ", + " [bold]NAME[/] [bold]ROLE[/] [bold]AGE[/]" + ]); + } +} diff --git a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TaskBadgeTests.cs b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TaskBadgeTests.cs index 0d218de4b68..6286d254b34 100644 --- a/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TaskBadgeTests.cs +++ b/src/Nitro/CommandLine/test/CommandLine.Tests/Tui/Widgets/TaskBadgeTests.cs @@ -306,6 +306,28 @@ public void Render_Should_RenderAsValidMarkup_When_StatusIsTombstone() Assert.Contains("Title", console.Output); } + [Fact] + public void PriorityStyle_Should_MatchTheStyleEmbeddedInRender_When_SamePriority() + { + // arrange + const int priority = TaskPriorities.Medium; + + // act + var style = TaskBadge.PriorityStyle(priority); + var line = TaskBadge.Render( + id: "T-1", + title: "Fix bug", + status: TaskStates.Open, + priority: priority, + type: TaskTypes.Task, + selected: false, + maxWidth: 80); + + // assert + Assert.Equal("yellow", style); + Assert.Contains($"[{style}]P2[/]", line); + } + [Fact] public void Render_Should_RenderAsValidMarkup_When_PriorityIsOutOfRange() { diff --git a/src/Nitro/CommandLine/test/e2e/README.md b/src/Nitro/CommandLine/test/e2e/README.md index 356667f722e..e8a6d187b43 100644 --- a/src/Nitro/CommandLine/test/e2e/README.md +++ b/src/Nitro/CommandLine/test/e2e/README.md @@ -30,10 +30,11 @@ layer: a handful of representative flows, not exhaustive. | `board-maximize` | the Tasks tab's maximize toggle (`z`) | the single-column maximized layout | | `search` | search mode (`/`) in the Tasks tab (bare `nitro agent`) | live query filtering and opening a result's detail pane | | `detail` | the Tasks tab's detail pane and dependency tree (`t`, `d`, `u`) | the detail body and tree explorer navigation | -| `mail-send` | `agent register/mail send/inbox/reply/read --thread` over a copy of the fixture | the mail send/inbox/reply/read round trip, one actor registered with a role | +| `mail-send` | `agent register/list/mail send/inbox/reply/read --thread` over a copy of the fixture | the mail send/inbox/reply/read round trip, one actor registered with a role, and the unified `agent list` shape | | `mail-error` | `nitro agent mail send` to an invalid recipient name | the agent-name-normalization rejection and non-zero exit rendering | -| `mail-board` | the Mail tab's actor-less Workspace mailbox (bare `nitro agent`, `]` to switch) | read-only navigation, fold/list/thread toggles, and per-agent filtering | -| `agents` | the Agents tab (bare `nitro agent`, `A` to switch) | the fixture's remote agent session and detail pane | +| `mail-board` | the Mail tab's actor-less Workspace mailbox (bare `nitro agent`, `]` to switch) | the read-only thread table, per-agent filtering, and the Enter thread popover | +| `agents` | the Agents tab (bare `nitro agent`, `A` to switch) | the unified agent table's presence states and header counts, and the Enter detail popover | +| `memory-board` | the Memory tab (bare `nitro agent`, `E` to switch) | the curated/journal table, the kind filter, and the Enter entry popover | `help` is a trivial smoke flow that proves the pipeline itself, independently of the fixture-backed flows below it. It asks for help on @@ -57,14 +58,40 @@ The `mail-*` flows are a handful of representative mail flows, not exhaustive per-command coverage (that is the unit tier's job): `mail-send` runs live against a copy of the shared fixture (register two actors via the root `nitro agent register` command -(one with `--role`), send with `--cc`, inbox as the recipient, read with -`--thread` after a reply), so its ids and dates need the `mail-send` -SCRUBS entry in [`run.sh`](run.sh); `mail-board` runs against the shared +(one with `--role`), list them with `nitro agent list` to check the unified +agent table's shape, send with `--cc`, inbox as the recipient, read with +`--thread` after a reply), so its ids, dates, and one live agent's relative +age need the `mail-send` SCRUBS entry in [`run.sh`](run.sh); `mail-board` +runs against the shared seeded fixture ([`fixtures/mail-seed.sql`](fixtures/mail-seed.sql)) with timestamps fixed far enough in the past that the board's age column always renders a fixed date, so it needs no SCRUBS entry. Mail commands need no auth, they never call the Nitro backend. +`agents` runs against the same shared fixture, extended by +[`fixtures/agents-seed.sql`](fixtures/agents-seed.sql) to put its agents +into the three states `AgentStateResolver` derives from a row (Online, +Unreachable, Offline) and add a fourth, already soft-deleted agent that +must never appear. The Online one is a fresh name with no mail or task +history, not one of `mail-seed.sql`'s three message participants, since +giving one of those a harness would also change mail-board-flow's own +committed golden (see `fixtures/agents-seed.sql`'s header). Online is +also a live, time-windowed state with no way to pin it to a past timestamp +the way every other fixture value here is, so its last_seen_at is +refreshed to the real current time at fixture-prepare time instead, and +the resulting relative age needs its own `agents` SCRUBS entry in +[`run.sh`](run.sh), the same reason `mail-send` needs one for the agent it +registers live. + +`memory-board` runs against the same shared fixture, extended by +[`fixtures/memory-seed.sql`](fixtures/memory-seed.sql) with two curated +memories and one journal entry, at the same fixed-past timestamps as +`mail-seed.sql`'s messages, so it too needs no SCRUBS entry. The Memory tab +shows every entry in the workspace, so its rows sit alongside the three +journal entries `agents-seed.sql` already seeds for `nora`; see +`memory-seed.sql`'s own header for the resulting combined row counts. +Memory commands need no auth, they never call the Nitro backend. + Keep `MARKERS`/`ALL_FLOWS` in [`run.sh`](run.sh) in sync with the tape set as flows are added. diff --git a/src/Nitro/CommandLine/test/e2e/agent-root-flow.gif b/src/Nitro/CommandLine/test/e2e/agent-root-flow.gif index 306d070c04c..688deef46cb 100644 Binary files a/src/Nitro/CommandLine/test/e2e/agent-root-flow.gif and b/src/Nitro/CommandLine/test/e2e/agent-root-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/agent-root-flow.tape b/src/Nitro/CommandLine/test/e2e/agent-root-flow.tape index a1e6a2134cd..c13bd076b70 100644 --- a/src/Nitro/CommandLine/test/e2e/agent-root-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/agent-root-flow.tape @@ -42,7 +42,7 @@ Type `nitro agent` Enter # Initial frame: same sentinel as board-flow.tape's first Wait+Screen (the # Tasks tab's board, focus on "Blocked", selection on acme-a1b), now with # the tab strip rendered above it. -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ # 'q' requests quit; the shell renders the "Quit? (y/n)" confirmation dialog. Type "q" diff --git a/src/Nitro/CommandLine/test/e2e/agents-flow.gif b/src/Nitro/CommandLine/test/e2e/agents-flow.gif index 065bde8e0f8..032023b5d36 100644 Binary files a/src/Nitro/CommandLine/test/e2e/agents-flow.gif and b/src/Nitro/CommandLine/test/e2e/agents-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/agents-flow.golden.txt b/src/Nitro/CommandLine/test/e2e/agents-flow.golden.txt index 4e7b7714bdc..f5374aae58a 100644 --- a/src/Nitro/CommandLine/test/e2e/agents-flow.golden.txt +++ b/src/Nitro/CommandLine/test/e2e/agents-flow.golden.txt @@ -1,35 +1,35 @@ [T]asks [M]ail [A]gents M[e]mory -โ•ญโ”€Agents (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญโ”€bobโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ > bob โ—‡ claude-code started 2026-01-01 hโ€ฆ โ”‚โ”‚ Session โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ Actor: bob โ”‚ -โ”‚ โ”‚โ”‚ Role: - โ”‚ -โ”‚ โ”‚โ”‚ State: remote โ”‚ -โ”‚ โ”‚โ”‚ Harness: claude-code โ”‚ -โ”‚ โ”‚โ”‚ Session id: e2e-remote-session โ”‚ -โ”‚ โ”‚โ”‚ Host: e2e-remote-host-fixture โ”‚ -โ”‚ โ”‚โ”‚ Cwd: /tmp/remote-cwd โ”‚ -โ”‚ โ”‚โ”‚ Workspace: /tmp/remote-workspace โ”‚ -โ”‚ โ”‚โ”‚ Endpoint: none โ”‚ -โ”‚ โ”‚โ”‚ Started: 2026-01-01 06:00 โ”‚ -โ”‚ โ”‚โ”‚ Last heard: 2026-01-01 06:00 โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ Identity โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ Name: bob โ”‚ -โ”‚ โ”‚โ”‚ Role: - โ”‚ -โ”‚ โ”‚โ”‚ Client: - โ”‚ -โ”‚ โ”‚โ”‚ Implicit: no โ”‚ -โ”‚ โ”‚โ”‚ Registered: 2026-01-01 07:00 โ”‚ -โ”‚ โ”‚โ”‚ Last seen: 2026-01-01 07:00 โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ Sent mail โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ 2026-01-01 Billing review -> e2e-agent, aliโ€ฆ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ -hjkl move enter open r refresh y copy id z zoom esc back q quit [ ] shift+letter tab +โ•ญโ”€Agents (1 online / 4)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ +โ”‚ โ”‚ +โ”‚ NAME ROLE HARNESS STARTED LAST SEEN โ”‚ +โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ +โ”‚ > โ— nora planner Claude Code 2026-01-01 AG ago โ”‚ +โ”‚ โ— alice - - 2026-01-01 AG ago โ”‚ +โ”‚ โ— bob - - 2026-01-01 2026-01-01 โ”‚ +โ”‚ โ— e2e-agent - - 2026-01-01 AG ago โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ +hjkl move enter open d delete D delete offline y copy id r refresh / search โ€ฆ diff --git a/src/Nitro/CommandLine/test/e2e/agents-flow.tape b/src/Nitro/CommandLine/test/e2e/agents-flow.tape index 4fdca190ee9..6cedff9f1ec 100644 --- a/src/Nitro/CommandLine/test/e2e/agents-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/agents-flow.tape @@ -1,31 +1,64 @@ -# End-to-end recording of the Agents tab: the registered agent list next to -# its detail pane, keystroke-driven, against the deterministic fixture -# workspace (fixtures/seed.sql + fixtures/mail-seed.sql + fixtures/agents-seed.sql, -# all in the one out/fixture/acme agents.db), mirroring board-flow.tape's/ -# mail-board-flow.tape's structure. +# End-to-end recording of the Agents tab: the unified agent table, its +# presence bubbles and header counts, and the Enter detail popover, against +# the deterministic fixture workspace (fixtures/seed.sql + mail-seed.sql + +# agents-seed.sql, all in the one out/fixture/acme agents.db), mirroring +# board-flow.tape's/mail-board-flow.tape's structure. # # Launched via bare `nitro agent`, landing on the Tasks tab first (the same # first frame board-flow.tape and mail-board-flow.tape both assert), then # Shift+A (TabSwitchKeys.ResolveMnemonic, the tab strip's [A]gents mnemonic) # jumps straight to Agents. # -# Presence badges use one glyph per AgentRowBadge.PresenceGlyph: offline, -# online, unreachable, or remote. The list is built from AgentsState.RefreshAsync -# calling AgentSessionRegistry.ListParticipantsAsync, one row per live -# agent_sessions row (harness, session id), not one row per registered -# agent: an agent with no session row simply has no participant row and so -# never appears in the tab at all, offline or otherwise. The fixture seeds -# exactly one session (bob, remote); alice and e2e-agent, which have no -# session row, are absent from the list entirely (fixtures/agents-seed.sql's -# header explains the remote-vs-live distinction that made bob the one state -# a static SQL fixture can pin byte-stably). +# AgentsMode renders every non-deleted agent as one full-width table +# (AgentRowBadge), sorted Online, then Idle, then Unreachable, then Offline +# (AgentsState.ApplyFilterAndSort). fixtures/agents-seed.sql gives nora that +# Online state (a role, a harness, a live session, a non-'none' endpoint); +# alice and bob are both login-only (no harness/session, endpoint_kind +# 'none'), so both are Unreachable regardless of how stale bob's own beat +# is (AgentStateResolver checks the missing endpoint before the idle +# window), tied and broken by last-seen recency (alice fresh, bob stale); +# e2e-agent is the only Offline row (ended_at set). wren is soft-deleted and +# so never appears in the table's "1 online / 4" header count either (see +# that file's own header for why these four states land on these four +# names, and why the Online one specifically is a fresh name rather than +# one of mail-seed.sql's three message participants). # -# Drives: land on Agents, one row, the fixture's bob (remote) selected by -# default; its detail pane shows the new Session section (session id, host, -# started/last-heard) ahead of Identity, then Sent mail (m-fix006, shared -# with the mail board tape's own fixture data); no Tasks section, since bob -# is nobody's task assignee. Bare `nitro agent` is an actor-less observer and -# does not register its own board session. +# nora is Online and sorts first, so she is also the row Enter opens the +# popover on: AgentPopoverModel loads her identity plus her mail, ticket, +# and memory participation (AgentPopoverView). Her Mail and Tickets +# sections are both empty (she is not a party to any seeded message or +# task), so the cursor starts on Mail's own "show more" row +# (AgentPopoverModel.Locate: an empty section's show-more row is not +# preceded by any item rows) and j walks it past Tickets' equally-empty +# show-more row onto her three seeded memory_journal entries +# (fixtures/agents-seed.sql), listed most recent first. Further j presses +# move the selection down to the third (oldest) entry, where Enter now +# drills into it: a nested, read-only detail view rendered with the Memory +# tab's own renderer (AgentItemDetailMode.ForMemory / MemoryDetailView. +# RenderJournal), and Escape returns to the summary popover with the +# cursor unchanged. From there, j once more lands onto Memory's +# own "show more" row; Enter there opens its full-list view +# (AgentPopoverListMode), rendering all three entries, and j/k move the +# selection inside that list, exercising both the section-to-section +# cursor and the show-more list's own scrolling. The first Escape backs +# out of that list to the summary popover, and the second Escape closes +# the popover entirely, returning to the table. From there, Shift+D +# presses the table's own delete-offline-or-idle binding (AgentsKeyMap's D, +# distinct from the popover's per-agent 'd'), opening the confirmation +# TuiShell.TryOpenAgentDeleteOfflineDialog shows for the one currently +# Offline agent, e2e-agent ("Delete 1 offline or idle agents? This cannot +# be undone."); bob does not count, being Unreachable rather than Offline +# or Idle. A final Escape cancels it: TuiShell's Cancelled branch just +# clears the dialog, so the final frame is the table itself, unchanged. +# +# nora's last_seen_at is refreshed to the real current time by +# agents-seed.sql rather than pinned to a fixture-past timestamp (the state +# this table renders is a live, time-windowed computation with no +# host/PID escape hatch to pin it statically the way the old +# agent_sessions model's `Remote` state could be); the formatted age this +# produces ("just now"/"Nm ago") is normalized by run.sh's own `agents` SCRUBS +# entry before the diff, since it grows with however long a full `run.sh` +# takes to reach this, the last-recorded flow. # # Produces agents-flow.gif + agents-flow.txt. @@ -55,23 +88,72 @@ Type `nitro agent` Enter # Initial frame: the Tasks tab's board (same sentinel as board-flow.tape's # and mail-board-flow.tape's first Wait+Screen). -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ # Shift+A: TabSwitchKeys.ResolveMnemonic jumps straight to the Agents tab. -# The fixture-seeded bob session is the only participant and is selected by -# default. Bare `nitro agent` does not add a session row. Type "A" -Wait+Screen@30s /Agents \(1\)/ -Wait+Screen@30s /โ”€bobโ”€/ -Wait+Screen@30s /bob\s+โ—‡/ -Wait+Screen@30s /Session/ -Wait+Screen@30s /Host: e2e-remote-host-fixture/ - -# bob is nobody's task assignee, so the Tasks section is omitted entirely -# (AgentDetailBody.Build drops an empty section, header included) - the -# detail pane goes straight from Identity to Sent mail. -Wait+Screen@30s /Name: bob/ -Wait+Screen@30s /Billing review/ +Wait+Screen@30s /Agents \(1 online \/ 4\)/ + +# Sorted Online first: nora (role, harness) is the selected top row. +Wait+Screen@30s /nora\s+planner\s+Claude Code/ + +# Enter opens the detail popover for the selected (Online) agent. +Enter +Wait+Screen@30s /State: โ— Online/ +Wait+Screen@30s /Role: planner/ +Wait+Screen@30s /Harness: claude-code 2\.4\.1/ +Wait+Screen@30s /Session id: e2e-online-session/ + +# The cursor starts on Mail's own "show more" row (nora has no mail at +# all, so that row is the first selectable one). j moves it past the +# equally-empty Tickets show-more row onto Memory's three seeded journal +# entries, most recent first. +Type "j" +Type "j" +Wait+Screen@30s /journal\s+2026-01-01\s+Fusion warnings are non-fatal\./ + +# j walks the cursor down through the second entry to the third (oldest). +Type "j" +Type "j" + +# Enter drills into the selected journal entry: a nested, read-only detail +# view rendered with the Memory tab's own renderer. +Enter +Wait+Screen@30s /Prefer small PRs over big changes\./ +Wait+Screen@30s /Created: 2026-01-01/ + +# Esc returns to the summary popover with the cursor unchanged. +Escape +Wait+Screen@30s /State: โ— Online/ + +# j once more lands on Memory's own "show more" row; Enter opens its full +# list view. +Type "j" +Enter +Wait+Screen@30s /Memory \(3\)/ +Wait+Screen@30s /Prefer small PRs over big changes\./ + +# j/k move the selection inside the full list itself. +Type "j" +Type "k" + +# Esc backs out of the show-more list to the summary popover. +Escape +Wait+Screen@30s /State: โ— Online/ + +# Esc again closes the popover entirely, back on the table. +Escape +Wait+Screen@30s /Agents \(1 online \/ 4\)/ + +# Shift+D opens the table-level delete-offline-or-idle confirmation +# (distinct from the popover's per-agent 'd'), counting only e2e-agent +# (bob is Unreachable, not Offline or Idle); Esc cancels it, returning to +# the table. +Type "D" +Wait+Screen@30s /Delete 1 offline or idle agents\? This cannot be undone\./ +Escape +Wait+Screen@30s /Agents \(1 online \/ 4\)/ +Wait+Screen@30s /> โ— nora/ Sleep 1500ms Screenshot agents-flow-final.png diff --git a/src/Nitro/CommandLine/test/e2e/board-flow.gif b/src/Nitro/CommandLine/test/e2e/board-flow.gif index e780c787883..0f25a8ab38a 100644 Binary files a/src/Nitro/CommandLine/test/e2e/board-flow.gif and b/src/Nitro/CommandLine/test/e2e/board-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/board-flow.golden.txt b/src/Nitro/CommandLine/test/e2e/board-flow.golden.txt index 5f3fc51981f..3a18d2da293 100644 --- a/src/Nitro/CommandLine/test/e2e/board-flow.golden.txt +++ b/src/Nitro/CommandLine/test/e2e/board-flow.golden.txt @@ -1,35 +1,35 @@ [T]asks [M]ail [A]gents M[e]mory -โ•ญโ”€Blocked (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ โ—‹ [B] P0 acme-a1b Checkout crashes on Safari โ”‚ -โ”‚ โ—‹ [E] P1 acme-epic1 Launch v2 pricing page โ”‚ -โ”‚ โ—‹ [T] P2 acme-epic1.2 Wire up billing API โ”‚ -โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ +Blocked (3) + +Deferred (1) -โ•ญโ”€Deferred (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ โธ [C] P4 acme-e5f Rotate staging API keys โ”‚ +โ•ญโ”€In Progress (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ +โ”‚ โ”‚ +โ”‚ TYPE PRIO ID TITLE โ”‚ +โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ +โ”‚ > โ— task P2 acme-epic1.1 Draft new pricing copy โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - -โ•ญโ”€Ready (0)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - -โ•ญโ”€In Progress (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ > โ— [T] P2 acme-epic1.1 Draft new pricing copy โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - -โ•ญโ”€Closed (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ โœ“ [F] P3 acme-c3d Add dark mode toggle โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ + +Closed (1) hjkl move enter open r refresh y copy id z zoom esc back q quit [ ] shift+letter tab diff --git a/src/Nitro/CommandLine/test/e2e/board-flow.tape b/src/Nitro/CommandLine/test/e2e/board-flow.tape index c15507279ec..f58c36d9c9d 100644 --- a/src/Nitro/CommandLine/test/e2e/board-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/board-flow.tape @@ -3,14 +3,15 @@ # # The board TUI (raw-key event loop, full-screen alternate-screen rendering) # cannot be exercised by the in-process test tier; this is the VHS tier's job. -# Drives column focus (Left/Right) and row selection (Up/Down) across all -# five of the fixture's columns (see fixtures/seed.sql and BoardView.Default), -# syncing every transition on a Wait+Screen sentinel anchored on the -# selection prefix ("> ") next to a literal card title, or (for the empty -# "Ready" column) the focused panel's own box-drawing top border, never on -# Sleep. Fixed geometry (Width/Height below) is the stability lever for this -# full-screen layout: changing it requires `--update` of every board-flow* -# golden. +# Drives column focus (Left/Right) and row selection (Up/Down) across the +# fixture's four non-empty columns (see fixtures/seed.sql and +# BoardView.Default; the empty "Ready" column is hidden, so it is never +# focused), syncing every transition on a Wait+Screen sentinel anchored on +# the selection prefix ("> ") next to a card's glyph, type, priority, id, and +# title cells (tolerant of the table's column padding via " +"), never on +# Sleep. Fixed geometry (Width/Height below) is the stability lever for +# this full-screen layout: changing it requires `--update` of every +# board-flow* golden. # # Column membership below is computed by BoardDataLoader/TaskStore # ComputeBlockedAsync against fixtures/seed.sql, not just each task's own @@ -18,7 +19,7 @@ # (acme-epic1.2), so it lands in "Blocked" (not "Ready"); acme-epic1.2 is # open but blocked by the still-in_progress acme-epic1.1, so it is also in # "Blocked"; acme-a1b is blocked by acme-epic1.2. That leaves the "Ready" -# column empty for this fixture. +# column empty for this fixture, and hidden from the board entirely. # # Launched via bare `nitro agent` so the tab strip # is on screen throughout, and closes by demonstrating the epic's visible @@ -55,55 +56,51 @@ Type `nitro agent` Enter # Initial frame: focus starts on "Blocked" (index 0, 3 cards), selection on # its first row (acme-a1b, P0, sorted ahead of acme-epic1 P1 and # acme-epic1.2 P2). -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ # Down: move selection onto the column's second row (acme-epic1, an epic # blocked by its own open children). Down -Wait+Screen@30s /> โ—‹ \[E\] P1 acme-epic1 Launch v2 pricing page/ +Wait+Screen@30s /> โ—‹ +epic +P1 +acme-epic1 +Launch v2 pricing page/ # Down: onto the third row (acme-epic1.2). Down -Wait+Screen@30s /> โ—‹ \[T\] P2 acme-epic1\.2 Wire up billing API/ +Wait+Screen@30s /> โ—‹ +task +P2 +acme-epic1\.2 +Wire up billing API/ # Up: back onto the second row (acme-epic1). Up -Wait+Screen@30s /> โ—‹ \[E\] P1 acme-epic1 Launch v2 pricing page/ +Wait+Screen@30s /> โ—‹ +epic +P1 +acme-epic1 +Launch v2 pricing page/ # Right: focus "Deferred" (index 1), whose only card is acme-e5f. Right -Wait+Screen@30s /> โธ \[C\] P4 acme-e5f Rotate staging API keys/ - -# Right: focus "Ready" (index 2). Empty for this fixture (both open tasks -# are blocked), so sync on the focused panel's own top border instead of a -# card row. -Right -Wait+Screen@30s /โ•ญโ”€Ready \(0\)โ”€/ +Wait+Screen@30s /> โธ +chore +P4 +acme-e5f +Rotate staging API keys/ # Right: focus "In Progress" (index 3), whose only card is acme-epic1.1. +# The empty "Ready" column (index 2) is hidden, so this single Right press +# moves focus straight past it. Right -Wait+Screen@30s /> โ— \[T\] P2 acme-epic1\.1 Draft new pricing copy/ +Wait+Screen@30s /> โ— +task +P2 +acme-epic1\.1 +Draft new pricing copy/ # Right: focus "Closed" (index 4), whose only card is acme-c3d. Right -Wait+Screen@30s /> โœ“ \[F\] P3 acme-c3d Add dark mode toggle/ +Wait+Screen@30s /> โœ“ +feature +P3 +acme-c3d +Add dark mode toggle/ # Left: back to "In Progress". Left -Wait+Screen@30s /> โ— \[T\] P2 acme-epic1\.1 Draft new pricing copy/ +Wait+Screen@30s /> โ— +task +P2 +acme-epic1\.1 +Draft new pricing copy/ # ']': TabSwitchKeys moves to the next tab (Mail), whose data comes from # the same fixture's mail-seed.sql (see mail-board-flow.tape). MailState -# defaults to the Workspace mailbox, so the list pane -# opens titled "Workspace (5)", not Inbox. +# defaults to the Workspace mailbox, so the table +# opens titled "Mail (5)", not Inbox. Type "]" -Wait+Screen@30s /Workspace \(5\)/ +Wait+Screen@30s /Mail \(5\)/ # '[': back to the Tasks tab. The board's mode stack was never touched while # Mail was active, so the selection is exactly where it was left ("In # Progress", acme-epic1.1). Final state for the golden. Type "[" -Wait+Screen@30s /> โ— \[T\] P2 acme-epic1\.1 Draft new pricing copy/ +Wait+Screen@30s /> โ— +task +P2 +acme-epic1\.1 +Draft new pricing copy/ Sleep 1500ms Screenshot board-flow-final.png diff --git a/src/Nitro/CommandLine/test/e2e/board-maximize-flow.gif b/src/Nitro/CommandLine/test/e2e/board-maximize-flow.gif index 57819aee9fb..4854cac83f7 100644 Binary files a/src/Nitro/CommandLine/test/e2e/board-maximize-flow.gif and b/src/Nitro/CommandLine/test/e2e/board-maximize-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/board-maximize-flow.golden.txt b/src/Nitro/CommandLine/test/e2e/board-maximize-flow.golden.txt index fdf0774054d..5ec11608d3f 100644 --- a/src/Nitro/CommandLine/test/e2e/board-maximize-flow.golden.txt +++ b/src/Nitro/CommandLine/test/e2e/board-maximize-flow.golden.txt @@ -1,34 +1,34 @@ [T]asks [M]ail [A]gents M[e]mory -โ•ญโ”€Blocked (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ โ—‹ [B] P0 acme-a1b Checkout crashes on Safari โ”‚ -โ”‚ โ—‹ [E] P1 acme-epic1 Launch v2 pricing page โ”‚ -โ”‚ โ—‹ [T] P2 acme-epic1.2 Wire up billing API โ”‚ -โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ +Blocked (3) + +Deferred (1) -โ•ญโ”€Deferred (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ โธ [C] P4 acme-e5f Rotate staging API keys โ”‚ +In Progress (1) + +โ•ญโ”€Closed (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ +โ”‚ โ”‚ +โ”‚ TYPE PRIO ID TITLE โ”‚ +โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ +โ”‚ > โœ“ feature P3 acme-c3d Add dark mode toggle โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - -โ•ญโ”€Ready (0)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - -โ•ญโ”€In Progress (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ โ— [T] P2 acme-epic1.1 Draft new pricing copy โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ - -โ•ญโ”€Closed (1)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ > โœ“ [F] P3 acme-c3d Add dark mode toggle โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ diff --git a/src/Nitro/CommandLine/test/e2e/board-maximize-flow.tape b/src/Nitro/CommandLine/test/e2e/board-maximize-flow.tape index 8fe318e421b..141ee9ca62d 100644 --- a/src/Nitro/CommandLine/test/e2e/board-maximize-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/board-maximize-flow.tape @@ -5,12 +5,13 @@ # column at full width with a "/" header suffix (rendered as # " - / ()" by BoardMode.RenderMaximized + # ColumnPane.Render), Right moves which column is maximized, and a second -# 'z' returns to the five-column grid. Every transition syncs on a -# Wait+Screen sentinel anchored on a literal column header (with its +# 'z' returns to the four-column grid (the fixture's empty "Ready" column is +# hidden, so is 4, not the view's full five). Every transition syncs +# on a Wait+Screen sentinel anchored on a literal column header (with its # fixture task count) or card row from fixtures/seed.sql, never on Sleep. # Fixed geometry (Width/Height below) is the stability lever for this # full-screen layout: changing it requires `--update` of every board-flow* -# golden. +# golden. Height matches board-flow.tape. # # Launched via bare `nitro agent`, same as # board-flow.tape, so the tab strip is on screen throughout; this flow's own @@ -42,31 +43,30 @@ Show Type `nitro agent` Enter # Initial frame: five-column grid, focus on "Blocked" (index 0), selection -# on its first row (acme-a1b). -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +# on its first row (acme-a1b); tolerant of the task table's column padding +# via " +". +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ -# z: maximize the focused column ("Blocked", 1 of 5, 3 cards). +# z: maximize the focused column ("Blocked", 1 of 4, 3 cards). The empty +# "Ready" column is hidden, so the visible count is 4, not the view's full +# five (see board-flow.tape's header). Type "z" -Wait+Screen@30s /Blocked - 1\/5 \(3\)/ +Wait+Screen@30s /Blocked - 1\/4 \(3\)/ -# Right: the maximized column follows focus to "Deferred" (2 of 5, 1 card). +# Right: the maximized column follows focus to "Deferred" (2 of 4, 1 card). Right -Wait+Screen@30s /Deferred - 2\/5 \(1\)/ +Wait+Screen@30s /Deferred - 2\/4 \(1\)/ -# Right: "Ready" (3 of 5, 0 cards: both open tasks in this fixture are -# blocked, see board-flow.tape's header). +# Right: "In Progress" (3 of 4, 1 card). The hidden "Ready" column is +# skipped, so this single Right press moves focus straight past it. Right -Wait+Screen@30s /Ready - 3\/5 \(0\)/ +Wait+Screen@30s /In Progress - 3\/4 \(1\)/ -# Right: "In Progress" (4 of 5, 1 card). +# Right: "Closed" (4 of 4, 1 card). Right -Wait+Screen@30s /In Progress - 4\/5 \(1\)/ +Wait+Screen@30s /Closed - 4\/4 \(1\)/ -# Right: "Closed" (5 of 5, 1 card). -Right -Wait+Screen@30s /Closed - 5\/5 \(1\)/ - -# z: restore the five-column grid, still focused on "Closed". Final state +# z: restore the four-column grid, still focused on "Closed". Final state # for the golden: the neighboring "In Progress (1)" column header is visible # again, which only happens outside Maximized layout (Maximized shows one # column). diff --git a/src/Nitro/CommandLine/test/e2e/detail-flow.gif b/src/Nitro/CommandLine/test/e2e/detail-flow.gif index 16c8f6c2742..336182e0b30 100644 Binary files a/src/Nitro/CommandLine/test/e2e/detail-flow.gif and b/src/Nitro/CommandLine/test/e2e/detail-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/detail-flow.tape b/src/Nitro/CommandLine/test/e2e/detail-flow.tape index 2d91e13c615..8e4faedf5ac 100644 --- a/src/Nitro/CommandLine/test/e2e/detail-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/detail-flow.tape @@ -64,7 +64,7 @@ Show Type `nitro agent` Enter # Board's initial frame (same sentinel as board-flow.tape). -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ # '/' into search mode; the pending empty query resolves to all six fixture # tasks on the next tick, ordered by priority then created_at, selection on diff --git a/src/Nitro/CommandLine/test/e2e/fixtures/README.md b/src/Nitro/CommandLine/test/e2e/fixtures/README.md index a3093b584b3..c23ffd4e863 100644 --- a/src/Nitro/CommandLine/test/e2e/fixtures/README.md +++ b/src/Nitro/CommandLine/test/e2e/fixtures/README.md @@ -1,10 +1,10 @@ # Fixture agent workspace -`seed.sql`, `mail-seed.sql`, and `agents-seed.sql` are a deterministic -dataset for the `nitro agent` e2e tapes: task data, mail data, and agent -presence data, applied to the same unified workspace database. IDs, -timestamps, and actors are all hardcoded so a recording that reads this data -is byte-stable across runs, wall-clock time, and machines. +`seed.sql`, `mail-seed.sql`, `agents-seed.sql`, and `memory-seed.sql` are a +deterministic dataset for the `nitro agent` e2e tapes: task data, mail data, +agent presence data, and memory data, applied to the same unified workspace +database. IDs, timestamps, and actors are all hardcoded so a recording that +reads this data is byte-stable across runs, wall-clock time, and machines. ## How run.sh uses it @@ -26,20 +26,25 @@ Before recording any flow, `run.sh` prepares `out/fixture/acme/` on the host that the seed files are out of date. Seed drift against a real schema change is instead caught by the `sqlite3` apply step failing on a missing column and by the `FIXTURE_*_MARKER` guard queries below. -4. Apply `seed.sql`, then `mail-seed.sql`, then `agents-seed.sql`, with the - `sqlite3` CLI against `out/fixture/acme/.nitro/agents/agents.db`. - `seed.sql` (`tasks`/`dependencies`/`labels`/`comments`/`events`/ - `child_counters`) and `mail-seed.sql` (`agents`/`messages`/ - `message_recipients`) insert into disjoint tables, so their own order - does not matter; `agents-seed.sql` (`agent_sessions`) must run after - `mail-seed.sql` since its one row's `agent_name` references a name - `mail-seed.sql` inserts. +4. Apply `seed.sql`, then `mail-seed.sql`, then `agents-seed.sql`, then + `memory-seed.sql`, with the `sqlite3` CLI against + `out/fixture/acme/.nitro/agents/agents.db`. `seed.sql` + (`tasks`/`dependencies`/`labels`/`comments`/`events`/`child_counters`), + `mail-seed.sql` (`agents`/`messages`/`message_recipients`), and + `memory-seed.sql` (`memory_curated`/`memory_journal`) insert into disjoint + tables, so their own order does not matter relative to each other; + `agents-seed.sql` must run after `mail-seed.sql` since it updates two of + the `agents` rows `mail-seed.sql` inserts (`alice`, `e2e-agent`) rather + than inserting them itself, alongside two further agents of its own + (`nora`, `wren`). 5. Guard: run `bin/nitro agent tasks list` inside `out/fixture/acme` and grep for `acme-epic1`, then run `bin/nitro agent mail inbox` (as `e2e-agent`) and grep for `Retro notes`, then run `bin/nitro agent list` and grep for - `bob remote`. If any marker is missing, schema drift is failing fast - here, with a pointer back to this file, instead of surfacing later as a - confusing golden diff inside a tape's `Hide` block. + `planner`, then run `bin/nitro agent memory recent --collection all` and + grep for the id `e2emem00000000000000000001`. If any marker is missing, + schema drift is failing fast here, with a pointer back to this file, + instead of surfacing later as a confusing golden diff inside a tape's + `Hide` block. A tape only ever `cp -r`s the prepared `out/fixture/acme` directory into its own throwaway `/tmp/work`; no task- or mail-mutating command inside a tape's @@ -91,23 +96,57 @@ independent of the wall-clock date a recording actually runs on. ## The agents dataset -One `agent_sessions` row: `bob` bound to a `claude-code` session whose `host` -is the fixed string `e2e-remote-host-fixture`, deliberately foreign to -whatever the recording machine's own instance id resolves to -(`NitroInstanceIdProvider`). `AgentSessionRegistry.ListAsync` renders any -session row on a foreign host as `Remote` unconditionally, with no PID -liveness check at all, unlike `Online`/`Unreachable`, both of which require a -real, live process on the CURRENT host and so cannot be pinned from a static -SQL fixture. `alice` and `e2e-agent` have no session row and so render -`Offline`, the default for zero live sessions. See `agents-seed.sql`'s own -header for the full reasoning. +`agents-seed.sql` refreshes two of the three agents `mail-seed.sql` already +inserted and adds two of its own, to exercise the three states +`AgentStateResolver` derives from a row plus a fourth, already soft-deleted +agent: + +| Name | State | Notes | +| --- | --- | --- | +| `alice` | Unreachable | login-only: no harness, no session, `endpoint_kind` stays `'none'` | +| `bob` | Offline | untouched here; stale `last_seen_at` (mail-seed.sql's own) | +| `e2e-agent` | Offline | `ended_at` set; still usable as the mail/task actor elsewhere in this fixture | +| `nora` | Online | a role, a `claude-code` harness, a live session, a non-`none` endpoint; no mail/task/memory participation | +| `wren` | (never shown) | `deleted_at` set on insert | + +Online and Unreachable both require a `last_seen_at` inside the current +30-minute window (`AgentStateResolver.OnlineWindow`), a live, time-windowed +check with no host/PID escape hatch to pin it from a static SQL fixture the +way the old `agent_sessions` model's `Remote` state could; `alice`'s and +`nora`'s `last_seen_at` are set to SQLite's own `datetime('now')` instead of +a fixture-past timestamp, so they always land inside that window however +long after this file runs a tape actually records. The relative age that +produces is normalized by the `agents` (and `mail-send`) SCRUBS entry in +[`run.sh`](../run.sh) before the diff. The Online state specifically goes to +a fresh name, `nora`, rather than to `alice` or `bob`: both are mail-seed.sql +message participants, and `MailDetailView.AttributeHarness` renders either +one's name with a harness attribution wherever mail-board-flow.tape's own +fixed fixture happens to show it, which would change that flow's committed +golden even though this ticket touches only agents-flow and mail-send-flow. +`nora` and `wren` both sort after `e2e-agent` alphabetically, so neither +shifts mail-board-flow.tape's own agent-filter picker navigation either. See +`agents-seed.sql`'s own header for the full reasoning. + +## The memory dataset + +`memory-seed.sql` inserts two curated memories and one journal entry +directly into `memory_curated`/`memory_journal`, at the same fixed-past +`created_at`/`updated_at` timestamps `mail-seed.sql` uses for its messages, +so the Memory tab's age column is likewise always a fixed `yyyy-MM-dd` +string. Every id is a syntactically valid `MemoryId` (26 lowercase Crockford +base32 characters), the same check a popover load runs before it can render +a row. The Memory tab shows every entry in the workspace, so this file's +three rows sit alongside the three journal entries `agents-seed.sql` already +seeded for `nora`; see `memory-seed.sql`'s own header for the combined +counts memory-board-flow.tape asserts. ## Regenerating after a schema change -`seed.sql`/`mail-seed.sql`/`agents-seed.sql` are plain lists of `INSERT` -statements against `TaskStoreSchema.Create`/`MailStoreSchema.Create`/ -`AgentSessionSchema.Create`; there is no code generator. After changing any -of the three schemas (a new column, a new `NOT NULL` constraint, a renamed +`seed.sql`/`mail-seed.sql`/`agents-seed.sql`/`memory-seed.sql` are plain +lists of `INSERT`/`UPDATE` statements against `TaskStoreSchema.Create`/ +`MailStoreSchema.Create`/`AgentRegistrySchema.Create`/ +`MemoryStoreSchema.Create`; there is no code generator. After changing any +of the four schemas (a new column, a new `NOT NULL` constraint, a renamed table): 1. Bump `AgentDatabase.CurrentVersion` as usual for the production change. @@ -116,9 +155,8 @@ table): string/`NULL` per the column's own default, unless the fixture should exercise the new column specifically). 3. Re-run `./run.sh help` (or any flow). The prepare-fixture step reapplies - both seed files from scratch every run, so a missed column surfaces - immediately as a `sqlite3` constraint error, and the two guard queries - catch a renamed table or column before any tape records against stale - data. + all four seed files from scratch every run, so a missed column surfaces + immediately as a `sqlite3` constraint error, and the guard queries catch + a renamed table or column before any tape records against stale data. 4. To inspect the seeded data directly: `sqlite3 out/fixture/acme/.nitro/agents/agents.db ".dump"`. diff --git a/src/Nitro/CommandLine/test/e2e/fixtures/agents-seed.sql b/src/Nitro/CommandLine/test/e2e/fixtures/agents-seed.sql index 0167080bf0e..49f22cb4f23 100644 --- a/src/Nitro/CommandLine/test/e2e/fixtures/agents-seed.sql +++ b/src/Nitro/CommandLine/test/e2e/fixtures/agents-seed.sql @@ -1,49 +1,112 @@ --- Deterministic agent_sessions fixture for the agents-flow e2e tape (the --- Agents tab's live participant list with presence badges). +-- Deterministic agent-presence fixture for the agents-flow e2e tape (the +-- Agents tab's table, its Enter popover, and `nitro agent list`'s shape). -- --- Applied by run.sh after mail-seed.sql (agent_name references agents.name, --- which mail-seed.sql populates) against the same unified agent workspace --- database seed.sql/mail-seed.sql seed. See fixtures/README.md. +-- Applied by run.sh after mail-seed.sql, which already inserts alice, bob, +-- and e2e-agent as bare `agents` rows (name/registered_at/started_at/ +-- last_seen_at only, every other column left at its schema default: no +-- role, no harness, endpoint_kind 'none'). This file refreshes alice's +-- last_seen_at in place and inserts two further agents, nora and wren. -- --- AgentsState.RefreshAsync builds the tab's rows from --- AgentSessionRegistry.ListParticipantsAsync, which selects from --- agent_sessions only, one row per live session, not one row per --- registered agent. An agent with no session row (e2e-agent, alice in this --- fixture) is therefore not a participant at all and never appears in the --- tab, offline or otherwise; the old per-registered-agent `Offline` (`โ—‹`) --- state no longer applies here. +-- alice, bob, and e2e-agent are also mail-seed.sql's message participants, +-- and MailDetailView.AttributeHarness renders any of them with a non-empty +-- `harness` as "name (harness)" wherever mail-board-flow.tape's fixed +-- fixture happens to show that name (bob as m-fix002's sender, alice as +-- its cc, in the flow's own final frame). Giving either of them a harness +-- would therefore change mail-board-flow's committed golden even though +-- this ticket touches only agents-flow and mail-send-flow, so the one +-- Online state here (a harness, a live session, a non-'none' endpoint) +-- goes to nora, a name with no mail or task participation at all, instead +-- of reusing one of the three. nora and wren both sort after "e2e-agent" +-- alphabetically, so neither shifts mail-board-flow.tape's own agent-filter +-- picker navigation, which counts on "bob" staying its third entry +-- (All agents, alice, bob, e2e-agent, ...). -- --- For the one session row this fixture does seed, presence still resolves --- from the row's `host` column against the CURRENT machine's own instance --- id (NitroInstanceIdProvider, a hash of /etc/machine-id or a generated --- fallback): a row whose host differs from that id renders `Remote` (`โ—‡`) --- unconditionally and is never reaped, since AgentSessionRegistry.ReapAsync --- only ever reaps rows matching the CURRENT host. That also keeps this row --- stable against the heartbeat staleness rule reaping now uses: a --- last_beat_at this old would be swept immediately on the current host. --- `host` below is an arbitrary string that can never coincidentally equal a --- real machine's hashed instance id or generated fallback GUID. +-- alice is the one login-only agent: harness/session_id stay NULL and +-- endpoint_kind stays 'none' (mail-seed.sql's row default); only her +-- last_seen_at is refreshed to SQLite's own datetime('now') rather than a +-- hardcoded past timestamp, so she resolves to Unreachable (recently seen, +-- no endpoint), not Offline, however long after this file runs the +-- agents-flow tape actually records (see run.sh's own `agents` SCRUBS +-- entry for the one piece of her rendering that stays genuinely relative: +-- the formatted age itself). mail-send-flow.tape's own +-- `register --actor alice --role reviewer` overwrites her role in its own +-- throwaway copy of this fixture and never touches harness/session, so +-- that flow's `nitro agent list` step still shows her without one. +-- +-- bob is left untouched here (mail-send-flow.tape's `register --actor bob`, +-- no --role, only touches last_seen_at itself and reports his role as is, +-- so leaving it empty here keeps that flow's existing "Actor 'bob'." +-- output unchanged); his stale last_seen_at does not change his state in +-- the Agents tab, since AgentStateResolver checks the missing endpoint +-- before the idle window, so bob resolves Unreachable just like alice +-- (tied with her there, broken by last-seen recency: alice fresh, bob +-- stale). +-- +-- e2e-agent is the one ended agent: ended_at is set to a fixed past +-- timestamp. AgentStateResolver checks ended_at before last_seen_at at +-- all, so this row renders Offline regardless of how recently it was +-- seen. Its last_seen_at is not a fixture-fixed value: run.sh's own +-- fixture guard (`nitro agent mail inbox --actor e2e-agent`) touches this +-- row on every run.sh invocation and refreshes it to the real current +-- time, so its Last Seen column is covered by the agents SCRUBS entry +-- like nora's and alice's. Ending it does not affect its use as the +-- mail/task actor elsewhere in this fixture: mail send only rejects an +-- unknown or deleted recipient, never an ended one, and no task command +-- reads agent state at all. +-- +-- nora is the one Online agent, with a role: a harness, a session id, and +-- a non-'none' endpoint_kind (AgentStateResolver.Resolve only returns +-- Online when none of "ended", "deleted", or "endpoint_kind = none" hold, +-- alongside a last_seen_at inside its 30-minute online window). Her +-- last_seen_at is likewise computed with datetime('now'). She has memory +-- participation only: the three memory_journal rows below, at fixed past +-- created_at values, and no mail or task participation at all, so +-- agents-flow.tape's own popover walkthrough steps past the empty Mail +-- and Tickets show-more rows before it reaches her populated Memory +-- section and its show-more list. She is the only name here that can +-- carry a harness without perturbing mail-board-flow. +-- +-- wren is the one deleted agent: deleted_at is set on insert, so every +-- non-deleted read excludes her outright, including the mail Workspace +-- mailbox's own agent-filter picker. BEGIN TRANSACTION; -INSERT INTO agent_sessions ( - harness, session_id, agent_name, binding_kind, host, - cwd, workspace_path, endpoint_kind, endpoint_addr, started_at, last_beat_at +UPDATE agents SET + last_seen_at = strftime('%Y-%m-%d %H:%M:%S', 'now') || '.0000000+00:00' +WHERE name = 'alice'; + +UPDATE agents SET + ended_at = '2026-01-02 00:00:00.0000000+00:00' +WHERE name = 'e2e-agent'; + +INSERT INTO agents ( + name, role, harness, harness_version, session_id, cwd, workspace_path, + registered_at, started_at, last_seen_at, endpoint_kind, endpoint_addr ) VALUES ( - 'claude-code', 'e2e-remote-session', 'bob', 'explicit', 'e2e-remote-host-fixture', - '/tmp/remote-cwd', '/tmp/remote-workspace', - 'none', '', '2026-01-01 06:00:00.0000000+00:00', '2026-01-01 06:00:00.0000000+00:00' + 'nora', 'planner', 'claude-code', '2.4.1', 'e2e-online-session', + '/tmp/work/acme', '/tmp/work/acme', + '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00', + strftime('%Y-%m-%d %H:%M:%S', 'now') || '.0000000+00:00', + 'claude-peer', 'peer://e2e-online-session' ); --- The durable identity row for the same session. `nitro agent list` joins --- agent_session_identities to the live agent_sessions row by --- (harness, session_id), so a session seeded without its identity is listed --- as "no session" no matter what agent_sessions holds. -INSERT INTO agent_session_identities ( - harness, session_id, actor, role, actor_revision, created_at, last_seen_at -) VALUES ( - 'claude-code', 'e2e-remote-session', 'bob', '', 1, - '2026-01-01 06:00:00.0000000+00:00', '2026-01-01 06:00:00.0000000+00:00' +INSERT INTO agents (name, registered_at, started_at, last_seen_at, deleted_at) VALUES ( + 'wren', + '2026-01-01 07:00:00.0000000+00:00', + '2026-01-01 07:00:00.0000000+00:00', + '2026-01-01 07:00:00.0000000+00:00', + '2026-01-01 09:00:00.0000000+00:00' ); +-- Memory ids must be syntactically valid per MemoryId.IsValid (exactly 26 +-- lowercase Crockford base32 characters: 0-9 and a-z minus i, l, o, u), the +-- same check MemoryStore.LoadJournalAsync runs via MemoryId.Require before a +-- popover load can render these rows; a human-readable id like 'mj-nora-1' +-- fails that check and surfaces as an "Invalid memory id" ExitException. +INSERT INTO memory_journal (id, body, created_at, created_by) VALUES + ('e2enramemj0000000000000001', 'Prefer small PRs over big changes.', '2026-01-01 08:00:00.0000000+00:00', 'nora'), + ('e2enramemj0000000000000002', 'Staging resets nightly at 02:00 UTC.', '2026-01-01 08:05:00.0000000+00:00', 'nora'), + ('e2enramemj0000000000000003', 'Fusion warnings are non-fatal.', '2026-01-01 08:10:00.0000000+00:00', 'nora'); + COMMIT; diff --git a/src/Nitro/CommandLine/test/e2e/fixtures/mail-seed.sql b/src/Nitro/CommandLine/test/e2e/fixtures/mail-seed.sql index 15848e625e6..5a00e78baf6 100644 --- a/src/Nitro/CommandLine/test/e2e/fixtures/mail-seed.sql +++ b/src/Nitro/CommandLine/test/e2e/fixtures/mail-seed.sql @@ -26,10 +26,10 @@ BEGIN TRANSACTION; -- agents ----------------------------------------------------------------- -- e2e-agent backs the identity-dependent mail command fixtures. -INSERT INTO agents (name, registered_at, last_seen_at) VALUES - ('e2e-agent', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00'), - ('alice', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00'), - ('bob', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00'); +INSERT INTO agents (name, registered_at, started_at, last_seen_at) VALUES + ('e2e-agent', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00'), + ('alice', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00'), + ('bob', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00', '2026-01-01 07:00:00.0000000+00:00'); -- messages ----------------------------------------------------------------- -- Three messages land in e2e-agent's inbox (they are a `to` recipient of diff --git a/src/Nitro/CommandLine/test/e2e/fixtures/memory-seed.sql b/src/Nitro/CommandLine/test/e2e/fixtures/memory-seed.sql new file mode 100644 index 00000000000..1de623250c6 --- /dev/null +++ b/src/Nitro/CommandLine/test/e2e/fixtures/memory-seed.sql @@ -0,0 +1,44 @@ +-- Deterministic memory fixture for the memory-board-flow e2e tape (the +-- Memory tab's table, its kind filter, and the Enter entry popover). +-- +-- Applied by run.sh after mail-seed.sql and agents-seed.sql, against the +-- same unified agent workspace database seed.sql already seeds (schema and +-- PRAGMA user_version come from the real binary, not from this file). +-- Every id, timestamp, and actor here is hardcoded so a recording that +-- reads this data is byte-stable across runs. +-- +-- Every id is a syntactically valid MemoryId (exactly 26 lowercase +-- Crockford base32 characters: 0-9 and a-z minus i, l, o, u), the same +-- check MemoryStore runs via MemoryId.Require before a popover load can +-- render a row; a human-readable id like 'mem-curated-1' fails that check +-- and surfaces as an "Invalid memory id" ExitException. +-- +-- All timestamps use the exact text format MemoryStore/Microsoft.Data. +-- Sqlite writes for a DateTimeOffset ("yyyy-MM-dd HH:mm:ss.fffffff+00:00"), +-- UTC, on the same fixed date (2026-01-01) mail-seed.sql uses, far enough +-- in the past that AgentAges.Format/MailAges.Format always land in their +-- "week or older" branch, independent of the wall-clock date a recording +-- actually runs on, so this flow needs no SCRUBS entry either. +-- +-- Two curated memories (e2emem...0001, a fact; e2emem...0002, a decision) +-- and one journal entry (e2emem...0003). The Memory tab shows every entry +-- in the workspace, not just this file's own: agents-seed.sql (applied +-- just before this file, to the same shared fixture) already seeds three +-- journal entries for `nora`, so the table's default "All" view totals six +-- rows ("Memory (6)"), and the Journal filter totals four ("Journal (4)"), +-- with this file's own entry sorting third among them (its created_at ties +-- one of nora's, broken by id: "e2emem..." sorts before "e2enramemj..."). +-- See memory-board-flow.tape's own header for the full row-order reasoning. +-- Neither curated row's updated_at differs from its created_at, so the +-- popover's optional "Updated" field never renders for either. + +BEGIN TRANSACTION; + +INSERT INTO memory_curated (id, type, body, created_at, updated_at, created_by) VALUES + ('e2emem00000000000000000001', 'fact', 'Ops runbook lives at docs/ops.md.', '2026-01-01 09:00:00.0000000+00:00', '2026-01-01 09:00:00.0000000+00:00', 'alice'), + ('e2emem00000000000000000002', 'decision', 'Ship database migrations before app code.', '2026-01-01 10:00:00.0000000+00:00', '2026-01-01 10:00:00.0000000+00:00', 'bob'); + +INSERT INTO memory_journal (id, body, created_at, created_by) VALUES + ('e2emem00000000000000000003', 'Follow up on the flaky checkout test.', '2026-01-01 08:00:00.0000000+00:00', 'e2e-agent'); + +COMMIT; diff --git a/src/Nitro/CommandLine/test/e2e/mail-board-flow.gif b/src/Nitro/CommandLine/test/e2e/mail-board-flow.gif index 2aa679c5e02..39861262fba 100644 Binary files a/src/Nitro/CommandLine/test/e2e/mail-board-flow.gif and b/src/Nitro/CommandLine/test/e2e/mail-board-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/mail-board-flow.golden.txt b/src/Nitro/CommandLine/test/e2e/mail-board-flow.golden.txt index 193af00f6e3..fde73b9991c 100644 --- a/src/Nitro/CommandLine/test/e2e/mail-board-flow.golden.txt +++ b/src/Nitro/CommandLine/test/e2e/mail-board-flow.golden.txt @@ -1,35 +1,35 @@ [T]asks [M]ail [A]gents M[e]mory -โ•ญโ”€Workspace: bob (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญโ”€m-fix002 Billing reviewโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ -โ”‚ From To Suโ€ฆ Age โ”‚โ”‚ From: bob โ”‚ -โ”‚ > bob e2e-agent+1 Biโ€ฆ 2026-01-01 โ”‚โ”‚ To: e2e-agent โ”‚ -โ”‚ e2e-agent bob Stโ€ฆ 2026-01-01 โ”‚โ”‚ Cc: alice โ”‚ -โ”‚ alice bob Deโ€ฆ 2026-01-01 โ”‚โ”‚ Date: 2026-01-01 10:00 โ”‚ -โ”‚ โ”‚โ”‚ e2e-agent: read 2026-01-02 08:00 โ”‚ -โ”‚ โ”‚โ”‚ alice: unread โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ Needs review before merge. โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ”‚ โ”‚โ”‚ โ”‚ -โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ -hjkl move tab switch pane enter focus detail y copy id f filter t thread โ€ฆ +โ•ญโ”€Mail: bob (3)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ +โ”‚ โ”‚ +โ”‚ SUBJECT FROM TO MESSAGES LAST ACTIVITY โ”‚ +โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ +โ”‚ > Billing review bob e2e-agent+1 1 2026-01-01 โ”‚ +โ”‚ Standup notes e2e-agent bob 1 2026-01-01 โ”‚ +โ”‚ Deploy window alice bob 1 2026-01-01 โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ +hjkl move enter open p filter agent / search y copy id r refresh esc back q quit โ€ฆ diff --git a/src/Nitro/CommandLine/test/e2e/mail-board-flow.tape b/src/Nitro/CommandLine/test/e2e/mail-board-flow.tape index e382fd01b16..3c939262004 100644 --- a/src/Nitro/CommandLine/test/e2e/mail-board-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/mail-board-flow.tape @@ -3,9 +3,10 @@ # the board observes the Workspace mailbox and refuses identity-dependent # writes or Inbox/Sent jumps. # -# The flow covers the Workspace thread list, the read-only footer, row -# selection, fold expansion, flat list mode, the detail thread toggle, and -# the per-agent Workspace filter. Fixed fixture timestamps keep every rendered +# The flow covers the Mail tab's full-width thread table (one row per thread: +# subject, from, to, message count, and last-activity columns), the per-agent +# Workspace filter, and the Enter thread popover (mirroring board-flow.tape's/ +# agents-flow.tape's structure). Fixed fixture timestamps keep every rendered # age deterministic, so this flow needs no SCRUBS entry. # Produces mail-board-flow.gif + mail-board-flow.txt. @@ -34,33 +35,13 @@ Show Type `nitro agent` Enter # Initial frame: the Tasks tab's board. -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ -# Move to Mail. Actor-less boards always open the read-only Workspace mailbox. +# Move to Mail. Actor-less boards always open the read-only Workspace mailbox, +# rendered as one full-width table of every thread (MailTable/MailMode). Type "]" -Wait+Screen@30s /Workspace \(5\)/ -Wait+Screen@30s /From\s+To\s+Age/ -Wait+Screen@30s /f filter/ - -# Select the "Retro notes" thread. -Down -Down -Wait+Screen@30s /Thread: Retro notes/ - -# Expand the selected thread in the list pane. -Type "z" -Type "o" -Wait+Screen@30s />\s+โ–พ/ -Wait+Screen@30s /โ””\s+alice/ -Wait+Screen@30s /โ””\s+e2e-agent\s+alice/ - -# Switch from five thread rollups to the six-message flat stream. -Type "V" -Wait+Screen@30s /Workspace \(6\)/ - -# Toggle the selected message's detail pane to its full thread. -Type "t" -Wait+Screen@30s /Notes are attached, take a look\./ +Wait+Screen@30s /Mail \(5\)/ +Wait+Screen@30s /SUBJECT\s+FROM\s+TO\s+MESSAGES\s+LAST ACTIVITY/ # Filter the Workspace mailbox to bob. The picker is ordered as All agents, # alice, bob, e2e-agent, so bob is two rows below the default selection. @@ -69,7 +50,19 @@ Wait+Screen@30s /Filter by agent/ Down Down Enter -Wait+Screen@30s /Workspace: bob \(3\)/ +Wait+Screen@30s /Mail: bob \(3\)/ + +# Enter opens the first (and, sorted by last activity, most recent) row's +# thread in a read-only popover: the subject as its title, a Participants +# header field, and the thread's messages oldest first. +Enter +Wait+Screen@30s /Billing review/ +Wait+Screen@30s /Participants:/ +Wait+Screen@30s /Needs review before merge\./ + +# Esc closes the popover, back on the filtered table. +Escape +Wait+Screen@30s /Mail: bob \(3\)/ Sleep 1500ms Screenshot mail-board-flow-final.png diff --git a/src/Nitro/CommandLine/test/e2e/mail-send-flow.gif b/src/Nitro/CommandLine/test/e2e/mail-send-flow.gif index e0527b1d1ba..8173c6c5261 100644 Binary files a/src/Nitro/CommandLine/test/e2e/mail-send-flow.gif and b/src/Nitro/CommandLine/test/e2e/mail-send-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/mail-send-flow.golden.txt b/src/Nitro/CommandLine/test/e2e/mail-send-flow.golden.txt index a0a55864cd8..720aa9f86ad 100644 --- a/src/Nitro/CommandLine/test/e2e/mail-send-flow.golden.txt +++ b/src/Nitro/CommandLine/test/e2e/mail-send-flow.golden.txt @@ -2,6 +2,11 @@ $ nitro agent register --actor alice --role reviewer โœ“ Actor 'alice', role 'reviewer'. $ nitro agent register --actor bob โœ“ Actor 'bob'. +$ nitro agent list +nora planner Claude Code 2026-01-01 AG yes +alice reviewer - 2026-01-01 AG no +bob - - 2026-01-01 AG no +e2e-agent - - 2026-01-01 AG no $ nitro agent mail send --to bob --actor alice --cc alice --subject Status --body All-good โœ“ Sent 'm-XXX' to bob, alice. $ nitro agent mail inbox --actor bob diff --git a/src/Nitro/CommandLine/test/e2e/mail-send-flow.tape b/src/Nitro/CommandLine/test/e2e/mail-send-flow.tape index 47e35472e3c..d9baf004138 100644 --- a/src/Nitro/CommandLine/test/e2e/mail-send-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/mail-send-flow.tape @@ -61,6 +61,25 @@ Type `export PATH=/src/src/Nitro/CommandLine/test/e2e/bin:$PATH` Enter Type `export HOME=/tmp/home` Enter Type `mkdir -p "$HOME"` Enter Type `rm -rf /tmp/work && mkdir -p /tmp/work && cp -r /vhs/fixture/acme /tmp/work/acme && cd /tmp/work/acme` Enter +# `nitro agent list` (ListAgentCommand.Order) breaks ties between agents in +# the same state by their last-seen time floored to a clock-aligned 5-minute +# window, then by name (see AgentStateResolver.LastSeenWindowStart). The two +# live `register` calls below each touch last_seen_at to the real wall clock +# at the instant they run, so if they straddle a window boundary (e.g. one +# lands at 10:04:59, the next at 10:05:00) bob's newer window would sort him +# ahead of alice, flipping the two rows the `list` step asserts and failing +# the golden on an unlucky run. Shadow `nitro` with a function that, after +# every real `agent register`, pins both agents' last_seen_at to one +# identical timestamp computed once and written in a single statement, so +# both get the exact same value regardless of the real elapsed time between +# the two registrations, forcing the tie back onto name order every run. +# `command nitro` still resolves the real binary via the PATH exported +# above. The VHS image has no `sqlite3` CLI, only `python3`'s stdlib +# `sqlite3` module; the written format matches the `Microsoft.Data.Sqlite`- +# persisted `DateTimeOffset` text fixtures/agents-seed.sql already uses for +# the same column. This lives in the hidden setup, not the visible demo, so +# `register`'s own printed output (and the recorded frame) is unaffected. +Type `nitro() { command nitro "$@"; local rc=$?; if [ "$1 $2" = "agent register" ]; then python3 -c 'import sqlite3, datetime; now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + ".0000000+00:00"; c = sqlite3.connect(".nitro/agents/agents.db"); c.execute("UPDATE agents SET last_seen_at = ? WHERE name IN (?, ?)", (now, "alice", "bob")); c.commit()'; fi; return $rc; }` Enter Type `clear` Enter Show @@ -77,6 +96,20 @@ Type `nitro agent register --actor bob` Enter Wait+Screen@30s /Actor 'bob'/ Sleep 500ms +# The new unified `agents` table's list shape (ListAgentCommand): one line +# per agent, Name/Role/Harness/Started/Last seen/Online columns. Neither +# actor here has a harness or a live session (register only ever sets role +# and touches last_seen_at), so both are Unreachable ("no"); this step only +# asserts their two rows, not the full listing, since fixtures/agents- +# seed.sql's own Online agent (nora, an Online "yes" row here too) and +# stale-offline bob also show up in this same shared fixture (see that +# file's header for why the Online one is a name with no mail history +# rather than alice or bob). +Type `nitro agent list` Enter +Wait+Screen@30s /alice\s+reviewer\s+-\s+\S+\s+\S+\s+no/ +Wait+Screen@30s /bob\s+-\s+-\s+\S+\s+\S+\s+no/ +Sleep 500ms + # Send from alice to bob, cc'ing alice itself so the run exercises # --cc without needing a third registered actor. Type `nitro agent mail send --to bob --actor alice --cc alice --subject Status --body All-good` Enter @@ -89,8 +122,14 @@ Sleep 500ms # Captures the id from bob's own inbox listing (its first column, see # MailInboxRow.Format) rather than from the send command's own output. +# This spawns its own nitro process inside the substitution, so it needs a +# longer settle than the single Sleep 500ms every other step here uses: +# typing the next line before this one's inbox+awk pipeline actually +# returns races the still-running foreground command, corrupting the +# prompt redraw (the same class of race the header comment above warns +# about, just with a slower command behind it). Type `MSG_ID=$(nitro agent mail inbox --actor bob | awk 'NR==1{print $1}')` Enter -Sleep 500ms +Sleep 2000ms Type `echo "captured $MSG_ID"` Enter Wait+Screen@30s /captured m-/ Sleep 500ms diff --git a/src/Nitro/CommandLine/test/e2e/memory-board-flow.gif b/src/Nitro/CommandLine/test/e2e/memory-board-flow.gif new file mode 100644 index 00000000000..8f08ffbcaf7 Binary files /dev/null and b/src/Nitro/CommandLine/test/e2e/memory-board-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/memory-board-flow.golden.txt b/src/Nitro/CommandLine/test/e2e/memory-board-flow.golden.txt new file mode 100644 index 00000000000..83d6708c8b8 --- /dev/null +++ b/src/Nitro/CommandLine/test/e2e/memory-board-flow.golden.txt @@ -0,0 +1,35 @@ + [T]asks [M]ail [A]gents M[e]mory +โ•ญโ”€Journal (4)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ +โ”‚ โ”‚ +โ”‚ KIND TYPE TAGS AGE โ”‚ +โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ +โ”‚ journal - - 2026-01-01 โ”‚ +โ”‚ journal - - 2026-01-01 โ”‚ +โ”‚ > journal - - 2026-01-01 โ”‚ +โ”‚ journal - - 2026-01-01 โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ”‚ โ”‚ +โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ +hjkl move enter open f all/curated/journal / search y copy id r refresh esc back โ€ฆ diff --git a/src/Nitro/CommandLine/test/e2e/memory-board-flow.tape b/src/Nitro/CommandLine/test/e2e/memory-board-flow.tape new file mode 100644 index 00000000000..e6c131d4b81 --- /dev/null +++ b/src/Nitro/CommandLine/test/e2e/memory-board-flow.tape @@ -0,0 +1,94 @@ +# End-to-end recording of the Memory tab: the unified curated/journal table, +# its kind filter, and the Enter entry popover, against the deterministic +# fixture workspace (fixtures/seed.sql + mail-seed.sql + agents-seed.sql + +# memory-seed.sql), mirroring board-flow.tape's/mail-board-flow.tape's/ +# agents-flow.tape's structure. +# +# Launched via bare `nitro agent`, landing on the Tasks tab first (the same +# first frame every other bare-launch tape asserts), then Shift+E +# (TabSwitchKeys.ResolveMnemonic, the tab strip's M[e]mory mnemonic) jumps +# straight to Memory. +# +# The Memory tab shows every curated memory and journal entry in the +# workspace, not just this flow's own: fixtures/agents-seed.sql (applied to +# the same shared fixture for agents-flow.tape's popover walkthrough) already +# seeds three journal entries for `nora`, so fixtures/memory-seed.sql's own +# two curated memories and one journal entry bring the default "All" view to +# six rows total ("Memory (6)"), not three. 'f' (MemoryState. +# CycleFilterAsync) cycles All -> Curated -> Journal -> All; pressing it +# twice lands on Journal, whose four rows are nora's three plus this flow's +# own ("Journal (4)"), sorted most recent first: nora's two newer entries, +# then this flow's own entry and nora's oldest tie-broken by id ("e2emem..." +# sorts before "e2enramemj..."), so this flow's own entry is the table's +# third Journal row. Two more `j` presses select it; Enter then opens it in +# a read-only popover titled with its own id (MemoryEntryPopoverView. +# BuildHeader), showing "Kind: journal" and its wrapped body; Escape closes +# it, back on the filtered table. +# +# Every fixture timestamp is fixed far enough in the past (2026-01-01) that +# every rendered age lands in AgentAges.Format's/MailAges.Format's "week or +# older" branch, independent of the wall-clock date a recording actually +# runs on, so this flow needs no SCRUBS entry. +# +# Produces memory-board-flow.gif + memory-board-flow.txt. + +Output memory-board-flow.gif +Output memory-board-flow.txt + +Set Shell bash +Set FontSize 18 +Set Width 1100 +Set Height 850 +Set Padding 14 +Set TypingSpeed 50ms +Set CursorBlink false + +# --- setup (hidden) --- +Hide +Type `export PS1="$ "` Enter +Type `export PATH=/src/src/Nitro/CommandLine/test/e2e/bin:$PATH` Enter +Type `export HOME=/tmp/home` Enter +Type `mkdir -p "$HOME"` Enter +Type `rm -rf /tmp/work && mkdir -p /tmp/work && cp -r /vhs/fixture/acme /tmp/work/acme && cd /tmp/work/acme` Enter +Type `clear` Enter +Show + +# --- the demo --- +Type `nitro agent` Enter + +# Initial frame: the Tasks tab's board (same sentinel every other bare-launch +# tape asserts first). +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ + +# Shift+E: TabSwitchKeys.ResolveMnemonic jumps straight to the Memory tab. +Type "E" +Wait+Screen@30s /Memory \(6\)/ +Wait+Screen@30s /KIND\s+TYPE\s+TAGS\s+AGE/ + +# 'f' cycles the kind filter: All -> Curated -> Journal. Pressing it twice +# lands on Journal (nora's three seeded entries plus this flow's own). +Type "f" +Type "f" +Wait+Screen@30s /Journal \(4\)/ + +# This flow's own journal entry is the third Journal row (see header +# comment); two `j` presses move the selection onto it. The table no longer +# shows its body, so the popover below is this step's own assertion that +# the right row was reached. +Type "j" +Type "j" + +# Enter opens the selected row's read-only popover: its own id as the title, +# its Kind field, and its wrapped body. +Enter +Wait+Screen@30s /e2emem00000000000000000003/ +Wait+Screen@30s /Kind: journal/ +Wait+Screen@30s /Follow up on the flaky checkout test\./ + +# Esc closes the popover, back on the filtered table. +Escape +Wait+Screen@30s /Journal \(4\)/ + +Sleep 1500ms +Screenshot memory-board-flow-final.png +Sleep 500ms diff --git a/src/Nitro/CommandLine/test/e2e/run.sh b/src/Nitro/CommandLine/test/e2e/run.sh index c7f49924e9b..505443c76ce 100755 --- a/src/Nitro/CommandLine/test/e2e/run.sh +++ b/src/Nitro/CommandLine/test/e2e/run.sh @@ -53,16 +53,22 @@ declare -A MARKERS=( [close-reopen]="Reopened task 'acme-a1b'." [dep-tree]="acme-epic1.1" [error]="[nitro exit: 1]" - [board]="> โ— [T] P2 acme-epic1.1 Draft new pricing copy" + # The board's task table pads TYPE to a minimum of 8 cells (the type name + # spelled out) and PRIO to a constant 4 cells, and gutters every column + # with 4 spaces, so the 10 spaces before "P2" and the 4 before + # "acme-epic1.1" are exact regardless of which other tasks share this + # fixture's "In Progress" column. + [board]="> โ— task P2 acme-epic1.1 Draft new pricing copy" [board-maximize]="In Progress (1)" [search]="> โ— parent-child <-" [detail]="acme-epic1 ยท blocking ยท depended on by" [mail-send]="Thanks-noted" [mail-error]="[nitro exit: 1]" - [mail-board]="Workspace: bob (3)" - [agents]="Billing review" + [mail-board]="Mail: bob (3)" + [agents]="Agents (1 online / 4)" + [memory-board]="Journal (4)" ) -ALL_FLOWS=(help init agent-root list show create close-reopen dep-tree error board board-maximize search detail mail-send mail-error mail-board agents) +ALL_FLOWS=(help init agent-root list show create close-reopen dep-tree error board board-maximize search detail mail-send mail-error mail-board agents memory-board) # Per-flow sed expressions (extended regex, `sed -E`) applied to the extracted # frame before it is compared with (or written as) the golden. Empty by default. @@ -72,9 +78,37 @@ ALL_FLOWS=(help init agent-root list show create close-reopen dep-tree error boa # normalize it to a fixed placeholder before diffing. The expression is a # single literal substitution (no alternation/backreferences) so it cannot # fail on a well-formed frame. +# `agents` and `mail-send`'s own `nitro agent list` step both show a live +# agent's `last_seen_at`, refreshed to the real current time by +# fixtures/agents-seed.sql (for `agents` to render Online/Unreachable +# instead of stale-Offline, see that file's header) or by `register` +# touching the row (for `mail-send`). Both render an age that grows with +# however long the run takes to reach that flow, so it is normalized to a +# fixed placeholder before diffing rather than pinned to a literal fixture +# value the way every other timestamp in these fixtures is. `agents`'s TUI +# rendering (AgentRowBadge/AgentPopoverView) shows "just now" for a fresh +# timestamp, "N[mh] ago" for a relative one (e.g. "3m ago", "12h ago"), or +# a bare date with no suffix once it is a week or more old; `mail-send`'s +# `nitro agent list` line instead shows the unsuffixed "now"/"3m"/"2h" and +# is anchored on the Online column ("yes"/"no") that always follows it, so +# it cannot also match the deterministic "now" the same line's `mail inbox` +# step prints for a just-sent message's own age. Both contexts pad this +# value to a width computed from the real pre-scrub text (the popover +# panel's own fixed border; `PadRight` against the widest column value for +# the CLI table), so every substitution below keeps that padded span's +# total length exactly what it was: for `agents`, "just now" is 8 +# characters and becomes "AG ago ", a 2-digit unit plus " ago" (e.g. +# "12m ago") is 7 characters and becomes "AG ago ", and a 1-digit unit +# plus " ago" (e.g. "3m ago") is 6 characters already and becomes +# "AG ago" alone. Getting this wrong still passes a same-run diff (both +# sides of that recording agree with themselves) but fails the next run +# the instant the live clock crosses a digit-count boundary a `--update` +# run didn't happen to land on. declare -A SCRUBS=( [create]='s/acme-[a-z0-9.]+/acme-XXX/g' - [mail-send]='s/m-[a-z0-9]+/m-XXX/g; s/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}/DATE/g' + [mail-send]='s/m-[a-z0-9]+/m-XXX/g; s/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}/DATE/g; '\ +'s/(now|[0-9]{2}[mh])( +)(yes|no)$/AG \2\3/g; s/([0-9])[mh]( +)(yes|no)$/AG\2\3/g' + [agents]='s/just now/AG ago /g; s/[0-9]{2}[mh] ago/AG ago /g; s/[0-9][mh] ago/AG ago/g' ) # --- args: optional --update plus an optional subset of flow names ------------ @@ -157,7 +191,8 @@ if [[ -z "$FIXTURE_SCHEMA_VERSION" ]]; then fi FIXTURE_TASK_MARKER="acme-epic1" FIXTURE_MAIL_MARKER="Retro notes" -FIXTURE_AGENTS_MARKER="bob remote" +FIXTURE_AGENTS_MARKER="planner" +FIXTURE_MEMORY_MARKER="e2emem00000000000000000001" echo "==> preparing fixture workspace (out/fixture/acme)" rm -rf "$FIXTURE_DIR" @@ -189,7 +224,12 @@ if ! sqlite3 "$FIXTURE_DB" < "$SCRIPT_DIR/fixtures/mail-seed.sql"; then fi if ! sqlite3 "$FIXTURE_DB" < "$SCRIPT_DIR/fixtures/agents-seed.sql"; then echo "==> fixture prepare FAILED: agents-seed.sql did not apply cleanly to $FIXTURE_DB" >&2 - echo " the agent_sessions schema likely drifted from fixtures/agents-seed.sql; see fixtures/README.md" >&2 + echo " the agents schema likely drifted from fixtures/agents-seed.sql; see fixtures/README.md" >&2 + exit 2 +fi +if ! sqlite3 "$FIXTURE_DB" < "$SCRIPT_DIR/fixtures/memory-seed.sql"; then + echo "==> fixture prepare FAILED: memory-seed.sql did not apply cleanly to $FIXTURE_DB" >&2 + echo " the memory schema likely drifted from fixtures/memory-seed.sql; see fixtures/README.md" >&2 exit 2 fi @@ -206,7 +246,13 @@ if ! ( cd "$FIXTURE_DIR" && "$BIN_DIR/nitro" agent mail inbox --actor e2e-agent fi if ! ( cd "$FIXTURE_DIR" && "$BIN_DIR/nitro" agent list ) | grep -q "$FIXTURE_AGENTS_MARKER"; then echo "==> fixture guard FAILED: 'nitro agent list' did not show '$FIXTURE_AGENTS_MARKER'" >&2 - echo " the agent_sessions schema likely drifted from fixtures/agents-seed.sql; see fixtures/README.md" >&2 + echo " the agents schema likely drifted from fixtures/agents-seed.sql; see fixtures/README.md" >&2 + exit 2 +fi +if ! ( cd "$FIXTURE_DIR" && "$BIN_DIR/nitro" agent memory recent --collection all ) \ + | grep -q "$FIXTURE_MEMORY_MARKER"; then + echo "==> fixture guard FAILED: 'nitro agent memory recent' did not show '$FIXTURE_MEMORY_MARKER'" >&2 + echo " the memory schema likely drifted from fixtures/memory-seed.sql; see fixtures/README.md" >&2 exit 2 fi echo " fixture ready, guard passed" @@ -254,9 +300,10 @@ for flow in "${FLOWS[@]}"; do recorded_ok=1 fi - # 3b. Normalize non-deterministic content (task IDs, dates) before compare/update. + # 3b. Portable in-place edit (GNU and BSD sed). if [[ "$recorded_ok" == "1" && -n "${SCRUBS[$flow]:-}" ]]; then - sed -E -i "${SCRUBS[$flow]}" "$frame" + sed -E "${SCRUBS[$flow]}" "$frame" > "$frame.tmp" + mv "$frame.tmp" "$frame" fi # 4. Update or verify. diff --git a/src/Nitro/CommandLine/test/e2e/search-flow.gif b/src/Nitro/CommandLine/test/e2e/search-flow.gif index e622f4dddcc..a06dd775725 100644 Binary files a/src/Nitro/CommandLine/test/e2e/search-flow.gif and b/src/Nitro/CommandLine/test/e2e/search-flow.gif differ diff --git a/src/Nitro/CommandLine/test/e2e/search-flow.tape b/src/Nitro/CommandLine/test/e2e/search-flow.tape index 7e5a5647ee2..aa440fa68bb 100644 --- a/src/Nitro/CommandLine/test/e2e/search-flow.tape +++ b/src/Nitro/CommandLine/test/e2e/search-flow.tape @@ -61,7 +61,7 @@ Type `nitro agent` Enter # Board's initial frame (same sentinel as board-flow.tape): focus starts on # "Blocked", selection on its first row, acme-a1b. -Wait+Screen@30s /> โ—‹ \[B\] P0 acme-a1b Checkout crashes on Safari/ +Wait+Screen@30s /> โ—‹ +bug +P0 +acme-a1b +Checkout crashes on Safari/ # '/' jumps into search mode (TuiShell.HandleMessage FocusSearchRequested), # focus on the query input. The pending query from mode entry (TaskQuery.Empty) diff --git a/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/already-installed.json b/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/already-installed.json index 6b3ea71ede2..dcc526036bb 100644 --- a/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/already-installed.json +++ b/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/already-installed.json @@ -33,6 +33,17 @@ ] } ], + "Notification": [ + { + "hooks": [ + { + "type": "command", + "command": "/home/agent/.dotnet/tools/nitro agent hook claude notification", + "timeout": 10 + } + ] + } + ], "SessionEnd": [ { "hooks": [ diff --git a/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/four-events.json b/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/four-events.json new file mode 100644 index 00000000000..6b3ea71ede2 --- /dev/null +++ b/src/Nitro/CommandLine/test/fixtures/hooks/claude/install/four-events.json @@ -0,0 +1,48 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "/home/agent/.dotnet/tools/nitro agent hook claude session-start", + "timeout": 10 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "/home/agent/.dotnet/tools/nitro agent hook claude user-prompt-submit", + "timeout": 10 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "/home/agent/.dotnet/tools/nitro agent hook claude stop", + "timeout": 10 + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "/home/agent/.dotnet/tools/nitro agent hook claude session-end", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/src/Nitro/CommandLine/test/fixtures/hooks/claude/uninstall/with-foreign.json b/src/Nitro/CommandLine/test/fixtures/hooks/claude/uninstall/with-foreign.json index 09e1dba5cad..7901c27f62e 100644 --- a/src/Nitro/CommandLine/test/fixtures/hooks/claude/uninstall/with-foreign.json +++ b/src/Nitro/CommandLine/test/fixtures/hooks/claude/uninstall/with-foreign.json @@ -42,6 +42,17 @@ ] } ], + "Notification": [ + { + "hooks": [ + { + "type": "command", + "command": "/home/agent/.dotnet/tools/nitro agent hook claude notification", + "timeout": 10 + } + ] + } + ], "SessionEnd": [ { "hooks": [ diff --git a/website/content/docs/nitro/cli/agent-hooks.md b/website/content/docs/nitro/cli/agent-hooks.md index 2da5f7f109b..34ae62c3295 100644 --- a/website/content/docs/nitro/cli/agent-hooks.md +++ b/website/content/docs/nitro/cli/agent-hooks.md @@ -19,7 +19,7 @@ nitro agent hooks opencode install # Claude Code -Claude Code hook entries live in a `settings.json` file and cover four events: `SessionStart`, `UserPromptSubmit`, `Stop`, and `SessionEnd`. Each entry runs `nitro agent hook claude `. The `Stop` entry is a hard gate: it can block the turn from ending, up to three times per turn, until unread mail is read, resetting on the next `UserPromptSubmit`. +Claude Code hook entries live in a `settings.json` file and cover five events: `SessionStart`, `UserPromptSubmit`, `Stop`, `Notification`, and `SessionEnd`. Each entry runs `nitro agent hook claude `. The `Stop` entry is a hard gate: it can block the turn from ending, up to three times per turn, until unread mail is read, resetting on the next `UserPromptSubmit`. The `Notification` entry only refreshes the agent's last-seen time, and only when Claude Code's `notification_type` is `idle_prompt`. `install` and `uninstall` only ever touch the entries Nitro itself owns; hook entries another tool added for the same event are left in place.