refactor(interactive): remove streaming interactive stack (superseded by ConPTY)

The embedded ConPTY terminal replaced the in-app streaming interactive session, so
delete the dead stack: StreamingClaudeSession, InteractiveSessionService,
ProcessClaudeStreamTransport, IClaudeStreamTransport, ILiveSession, LiveSessionRegistry,
IdleSessionReaper (+ WorkerConfig.InteractiveIdleTimeoutMinutes), the WorkerHub
interactive methods + HubBroadcaster events, IWorkerClient interactive members, the
TaskMonitorViewModel composer + SessionTerminalView composer markup, and the old
'Run interactively' entry. AskUser/PendingQuestionRegistry, the autonomous path,
planning, ResumeTaskInTerminal, and all ConPTY code are kept. Localization pruned.
This commit is contained in:
mika kuns
2026-07-23 16:47:16 +02:00
parent d8194ad57e
commit c412a84fdf
40 changed files with 23 additions and 2338 deletions
+2 -11
View File
@@ -128,7 +128,6 @@
"ctxMarkAs": "Markieren als",
"ctxMarkDone": "Erledigt",
"ctxMarkCancelled": "Abgebrochen",
"ctxRunInteractively": "Interaktiv ausführen",
"ctxOpenConPtySession": "ConPTY-Sitzung öffnen",
"ctxPickUpInTerminal": "Im Terminal fortsetzen",
"ctxOpenPlanningSession": "Planungssitzung öffnen",
@@ -247,15 +246,7 @@
"chipDone": "FERTIG",
"chipFailed": "FEHLGESCHLAGEN",
"reviewContinueTip": "Dieses Feedback senden und die Aufgabe erneut ausführen",
"reviewResetTip": "Alle Änderungen verwerfen und die Aufgabe auf Leerlauf zurücksetzen",
"composer": {
"placeholder": "Nachricht an die Sitzung…",
"send": "Senden",
"stop": "Sitzung beenden",
"interrupt": "Aktuellen Zug unterbrechen",
"queued": "Wartet — wird nach dem aktuellen Zug gesendet",
"unqueue": "Aus Warteschlange entfernen"
}
"reviewResetTip": "Alle Änderungen verwerfen und die Aufgabe auf Leerlauf zurücksetzen"
},
"missionControl": {
"openInApp": "In App öffnen",
@@ -513,7 +504,7 @@
"taskStatus": { "idle": "Leerlauf", "queued": "In Warteschlange", "running": "Läuft", "waitingForReview": "Wartet auf Prüfung", "waitingForChildren": "Wartet auf Verbesserungen", "done": "Fertig", "failed": "Fehlgeschlagen", "cancelled": "Abgebrochen", "parked": "Geparkt" },
"planningBadge": { "active": "PLANUNG", "finalized": "GEPLANT" },
"taskRow": { "createdPrefix": "Erstellt {0}", "stepsText": "{0}/{1} Schritte" },
"tasksIsland": { "completedHeader": "ABGESCHLOSSEN", "completedHeaderCount": "ABGESCHLOSSEN · {0}", "runInteractiveFailed": "Interaktiv ausführen fehlgeschlagen: {0}", "planningOpenFailed": "Planungssitzung konnte nicht geöffnet werden: {0}", "pickUpInTerminalFailed": "Im Terminal fortsetzen fehlgeschlagen: {0}", "approveFailed": "Genehmigen & Mergen fehlgeschlagen: {0}" },
"tasksIsland": { "completedHeader": "ABGESCHLOSSEN", "completedHeaderCount": "ABGESCHLOSSEN · {0}", "planningOpenFailed": "Planungssitzung konnte nicht geöffnet werden: {0}", "pickUpInTerminalFailed": "Im Terminal fortsetzen fehlgeschlagen: {0}", "approveFailed": "Genehmigen & Mergen fehlgeschlagen: {0}" },
"diff": { "loadFailed": "Diff konnte nicht geladen werden: {0}", "noChanges": "Keine Änderungen anzuzeigen.", "unavailable": "Diff nicht mehr verfügbar — Commit-Bereich unvollständig." },
"planningDiff": { "hubError": "Kombinierte Vorschau konnte nicht erstellt werden (Hub-Fehler).", "conflict": "Kombinierte Vorschau nicht möglich: Teilaufgabe {0} steht im Konflikt mit einer früheren Teilaufgabe ({1} Dateien)." },
"merge": { "commitMessage": "Merge-Aufgabe: {0}", "workerOfflineBranches": "Worker offline — Branches können nicht aufgelistet werden.", "loadBranchesFailed": "Branches konnten nicht geladen werden: {0}", "merged": "Zusammengeführt.", "conflict": "Merge-Konflikt — Ziel-Branch wiederhergestellt. Manuell oder über Fortsetzen lösen, dann erneut versuchen.", "blocked": "Blockiert: {0}", "unknownStatus": "Unbekannter Status: {0}", "mergeFailed": "Merge fehlgeschlagen: {0}" },
+2 -11
View File
@@ -128,7 +128,6 @@
"ctxMarkAs": "Mark as",
"ctxMarkDone": "Done",
"ctxMarkCancelled": "Cancelled",
"ctxRunInteractively": "Run interactively",
"ctxOpenConPtySession": "Open ConPTY session",
"ctxPickUpInTerminal": "Pick up in terminal",
"ctxOpenPlanningSession": "Open planning Session",
@@ -247,15 +246,7 @@
"chipDone": "DONE",
"chipFailed": "FAILED",
"reviewContinueTip": "Send this feedback and re-run the task",
"reviewResetTip": "Discard all changes and reset the task to Idle",
"composer": {
"placeholder": "Message the session…",
"send": "Send",
"stop": "Stop session",
"interrupt": "Interrupt current turn",
"queued": "Queued — sends after the current turn",
"unqueue": "Remove from queue"
}
"reviewResetTip": "Discard all changes and reset the task to Idle"
},
"missionControl": {
"openInApp": "Open in app",
@@ -513,7 +504,7 @@
"taskStatus": { "idle": "Idle", "queued": "Queued", "running": "Running", "waitingForReview": "Waiting for Review", "waitingForChildren": "Waiting for Improvements", "done": "Done", "failed": "Failed", "cancelled": "Cancelled", "parked": "Parked" },
"planningBadge": { "active": "PLANNING", "finalized": "PLANNED" },
"taskRow": { "createdPrefix": "Created {0}", "stepsText": "{0}/{1} steps" },
"tasksIsland": { "completedHeader": "COMPLETED", "completedHeaderCount": "COMPLETED · {0}", "runInteractiveFailed": "Run interactively failed: {0}", "planningOpenFailed": "Couldn't open planning session: {0}", "pickUpInTerminalFailed": "Pick up in terminal failed: {0}", "approveFailed": "Approve & merge failed: {0}" },
"tasksIsland": { "completedHeader": "COMPLETED", "completedHeaderCount": "COMPLETED · {0}", "planningOpenFailed": "Couldn't open planning session: {0}", "pickUpInTerminalFailed": "Pick up in terminal failed: {0}", "approveFailed": "Approve & merge failed: {0}" },
"diff": { "loadFailed": "Failed to load diff: {0}", "noChanges": "No changes to show.", "unavailable": "Diff no longer available — commit range incomplete." },
"planningDiff": { "hubError": "Could not build combined preview (hub error).", "conflict": "Cannot build combined preview: subtask {0} conflicts with an earlier subtask ({1} files)." },
"merge": { "commitMessage": "Merge task: {0}", "workerOfflineBranches": "Worker offline — cannot list branches.", "loadBranchesFailed": "Failed to load branches: {0}", "merged": "Merged.", "conflict": "Merge conflict — target branch restored. Resolve manually or via Continue, then retry.", "blocked": "Blocked: {0}", "unknownStatus": "Unknown status: {0}", "mergeFailed": "Merge failed: {0}" },
+2 -2
View File
@@ -35,7 +35,7 @@ Design/ — Tokens.axaml (design tokens; merged before styles) + IslandStyle
- **IslandsShellViewModel** — root coordinator; owns the three island VMs and the `WorkerClient`, wires cross-island events (selection, notes/prep mode, conflict resolution), owns connection state, the update banner, the inline worker-log strip (clickable → Log Visualizer overlay via `OpenLogVisualizerCommand`; `FlashFooterError` surfaces UI-action failures + the worker's Serilog Warn/Error there), responsive-layout flags (`ShowLists`/`ShowDetails` by window width), `PrimeStatus` flash, and the modal openers (About, RepoImport, WeeklyReport, WorktreesOverview, WorkerConnection help, LogVisualizer) plus `RestartWorkerAsync`/`CheckForUpdatesAsync`. Hosts `UpdateCheckService`.
- **ListsIslandViewModel** — smart lists (My Day, Important, Planned, virtual queued/running/review), user lists, selection, list CRUD, drag-reorder, badge counts, opens list settings / repo import / worktrees overview, `OpenInExplorer`/`OpenInTerminal`.
- **TasksIslandViewModel** — open/overdue/completed groups for the selected list with hierarchy-aware regrouping; task CRUD, drag-reorder, toggle done/star, schedule, enqueue/dequeue, cancel; review actions (approve, reject-rerun, reject-park, cancel); planning session lifecycle (open/resume/discard/finalize, `QueuePlanningSubtasksAsync`); `RunInteractivelyAsync`, `RefineTask`; MyDay extras (`IsMyDayList`, `ClearDayCommand`, `ShowPrepLogCommand`) and the pinned Notes pseudo-row (`ShowNotesRow`, `OpenNotesCommand`). Raises `NotesRequested`/`PrepRequested` events consumed by the shell.
- **TasksIslandViewModel** — open/overdue/completed groups for the selected list with hierarchy-aware regrouping; task CRUD, drag-reorder, toggle done/star, schedule, enqueue/dequeue, cancel; review actions (approve, reject-rerun, reject-park, cancel); planning session lifecycle (open/resume/discard/finalize, `QueuePlanningSubtasksAsync`); `RefineTask`, `OpenConPtySessionRequested` (embedded ConPTY terminal), `PickUpInTerminalAsync`; MyDay extras (`IsMyDayList`, `ClearDayCommand`, `ShowPrepLogCommand`) and the pinned Notes pseudo-row (`ShowNotesRow`, `OpenNotesCommand`). Raises `NotesRequested`/`PrepRequested` events consumed by the shell.
- **DetailsIslandViewModel** — the detail pane for a bound `TaskRowViewModel`. Owns live-log streaming (`Log` via `StreamLineFormatter`), debounced title/description editing, subtasks, session-outcome/roadblock split (splits `Result` at the roadblock marker into two cards), the three-tab work console (`output`/`git`/`session`), child surfacing (`ChildOutcomes` rows plus `ChildrenNeedingAttention`/`HasChildrenNeedingAttention` — children that failed, were cancelled, await review, or reported roadblocks — drive an attention band on the Session tab, which is only visible when `HasChildOutcomes`), and the modes: `IsNotesMode` (hosts `NotesEditorViewModel`), `IsPrepMode`, computed `IsTaskDetailVisible = !IsNotesMode && !IsPrepMode`. Three concerns are extracted into section VMs exposed as properties: **AgentConfigEditorViewModel** (scope=Task; per-task Model/MaxTurns/AgentPath overrides with `InheritedBadge` + `InheritanceResolver`, additive SystemPrompt, debounced auto-save; exposed as `AgentSettings`), **MergeSectionViewModel** (merge-target selection, mergeability indicator via `MergePreviewPresenter` over `PreviewMergeAsync`, `OpenDiffAsync` and `ReviewCombinedDiffCommand` — both build a `DiffViewerViewModel` and call `ShowDiffViewer`), **PrepPanelViewModel** (daily-prep panel: `PrepLog`, `PlanDayCommand``RunDailyPrepNowAsync`, persisted last run via `GetLastPrepLogAsync`). Attachments: `Attachments` (`ObservableCollection<AttachmentRowViewModel>`), `IsDragOver`, `DropStatus`, `CanAcceptDrop`, `AddFilesAsync`, `RemoveAttachmentCommand`; loads on task change; `ComposedPreview` includes attachment paths. Writes directly via `new AttachmentStore()` + `new TaskAttachmentRepository(ctx)`. Helper rows (`ChildOutcomeRowViewModel`, `SubtaskRowViewModel`, `LogLineViewModel`, `AttachmentRowViewModel`) live in the same file.
- **TaskRowViewModel** / **ListNavItemViewModel** — lightweight display VMs (task row: status, planning phase, parent/blocked links, roadblock count, computed `IsDraft`/`IsPlanned`/`IsChild`/`IsPlanningParent`/`CanRefine`; list row: kind Smart/Virtual/User, count, icon/dot keys, drop hints).
- **NotesEditorViewModel** — day navigator + bullet CRUD for daily notes via `INotesApi`.
@@ -45,7 +45,7 @@ Design/ — Tokens.axaml (design tokens; merged before styles) + IslandStyle
## Services
- **WorkerClient** / **IWorkerClient** — SignalR client connecting to `http://127.0.0.1:47821/hub`, auto-reconnect with exponential backoff. The surface tracks `WorkerHub` (see `src/ClaudeDo.Worker/CLAUDE.md` for the canonical method/event list); groups: task execution (RunNow/Cancel/Continue/Reset/SetTaskStatus), review (`ApproveReviewAsync(taskId, targetBranch) -> MergeResultDto`, reject-to-queue/idle, cancel review, `PreviewMergeAsync -> MergePreviewDto`), planning sessions (start/resume/discard/finalize, queue subtasks, pending draft count, interactive terminal, refine), planning aggregate/integration-branch diffs, unit-merge continue/abort, single-task conflict resolving (start/get-conflict-documents/write-resolution/continue/abort), worktrees (overview, set state, force remove, cleanup, reset all), agents, app settings, lists/config, weekly report, daily notes, daily prep (`RunDailyPrepNowAsync`, `ClearMyDayAsync`, `GetLastPrepLogAsync`), prime schedules, recent worker logs (`GetRecentLogsAsync`). Events mirror `HubBroadcaster` (task/worktree/list/run updates, prep events, planning-merge events, refine events, worker log). Lifecycle (`StartAsync`/`StopAsync`) and a few admin methods live only on the concrete `WorkerClient`.
- **WorkerClient** / **IWorkerClient** — SignalR client connecting to `http://127.0.0.1:47821/hub`, auto-reconnect with exponential backoff. The surface tracks `WorkerHub` (see `src/ClaudeDo.Worker/CLAUDE.md` for the canonical method/event list); groups: task execution (RunNow/Cancel/Continue/Reset/SetTaskStatus), review (`ApproveReviewAsync(taskId, targetBranch) -> MergeResultDto`, reject-to-queue/idle, cancel review, `PreviewMergeAsync -> MergePreviewDto`), planning sessions (start/resume/discard/finalize, queue subtasks, pending draft count, refine), pick-up-in-terminal + embedded ConPTY launch specs (`GetInteractiveLaunchSpecAsync`/`GetAdHocLaunchSpecAsync`), planning aggregate/integration-branch diffs, unit-merge continue/abort, single-task conflict resolving (start/get-conflict-documents/write-resolution/continue/abort), worktrees (overview, set state, force remove, cleanup, reset all), agents, app settings, lists/config, weekly report, daily notes, daily prep (`RunDailyPrepNowAsync`, `ClearMyDayAsync`, `GetLastPrepLogAsync`), prime schedules, recent worker logs (`GetRecentLogsAsync`). Events mirror `HubBroadcaster` (task/worktree/list/run updates, prep events, planning-merge events, refine events, worker log). Lifecycle (`StartAsync`/`StopAsync`) and a few admin methods live only on the concrete `WorkerClient`.
- **INotesApi** / **WorkerNotesApi** — daily-note CRUD (`ListAsync(day)`, `AddAsync`, `UpdateAsync`, `DeleteAsync`); UI DTO `DailyNoteDto(Id, Date, Text, SortOrder)`.
- **IPrimeScheduleApi** — prime-schedule CRUD (`ListAsync`, `UpsertAsync`, `DeleteAsync`).
- **UpdateCheckService** — polls releases, exposes `LastCheckStatus`/`LatestVersion`/`CheckNowAsync` (feeds the shell's update banner).
@@ -25,11 +25,6 @@ public interface IWorkerClient : INotifyPropertyChanged
/// <summary>A pending question was answered, timed out, or the run ended: (taskId, questionId).</summary>
event Action<string, string>? TaskQuestionResolvedEvent;
event Action<string>? InteractiveSessionStartedEvent;
event Action<string>? InteractiveSessionEndedEvent;
event Action<string, IReadOnlyList<string>>? InteractiveQueueChangedEvent;
event Action<string, string>? InteractiveMessageSentEvent;
event Action? PrepStartedEvent;
event Action<string>? PrepLineEvent;
event Action<bool>? PrepFinishedEvent;
@@ -51,10 +46,6 @@ public interface IWorkerClient : INotifyPropertyChanged
Task ContinueTaskAsync(string taskId, string followUpPrompt);
/// <summary>Answer a question a running task raised via AskUser.</summary>
Task AnswerTaskQuestionAsync(string taskId, string questionId, string answer);
Task SendInteractiveMessageAsync(string taskId, string text);
Task RemoveQueuedInteractiveMessageAsync(string taskId, string text);
Task StopInteractiveSessionAsync(string taskId);
Task InterruptInteractiveSessionAsync(string taskId);
/// <summary>The question a running task is currently blocked on, if any (for re-attach).</summary>
Task<PendingQuestionDto?> GetPendingQuestionAsync(string taskId);
Task ResetTaskAsync(string taskId);
@@ -83,9 +74,7 @@ public interface IWorkerClient : INotifyPropertyChanged
Task<MergeResultDto> ContinueConflictMergeAsync(string taskId);
Task AbortConflictMergeAsync(string taskId);
Task StartPlanningSessionAsync(string taskId, CancellationToken ct = default);
Task OpenInteractiveTerminalAsync(string taskId, CancellationToken ct = default);
// Picks up a task's Claude session in a real terminal window (--resume) — distinct
// from OpenInteractiveTerminalAsync (the in-app streaming session).
// Picks up a task's Claude session in a real terminal window (--resume).
Task ResumeTaskInTerminalAsync(string taskId, CancellationToken ct = default);
/// <summary>Launch spec for an embedded ConPTY terminal to open an interactive session
/// in a task's worktree (same worktree prep as an autonomous run).</summary>
-51
View File
@@ -49,10 +49,6 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerC
public event Action<string>? TaskUpdatedEvent;
public event Action<string, string, string>? TaskQuestionAskedEvent;
public event Action<string, string>? TaskQuestionResolvedEvent;
public event Action<string>? InteractiveSessionStartedEvent;
public event Action<string>? InteractiveSessionEndedEvent;
public event Action<string, IReadOnlyList<string>>? InteractiveQueueChangedEvent;
public event Action<string, string>? InteractiveMessageSentEvent;
public event Action? ConnectionRestoredEvent;
public event Action<string>? WorktreeUpdatedEvent;
public event Action<string>? ListUpdatedEvent;
@@ -152,26 +148,6 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerC
Dispatcher.UIThread.Post(() => TaskQuestionResolvedEvent?.Invoke(taskId, questionId));
});
_hub.On<string>("InteractiveSessionStarted", taskId =>
{
Dispatcher.UIThread.Post(() => InteractiveSessionStartedEvent?.Invoke(taskId));
});
_hub.On<string>("InteractiveSessionEnded", taskId =>
{
Dispatcher.UIThread.Post(() => InteractiveSessionEndedEvent?.Invoke(taskId));
});
_hub.On<string, IReadOnlyList<string>>("InteractiveQueueChanged", (taskId, pending) =>
{
Dispatcher.UIThread.Post(() => InteractiveQueueChangedEvent?.Invoke(taskId, pending));
});
_hub.On<string, string>("InteractiveMessageSent", (taskId, text) =>
{
Dispatcher.UIThread.Post(() => InteractiveMessageSentEvent?.Invoke(taskId, text));
});
_hub.On<string>("WorktreeUpdated", taskId =>
{
Dispatcher.UIThread.Post(() => WorktreeUpdatedEvent?.Invoke(taskId));
@@ -303,30 +279,6 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerC
catch { /* offline or already resolved — the UI clears optimistically */ }
}
public async Task SendInteractiveMessageAsync(string taskId, string text)
{
try { await _hub.InvokeAsync("SendInteractiveMessage", taskId, text); }
catch { /* offline or session already ended */ }
}
public async Task RemoveQueuedInteractiveMessageAsync(string taskId, string text)
{
try { await _hub.InvokeAsync("RemoveQueuedInteractiveMessage", taskId, text); }
catch { /* offline or session already ended */ }
}
public async Task StopInteractiveSessionAsync(string taskId)
{
try { await _hub.InvokeAsync("StopInteractiveSession", taskId); }
catch { /* offline */ }
}
public async Task InterruptInteractiveSessionAsync(string taskId)
{
try { await _hub.InvokeAsync("InterruptInteractiveSession", taskId); }
catch { /* offline */ }
}
public Task<PendingQuestionDto?> GetPendingQuestionAsync(string taskId)
=> TryInvokeAsync<PendingQuestionDto>("GetPendingQuestion", taskId);
@@ -558,9 +510,6 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerC
public async Task<PlanningSessionResumeInfo> ResumePlanningSessionAsync(string taskId, CancellationToken ct = default)
=> await _hub.InvokeAsync<PlanningSessionResumeInfo>("ResumePlanningSessionAsync", taskId, ct);
public async Task OpenInteractiveTerminalAsync(string taskId, CancellationToken ct = default)
=> await _hub.InvokeAsync("OpenInteractiveTerminalAsync", taskId, ct);
public async Task ResumeTaskInTerminalAsync(string taskId, CancellationToken ct = default)
=> await _hub.InvokeAsync("ResumeTaskInTerminal", taskId, ct);
@@ -71,9 +71,6 @@ public sealed partial class TaskMonitorViewModel : ViewModelBase, IMissionContro
private const string RoadblockMarker = "Roadblocks reported during the run:";
public ObservableCollection<QueuedMessageViewModel> QueuedMessages { get; } = new();
public bool HasQueuedMessages => QueuedMessages.Count > 0;
// Captured handler delegates for disposal
private readonly Action<string, string> _onTaskMessage;
private readonly Action<string, string, DateTime> _onTaskStarted;
@@ -81,19 +78,6 @@ public sealed partial class TaskMonitorViewModel : ViewModelBase, IMissionContro
private readonly Action<string> _onTaskUpdated;
private readonly Action<string, string, string> _onTaskQuestionAsked;
private readonly Action<string, string> _onTaskQuestionResolved;
private readonly Action<string> _onInteractiveStarted;
private readonly Action<string> _onInteractiveEnded;
private readonly Action<string, IReadOnlyList<string>> _onInteractiveQueueChanged;
private readonly Action<string, string> _onInteractiveMessageSent;
// Interactive composer — active while the worker is in an interactive session.
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubmitComposerCommand))]
private bool _isInteractiveLive;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubmitComposerCommand))]
private string _composerDraft = string.Empty;
// A question the running task raised via AskUser and is blocking on, plus the answer
// the user is typing. Ephemeral (in-memory + live events) — the task is still Running.
@@ -161,46 +145,6 @@ public sealed partial class TaskMonitorViewModel : ViewModelBase, IMissionContro
ClearPendingQuestion();
};
_worker.TaskQuestionResolvedEvent += _onTaskQuestionResolved;
_onInteractiveStarted = taskId =>
{
if (taskId == _subscribedTaskId) { IsInteractiveLive = true; AgentState = "running"; }
};
_worker.InteractiveSessionStartedEvent += _onInteractiveStarted;
_onInteractiveEnded = taskId =>
{
if (taskId != _subscribedTaskId) return;
IsInteractiveLive = false;
AgentState = "done";
QueuedMessages.Clear();
OnPropertyChanged(nameof(HasQueuedMessages));
};
_worker.InteractiveSessionEndedEvent += _onInteractiveEnded;
_onInteractiveQueueChanged = (taskId, pending) =>
{
if (taskId != _subscribedTaskId) return;
QueuedMessages.Clear();
foreach (var m in pending)
{
var text = m;
QueuedMessages.Add(new QueuedMessageViewModel
{
Text = text,
RemoveCommand = new CommunityToolkit.Mvvm.Input.RelayCommand(() => _ = RemoveQueuedAsync(text)),
});
}
OnPropertyChanged(nameof(HasQueuedMessages));
};
_worker.InteractiveQueueChangedEvent += _onInteractiveQueueChanged;
_onInteractiveMessageSent = (taskId, text) =>
{
if (taskId == _subscribedTaskId)
Log.Add(new LogLineViewModel { Kind = LogKind.User, Text = text });
};
_worker.InteractiveMessageSentEvent += _onInteractiveMessageSent;
}
// Surface a pending question (used by live event + re-attach hydration).
@@ -210,45 +154,6 @@ public sealed partial class TaskMonitorViewModel : ViewModelBase, IMissionContro
PendingQuestion = question;
}
// Used by Mission Control when it creates the monitor after the started event already fired.
public void SetInteractiveLive(bool live)
{
IsInteractiveLive = live;
if (live) AgentState = "running";
}
[RelayCommand(CanExecute = nameof(CanSubmitComposer))]
private async System.Threading.Tasks.Task SubmitComposer()
{
if (string.IsNullOrEmpty(_subscribedTaskId)) return;
var text = ComposerDraft;
if (string.IsNullOrWhiteSpace(text)) return;
ComposerDraft = string.Empty;
await _worker.SendInteractiveMessageAsync(_subscribedTaskId, text);
}
private bool CanSubmitComposer() => IsInteractiveLive && !string.IsNullOrWhiteSpace(ComposerDraft);
[RelayCommand]
private async System.Threading.Tasks.Task StopInteractive()
{
if (!string.IsNullOrEmpty(_subscribedTaskId) && IsInteractiveLive)
await _worker.StopInteractiveSessionAsync(_subscribedTaskId);
}
[RelayCommand]
private async System.Threading.Tasks.Task InterruptInteractive()
{
if (!string.IsNullOrEmpty(_subscribedTaskId) && IsInteractiveLive)
await _worker.InterruptInteractiveSessionAsync(_subscribedTaskId);
}
private async System.Threading.Tasks.Task RemoveQueuedAsync(string text)
{
if (!string.IsNullOrEmpty(_subscribedTaskId))
await _worker.RemoveQueuedInteractiveMessageAsync(_subscribedTaskId, text);
}
private void ClearPendingQuestion()
{
PendingQuestionId = null;
@@ -297,10 +202,6 @@ public sealed partial class TaskMonitorViewModel : ViewModelBase, IMissionContro
SessionOutcome = null;
Roadblocks = null;
ClearPendingQuestion();
IsInteractiveLive = false;
ComposerDraft = string.Empty;
QueuedMessages.Clear();
OnPropertyChanged(nameof(HasQueuedMessages));
}
[ObservableProperty]
@@ -524,15 +425,5 @@ public sealed partial class TaskMonitorViewModel : ViewModelBase, IMissionContro
_worker.TaskUpdatedEvent -= _onTaskUpdated;
_worker.TaskQuestionAskedEvent -= _onTaskQuestionAsked;
_worker.TaskQuestionResolvedEvent -= _onTaskQuestionResolved;
_worker.InteractiveSessionStartedEvent -= _onInteractiveStarted;
_worker.InteractiveSessionEndedEvent -= _onInteractiveEnded;
_worker.InteractiveQueueChangedEvent -= _onInteractiveQueueChanged;
_worker.InteractiveMessageSentEvent -= _onInteractiveMessageSent;
}
}
public sealed class QueuedMessageViewModel
{
public required string Text { get; init; }
public required System.Windows.Input.ICommand RemoveCommand { get; init; }
}
@@ -810,18 +810,8 @@ public sealed partial class TasksIslandViewModel : ViewModelBase, IDisposable
catch (Exception ex) { ErrorReported?.Invoke(Loc.T("vm.tasksIsland.planningOpenFailed", ex.Message)); }
}
[RelayCommand]
private async Task RunInteractivelyAsync(TaskRowViewModel? row)
{
if (row is null || _worker is null) return;
ForegroundHelper.AllowAny();
try { await _worker.OpenInteractiveTerminalAsync(row.Id); }
catch (Exception ex) { ErrorReported?.Invoke(Loc.T("vm.tasksIsland.runInteractiveFailed", ex.Message)); }
}
// Distinct from RunInteractivelyAsync (the old in-app streaming session) — this opens the
// task in an embedded ConPTY terminal pane in the Command Center. The shell owns the
// Mission Control view model, so this just raises an event for it to act on.
// Opens the task in an embedded ConPTY terminal pane in the Command Center. The shell owns
// the Mission Control view model, so this just raises an event for it to act on.
public event Action<string>? OpenConPtySessionRequested;
[RelayCommand]
@@ -22,7 +22,6 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
private readonly Action<string, string, string, DateTime> _onTaskFinished;
private readonly Action<string> _onTaskUpdated;
private readonly Action _onConnectionRestored;
private readonly Action<string> _onInteractiveStarted;
public ObservableCollection<TaskMonitorViewModel> Monitors { get; } = new();
@@ -94,14 +93,6 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
_onConnectionRestored = () => { SeedActive(); _ = RefreshQueueAsync(); };
_worker.ConnectionRestoredEvent += _onConnectionRestored;
_onInteractiveStarted = taskId =>
{
EnsureMonitor(taskId);
var m = Monitors.FirstOrDefault(x => x.SubscribedTaskId == taskId);
m?.SetInteractiveLive(true);
};
_worker.InteractiveSessionStartedEvent += _onInteractiveStarted;
SeedActive();
_ = RefreshQueueAsync();
}
@@ -231,8 +222,7 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
}
// Fetches the launch spec for a task's worktree and hosts an embedded ConPTY session as a
// Command Center pane (task-based only). A distinct entry point from RunInteractivelyAsync's
// streaming session — the two coexist until the streaming stack is removed.
// Command Center pane (task-based only).
public async System.Threading.Tasks.Task OpenConPtySessionAsync(string taskId)
{
if (string.IsNullOrEmpty(taskId)) return;
@@ -362,7 +352,6 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
_worker.TaskFinishedEvent -= _onTaskFinished;
_worker.TaskUpdatedEvent -= _onTaskUpdated;
_worker.ConnectionRestoredEvent -= _onConnectionRestored;
_worker.InteractiveSessionStartedEvent -= _onInteractiveStarted;
Monitors.CollectionChanged -= OnMonitorsChanged;
ConPtySessions.CollectionChanged -= OnConPtySessionsChanged;
Panes.CollectionChanged -= OnPanesChanged;
@@ -263,83 +263,6 @@
Command="{Binding RejectReviewCommand}" />
</Grid>
<!-- Interactive composer + queued strip — chat with a live in-app session -->
<StackPanel DockPanel.Dock="Bottom" Orientation="Vertical">
<!-- Queued messages strip -->
<Border IsVisible="{Binding Monitor.HasQueuedMessages}"
BorderBrush="{DynamicResource LineBrush}"
BorderThickness="0,1,0,0"
Padding="12,4">
<StackPanel Spacing="2">
<TextBlock Classes="meta"
Text="{loc:Tr session.composer.queued}"
Foreground="{DynamicResource TextMuteBrush}" />
<ItemsControl ItemsSource="{Binding Monitor.QueuedMessages}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:QueuedMessageViewModel">
<Grid ColumnDefinitions="Auto,*,Auto" Margin="0,1">
<TextBlock Grid.Column="0"
Text="⧗"
Foreground="{DynamicResource TextMuteBrush}"
FontFamily="{StaticResource MonoFont}"
FontSize="{StaticResource FontSizeMono}"
VerticalAlignment="Center"
Margin="0,0,6,0" />
<TextBlock Grid.Column="1"
Text="{Binding Text}"
Foreground="{DynamicResource TextDimBrush}"
FontFamily="{StaticResource MonoFont}"
FontSize="{StaticResource FontSizeMono}"
TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
<Button Grid.Column="2"
Classes="title-ctrl"
Command="{Binding RemoveCommand}"
ToolTip.Tip="{loc:Tr session.composer.unqueue}"
Margin="4,0,0,0">
<PathIcon Data="{StaticResource Icon.WinClose}" Width="8" Height="8"/>
</Button>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- Composer input row -->
<Grid IsVisible="{Binding Monitor.IsInteractiveLive}"
ColumnDefinitions="Auto,*,Auto,Auto"
Margin="12,2,12,8">
<TextBlock Grid.Column="0" Text="&#x276F;"
FontFamily="{StaticResource MonoFont}"
FontSize="{StaticResource FontSizeMono}"
Foreground="{DynamicResource AccentBrush}"
VerticalAlignment="Center" Margin="0,0,8,0" />
<TextBox Grid.Column="1"
Classes="review-prompt"
Text="{Binding Monitor.ComposerDraft, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
AcceptsReturn="False"
TextWrapping="Wrap"
MaxHeight="160"
PlaceholderText="{loc:Tr session.composer.placeholder}"
VerticalContentAlignment="Center"
FontFamily="{StaticResource MonoFont}"
FontSize="{StaticResource FontSizeMono}">
<TextBox.KeyBindings>
<KeyBinding Gesture="Enter" Command="{Binding Monitor.SubmitComposerCommand}" />
</TextBox.KeyBindings>
</TextBox>
<Button Grid.Column="2" Classes="prompt-action"
VerticalAlignment="Center" Margin="12,0,0,0"
Command="{Binding Monitor.InterruptInteractiveCommand}"
ToolTip.Tip="{loc:Tr session.composer.interrupt}">
<PathIcon Data="{StaticResource Icon.Stop}" Width="10" Height="10"/>
</Button>
<Button Grid.Column="3" Classes="prompt-action accent" Content="[Send]"
VerticalAlignment="Center" Margin="4,0,0,0"
Command="{Binding Monitor.SubmitComposerCommand}" />
</Grid>
</StackPanel>
<ScrollViewer Name="LogScroll"
VerticalScrollBarVisibility="Visible"
AllowAutoHide="False"
@@ -50,79 +50,6 @@
</Border>
</Grid>
<!-- ── Queued strip + Composer bar ── -->
<StackPanel DockPanel.Dock="Bottom" Orientation="Vertical">
<!-- Queued messages strip -->
<Border IsVisible="{Binding #Root.HasQueuedMessages}"
Background="{DynamicResource Surface2Brush}"
BorderBrush="{DynamicResource LineBrush}"
BorderThickness="0,0,0,1"
Padding="8,4">
<StackPanel Spacing="2">
<TextBlock Classes="meta"
Text="{loc:Tr session.composer.queued}"
Foreground="{DynamicResource TextMuteBrush}" />
<ItemsControl ItemsSource="{Binding #Root.QueuedMessages}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:QueuedMessageViewModel">
<Grid ColumnDefinitions="Auto,*,Auto" Margin="0,1">
<TextBlock Grid.Column="0"
Text="⧗"
Foreground="{DynamicResource TextMuteBrush}"
FontFamily="{StaticResource MonoFont}"
FontSize="{StaticResource FontSizeMono}"
VerticalAlignment="Center"
Margin="0,0,6,0" />
<TextBlock Grid.Column="1"
Text="{Binding Text}"
Foreground="{DynamicResource TextDimBrush}"
FontFamily="{StaticResource MonoFont}"
FontSize="{StaticResource FontSizeMono}"
TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
<Button Grid.Column="2"
Classes="title-ctrl"
Command="{Binding RemoveCommand}"
ToolTip.Tip="{loc:Tr session.composer.unqueue}"
Margin="4,0,0,0">
<PathIcon Data="{StaticResource Icon.WinClose}" Width="8" Height="8"/>
</Button>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- Composer input row -->
<Border IsVisible="{Binding #Root.IsComposerVisible}"
Background="{DynamicResource Surface2Brush}"
BorderBrush="{DynamicResource LineBrush}"
BorderThickness="0,1,0,0"
Padding="6,5">
<Grid ColumnDefinitions="*,Auto,Auto">
<TextBox Grid.Column="0"
Text="{Binding #Root.ComposerText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
PlaceholderText="{Binding #Root.ComposerPlaceholder}"
AcceptsReturn="False">
<TextBox.KeyBindings>
<KeyBinding Gesture="Enter" Command="{Binding #Root.SubmitCommand}"/>
</TextBox.KeyBindings>
</TextBox>
<Button Grid.Column="1"
Margin="6,0,0,0"
Classes="title-ctrl"
Command="{Binding #Root.InterruptCommand}"
ToolTip.Tip="{loc:Tr session.composer.interrupt}">
<PathIcon Data="{StaticResource Icon.Stop}" Width="10" Height="10"/>
</Button>
<Button Grid.Column="2"
Margin="6,0,0,0"
Content="{loc:Tr session.composer.send}"
Command="{Binding #Root.SubmitCommand}"/>
</Grid>
</Border>
</StackPanel>
<!-- ── Log output ── -->
<ScrollViewer Name="LogScroll"
VerticalScrollBarVisibility="Visible"
@@ -1,9 +1,7 @@
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
namespace ClaudeDo.Ui.Views.Islands;
@@ -19,33 +17,12 @@ public partial class SessionTerminalView : UserControl
AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(IsDone));
public static readonly StyledProperty<bool> IsFailedProperty =
AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(IsFailed));
public static readonly StyledProperty<bool> IsComposerVisibleProperty =
AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(IsComposerVisible), defaultValue: false);
public static readonly StyledProperty<string?> ComposerTextProperty =
AvaloniaProperty.Register<SessionTerminalView, string?>(nameof(ComposerText), defaultBindingMode: BindingMode.TwoWay);
public static readonly StyledProperty<ICommand?> SubmitCommandProperty =
AvaloniaProperty.Register<SessionTerminalView, ICommand?>(nameof(SubmitCommand));
public static readonly StyledProperty<ICommand?> InterruptCommandProperty =
AvaloniaProperty.Register<SessionTerminalView, ICommand?>(nameof(InterruptCommand));
public static readonly StyledProperty<string?> ComposerPlaceholderProperty =
AvaloniaProperty.Register<SessionTerminalView, string?>(nameof(ComposerPlaceholder));
public static readonly StyledProperty<System.Collections.IEnumerable?> QueuedMessagesProperty =
AvaloniaProperty.Register<SessionTerminalView, System.Collections.IEnumerable?>(nameof(QueuedMessages));
public static readonly StyledProperty<bool> HasQueuedMessagesProperty =
AvaloniaProperty.Register<SessionTerminalView, bool>(nameof(HasQueuedMessages), defaultValue: false);
public IEnumerable? Entries { get => GetValue(EntriesProperty); set => SetValue(EntriesProperty, value); }
public string? Label { get => GetValue(LabelProperty); set => SetValue(LabelProperty, value); }
public bool IsRunning { get => GetValue(IsRunningProperty); set => SetValue(IsRunningProperty, value); }
public bool IsDone { get => GetValue(IsDoneProperty); set => SetValue(IsDoneProperty, value); }
public bool IsFailed { get => GetValue(IsFailedProperty); set => SetValue(IsFailedProperty, value); }
public bool IsComposerVisible { get => GetValue(IsComposerVisibleProperty); set => SetValue(IsComposerVisibleProperty, value); }
public string? ComposerText { get => GetValue(ComposerTextProperty); set => SetValue(ComposerTextProperty, value); }
public ICommand? SubmitCommand { get => GetValue(SubmitCommandProperty); set => SetValue(SubmitCommandProperty, value); }
public ICommand? InterruptCommand { get => GetValue(InterruptCommandProperty); set => SetValue(InterruptCommandProperty, value); }
public string? ComposerPlaceholder { get => GetValue(ComposerPlaceholderProperty); set => SetValue(ComposerPlaceholderProperty, value); }
public System.Collections.IEnumerable? QueuedMessages { get => GetValue(QueuedMessagesProperty); set => SetValue(QueuedMessagesProperty, value); }
public bool HasQueuedMessages { get => GetValue(HasQueuedMessagesProperty); set => SetValue(HasQueuedMessagesProperty, value); }
private INotifyCollectionChanged? _subscribedCollection;
@@ -49,8 +49,6 @@
<MenuItem Header="{loc:Tr tasks.ctxMarkCancelled}" Tag="Cancelled" Click="OnSetStatusClick"/>
</MenuItem>
<Separator/>
<MenuItem Header="{loc:Tr tasks.ctxRunInteractively}"
Click="OnRunInteractivelyClick"/>
<MenuItem Header="{loc:Tr tasks.ctxOpenConPtySession}"
Click="OnOpenConPtySessionClick"/>
<MenuItem Header="{loc:Tr tasks.ctxPickUpInTerminal}"
@@ -61,12 +61,6 @@ public partial class TaskRowView : UserControl
await vm.OpenPlanningSessionCommand.ExecuteAsync(row);
}
private async void OnRunInteractivelyClick(object? sender, RoutedEventArgs e)
{
if (DataContext is TaskRowViewModel row && FindTasksVm() is { } vm)
await vm.RunInteractivelyCommand.ExecuteAsync(row);
}
private void OnOpenConPtySessionClick(object? sender, RoutedEventArgs e)
{
if (DataContext is TaskRowViewModel row && FindTasksVm() is { } vm)
@@ -107,14 +107,7 @@
Label="{Binding DisplayTitle}"
IsRunning="{Binding IsRunning}"
IsDone="{Binding IsDone}"
IsFailed="{Binding IsFailed}"
IsComposerVisible="{Binding IsInteractiveLive}"
ComposerText="{Binding ComposerDraft, Mode=TwoWay}"
SubmitCommand="{Binding SubmitComposerCommand}"
InterruptCommand="{Binding InterruptInteractiveCommand}"
ComposerPlaceholder="{loc:Tr session.composer.placeholder}"
QueuedMessages="{Binding QueuedMessages}"
HasQueuedMessages="{Binding HasQueuedMessages}" />
IsFailed="{Binding IsFailed}" />
</DockPanel>
</Border>
+3 -2
View File
@@ -12,7 +12,7 @@ Worker/
Worktrees/ — WorktreeMaintenanceService
Agents/ — AgentFileService, DefaultAgentSeeder
Runner/ — TaskRunner + Claude CLI integration; TaskRunMcpService/TaskRunMcpContext/TaskRunTokenRegistry (in-task MCP wired during execution)
Planning/ — PlanningSessionManager, PlanningChainCoordinator, PlanningMcpService, PlanningMergeOrchestrator, PlanningAggregator, PlanningSessionContext/PlanningTokenAuth/PlanningMcpContextAccessor, WindowsTerminalLauncher (ITerminalLauncher) — wt launcher for planning + interactive sessions
Planning/ — PlanningSessionManager, PlanningChainCoordinator, PlanningMcpService, PlanningMergeOrchestrator, PlanningAggregator, PlanningSessionContext/PlanningTokenAuth/PlanningMcpContextAccessor, WindowsTerminalLauncher (ITerminalLauncher) — wt launcher for planning sessions + pick-up-in-terminal
Refine/ — RefineRunner + RefinePrompt (hub `RefineTask`; broadcasts RefineStarted/RefineFinished)
External/ — ExternalMcpService + sibling tool classes
Config/ — WorkerConfig
@@ -154,7 +154,8 @@ Each CLI invocation is recorded in the `task_runs` table via `TaskRunRepository`
- Execution: `Ping`, `GetActive`, `RunNow`, `CancelTask`, `WakeQueue`, `ContinueTask`, `ResetTask`, `SetTaskStatus`, `RefineTask`
- Review/merge: `ApproveReview(taskId, targetBranch) -> MergeResultDto` (childless task: merges its worktree then Done, conflict stays WaitingForReview; task with children: drives `PlanningMergeOrchestrator` to merge the whole unit), `ContinuePlanningMerge` / `AbortPlanningMerge` (resolve a unit-merge conflict), `PreviewMerge(taskId, targetBranch) -> MergePreviewDto` (non-destructive mergeability check), `RejectReviewToQueue`, `RejectReviewToIdle`, `CancelReview`, `MergeTask`, `GetMergeTargets`
- Single-task conflict resolver (Layer C): `StartConflictMerge`, `GetMergeConflictDocuments` (segments), `WriteConflictResolution`, `ContinueConflictMerge`, `AbortConflictMerge` (service-level `TaskMergeService.ContinueMergeAsync`/`AbortMergeAsync` keep their names)
- Planning sessions: `StartPlanningSession`, `ResumePlanningSession`, `DiscardPlanningSession`, `FinalizePlanningSession`, `QueuePlanningSubtasks`, `GetPendingDraftCount`, `OpenInteractiveTerminal`, `GetPlanningAggregate` (per-subtask diffs), `BuildPlanningIntegrationBranch` (combined diff)
- Planning sessions: `StartPlanningSession`, `ResumePlanningSession`, `DiscardPlanningSession`, `FinalizePlanningSession`, `QueuePlanningSubtasks`, `GetPendingDraftCount`, `GetPlanningAggregate` (per-subtask diffs), `BuildPlanningIntegrationBranch` (combined diff)
- Interactive sessions (embedded ConPTY, UI process): `ResumeTaskInTerminal` (pick-up-in-terminal), `GetInteractiveLaunchSpec`, `GetAdHocLaunchSpec`
- Worktrees: `CleanupFinishedWorktrees`, `ResetAllWorktrees`, `GetWorktreesOverview`, `SetWorktreeState`, `ForceRemoveWorktree`
- Agents/settings/lists: `GetAgents`, `RefreshAgents`, `RestoreDefaultAgents`, `GetAppSettings`, `UpdateAppSettings`, `UpdateList`, `UpdateListConfig`, `GetListConfig`, `UpdateTaskAgentSettings`
- Reports/notes/prep: `GetWeekReport`, `GenerateWeekReport`, `GetDailyNotes`, `AddDailyNote`, `UpdateDailyNote`, `DeleteDailyNote`, `RunDailyPrepNow`, `ClearMyDay`, `GetLastPrepLog`, `ListPrimeSchedules`, `UpsertPrimeSchedule`, `DeletePrimeSchedule`
@@ -41,10 +41,6 @@ public sealed class WorkerConfig
[JsonPropertyName("external_mcp_api_key")]
public string? ExternalMcpApiKey { get; set; }
/// <summary>Interactive/streaming sessions idle longer than this are stopped by IdleSessionReaper. 0 disables reaping.</summary>
[JsonPropertyName("interactive_idle_timeout_minutes")]
public int InteractiveIdleTimeoutMinutes { get; set; } = 30;
[JsonPropertyName("online_inbox")]
public OnlineInboxConfig OnlineInbox { get; set; } = new();
-12
View File
@@ -77,16 +77,4 @@ public sealed class HubBroadcaster : IPrimeBroadcaster, IRefineBroadcaster
Task IRefineBroadcaster.RefineStartedAsync(string taskId) => RefineStarted(taskId);
Task IRefineBroadcaster.RefineFinishedAsync(string taskId, bool success, string? error) =>
RefineFinished(taskId, success, error);
public Task InteractiveSessionStarted(string taskId) =>
_hub.Clients.All.SendAsync("InteractiveSessionStarted", taskId);
public Task InteractiveSessionEnded(string taskId) =>
_hub.Clients.All.SendAsync("InteractiveSessionEnded", taskId);
public Task InteractiveQueueChanged(string taskId, IReadOnlyList<string> pending) =>
_hub.Clients.All.SendAsync("InteractiveQueueChanged", taskId, pending);
public Task InteractiveMessageSent(string taskId, string text) =>
_hub.Clients.All.SendAsync("InteractiveMessageSent", taskId, text);
}
+2 -21
View File
@@ -127,7 +127,6 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
private readonly OnlineInboxConfig _onlineInboxConfig;
private readonly OnlineTokenStore _onlineTokenStore;
private readonly Runner.PendingQuestionRegistry _pendingQuestions;
private readonly InteractiveSessionService _interactive;
private readonly LogRingBuffer? _logBuffer;
private readonly ISessionSkillRegistry _skillRegistry;
private readonly IInteractiveLaunchSpecService? _interactiveLaunchSpec;
@@ -156,7 +155,6 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
OnlineInboxConfig onlineInboxConfig,
OnlineTokenStore onlineTokenStore,
Runner.PendingQuestionRegistry pendingQuestions,
InteractiveSessionService interactive,
ISessionSkillRegistry skillRegistry,
LogRingBuffer? logBuffer = null,
IInteractiveLaunchSpecService? interactiveLaunchSpec = null)
@@ -184,7 +182,6 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
_onlineInboxConfig = onlineInboxConfig;
_onlineTokenStore = onlineTokenStore;
_pendingQuestions = pendingQuestions;
_interactive = interactive;
_skillRegistry = skillRegistry;
_logBuffer = logBuffer;
_interactiveLaunchSpec = interactiveLaunchSpec;
@@ -624,13 +621,9 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
return ctx;
}
public Task OpenInteractiveTerminalAsync(string taskId) =>
_interactive.StartAsync(taskId, Context.ConnectionAborted);
// Picks up a task's Claude session in a real terminal window (--resume) so the user can
// drive it by hand — distinct from OpenInteractiveTerminalAsync (the in-app streaming
// session). Only for tasks the worker isn't actively running, with a persisted session
// id and a live worktree.
// drive it by hand. Only for tasks the worker isn't actively running, with a persisted
// session id and a live worktree.
public Task ResumeTaskInTerminal(string taskId) => HubGuard(async () =>
{
await using var ctx = await _dbFactory.CreateDbContextAsync();
@@ -680,18 +673,6 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
return _interactiveLaunchSpec.BuildForDirectoryAsync(directory, Context.ConnectionAborted);
});
public Task SendInteractiveMessage(string taskId, string text) =>
_interactive.SendAsync(taskId, text, Context.ConnectionAborted);
public Task StopInteractiveSession(string taskId) =>
_interactive.StopAsync(taskId, Context.ConnectionAborted);
public Task InterruptInteractiveSession(string taskId) =>
_interactive.InterruptAsync(taskId, Context.ConnectionAborted);
public Task RemoveQueuedInteractiveMessage(string taskId, string text) =>
_interactive.RemoveQueuedAsync(taskId, text, Context.ConnectionAborted);
public async Task<DiscardPlanningOutcome> DiscardPlanningSessionAsync(string taskId, bool dequeueQueuedChildren = false)
{
var outcome = await _planning.DiscardAsync(taskId, dequeueQueuedChildren, Context.ConnectionAborted);
@@ -1,172 +0,0 @@
using System.Text;
using ClaudeDo.Data;
using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.Config;
using ClaudeDo.Worker.Hub;
using ClaudeDo.Worker.Runner;
using ClaudeDo.Worker.Runner.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace ClaudeDo.Worker.Planning;
public sealed class InteractiveSessionService
{
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
private readonly WorkerConfig _cfg;
private readonly HubBroadcaster _broadcaster;
private readonly LiveSessionRegistry _registry;
private readonly ILoggerFactory _loggerFactory;
// Optional factory for tests. Signature: (onLine) -> (session, waitForExitTask).
// The waitForExitTask completes when the underlying process has exited.
private readonly Func<string, IReadOnlyList<string>, Func<string, Task>, (ILiveSession session, Task exitTask)>? _sessionFactory;
public InteractiveSessionService(
IDbContextFactory<ClaudeDoDbContext> dbFactory,
WorkerConfig cfg,
HubBroadcaster broadcaster,
LiveSessionRegistry registry,
ILoggerFactory loggerFactory,
Func<string, IReadOnlyList<string>, Func<string, Task>, (ILiveSession session, Task exitTask)>? sessionFactory = null)
{
_dbFactory = dbFactory;
_cfg = cfg;
_broadcaster = broadcaster;
_registry = registry;
_loggerFactory = loggerFactory;
_sessionFactory = sessionFactory;
}
public async Task StartAsync(string taskId, CancellationToken ct)
{
if (_registry.TryGet(taskId, out _))
throw new InvalidOperationException("An interactive session is already running for this task.");
await using var ctx = _dbFactory.CreateDbContext();
var tasks = new TaskRepository(ctx);
var lists = new ListRepository(ctx);
var task = await tasks.GetByIdAsync(taskId, ct)
?? throw new InvalidOperationException($"Task {taskId} not found.");
var list = await lists.GetByIdAsync(task.ListId, ct)
?? throw new InvalidOperationException($"List {task.ListId} not found.");
var workingDir = list.WorkingDir;
if (string.IsNullOrWhiteSpace(workingDir) || !Directory.Exists(workingDir))
throw new InvalidOperationException(
$"List '{list.Name}' has no valid working directory configured.");
var seededPrompt = BuildInteractivePrompt(task);
var args = new[]
{
"-p",
"--input-format", "stream-json",
"--output-format", "stream-json",
"--verbose",
"--replay-user-messages",
"--model", ModelRegistry.PlanningAlias,
"--permission-mode", "auto",
};
Func<string, Task> onLine = line =>
{
_registry.Touch(taskId);
return _broadcaster.TaskMessage(taskId, "[stdout] " + line);
};
ILiveSession session;
Task exitTask;
if (_sessionFactory is not null)
{
// Factory is responsible for providing a ready-to-use session and its exit signal.
(session, exitTask) = _sessionFactory(workingDir, args, onLine);
}
else
{
var transport = new ProcessClaudeStreamTransport(
_cfg,
_loggerFactory.CreateLogger<ProcessClaudeStreamTransport>());
var streamingSession = new StreamingClaudeSession(
transport,
onLine,
_loggerFactory.CreateLogger<StreamingClaudeSession>(),
onQueueChanged: pending => _ = _broadcaster.InteractiveQueueChanged(taskId, pending),
onUserMessageSent: text => _ = _broadcaster.InteractiveMessageSent(taskId, text));
await streamingSession.StartAsync(args, workingDir, seededPrompt, ct);
session = streamingSession;
exitTask = transport.WaitForExitAsync();
}
_registry.Register(taskId, session);
await _broadcaster.InteractiveSessionStarted(taskId);
var logger = _loggerFactory.CreateLogger<InteractiveSessionService>();
_ = WatchExitAsync(taskId, exitTask, logger);
}
private async Task WatchExitAsync(string taskId, Task exitTask, ILogger logger)
{
try
{
await exitTask;
}
catch (Exception ex)
{
logger.LogWarning(ex, "Interactive session exit watcher caught an exception for task {task_id}", taskId);
}
finally
{
_registry.Unregister(taskId);
try { await _broadcaster.InteractiveSessionEnded(taskId); }
catch (Exception ex) { logger.LogWarning(ex, "InteractiveSessionEnded broadcast failed for task {task_id}", taskId); }
}
}
public async Task SendAsync(string taskId, string text, CancellationToken ct)
{
if (!_registry.TryGet(taskId, out var session))
throw new InvalidOperationException("No interactive session is running for this task.");
_registry.Touch(taskId);
await session.SendUserMessageAsync(text, ct);
}
public async Task RemoveQueuedAsync(string taskId, string text, CancellationToken ct)
{
if (_registry.TryGet(taskId, out var session))
{
_registry.Touch(taskId);
await session.RemoveQueuedAsync(text, ct);
}
}
public async Task InterruptAsync(string taskId, CancellationToken ct)
{
if (_registry.TryGet(taskId, out var session))
{
_registry.Touch(taskId);
await session.InterruptAsync(ct);
}
}
public async Task StopAsync(string taskId, CancellationToken ct)
{
// StopAsync removes from registry and kills the session.
// The exit watcher will fire InteractiveSessionEnded once the process exits,
// so we don't broadcast here — the watcher is the single authoritative source.
await _registry.StopAsync(taskId);
}
private static string BuildInteractivePrompt(TaskEntity task)
{
var sb = new StringBuilder();
sb.AppendLine($"# Task: {task.Title}");
if (!string.IsNullOrWhiteSpace(task.Description))
{
sb.AppendLine();
sb.AppendLine(task.Description);
}
return sb.ToString();
}
}
@@ -2,7 +2,7 @@ namespace ClaudeDo.Worker.Planning;
// Launches the Claude CLI in a visible terminal for human-driven planning sessions.
// Not used for headless task execution (that path is ClaudeProcess, prompt over stdin)
// nor for interactive sessions (those use InteractiveSessionService + StreamingClaudeSession).
// nor for embedded ConPTY interactive sessions (those use IInteractiveLaunchSpecService).
public interface ITerminalLauncher
{
Task LaunchPlanningStartAsync(PlanningSessionStartContext ctx, CancellationToken cancellationToken);
-3
View File
@@ -85,9 +85,6 @@ builder.Services.AddSingleton<TaskMergeService>();
builder.Services.AddSingleton<PlanningAggregator>();
builder.Services.AddSingleton<PlanningMergeOrchestrator>();
builder.Services.AddSingleton<PlanningChainCoordinator>();
builder.Services.AddSingleton<LiveSessionRegistry>();
builder.Services.AddSingleton<InteractiveSessionService>();
builder.Services.AddHostedService<IdleSessionReaper>();
// Queue dispatch primitives. QueueWaker holds the wake semaphore; the queue picker
// performs atomic Queued→Running claim. Both injected into the state service so it
@@ -1,49 +0,0 @@
using ClaudeDo.Worker.Config;
namespace ClaudeDo.Worker.Runner;
// Stops interactive/streaming sessions that have gone idle. Interactive `claude` processes wait
// on stdin and never exit on their own, and there is no client-disconnect teardown — so an
// abandoned chat (UI closed, navigated away, crashed) keeps its claude.exe (+ conhost) alive for
// the worker's entire lifetime. Under a long-running autostart worker these pile up (observed:
// ~170 child processes). This sweep reaps the idle ones.
public sealed class IdleSessionReaper : BackgroundService
{
private static readonly TimeSpan SweepInterval = TimeSpan.FromMinutes(5);
private readonly LiveSessionRegistry _registry;
private readonly WorkerConfig _cfg;
private readonly ILogger<IdleSessionReaper> _logger;
public IdleSessionReaper(LiveSessionRegistry registry, WorkerConfig cfg, ILogger<IdleSessionReaper> logger)
{
_registry = registry;
_cfg = cfg;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var idleTimeout = TimeSpan.FromMinutes(_cfg.InteractiveIdleTimeoutMinutes);
if (idleTimeout <= TimeSpan.Zero)
return; // reaper disabled
using var timer = new PeriodicTimer(SweepInterval);
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
var reaped = await _registry.ReapIdleAsync(DateTime.UtcNow, idleTimeout);
if (reaped.Count > 0)
_logger.LogInformation(
"Reaped {session_count} idle interactive session(s) after {idle_minutes} min: {task_ids}",
reaped.Count, _cfg.InteractiveIdleTimeoutMinutes, string.Join(", ", reaped));
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
_logger.LogWarning(ex, "Idle session reap sweep failed");
}
}
}
}
@@ -1,11 +0,0 @@
namespace ClaudeDo.Worker.Runner.Interfaces;
public interface IClaudeStreamTransport : IAsyncDisposable
{
Task StartAsync(IReadOnlyList<string> args, string workingDirectory, CancellationToken ct);
Task WriteLineAsync(string jsonLine, CancellationToken ct);
event Func<string, Task>? LineReceived;
event Func<string, Task>? StderrReceived;
void Kill();
Task WaitForExitAsync();
}
@@ -1,10 +0,0 @@
namespace ClaudeDo.Worker.Runner.Interfaces;
public interface ILiveSession : IAsyncDisposable
{
bool IsTurnInFlight { get; }
Task SendUserMessageAsync(string text, CancellationToken ct);
Task RemoveQueuedAsync(string text, CancellationToken ct);
Task InterruptAsync(CancellationToken ct);
Task StopAsync();
}
@@ -1,87 +0,0 @@
using System.Collections.Concurrent;
using ClaudeDo.Worker.Runner.Interfaces;
namespace ClaudeDo.Worker.Runner;
// Singleton in-memory registry of active live streaming sessions.
// A session's lifetime matches its associated task run; dead entries are removed by the runner.
//
// Interactive (stream-json) sessions never exit on their own — they wait on stdin — and there is
// no client-disconnect teardown, so an abandoned chat would otherwise keep its claude.exe alive
// for the worker's whole lifetime. IdleSessionReaper periodically stops sessions that have seen
// no activity past a timeout (see ReapIdleAsync); Touch() records that activity.
public sealed class LiveSessionRegistry
{
private sealed class Entry
{
public required ILiveSession Session { get; init; }
public long LastActivityTicksUtc;
}
private readonly ConcurrentDictionary<string, Entry> _sessions = new();
public void Register(string taskId, ILiveSession session)
{
if (_sessions.TryRemove(taskId, out var existing))
{
// Best-effort stop of the replaced session; don't await to avoid deadlock risk.
_ = existing.Session.StopAsync().ContinueWith(t =>
{
if (t.IsFaulted) { /* swallow — old session is already orphaned */ }
}, TaskScheduler.Default);
}
_sessions[taskId] = new Entry { Session = session, LastActivityTicksUtc = DateTime.UtcNow.Ticks };
}
// Marks a session as active so the idle reaper leaves it alone. Called on every user
// message and every output line. No-op if the session is not (yet) registered.
public void Touch(string taskId)
{
if (_sessions.TryGetValue(taskId, out var entry))
Interlocked.Exchange(ref entry.LastActivityTicksUtc, DateTime.UtcNow.Ticks);
}
public bool TryGet(string taskId, out ILiveSession session)
{
if (_sessions.TryGetValue(taskId, out var entry))
{
session = entry.Session;
return true;
}
session = null!;
return false;
}
public void Unregister(string taskId) => _sessions.TryRemove(taskId, out _);
public async Task StopAsync(string taskId)
{
if (_sessions.TryRemove(taskId, out var entry))
await entry.Session.StopAsync();
}
// Stops and removes every session whose last activity is older than (nowUtc - idleTimeout),
// skipping any session with a turn in flight (an agent that's actively working, even if quiet).
// Returns the reaped task ids.
public async Task<IReadOnlyList<string>> ReapIdleAsync(DateTime nowUtc, TimeSpan idleTimeout)
{
var cutoffTicks = (nowUtc - idleTimeout).Ticks;
List<string>? reaped = null;
foreach (var kvp in _sessions)
{
var entry = kvp.Value;
if (entry.Session.IsTurnInFlight) continue;
if (Interlocked.Read(ref entry.LastActivityTicksUtc) > cutoffTicks) continue;
if (_sessions.TryRemove(kvp.Key, out var removed))
{
try { await removed.Session.StopAsync(); }
catch { /* already dead — leave it removed */ }
(reaped ??= new()).Add(kvp.Key);
}
}
return reaped ?? (IReadOnlyList<string>)Array.Empty<string>();
}
}
@@ -1,111 +0,0 @@
using System.Diagnostics;
using System.Text;
using ClaudeDo.Worker.Config;
using ClaudeDo.Worker.Runner.Interfaces;
namespace ClaudeDo.Worker.Runner;
public sealed class ProcessClaudeStreamTransport : IClaudeStreamTransport
{
private readonly WorkerConfig _cfg;
private readonly ILogger<ProcessClaudeStreamTransport> _logger;
private Process? _process;
private Task? _stdoutTask;
private Task? _stderrTask;
public event Func<string, Task>? LineReceived;
public event Func<string, Task>? StderrReceived;
public ProcessClaudeStreamTransport(WorkerConfig cfg, ILogger<ProcessClaudeStreamTransport> logger)
{
_cfg = cfg;
_logger = logger;
}
public Task StartAsync(IReadOnlyList<string> args, string workingDirectory, CancellationToken ct)
{
var psi = new ProcessStartInfo
{
FileName = _cfg.ClaudeBin,
WorkingDirectory = workingDirectory,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
};
foreach (var arg in args)
psi.ArgumentList.Add(arg);
psi.Environment["MCP_TOOL_TIMEOUT"] = "200000";
_process = new Process { StartInfo = psi };
_process.Start();
ProcessJobObject.Assign(_process, _logger);
// Keep stdin open — turns are driven by WriteLineAsync calls.
_process.StandardInput.AutoFlush = false;
_stdoutTask = Task.Run(async () =>
{
while (await _process.StandardOutput.ReadLineAsync() is { } line)
{
if (string.IsNullOrEmpty(line)) continue;
var handler = LineReceived;
if (handler is not null)
{
try { await handler(line); }
catch (Exception ex) { _logger.LogWarning(ex, "LineReceived handler threw"); }
}
}
}, CancellationToken.None);
_stderrTask = Task.Run(async () =>
{
while (await _process.StandardError.ReadLineAsync() is { } line)
{
if (string.IsNullOrEmpty(line)) continue;
var handler = StderrReceived;
if (handler is not null)
{
try { await handler(line); }
catch (Exception ex) { _logger.LogWarning(ex, "StderrReceived handler threw"); }
}
}
}, CancellationToken.None);
return Task.CompletedTask;
}
public async Task WriteLineAsync(string jsonLine, CancellationToken ct)
{
if (_process is null) throw new InvalidOperationException("Transport not started.");
await _process.StandardInput.WriteAsync((jsonLine + "\n").AsMemory(), ct);
await _process.StandardInput.FlushAsync(ct);
}
public void Kill()
{
try { _process?.Kill(entireProcessTree: true); }
catch { /* already exited */ }
}
public async Task WaitForExitAsync()
{
if (_process is not null)
await _process.WaitForExitAsync(CancellationToken.None);
if (_stdoutTask is not null) await _stdoutTask;
if (_stderrTask is not null) await _stderrTask;
}
public async ValueTask DisposeAsync()
{
Kill();
await WaitForExitAsync();
_process?.Dispose();
}
}
@@ -1,207 +0,0 @@
using System.Text.Json;
using ClaudeDo.Worker.Runner.Interfaces;
namespace ClaudeDo.Worker.Runner;
public sealed class StreamingClaudeSession : ILiveSession
{
private readonly IClaudeStreamTransport _transport;
private readonly Func<string, Task> _onLine;
private readonly ILogger<StreamingClaudeSession> _logger;
private readonly Action<IReadOnlyList<string>>? _onQueueChanged;
private readonly Action<string>? _onUserMessageSent;
private readonly SemaphoreSlim _sendLock = new(1, 1);
private volatile bool _isTurnInFlight;
private readonly Queue<string> _pending = new();
public bool IsTurnInFlight => _isTurnInFlight;
public StreamingClaudeSession(
IClaudeStreamTransport transport,
Func<string, Task> onLine,
ILogger<StreamingClaudeSession> logger,
Action<IReadOnlyList<string>>? onQueueChanged = null,
Action<string>? onUserMessageSent = null)
{
_transport = transport;
_onLine = onLine;
_logger = logger;
_onQueueChanged = onQueueChanged;
_onUserMessageSent = onUserMessageSent;
}
private IReadOnlyList<string> SnapshotPending() => _pending.ToArray();
public async Task StartAsync(
IReadOnlyList<string> args,
string workingDirectory,
string firstPrompt,
CancellationToken ct)
{
_transport.LineReceived += HandleLineAsync;
await _transport.StartAsync(args, workingDirectory, ct);
await SendTurnAsync(firstPrompt, ct);
_onUserMessageSent?.Invoke(firstPrompt);
}
private async Task HandleLineAsync(string line)
{
try { await _onLine(line); }
catch (Exception ex) { _logger.LogWarning(ex, "onLine callback threw"); }
bool isResult;
try
{
using var doc = JsonDocument.Parse(line);
isResult = doc.RootElement.TryGetProperty("type", out var typeProp)
&& typeProp.GetString() == "result";
}
catch { isResult = false; }
if (!isResult) return;
// Turn ended — flush one queued message if available.
string? flushedText = null;
IReadOnlyList<string>? remainingSnapshot = null;
await _sendLock.WaitAsync();
try
{
_isTurnInFlight = false;
if (_pending.Count > 0)
{
flushedText = _pending.Dequeue();
remainingSnapshot = SnapshotPending();
await SendTurnAsync(flushedText, CancellationToken.None);
}
}
finally
{
_sendLock.Release();
}
if (flushedText is not null)
{
_onQueueChanged?.Invoke(remainingSnapshot!);
_onUserMessageSent?.Invoke(flushedText);
}
}
public async Task SendUserMessageAsync(string text, CancellationToken ct)
{
bool enqueued = false;
IReadOnlyList<string>? snapshot = null;
await _sendLock.WaitAsync(ct);
try
{
if (_isTurnInFlight || _pending.Count > 0)
{
_pending.Enqueue(text);
snapshot = SnapshotPending();
enqueued = true;
}
else
{
await SendTurnAsync(text, ct);
}
}
finally
{
_sendLock.Release();
}
if (enqueued)
_onQueueChanged?.Invoke(snapshot!);
else
_onUserMessageSent?.Invoke(text);
}
public async Task RemoveQueuedAsync(string text, CancellationToken ct)
{
IReadOnlyList<string>? snapshot = null;
await _sendLock.WaitAsync(ct);
try
{
if (_pending.Count == 0) return;
var list = _pending.ToList();
var idx = list.IndexOf(text);
if (idx < 0) return;
list.RemoveAt(idx);
_pending.Clear();
foreach (var item in list)
_pending.Enqueue(item);
snapshot = SnapshotPending();
}
finally
{
_sendLock.Release();
}
if (snapshot is not null)
_onQueueChanged?.Invoke(snapshot);
}
public async Task InterruptAsync(CancellationToken ct)
{
await _sendLock.WaitAsync(ct);
try
{
if (!_isTurnInFlight) return;
var requestId = Guid.NewGuid().ToString();
var payload = JsonSerializer.Serialize(new
{
type = "control_request",
request_id = requestId,
request = new { subtype = "interrupt" }
});
try { await _transport.WriteLineAsync(payload, ct); }
catch (Exception ex) { _logger.LogWarning(ex, "Failed to write interrupt control_request; degrading gracefully."); }
}
finally
{
_sendLock.Release();
}
}
private async Task SendTurnAsync(string text, CancellationToken ct)
{
_isTurnInFlight = true;
var payload = JsonSerializer.Serialize(new
{
type = "user",
message = new
{
role = "user",
content = new[]
{
new { type = "text", text }
}
},
parent_tool_use_id = (string?)null
});
await _transport.WriteLineAsync(payload, ct);
}
public async Task StopAsync()
{
_transport.Kill();
await _transport.WaitForExitAsync();
}
public async ValueTask DisposeAsync()
{
await StopAsync();
await _transport.DisposeAsync();
_sendLock.Dispose();
}
}