using System.Collections.Concurrent; using System.Text.Json; using System.Threading.Channels; using Capacitor.Cli.Core; using Capacitor.Cli.Core.Handoff; using Capacitor.Cli.Core.LocalIpc; using Capacitor.Cli.Daemon.Services; using Microsoft.Extensions.Logging.Abstractions; namespace Capacitor.Cli.Daemon.Tests.Unit.Services; /// /// Captures LaunchFailedAsync calls and no-ops the other server-side methods /// so the orchestrator's launch flow doesn't touch a real SignalR connection. /// sealed class CaptureServerConnection : ServerConnection { readonly DaemonConfig _config; public CaptureServerConnection(DaemonConfig? config = null) : this(config ?? new() { Name = "test", ServerUrl = "http://127.0.0.1:1" }, 0) { } CaptureServerConnection(DaemonConfig config, int _) : base( config, new FixedCredentialSource(), NullLoggerFactory.Instance, NullLogger.Instance, TimeProvider.System) => _config = config; public string? ConnectionIdForTest { get; set; } = "connection-1"; internal override string? CurrentConnectionId => ConnectionIdForTest; readonly List<(string AgentId, string Reason)> _launchFailedCalls = []; /// A snapshot: the orchestrator reports a failed launch from its own tasks, so a test /// reading this while an agent is still winding down must not enumerate a list being appended. public IReadOnlyList<(string AgentId, string Reason)> LaunchFailedCalls { get { lock (_launchFailedCalls) return [.. _launchFailedCalls]; } } /// When set, LaunchFailedAsync still RECORDS the call (so a test can assert the /// send was attempted) but returns a faulted task — for the finalizer's verdict-report /// fault-containment test (a report fault must never skip CleanupAgentAsync/unregister). public Exception? LaunchFailedThrow { get; init; } /// Completed the instant LaunchFailedAsync is entered (after recording the call) — /// lets a test prove the finalizer is genuinely INSIDE its verdict-report await, so a /// concurrent status emitter (reconnect re-registration) can be driven in exactly that /// window. public TaskCompletionSource? LaunchFailedEntered { get; init; } /// When set, LaunchFailedAsync awaits this task before returning — holding the /// finalizer's report open so a concurrent emission can race it deterministically. public TaskCompletionSource? LaunchFailedGate { get; init; } /// When set, EndAgentSessionAsync blocks until this token is cancelled, /// simulating a session-end call stuck waiting for a SignalR reconnect. public CancellationTokenSource? EndSessionBlockUntil { get; init; } /// Reasons passed to EndAgentSessionAsync, in call order. public List EndSessionReasons { get; } = []; int _registerDaemonCalls; /// Full daemon re-registrations requested (the capability self-heal's /// ReRegisterAsync lands here). No-op'd: there is no hub to register with. public int RegisterDaemonCalls => Volatile.Read(ref _registerDaemonCalls); public Exception? RegisterDaemonThrow { get; set; } internal override Task RegisterDaemonAsync(RegistrationAttempt attempt) { Interlocked.Increment(ref _registerDaemonCalls); if (RegisterDaemonThrow is { } ex) return Task.FromException(ex); attempt.Sending(_config.Advertisement); attempt.Accept(); return Task.CompletedTask; } /// The server's answer to each takeover begin, which may throw as the hub would; unset, the server /// lacks the method. public Func? BeginHandoff { get; set; } /// The server's answer to each lease renewal; unset, every renewal succeeds. public Func>? RenewHandoff { get; set; } public ConcurrentQueue<(string Source, string Successor, HandoffTakeoverAdmission? Admission)> HandoffBegins { get; } = new(); public ConcurrentQueue HandoffRenews { get; } = new(); public ConcurrentQueue HandoffEnds { get; } = new(); internal override Task InvokeBeginHandoffTakeoverRawAsync(string source, string successor, CancellationToken ct) { HandoffTakeoverAdmission? admission = null; try { if (BeginHandoff is null) throw new Microsoft.AspNetCore.SignalR.HubException( $"Failed to invoke '{BeginHandoffTakeoverMethod}' due to an error on the server. HubException: Method does not exist."); admission = BeginHandoff(source, successor); } finally { HandoffBegins.Enqueue((source, successor, admission)); } return Task.FromResult(admission); } /// The server's answer to each restart-resume lease begin, which may throw as the hub would; unset, the /// server lacks the method. public Func? BeginResume { get; set; } public ConcurrentQueue ResumeBegins { get; } = new(); /// When set, the lease call never completes, as a server holding the invocation open would. public bool BeginResumeHangs { get; init; } internal override Task InvokeBeginSourceResumeRawAsync(string sessionId, CancellationToken ct) { ResumeBegins.Enqueue(sessionId); if (BeginResumeHangs) return new TaskCompletionSource().Task; return BeginResume is { } answer ? Task.FromResult(answer(sessionId)) : throw new Microsoft.AspNetCore.SignalR.HubException( "Failed to invoke 'BeginSourceResume' due to an error on the server. HubException: Method does not exist."); } public override Task RenewHandoffTakeoverAsync(string token, CancellationToken ct) { HandoffRenews.Enqueue(token); return RenewHandoff?.Invoke(token, ct) ?? Task.FromResult(true); } /// The server's answer to each lease release; unset, every release succeeds. public Func? EndHandoff { get; set; } public override Task EndHandoffTakeoverAsync(string token) { HandoffEnds.Enqueue(token); return EndHandoff?.Invoke(token) ?? Task.CompletedTask; } public override async Task LaunchFailedAsync(string agentId, string reason) { lock (_launchFailedCalls) _launchFailedCalls.Add((agentId, reason)); LaunchFailedEntered?.TrySetResult(); if (LaunchFailedGate is { } gate) await gate.Task.ConfigureAwait(false); if (LaunchFailedThrow is { } ex) throw ex; } /// Every the orchestrator sent, in order — the /// out-of-cycle launch-stage reports as well as any periodic tick. Lets a launch-path test /// inspect what the WIRE carried at each point, which is the only way to observe the /// handshake window (no AgentInstance exists during it). readonly Lock _statusReportGate = new(); readonly List _statusReports = []; public IReadOnlyList StatusReports { get { lock (_statusReportGate) return [.. _statusReports]; } } public int StatusReportCount { get { lock (_statusReportGate) return _statusReports.Count; } } public override Task DaemonStatusReportAsync(DaemonStatusReport report) { lock (_statusReportGate) _statusReports.Add(report); return Task.CompletedTask; } /// Number of times to fail AgentRegisteredAsync before succeeding (drives /// the bounded per-agent re-registration retry test). public int AgentRegisteredFailTimes { get; init; } public int AgentRegisteredCallCount { get; private set; } /// Completed the instant AgentRegisteredAsync is entered — lets a test hold /// re-registration inside that await and publish a verdict there. public TaskCompletionSource? AgentRegisteredEntered { get; set; } /// When set, AgentRegisteredAsync awaits this before returning — holding the /// re-registration open across the AgentRegistered await. public TaskCompletionSource? AgentRegisteredGate { get; set; } /// When set, every non-failure AgentStatusChanged send checks this runtime's verdict /// AT SEND TIME (via the lock-synchronised ReadVerdict); if a launch-window verdict is already /// published, latches true — the exact /// "non-failure status after publication" invariant violation. public ITerminationVerdictSource? VerdictCaptureRuntime { get; set; } public bool NonFailureStatusSentAfterVerdictPublished { get; private set; } /// Every (agentId, model) pair the orchestrator registered — proves the AgentInstance /// the server sees carries the model the process actually runs (the pinned explicit-reviewer /// LaunchModel, not the dispatched cmd.Model). public List<(string AgentId, string? Model)> AgentRegisteredCalls { get; } = []; public List<(string AgentId, string? RepoPath)> AgentRegisteredRepoPaths { get; } = []; /// The applied Codex posture echoed on each registration, in call order — proves the /// initial registration and every reconnect re-registration report the same pair. public List<(string AgentId, string? Sandbox, string? Approval)> AgentRegisteredPostures { get; } = []; /// The runtime transport ("pty" | "app-server") echoed on each registration, in call /// order — proves initial and reconnect re-registration report the same value. public List<(string AgentId, string? Transport)> AgentRegisteredTransports { get; } = []; public List<(string AgentId, string? Vendor)> AgentRegisteredVendors { get; } = []; /// The account each registration named, in call order. public List<(string AgentId, string? Directory, string? AccountId, string? Label)> AgentRegisteredAccounts { get; } = []; /// The start title echoed on each registration, in call order. public List<(string AgentId, AgentStartTitle? Title)> AgentRegisteredTitles { get; } = []; /// The agent each registration says it continues, in call order. public List<(string AgentId, string? ContinuesAgentId)> AgentRegisteredContinues { get; } = []; /// The resumed session and first-announce flag each registration carries, in call order. public List<(string AgentId, string? ResumedSessionId, bool FirstAnnounce)> AgentRegisteredResumes { get; } = []; /// The server's answer per agent id; accepted when unset or null. public Func? RegistrationResponse { get; set; } public override async Task AgentRegisteredAsync( string agentId, string? prompt, string? model, string? effort, string? repoPath, string? sandboxPolicy = null, string? approvalPolicy = null, string? permissionPreset = null, string? runtimeTransport = null, string? vendor = null, AgentStartTitle? title = null, string? continuesAgentId = null, string? accountDirectory = null, string? accountId = null, string? accountLabel = null, string? resumedSessionId = null, bool resumeFirstAnnounce = false) { AgentRegisteredCallCount++; lock (AgentRegisteredRepoPaths) AgentRegisteredRepoPaths.Add((agentId, repoPath)); lock (AgentRegisteredContinues) AgentRegisteredContinues.Add((agentId, continuesAgentId)); lock (AgentRegisteredResumes) AgentRegisteredResumes.Add((agentId, resumedSessionId, resumeFirstAnnounce)); lock (AgentRegisteredTitles) AgentRegisteredTitles.Add((agentId, title)); lock (AcpCallOrder) AcpCallOrder.Add($"register:{agentId}"); lock (AgentRegisteredCalls) AgentRegisteredCalls.Add((agentId, model)); lock (AgentRegisteredPostures) AgentRegisteredPostures.Add((agentId, sandboxPolicy, approvalPolicy)); lock (AgentRegisteredTransports) AgentRegisteredTransports.Add((agentId, runtimeTransport)); lock (AgentRegisteredVendors) AgentRegisteredVendors.Add((agentId, vendor)); lock (AgentRegisteredAccounts) AgentRegisteredAccounts.Add((agentId, accountDirectory, accountId, accountLabel)); AgentRegisteredEntered?.TrySetResult(); if (AgentRegisteredGate is { } gate) await gate.Task.ConfigureAwait(false); if (AgentRegisteredCallCount <= AgentRegisteredFailTimes) throw new InvalidOperationException("transient re-register failure"); return RegistrationResponse?.Invoke(agentId) ?? AgentRegisteredResponse.Accepted; } // ── ACP bind/forward capture ──────────────────────────────────── // Overrides the RAW hub-invoke seams (mirroring AcpServerConnectionTests' TestServerConnection) // rather than the higher-level gated AcpSessionStartedAsync/SendAcpEventsAsync, so every call // still goes through the REAL ConnectionRetry/IsReady gating the production wiring relies on. // IsReady is overridden to true (no real hub connection exists in these tests) so that gating // resolves immediately instead of hanging forever waiting for a connection that never connects. /// Settable so a test can hold the daemon inside its registration bracket. public bool Ready { get; set; } = true; internal override bool IsReady => Ready; /// Every register/bind/events call, in the exact order the orchestrator issued them — /// the single source of truth for the bind-ordering and teardown-ordering assertions. public List AcpCallOrder { get; } = []; public List<(string AgentId, string Vendor, string AcpSessionId, string? Cwd, string? Model)> AcpSessionStartedCalls { get; } = []; public List<(string AgentId, string AcpSessionId, AcpEventEnvelope[] Envelopes)> AcpEventsCalls { get; } = []; /// Fires (unbounded, never blocks the caller) once per AcpSessionEvents call, carrying /// the 1-based call count — lets a test await "the Nth events call happened" deterministically /// instead of guessing with Task.Delay. public Channel AcpEventsCallSignal { get; } = Channel.CreateUnbounded(); /// Overrides the ack a given batch receives; defaults to "fully accepted". public Func? AcpEventsAckOverride { get; init; } /// Set to make the raw AcpSessionEvents invoke hang until this token is cancelled — /// simulates a server call that never returns, for the bounded-final-drain test (mirrors /// EndSessionBlockUntil's pattern). public CancellationTokenSource? AcpEventsBlockUntil { get; init; } /// One-shot gate: when set, the NEXT raw AcpSessionEvents invoke awaits this task /// before returning (then the field is cleared) — lets a test deterministically control /// exactly when one specific events call completes, without racing unrelated background /// work (e.g. CleanupAgentAsync's own worktree removal) that would otherwise let a call /// "eventually" go through regardless of the ordering under test. public TaskCompletionSource? PendingAcpEventsGate { get; set; } /// One-shot gate: when set, the NEXT raw AcpSessionStarted invoke awaits this task /// before returning (then the field is cleared) — models a bind call still in flight across /// a reconnect outage (reliability fix's stale-binding-race test), independent of /// ct so the test controls exactly when the "late bind" resolves. public TaskCompletionSource? PendingAcpBindGate { get; set; } internal override async Task InvokeAcpSessionStartedRawAsync( string agentId, string vendor, string acpSessionId, string? cwd, string? model, IReadOnlyDictionary? metadata, CancellationToken ct ) { lock (AcpCallOrder) { AcpCallOrder.Add($"bind:{agentId}"); AcpSessionStartedCalls.Add((agentId, vendor, acpSessionId, cwd, model)); } if (PendingAcpBindGate is { } gate) { PendingAcpBindGate = null; await gate.Task; } return AcpBindOutcome.Bound; } internal override async Task InvokeAcpSessionEventsRawAsync( string agentId, string acpSessionId, AcpEventEnvelope[] envelopes, CancellationToken ct ) { int callCount; lock (AcpCallOrder) { AcpCallOrder.Add($"events:{agentId}:{string.Join(',', envelopes.Select(e => e.Seq))}"); AcpEventsCalls.Add((agentId, acpSessionId, envelopes)); callCount = AcpEventsCalls.Count; } if (AcpEventsBlockUntil is { } blockCts) { // Linked with ct (unlike a bare blockCts.Token wait) so a per-agent CTS cancellation // propagates through exactly like a real _hub.InvokeAsync(..., cancellationToken: ct) // call would (reliability fix: forwarder-cancel-on-drain-timeout relies on // this). A ct-driven cancellation PROPAGATES (mirrors the real hub); blockCts alone // is purely test cleanup (releases an otherwise-abandoned background call) and falls // through to a normal successful return. using var linked = CancellationTokenSource.CreateLinkedTokenSource(blockCts.Token, ct); try { await Task.Delay(Timeout.InfiniteTimeSpan, linked.Token); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } catch (OperationCanceledException) { /* released by the test (blockCts) */ } } // Not interlocked: the forwarder always has exactly one send in flight at a time (its // single-in-flight-batch design), so this test double never sees concurrent callers. if (PendingAcpEventsGate is { } gate) { PendingAcpEventsGate = null; await gate.Task; } AcpEventsCallSignal.Writer.TryWrite(callCount); return AcpEventsAckOverride?.Invoke(envelopes) ?? (envelopes.Length == 0 ? new AcpBatchAck(-1, -1) : new AcpBatchAck(envelopes[^1].Seq, envelopes[^1].Seq)); } // ── Source-claim / confirm seams ─────────────────────────────────────────────── /// Outcome the raw AcpSessionSourceClaim invoke returns; default Bound@token-1. A Rejected /// outcome models the server declining ownership. public AcpSourceClaimOutcome? SourceClaimOutcome { get; init; } /// When set, the raw AcpSessionSourceClaim invoke returns a FAULTED task (after recording) — /// models a pre-source-claim server whose hub method doesn't exist (method-not-found). public Exception? SourceClaimThrow { get; init; } /// Fires (unbounded) once per source-claim call. public Channel SourceClaimSignal { get; } = Channel.CreateUnbounded(); /// Outcome the raw ConfirmSessionLaunch invoke returns; default Confirmed. A custom function /// sees the 1-based call count, so a test can model transient-then-terminal. public Func? ConfirmOutcome { get; init; } /// Ownership tokens passed to each confirm, in order; its count fires ConfirmSignal. public List ConfirmTokens { get; } = []; public Channel ConfirmSignal { get; } = Channel.CreateUnbounded(); internal override Task InvokeAcpSessionSourceClaimRawAsync( string agentId, string acpSessionId, CancellationToken ct) { lock (AcpCallOrder) AcpCallOrder.Add($"sourceClaim:{agentId}"); SourceClaimSignal.Writer.TryWrite(1); if (SourceClaimThrow is { } ex) return Task.FromException(ex); // method-not-found on a pre-source-claim server return Task.FromResult(SourceClaimOutcome ?? new AcpSourceClaimOutcome(AcpBindOutcome.Bound, 1, -1)); } internal override Task InvokeConfirmSessionLaunchRawAsync( string acpSessionId, long ownershipToken, CancellationToken ct) { int count; lock (AcpCallOrder) { AcpCallOrder.Add($"confirm:{ownershipToken}"); ConfirmTokens.Add(ownershipToken); count = ConfirmTokens.Count; } ConfirmSignal.Writer.TryWrite(count); return Task.FromResult(ConfirmOutcome?.Invoke(count) ?? AcpLaunchConfirmOutcome.Confirmed); } /// (AgentId, Status) pairs passed to every AgentStatusChangedAsync call, in /// call order — lets a test assert on the exact lifecycle transitions the orchestrator /// drove (e.g. Fix B/E's immediate Running flip for a no-terminal runtime). public List<(string AgentId, string Status)> StatusChangedCalls { get; } = []; /// The same calls with the session id the daemon reported alongside each status — the /// only place a test can see whether the FIRST status a server saw already named the session. public List<(string AgentId, string Status, string? SessionId)> StatusChangedWithSession { get; } = []; /// Thrown by every AgentStatusChangedAsync call while set. public Exception? StatusChangedThrow { get; set; } public override Task AgentStatusChangedAsync(string agentId, string status, string? sessionId) { if (StatusChangedThrow is { } ex) return Task.FromException(ex); // Capture BEFORE recording: was a launch-window verdict already published when this // non-failure status was sent? That ordering is the invariant a check-to-send race breaks. if (status is "Completed" or "Running" or "Starting" && VerdictCaptureRuntime?.ReadVerdict() is { ReapedInsideLaunchWindow: true }) NonFailureStatusSentAfterVerdictPublished = true; lock (StatusChangedCalls) StatusChangedCalls.Add((agentId, status)); lock (StatusChangedWithSession) StatusChangedWithSession.Add((agentId, status, sessionId)); return Task.CompletedTask; } /// Invoked when AgentUnregisteredAsync runs — the last step of /// CleanupAgentAsync, so a useful signal that local cleanup completed. public Action? OnAgentUnregistered { get; init; } /// Every agent id passed to AgentUnregisteredAsync, in call order. A /// single-flight teardown must unregister an agent exactly once even under a racing /// launch-catch + read-loop cleanup. public List AgentUnregisteredCalls { get; } = []; public Dictionary AgentUnregisteredStopReasons { get; } = []; /// Every dropped-input report, in call order — the only place a drop reason becomes /// observable to anyone but this daemon's own log. public List<(Guid DispatchId, string AgentId, string Reason)> InputRejections { get; } = []; /// When set, every dropped-input report is recorded and then held until this completes. public TaskCompletionSource? InputRejectionGate { get; init; } /// Every input acknowledgement, in call order. public List<(Guid DispatchId, string AgentId)> InputAcks { get; } = []; /// Runs inside each acknowledgement, after it is recorded, with its 1-based number. public Action? OnInputAcked { get; set; } public override Task SendInputAckedAsync(Guid dispatchId, string agentId) { int count; lock (InputAcks) { InputAcks.Add((dispatchId, agentId)); count = InputAcks.Count; } OnInputAcked?.Invoke(count); return Task.CompletedTask; } public override Task SendInputRejectedAsync(Guid dispatchId, string agentId, string reason) { lock (InputRejections) InputRejections.Add((dispatchId, agentId, reason)); return InputRejectionGate?.Task ?? Task.CompletedTask; } /// While set, every unregister fails as an unreachable server would, recording nothing. public Exception? AgentUnregisteredThrow { get; set; } /// While set, every unregister is recorded and then held until this completes; /// completes once one is held. public TaskCompletionSource? UnregisterGate { get; set; } public TaskCompletionSource UnregisterEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public override async Task AgentUnregisteredAsync(string agentId, string? stopReason = null) { if (AgentUnregisteredThrow is { } ex) throw ex; lock (AgentUnregisteredCalls) { AgentUnregisteredCalls.Add(agentId); AgentUnregisteredStopReasons[agentId] = stopReason; } lock (AttachedCallOrder) AttachedCallOrder.Add($"unregister:{agentId}"); OnAgentUnregistered?.Invoke(); if (UnregisterGate is { } gate) { UnregisterEntered.TrySetResult(); await gate.Task; } } public override Task UpdateRepoPathsAsync() => Task.CompletedTask; /// Set both to make every terminal send block until its ct cancels, then throw — /// so a send configured this way never reaches or /// , and a test that sets both alongside this is exercising only this. public TaskCompletionSource? SendEntered { get; init; } public TaskCompletionSource? SendUnblocked { get; init; } /// Runs before a terminal send is recorded; a test gates or fails the send here. public Func? TerminalSendGate { get; set; } public ConcurrentQueue<(string AgentId, byte[] Data)> TerminalSends { get; } = new(); int _terminalSendStarts; public int TerminalSendStarts => Volatile.Read(ref _terminalSendStarts); public override async Task SendTerminalOutputAsync(string agentId, string base64Data, CancellationToken ct = default) { Interlocked.Increment(ref _terminalSendStarts); if (SendEntered is not null) { SendEntered.TrySetResult(); try { await Task.Delay(Timeout.InfiniteTimeSpan, ct); } finally { SendUnblocked?.TrySetResult(); } } if (TerminalSendGate is { } gate) await gate(agentId, ct); TerminalSends.Enqueue((agentId, Convert.FromBase64String(base64Data))); } /// Every (agentId, event) pair passed to AppendAgentRunEventAsync, in call order. public List<(string AgentId, object Event)> RunEvents { get; } = []; /// When set, AppendAgentRunEventAsync records the event, then fails with this. public Exception? RunEventThrow { get; set; } public override Task AppendAgentRunEventAsync(string agentId, object evt) { lock (RunEvents) RunEvents.Add((agentId, evt)); return RunEventThrow is { } ex ? Task.FromException(ex) : Task.CompletedTask; } /// Every shutdown report, with the state of the token it was handed. The token matters /// more than the arguments: every other method on the real connection bakes in one that is /// already cancelled during teardown, so a report made with a cancelled token sends nothing and /// says nothing about it — a double that ignored the token would pass either way. public List<(string AgentId, string Status, string Reason, bool TokenAlreadyCancelled)> ShutdownReports { get; } = []; /// When set, the shutdown report blocks on this until its own token cancels — the hung /// server a shutdown must not wait on. public bool ShutdownReportHangs { get; init; } public List<(string AgentId, int? ExitCode)> ShutdownReportExitCodes { get; } = []; /// The daemon process each shutdown report's stop names as holding the run. public List<(string AgentId, string? RunInstanceId)> ShutdownReportRunInstances { get; } = []; public List UpdatedTitles { get; } = []; internal override Task UpdateTitleAsync(string sessionId, string title, CancellationToken ct) { lock (UpdatedTitles) UpdatedTitles.Add(title); return Task.FromResult(true); } /// The agents whose shutdown report carried the session end. public List ShutdownSessionEnds { get; } = []; protected override async Task SendShutdownReportAsync( string agentId, string? sessionId, string status, string reason, int? exitCode, string? runInstanceId, bool endSession, CancellationToken ct) { lock (ShutdownReports) { ShutdownReports.Add((agentId, status, reason, ct.IsCancellationRequested)); if (endSession) ShutdownSessionEnds.Add(agentId); } lock (ShutdownReportExitCodes) ShutdownReportExitCodes.Add((agentId, exitCode)); lock (ShutdownReportRunInstances) ShutdownReportRunInstances.Add((agentId, runInstanceId)); if (ShutdownReportHangs) await Task.Delay(Timeout.Infinite, ct); if (ShutdownReportGate is { } gate) await gate.Task.WaitAsync(ct); } /// When set, the shutdown report is recorded and then held until the gate completes. public TaskCompletionSource? ShutdownReportGate { get; set; } // ── Resolved-model report capture ────────────────────────────────── /// Every legacy (agentId, model) pair passed to ReportAgentResolvedModelAsync — proves /// the no-model / vendor-only launch keeps using the unchanged legacy channel. public List<(string AgentId, string Model)> ReportAgentResolvedModelCalls { get; } = []; /// Every explicit-model report passed to ReportExplicitReviewerModelResolvedAsync — proves /// an explicit-model launch reports the concrete resolved model on the dedicated v3 channel. public List ExplicitReviewerModelReports { get; } = []; /// Signals each ExplicitReviewerModelResolvedAsync call (1-based count) so a test can /// await the fire-and-forget report deterministically instead of racing Task.Delay. public Channel ExplicitReviewerModelReportSignal { get; } = Channel.CreateUnbounded(); public List CommandReports { get; } = []; public override Task ReportAgentCommandsAsync(string agentId, IReadOnlyList commands) { lock (CommandReports) CommandReports.Add(agentId); return Task.CompletedTask; } public List<(string AgentId, TerminalDialogDto? Dialog)> TerminalDialogReports { get; } = []; /// Runs as each dialog report is sent, before the next one can be. public Action? OnTerminalDialogReport { get; set; } /// When set, each dialog report stays in flight until this completes. public TaskCompletionSource? TerminalDialogReportHold { get; set; } public override Task ReportAgentTerminalDialogAsync(string agentId, TerminalDialogDto? dialog) { lock (TerminalDialogReports) TerminalDialogReports.Add((agentId, dialog)); OnTerminalDialogReport?.Invoke(agentId, dialog); return TerminalDialogReportHold?.Task ?? Task.CompletedTask; } public override Task ReportAgentResolvedModelAsync(string agentId, string model) { lock (ReportAgentResolvedModelCalls) ReportAgentResolvedModelCalls.Add((agentId, model)); return Task.CompletedTask; } public override Task ReportExplicitReviewerModelResolvedAsync(ExplicitReviewerModelResolvedV1 report) { int count; lock (ExplicitReviewerModelReports) { ExplicitReviewerModelReports.Add(report); count = ExplicitReviewerModelReports.Count; } ExplicitReviewerModelReportSignal.Writer.TryWrite(count); return Task.CompletedTask; } // ── Participant-park report capture ─────────────────────────────── /// The ack returns; default /// . A park state-machine test sets this to drive the three branches /// (Parked / Rejected / Ambiguous) deterministically. public ParkAck ParkOutcome { get; set; } = ParkAck.Parked; /// Every (agentId, canonicalSessionId, reason) passed to /// , in call order — lets a test assert the canonical /// thread id and reason the daemon reported, and (by emptiness) that a park that aborted at the /// claim never told the server at all. public List<(string AgentId, string CanonicalSessionId, string Reason)> ParkReports { get; } = []; /// Signalled the moment is entered (the park /// report is in flight) so a test can interleave a racing child-exit/finalize in the ack-await /// window. Null = no signal. public TaskCompletionSource? ParkEntered { get; init; } /// Held-open gate: when set, awaits it before /// returning , keeping the park ack in flight while a test exercises a /// concurrent finalize. Null = return the ack immediately. public TaskCompletionSource? ParkGate { get; init; } public override async Task ReportParticipantParkedAsync( string agentId, string canonicalSessionId, string reason, CancellationToken ct = default) { lock (ParkReports) ParkReports.Add((agentId, canonicalSessionId, reason)); ParkEntered?.TrySetResult(); if (ParkGate is { } gate) await gate.Task; return ParkOutcome; } protected override async Task SendEndAgentSessionAsync(string agentId, string reason) { EndSessionReasons.Add(reason); lock (AcpCallOrder) AcpCallOrder.Add($"endSession:{agentId}"); if (EndSessionBlockUntil is { } cts) { try { await Task.Delay(Timeout.InfiniteTimeSpan, cts.Token); } catch (OperationCanceledException) { /* released by the test */ } } return new EndAgentSessionResult(); } public override Task RequestPermissionAsync( string sessionId, string? toolName, JsonElement? toolInput, JsonElement? suggestions, CancellationToken ct = default ) => Task.FromResult(new PermissionDecision("deny", null, null)); // ── Attached agents: the raw hub seams, so the real connection builds every payload ────────── /// Every AgentRegisteredAcked payload. Hosted registrations stop at the override above, so /// only an attached agent's reaches here. public List AttachedRegistrations { get; } = []; /// The server's answer to each attached registration; accepted when unset or null. public Func? AttachedRegistrationAnswer { get; set; } /// Every attached registration and unregistration, in the order the server saw them. public List AttachedCallOrder { get; } = []; /// While set, every attached registration is recorded and then held until this completes; /// completes once one is held. public TaskCompletionSource? AttachedRegistrationGate { get; set; } public TaskCompletionSource AttachedRegistrationEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); internal override async Task InvokeAgentRegisteredAckedRawAsync(AgentRegistered registration) { lock (AttachedRegistrations) AttachedRegistrations.Add(registration); lock (AttachedCallOrder) AttachedCallOrder.Add($"register:{registration.AgentId}"); if (AttachedRegistrationGate is { } gate) { AttachedRegistrationEntered.TrySetResult(); await gate.Task; } return AttachedRegistrationAnswer?.Invoke(registration) ?? AgentRegisteredResponse.Accepted; } public List HandoverRequests { get; } = []; /// The server's answer to each handover request; handed over unless set. public Func HandoverAnswer { get; set; } = _ => new ConfirmInputHandoverResponse(InputHandoverOutcome.HandedOver); /// While set, every handover request is recorded and then held until this completes; /// completes once one is held. public TaskCompletionSource? HandoverGate { get; set; } public TaskCompletionSource HandoverEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); /// What the server answers the empty dispatch a daemon asks about to learn whether it takes attached agents: /// drop, as such a server answers it ahead of everything else, unless set. Never in . public Func> SteeringProbe { get; set; } = () => Task.FromResult(new ConfirmInputHandoverResponse(InputHandoverOutcome.Drop)); int _steeringProbes; public int SteeringProbes => Volatile.Read(ref _steeringProbes); internal override async Task InvokeConfirmInputHandoverRawAsync(ConfirmInputHandoverRequest request) { if (request.DispatchId == Guid.Empty) { Interlocked.Increment(ref _steeringProbes); return await SteeringProbe(); } lock (HandoverRequests) HandoverRequests.Add(request); if (HandoverGate is { } gate) { HandoverEntered.TrySetResult(); await gate.Task; } return HandoverAnswer(request); } /// While set, every link, Unconfirmed and attached rejection report fails as an unreachable server would. public Exception? AttachedReportThrow { get; set; } public List LinkReports { get; } = []; internal override Task InvokeReportInputLinkRawAsync(ReportInputLinkRequest request) { if (AttachedReportThrow is { } ex) return Task.FromException(ex); lock (LinkReports) LinkReports.Add(request); return Task.CompletedTask; } public List UnconfirmedReports { get; } = []; internal override Task InvokeReportInputUnconfirmedRawAsync(ReportInputUnconfirmedRequest request) { if (AttachedReportThrow is { } ex) return Task.FromException(ex); lock (UnconfirmedReports) UnconfirmedReports.Add(request); return Task.CompletedTask; } public List<(Guid DispatchId, string AgentId, string Reason)> AttachedRejections { get; } = []; /// Whether the server recorded each attached rejection on the named agent's stream; recorded unless set. public Func AttachedRejectionRecorded { get; set; } = (_, _) => true; /// While set, every attached rejection fails with this, as a server whose hub method refused it would, and /// counts in . public Exception? AttachedRejectionThrow { get; set; } public int AttachedRejectionAttempts { get; private set; } internal override Task InvokeSendInputRejectedRawAsync(Guid dispatchId, string agentId, string reason) { AttachedRejectionAttempts++; if (AttachedReportThrow is { } ex) return Task.FromException(ex); if (AttachedRejectionThrow is { } refused) return Task.FromException(refused); lock (AttachedRejections) AttachedRejections.Add((dispatchId, agentId, reason)); return Task.FromResult(AttachedRejectionRecorded(dispatchId, agentId)); } }