feat(worker): Handler-Session nach Usage-Limit-Reset automatisch neu starten
Eine List-Handler-ConPTY-Session, die mitten in einer Phase stirbt, war bisher
ein stilles totes Tile: InteractiveTerminalViewModel.OnSessionProcessExited
setzte nur bei einem Tod innerhalb des 5s-Grace-Fensters ein sichtbares Banner.
Neu:
- HandlerRoundState (JSON unter ~/.claudeDo/handler-rounds.json, keine
EF-Migration): Phase + Task-Set der laufenden Runde, geschrieben von
BuildForMergeHelperAsync ("triage") und BuildForMergeHelperHandoffAsync.
Ohne das existieren beide nur im transienten HandoffRequested-Broadcast.
- HandlerRestartCoordinator: entscheidet den Neustart, fail-closed. Beleg fuer
"war das Usage-Limit" ist FiveHour.Utilization >= 95 zum Todeszeitpunkt --
eine ConPTY-Session hat kein stdout, TaskRunner.IsUsageLimitMessage hat hier
nichts zu lesen. Nur bei PowerUse (beide Keys), max ein Neustart pro Runde,
Warten bis FiveHour.ResetsAt, dann HandoffRequested erneut broadcasten.
Verbraucht kein Handoff-Budget (HandoffRoundTracker.Register wird nicht
angefasst). WorkerLog-Zeilen beim Tod und beim Neustart.
- Ui meldet den Exit-Code (nur dort bekannt) via
WorkerHub.ReportInteractiveSessionExited, ohne selbst zu filtern.
Sibling zu UsageLimitAutoContinueCoordinator, kein Umbau davon: der sieht nur
headless Runs.
This commit is contained in:
@@ -146,6 +146,10 @@ public interface IWorkerClient : INotifyPropertyChanged
|
||||
/// session's role: "wait" | "merge" | "wait_final" | "merge_final".</summary>
|
||||
Task<LaunchSpec> GetMergeHelperHandoffLaunchSpecAsync(
|
||||
string taskId, IReadOnlyList<string> survivingTaskIds, string nextPhase, CancellationToken ct = default);
|
||||
/// <summary>Reports that a task-based ConPTY session's process exited non-zero after it had been
|
||||
/// running. The exit code only exists in this process; the worker decides whether it was a
|
||||
/// list-handler session killed by the usage limit and reopens the same phase after the 5h reset.</summary>
|
||||
Task ReportInteractiveSessionExitedAsync(string taskId, int exitCode, CancellationToken ct = default);
|
||||
/// <summary>Starts a planning session and returns the launch spec for an embedded ConPTY
|
||||
/// planning terminal (replaces StartPlanningSessionAsync's external wt window).</summary>
|
||||
Task<LaunchSpec> GetPlanningStartLaunchSpecAsync(string taskId, CancellationToken ct = default);
|
||||
|
||||
@@ -626,6 +626,9 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerC
|
||||
string taskId, IReadOnlyList<string> survivingTaskIds, string nextPhase, CancellationToken ct = default)
|
||||
=> await InvokeTimedAsync<LaunchSpec>("GetMergeHelperHandoffLaunchSpec", () => _hub.InvokeAsync<LaunchSpec>("GetMergeHelperHandoffLaunchSpec", taskId, survivingTaskIds, nextPhase, ct));
|
||||
|
||||
public Task ReportInteractiveSessionExitedAsync(string taskId, int exitCode, CancellationToken ct = default)
|
||||
=> InvokeTimedAsync("ReportInteractiveSessionExited", () => _hub.InvokeAsync("ReportInteractiveSessionExited", taskId, exitCode, ct));
|
||||
|
||||
public async Task<LaunchSpec> GetPlanningStartLaunchSpecAsync(string taskId, CancellationToken ct = default)
|
||||
=> await InvokeTimedAsync<LaunchSpec>("GetPlanningStartLaunchSpec", () => _hub.InvokeAsync<LaunchSpec>("GetPlanningStartLaunchSpec", taskId, ct));
|
||||
|
||||
|
||||
@@ -96,6 +96,13 @@ public sealed partial class InteractiveTerminalViewModel : ViewModelBase, IDispo
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Raised when the process died non-zero *after* clearing <see cref="StartupGraceWindow"/> —
|
||||
/// i.e. a session that ran, then broke. That used to be a silent dead tile with no signal at all;
|
||||
/// the worker turns it into a usage-limit auto-restart for list-handler sessions
|
||||
/// (<c>HandlerRestartCoordinator</c>). A startup death keeps using <see cref="StartError"/> instead:
|
||||
/// it never reached a state worth resuming.</summary>
|
||||
public event Action<int>? ExitedAfterStartup;
|
||||
|
||||
/// <summary>Internal (not private) so tests can drive it directly without a real ConPTY spawn.</summary>
|
||||
internal void OnSessionProcessExited(object? sender, int exitCode)
|
||||
{
|
||||
@@ -103,11 +110,16 @@ public sealed partial class InteractiveTerminalViewModel : ViewModelBase, IDispo
|
||||
HasExited = true;
|
||||
ExitCode = exitCode;
|
||||
|
||||
if (exitCode == 0) return;
|
||||
if (_startedAtUtc is not { } startedAt) return; // never reached "running" — nothing ran to resume
|
||||
|
||||
// Died at startup: route through the same banner as a launch-time failure instead of
|
||||
// leaving a dead terminal with no Retry affordance (ConPtyPaneViewModel.CanRetry
|
||||
// requires StartError).
|
||||
if (exitCode != 0 && _startedAtUtc is { } startedAt && _utcNow() - startedAt < StartupGraceWindow)
|
||||
if (_utcNow() - startedAt < StartupGraceWindow)
|
||||
StartError = $"Session exited immediately (code {exitCode}).";
|
||||
else
|
||||
ExitedAfterStartup?.Invoke(exitCode);
|
||||
}
|
||||
|
||||
/// <summary>Reports a failure that happened before <see cref="Start"/> could be called (e.g. the
|
||||
|
||||
@@ -36,6 +36,12 @@ public sealed partial class ConPtyPaneViewModel : ViewModelBase, IDisposable
|
||||
/// commits the worktree and moves the task to WaitingForReview.</summary>
|
||||
public event Action<string>? SubmitForReviewRequested;
|
||||
|
||||
/// <summary>Raised with <c>(taskId, exitCode)</c> when a task-based session that had been running
|
||||
/// dies non-zero. The host reports it to the worker, which decides whether this was a list
|
||||
/// handler killed by the usage limit and worth reopening. Ad-hoc panes never raise it — there is
|
||||
/// no task to reopen.</summary>
|
||||
public event Action<string, int>? SessionDiedAfterStartup;
|
||||
|
||||
/// <summary>Task-based pane — dedup'd by <see cref="TaskId"/>. Pass null for an ad-hoc pane
|
||||
/// (no task, never deduped); prefer <see cref="CreateAdHoc"/> at ad-hoc call sites.
|
||||
/// <paramref name="descriptorFactory"/> is resolved by the pane itself (in <see cref="Start"/>)
|
||||
@@ -49,7 +55,34 @@ public sealed partial class ConPtyPaneViewModel : ViewModelBase, IDisposable
|
||||
TaskId = taskId;
|
||||
_displayTitle = displayTitle;
|
||||
_descriptorFactory = descriptorFactory;
|
||||
Terminal.PropertyChanged += OnTerminalPropertyChanged;
|
||||
Subscribe(Terminal);
|
||||
}
|
||||
|
||||
// Terminal is swapped wholesale on Retry, so the handlers follow the property rather than being
|
||||
// wired once at construction. (The initial value comes from the field initializer, which never
|
||||
// runs through the setter -- hence the explicit Subscribe in the constructor.)
|
||||
partial void OnTerminalChanging(InteractiveTerminalViewModel? oldValue, InteractiveTerminalViewModel newValue)
|
||||
{
|
||||
if (oldValue is not null) Unsubscribe(oldValue);
|
||||
}
|
||||
|
||||
partial void OnTerminalChanged(InteractiveTerminalViewModel value) => Subscribe(value);
|
||||
|
||||
private void Subscribe(InteractiveTerminalViewModel terminal)
|
||||
{
|
||||
terminal.PropertyChanged += OnTerminalPropertyChanged;
|
||||
terminal.ExitedAfterStartup += OnTerminalExitedAfterStartup;
|
||||
}
|
||||
|
||||
private void Unsubscribe(InteractiveTerminalViewModel terminal)
|
||||
{
|
||||
terminal.PropertyChanged -= OnTerminalPropertyChanged;
|
||||
terminal.ExitedAfterStartup -= OnTerminalExitedAfterStartup;
|
||||
}
|
||||
|
||||
private void OnTerminalExitedAfterStartup(int exitCode)
|
||||
{
|
||||
if (TaskId is { } id) SessionDiedAfterStartup?.Invoke(id, exitCode);
|
||||
}
|
||||
|
||||
private readonly Func<System.Threading.Tasks.Task<TerminalLaunchDescriptor>> _descriptorFactory;
|
||||
@@ -111,16 +144,15 @@ public sealed partial class ConPtyPaneViewModel : ViewModelBase, IDisposable
|
||||
[RelayCommand(CanExecute = nameof(CanRetry))]
|
||||
private void Retry()
|
||||
{
|
||||
Terminal.PropertyChanged -= OnTerminalPropertyChanged;
|
||||
Terminal.Dispose();
|
||||
Terminal = new InteractiveTerminalViewModel();
|
||||
Terminal.PropertyChanged += OnTerminalPropertyChanged;
|
||||
var dead = Terminal;
|
||||
Terminal = new InteractiveTerminalViewModel(); // OnTerminalChanging/Changed move the handlers
|
||||
dead.Dispose();
|
||||
Start();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Terminal.PropertyChanged -= OnTerminalPropertyChanged;
|
||||
Unsubscribe(Terminal);
|
||||
Terminal.Kill();
|
||||
Terminal.Dispose();
|
||||
}
|
||||
|
||||
@@ -413,10 +413,28 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
|
||||
pane.ErrorReported += OnConPtyPaneError;
|
||||
pane.CloseRequested += CloseConPtySession;
|
||||
pane.SubmitForReviewRequested += OnPaneSubmitForReview;
|
||||
pane.SessionDiedAfterStartup += OnPaneSessionDied;
|
||||
ConPtySessions.Add(pane);
|
||||
pane.Start();
|
||||
}
|
||||
|
||||
// A ConPTY session that had been running died. The UI process owns the terminal, so this is the
|
||||
// only place the exit code exists -- report it and let the worker decide whether it was a list
|
||||
// handler killed by the usage limit and worth reopening after the reset
|
||||
// (HandlerRestartCoordinator). Every other pane is just a no-op there, so no filtering here.
|
||||
private async void OnPaneSessionDied(string taskId, int exitCode)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _worker.ReportInteractiveSessionExitedAsync(taskId, exitCode);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A worker that is down cannot restart anything anyway; the dead tile is already visible.
|
||||
ErrorReported?.Invoke(Loc.T("missionControl.conptyLaunchFailed", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private static async System.Threading.Tasks.Task<TerminalLaunchDescriptor> DescribeAsync(
|
||||
Func<System.Threading.Tasks.Task<LaunchSpec>> fetch)
|
||||
{
|
||||
@@ -457,6 +475,7 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
|
||||
pane.ErrorReported -= OnConPtyPaneError;
|
||||
pane.CloseRequested -= CloseConPtySession;
|
||||
pane.SubmitForReviewRequested -= OnPaneSubmitForReview;
|
||||
pane.SessionDiedAfterStartup -= OnPaneSessionDied;
|
||||
ConPtySessions.Remove(pane);
|
||||
pane.Dispose();
|
||||
}
|
||||
@@ -507,6 +526,7 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
|
||||
c.ErrorReported -= OnConPtyPaneError;
|
||||
c.CloseRequested -= CloseConPtySession;
|
||||
c.SubmitForReviewRequested -= OnPaneSubmitForReview;
|
||||
c.SessionDiedAfterStartup -= OnPaneSessionDied;
|
||||
c.Dispose();
|
||||
}
|
||||
ConPtySessions.Clear();
|
||||
|
||||
@@ -72,6 +72,7 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
private readonly TicketPatStore _ticketPat;
|
||||
private readonly TicketClientFactory _ticketClients;
|
||||
private readonly TicketImportService _ticketImport;
|
||||
private readonly HandlerRestartCoordinator? _handlerRestart;
|
||||
|
||||
public WorkerHub(
|
||||
QueueService queue,
|
||||
@@ -110,7 +111,8 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
TicketSystemConfig ticketConfig = null!,
|
||||
TicketPatStore ticketPat = null!,
|
||||
TicketClientFactory ticketClients = null!,
|
||||
TicketImportService ticketImport = null!)
|
||||
TicketImportService ticketImport = null!,
|
||||
HandlerRestartCoordinator? handlerRestart = null)
|
||||
{
|
||||
_queue = queue;
|
||||
_waker = waker;
|
||||
@@ -149,6 +151,7 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
_ticketPat = ticketPat;
|
||||
_ticketClients = ticketClients;
|
||||
_ticketImport = ticketImport;
|
||||
_handlerRestart = handlerRestart;
|
||||
}
|
||||
|
||||
// Persistence boundary for the session_skills JSON-array columns (task/list/global).
|
||||
@@ -786,6 +789,18 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
return _interactiveLaunchSpec.BuildForMergeHelperHandoffAsync(taskId, survivingTaskIds, nextPhase, Context.ConnectionAborted);
|
||||
});
|
||||
|
||||
// Reports that an embedded ConPTY session's process exited. Only the UI process owns the
|
||||
// terminal, so the exit code exists nowhere else; every decision about it (was this a list
|
||||
// handler, did the usage limit kill it, is PowerUse on, when does the window reset) belongs to
|
||||
// HandlerRestartCoordinator. Fire-and-forget on purpose: the coordinator's task stays parked
|
||||
// until the 5h reset, which is far longer than this connection or this hub instance lives, so
|
||||
// it must not run under Context.ConnectionAborted either.
|
||||
public void ReportInteractiveSessionExited(string taskId, int exitCode)
|
||||
{
|
||||
if (_handlerRestart is null) return;
|
||||
_ = _handlerRestart.OnSessionExitedAsync(taskId, exitCode, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Starts a planning session (worktree + prompt files + token, task -> Planning) and returns
|
||||
// the launch spec for an embedded ConPTY planning terminal -- the ConPTY replacement for
|
||||
// StartPlanningSessionAsync's external wt window. On any spec-build failure the just-started
|
||||
|
||||
@@ -95,6 +95,8 @@ builder.Services.AddSingleton<IRepoCloner, GitRepoCloner>();
|
||||
builder.Services.AddSingleton<ISessionSkillRegistry, SessionSkillRegistry>();
|
||||
builder.Services.AddSingleton<ISessionSkillSeeder, SessionSkillSeeder>();
|
||||
builder.Services.AddSingleton<HandoffRoundTracker>();
|
||||
builder.Services.AddSingleton<HandlerRoundState>();
|
||||
builder.Services.AddSingleton<HandlerRestartCoordinator>();
|
||||
builder.Services.AddSingleton<InteractiveLaunchSpecService>();
|
||||
builder.Services.AddSingleton<TaskRunner>();
|
||||
builder.Services.AddSingleton<WorktreeMaintenanceService>();
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Worker.Hub;
|
||||
using ClaudeDo.Worker.Usage;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ClaudeDo.Worker.Runner;
|
||||
|
||||
/// <summary>
|
||||
/// Reopens a list-handler ConPTY session that died on the Anthropic usage limit, once the 5h window
|
||||
/// resets — the interactive counterpart to <c>UsageLimitAutoContinueCoordinator</c>, which only ever
|
||||
/// sees headless task runs. Deliberately a sibling and not an extension of it: a ConPTY session has
|
||||
/// no <c>task_runs</c> row, no <c>FailureReason</c>, and is resumed by relaunching a phase rather
|
||||
/// than by <c>ContinueTask</c> through the override slot.
|
||||
///
|
||||
/// Driven by the UI (<c>WorkerHub.ReportInteractiveSessionExited</c>) because the exit code only
|
||||
/// exists in the process that owns the terminal. Everything else — was it the usage limit, is
|
||||
/// PowerUse on, which phase and task set, when does the window reset — is decided here.
|
||||
///
|
||||
/// Fails CLOSED, unlike the usage gate: every missing signal means "don't relaunch". An interactive
|
||||
/// session that pops back up at 3am uninvited is worse than one that stays dead.
|
||||
/// </summary>
|
||||
public sealed class HandlerRestartCoordinator
|
||||
{
|
||||
// The corroborating signal that this exit really was the usage limit. A ConPTY session gives us
|
||||
// nothing but an exit code -- there is no stdout to match against, so TaskRunner's
|
||||
// IsUsageLimitMessage regex (which reads the CLI's own "session limit reached" text) has nothing
|
||||
// to read here. The 5h utilization at the moment of death is the one independent witness we do
|
||||
// have, and it is pinned at 100% when the limit is what stopped the session. A crash, a manual
|
||||
// Ctrl-C, or a bad launch at 40% utilization is therefore NOT restarted.
|
||||
internal const int UsageLimitProofPct = 95;
|
||||
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly UsageState _usageState;
|
||||
private readonly HandlerRoundState _rounds;
|
||||
private readonly HubBroadcaster _broadcaster;
|
||||
private readonly ILogger<HandlerRestartCoordinator> _logger;
|
||||
|
||||
public HandlerRestartCoordinator(
|
||||
IDbContextFactory<ClaudeDoDbContext> dbFactory,
|
||||
UsageState usageState,
|
||||
HandlerRoundState rounds,
|
||||
HubBroadcaster broadcaster,
|
||||
ILogger<HandlerRestartCoordinator> logger)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_usageState = usageState;
|
||||
_rounds = rounds;
|
||||
_broadcaster = broadcaster;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Test seams — a real 5h wait is not a test.</summary>
|
||||
internal Func<DateTimeOffset> NowUtc { get; set; } = () => DateTimeOffset.UtcNow;
|
||||
internal Func<TimeSpan, CancellationToken, Task> Delay { get; set; } = (d, ct) => Task.Delay(d, ct);
|
||||
|
||||
/// <summary>Handles a ConPTY session's process exit. Returns true when a restart was claimed and
|
||||
/// carried out (the returned task completes only after the wait, so a caller that wants
|
||||
/// fire-and-forget must not await it). Any non-handler task, clean exit, non-usage-limit death,
|
||||
/// PowerUse-off list, or already-used round is a silent no-op.</summary>
|
||||
public async Task<bool> OnSessionExitedAsync(string taskId, int exitCode, CancellationToken ct = default)
|
||||
{
|
||||
if (exitCode == 0 || string.IsNullOrEmpty(taskId)) return false;
|
||||
|
||||
var round = _rounds.Get(taskId);
|
||||
// Not a list-handler session at all (a plain interactive task pane), or the initial triage
|
||||
// session, which has no handoff launch spec to reopen -- BuildForMergeHelperAsync needs the
|
||||
// list id and the original selection, and its dedupe/enhance work is not idempotent.
|
||||
if (round is null || !MergeHelperPhase.All.Contains(round.Phase, StringComparer.Ordinal)) return false;
|
||||
|
||||
var snapshot = _usageState.Snapshot;
|
||||
if (snapshot?.FiveHour is not { } fiveHour) return false;
|
||||
if (fiveHour.Utilization < UsageLimitProofPct) return false;
|
||||
if (fiveHour.ResetsAt is not { } resetsAt) return false;
|
||||
|
||||
int number;
|
||||
try
|
||||
{
|
||||
await using var ctx = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var task = await new TaskRepository(ctx).GetByIdAsync(taskId, ct);
|
||||
if (task is null) return false;
|
||||
number = task.Number;
|
||||
|
||||
// Both PowerUse keys, exactly as ComposeHandlerPromptAsync gates the PowerUse prompt
|
||||
// addendum: the global switch alone must not make an interactive run on some unrelated
|
||||
// list restart itself overnight.
|
||||
if (!(await new AppSettingsRepository(ctx).GetAsync(ct)).PowerUseEnabled) return false;
|
||||
if ((await new ListRepository(ctx).GetConfigAsync(task.ListId, ct))?.PowerUseAllowed != true) return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "HandlerRestartCoordinator: could not evaluate handler task {TaskId}; not restarting", taskId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// One restart per round, claimed before the wait -- a restart that dies again lands back
|
||||
// here and must stop, not relaunch.
|
||||
if (!_rounds.TryClaimAutoRestart(taskId)) return false;
|
||||
|
||||
try
|
||||
{
|
||||
await _broadcaster.WorkerLog(
|
||||
$"List handler #{number} died at the usage limit (5h {fiveHour.Utilization:0}%) — " +
|
||||
$"restarting phase {round.Phase} after the reset at {resetsAt.ToLocalTime():HH:mm}",
|
||||
WorkerLogLevel.Warn, DateTime.UtcNow);
|
||||
|
||||
var wait = resetsAt - NowUtc();
|
||||
if (wait > TimeSpan.Zero) await Delay(wait, ct);
|
||||
|
||||
await _broadcaster.HandoffRequested(taskId, round.TaskIds, round.Phase);
|
||||
await _broadcaster.WorkerLog(
|
||||
$"Auto-restarting list handler #{number} at phase {round.Phase} after usage-limit reset",
|
||||
WorkerLogLevel.Info, DateTime.UtcNow);
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Callers fire-and-forget this (WorkerHub.ReportInteractiveSessionExited), so an
|
||||
// unobserved throw here would be invisible.
|
||||
_logger.LogError(ex, "HandlerRestartCoordinator: auto-restart of handler task {TaskId} failed", taskId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Text.Json;
|
||||
using ClaudeDo.Data;
|
||||
|
||||
namespace ClaudeDo.Worker.Runner;
|
||||
|
||||
/// <summary>One list-handler round: the phase a session is running and the exact task set it was
|
||||
/// handed. Written every time a handler session is built, so an outside observer (a crashed tile,
|
||||
/// a deferred handoff) can reopen the SAME phase with the SAME set without the in-flight
|
||||
/// <c>HandoffRequested</c> broadcast that is the only other place these ids exist.</summary>
|
||||
/// <param name="Phase">A <see cref="MergeHelperPhase"/> value, or "triage" for the initial session
|
||||
/// (which has no handoff spec and therefore cannot be reopened — see HandlerRestartCoordinator).</param>
|
||||
/// <param name="AutoRestartUsed">Claimed once per round by HandlerRestartCoordinator, so a handler
|
||||
/// that dies again after its auto-restart stays dead instead of relaunching all night.</param>
|
||||
/// <param name="DeferredHandoffAt">Reserved for the "hand off cleanly before the usage limit"
|
||||
/// follow-up, which parks a handoff until the 5h reset and needs to survive a worker restart.</param>
|
||||
public sealed record HandlerRound(
|
||||
string HandlerTaskId,
|
||||
string Phase,
|
||||
IReadOnlyList<string> TaskIds,
|
||||
DateTime StartedAtUtc,
|
||||
bool AutoRestartUsed = false,
|
||||
DateTimeOffset? DeferredHandoffAt = null);
|
||||
|
||||
/// <summary>
|
||||
/// File-backed store for <see cref="HandlerRound"/>, one entry per handler task. Deliberately a
|
||||
/// JSON file under <c>~/.claudeDo/</c> (same Load/Save shape as <c>ClaudeDo.Ui.AppSettings</c>)
|
||||
/// rather than a DB column: rounds are process-lifetime scratch state that no query joins against,
|
||||
/// and an EF migration here would collide with the one the settings work owns this round.
|
||||
/// Every read/write goes through one lock and re-serializes the whole file — there are at most a
|
||||
/// handful of concurrent handler runs, so nothing here needs to be clever.
|
||||
/// </summary>
|
||||
public sealed class HandlerRoundState
|
||||
{
|
||||
// Entries older than this are dropped on the next save. A round that has been open for a week
|
||||
// is not coming back, and without a sweep the file only ever grows.
|
||||
private static readonly TimeSpan Retention = TimeSpan.FromDays(7);
|
||||
|
||||
private readonly string _path;
|
||||
private readonly object _lock = new();
|
||||
private Dictionary<string, HandlerRound>? _rounds;
|
||||
|
||||
public HandlerRoundState() : this(Path.Combine(Paths.AppDataRoot(), "handler-rounds.json"))
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Test seam — point the store at a temp file instead of the live app data root.</summary>
|
||||
internal HandlerRoundState(string path) => _path = path;
|
||||
|
||||
public HandlerRound? Get(string handlerTaskId)
|
||||
{
|
||||
lock (_lock)
|
||||
return Rounds().GetValueOrDefault(handlerTaskId);
|
||||
}
|
||||
|
||||
/// <summary>Overwrites this handler task's round. <see cref="HandlerRound.AutoRestartUsed"/> is
|
||||
/// carried over when the phase is unchanged: the auto-restart itself rebuilds the same phase's
|
||||
/// launch spec, which lands right back here, and a naive overwrite would hand the round a fresh
|
||||
/// restart budget every time — exactly the all-night relaunch loop the claim exists to prevent.
|
||||
/// A genuinely new phase is a new round and starts with a fresh budget.</summary>
|
||||
public void Save(HandlerRound round)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var rounds = Rounds();
|
||||
if (rounds.TryGetValue(round.HandlerTaskId, out var previous)
|
||||
&& string.Equals(previous.Phase, round.Phase, StringComparison.Ordinal)
|
||||
&& previous.AutoRestartUsed)
|
||||
{
|
||||
round = round with { AutoRestartUsed = true };
|
||||
}
|
||||
|
||||
rounds[round.HandlerTaskId] = round;
|
||||
Persist(rounds);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Takes this round's single auto-restart budget. False when there is no round for the
|
||||
/// task or its budget is already spent — the same "never twice" discipline
|
||||
/// <c>TaskRepository.TryClaimUsageLimitAutoContinueAsync</c> enforces for headless runs.</summary>
|
||||
public bool TryClaimAutoRestart(string handlerTaskId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var rounds = Rounds();
|
||||
if (!rounds.TryGetValue(handlerTaskId, out var round) || round.AutoRestartUsed) return false;
|
||||
|
||||
rounds[handlerTaskId] = round with { AutoRestartUsed = true };
|
||||
Persist(rounds);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Remove(string handlerTaskId)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var rounds = Rounds();
|
||||
if (rounds.Remove(handlerTaskId)) Persist(rounds);
|
||||
}
|
||||
}
|
||||
|
||||
// Callers hold _lock.
|
||||
private Dictionary<string, HandlerRound> Rounds()
|
||||
{
|
||||
if (_rounds is not null) return _rounds;
|
||||
try
|
||||
{
|
||||
if (File.Exists(_path))
|
||||
{
|
||||
_rounds = JsonSerializer.Deserialize<Dictionary<string, HandlerRound>>(
|
||||
File.ReadAllText(_path), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A corrupt/unreadable file must never block a handler launch — start empty.
|
||||
}
|
||||
return _rounds ??= new Dictionary<string, HandlerRound>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private void Persist(Dictionary<string, HandlerRound> rounds)
|
||||
{
|
||||
var cutoff = DateTime.UtcNow - Retention;
|
||||
foreach (var stale in rounds.Where(kv => kv.Value.StartedAtUtc < cutoff).Select(kv => kv.Key).ToList())
|
||||
rounds.Remove(stale);
|
||||
|
||||
try
|
||||
{
|
||||
var dir = Path.GetDirectoryName(_path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(_path, JsonSerializer.Serialize(rounds, new JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Losing persistence costs an auto-restart across a worker restart, never a launch.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ public sealed class InteractiveLaunchSpecService
|
||||
private readonly GitService _git;
|
||||
private readonly string _claudePath;
|
||||
private readonly HandoffRoundTracker _handoffRounds;
|
||||
private readonly HandlerRoundState _roundState;
|
||||
|
||||
public InteractiveLaunchSpecService(
|
||||
IDbContextFactory<ClaudeDoDbContext> dbFactory,
|
||||
@@ -52,7 +53,8 @@ public sealed class InteractiveLaunchSpecService
|
||||
WorktreeManager wtManager,
|
||||
GitService git,
|
||||
WorkerConfig cfg,
|
||||
HandoffRoundTracker handoffRounds)
|
||||
HandoffRoundTracker handoffRounds,
|
||||
HandlerRoundState roundState)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_skillSeeder = skillSeeder;
|
||||
@@ -61,6 +63,7 @@ public sealed class InteractiveLaunchSpecService
|
||||
_git = git;
|
||||
_claudePath = cfg.ClaudeBin;
|
||||
_handoffRounds = handoffRounds;
|
||||
_roundState = roundState;
|
||||
}
|
||||
|
||||
/// <summary>Builds a LaunchSpec for opening an interactive session in a task's worktree.
|
||||
@@ -342,9 +345,20 @@ public sealed class InteractiveLaunchSpecService
|
||||
["MCP_TOOL_TIMEOUT"] = McpToolTimeoutMs,
|
||||
};
|
||||
|
||||
// The opening round. Recorded so anything watching a handler run knows which round is live
|
||||
// (the deferred-handoff follow-up needs that), but marked "triage" rather than a
|
||||
// MergeHelperPhase value on purpose: there is no handoff spec for this phase, so
|
||||
// HandlerRestartCoordinator will not reopen it.
|
||||
_roundState.Save(new HandlerRound(handlerTaskId, TriagePhase, taskIds, DateTime.UtcNow));
|
||||
|
||||
return new LaunchSpec(repoDir, resolvedClaude, args, env);
|
||||
}
|
||||
|
||||
/// <summary>The <see cref="HandlerRound.Phase"/> marker for the initial (dedupe/enhance) handler
|
||||
/// session. Deliberately not a <see cref="MergeHelperPhase"/> value — that set is exactly the
|
||||
/// phases <see cref="BuildForMergeHelperHandoffAsync"/> can rebuild.</summary>
|
||||
public const string TriagePhase = "triage";
|
||||
|
||||
// Builds the LaunchSpec for the fresh session a merge-helper run hands off to for the given
|
||||
// phase -- SAME handler task id as the run that called handoff_list_handler, so
|
||||
// HandlerBaseCommit/HandlerHeadCommit and the review range stay untouched; this never creates
|
||||
@@ -449,6 +463,11 @@ public sealed class InteractiveLaunchSpecService
|
||||
["MCP_TOOL_TIMEOUT"] = McpToolTimeoutMs,
|
||||
};
|
||||
|
||||
// Persist the round that is about to start. Phase + task set only exist in the transient
|
||||
// HandoffRequested broadcast otherwise, so without this a dead tile cannot be reopened at
|
||||
// the same phase with the same set (see HandlerRestartCoordinator).
|
||||
_roundState.Save(new HandlerRound(taskId, nextPhase, survivingTaskIds, DateTime.UtcNow));
|
||||
|
||||
return new LaunchSpec(repoDir, resolvedClaude, args, env);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user