feat(interactive): worker launch-spec for embedded ConPTY sessions

Adds InteractiveLaunchSpecService + GetInteractiveLaunchSpec hub method that
prepares a task worktree (session-skills seeding, run env) and returns a
LaunchSpec {cwd,exe,args,env} for a UI-hosted ConPTY terminal. Reuses
ISessionSkillSeeder, TaskRunner.UnionSkillNames, and WindowsTerminalLauncher
resume-arg/resolve logic. Guards mirror ResumeTaskInTerminal; a never-run task
yields a fresh-start spec instead of an error.
This commit is contained in:
mika kuns
2026-07-23 16:47:15 +02:00
parent d91ad2d635
commit 1245e75902
11 changed files with 408 additions and 3 deletions
+15 -1
View File
@@ -130,6 +130,7 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
private readonly InteractiveSessionService _interactive;
private readonly LogRingBuffer? _logBuffer;
private readonly ISessionSkillRegistry _skillRegistry;
private readonly IInteractiveLaunchSpecService? _interactiveLaunchSpec;
public WorkerHub(
QueueService queue,
@@ -157,7 +158,8 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
Runner.PendingQuestionRegistry pendingQuestions,
InteractiveSessionService interactive,
ISessionSkillRegistry skillRegistry,
LogRingBuffer? logBuffer = null)
LogRingBuffer? logBuffer = null,
IInteractiveLaunchSpecService? interactiveLaunchSpec = null)
{
_queue = queue;
_waker = waker;
@@ -185,6 +187,7 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
_interactive = interactive;
_skillRegistry = skillRegistry;
_logBuffer = logBuffer;
_interactiveLaunchSpec = interactiveLaunchSpec;
}
// Persistence boundary for the session_skills JSON-array columns (task/list/global).
@@ -657,6 +660,17 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
}
});
// Builds the launch spec an embedded ConPTY terminal (UI process) needs to open an
// interactive Claude session in a task's worktree -- same worktree prep as an
// autonomous run (session-skills seeding, run env vars), --resume if the task has a
// persisted session or a fresh-start spec otherwise. Guards mirror ResumeTaskInTerminal.
public Task<LaunchSpec> GetInteractiveLaunchSpec(string taskId) => HubGuard(() =>
{
if (_interactiveLaunchSpec is null)
throw new InvalidOperationException("Interactive launch spec service is not configured.");
return _interactiveLaunchSpec.BuildForTaskAsync(taskId, Context.ConnectionAborted);
});
public Task SendInteractiveMessage(string taskId, string text) =>
_interactive.SendAsync(taskId, text, Context.ConnectionAborted);
@@ -106,7 +106,12 @@ public sealed class WindowsTerminalLauncher : ITerminalLauncher
// Resumes a session by id in default (interactive) permission mode: the user drives
// tool approvals in the terminal, unlike planning which pins --permission-mode plan.
internal static string BuildResumeCommand(string claudePath, string claudeSessionId) =>
BuildPwshCommand(claudePath, new[] { "--resume", claudeSessionId });
BuildPwshCommand(claudePath, BuildResumeArgs(claudeSessionId));
// The raw claude CLI args for a --resume launch, shared with InteractiveLaunchSpecService
// (which needs the bare Exe/Args pair for a ConPTY host, not a wrapped pwsh command line).
internal static IReadOnlyList<string> BuildResumeArgs(string claudeSessionId) =>
new[] { "--resume", claudeSessionId };
// Builds the PowerShell command that launches an interactive planning session.
// Arg order matters: variadic flags (--allowedTools, --add-dir) come first; the
@@ -174,7 +179,9 @@ public sealed class WindowsTerminalLauncher : ITerminalLauncher
?? throw new TerminalLaunchException("Failed to start Windows Terminal process.");
}
private static string? Resolve(string pathOrName)
// Not private: reused by InteractiveLaunchSpecService to resolve the claude executable
// for a ConPTY-hosted launch spec the same way a wt-launched terminal resolves it.
internal static string? Resolve(string pathOrName)
{
if (File.Exists(pathOrName))
return pathOrName;
+1
View File
@@ -77,6 +77,7 @@ builder.Services.AddSingleton<PendingQuestionRegistry>();
builder.Services.AddSingleton<IRepoCloner, GitRepoCloner>();
builder.Services.AddSingleton<ISessionSkillRegistry, SessionSkillRegistry>();
builder.Services.AddSingleton<ISessionSkillSeeder, SessionSkillSeeder>();
builder.Services.AddSingleton<IInteractiveLaunchSpecService, InteractiveLaunchSpecService>();
builder.Services.AddSingleton<TaskRunner>();
builder.Services.AddSingleton<WorktreeMaintenanceService>();
builder.Services.AddSingleton<TaskResetService>();
@@ -0,0 +1,95 @@
using ClaudeDo.Data;
using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.Config;
using ClaudeDo.Worker.Planning;
using ClaudeDo.Worker.Skills;
using Microsoft.EntityFrameworkCore;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
namespace ClaudeDo.Worker.Runner;
// Builds the launch spec an embedded ConPTY terminal needs to open an interactive Claude
// session in an existing task's worktree -- the SAME worktree prep as an autonomous run:
// session-skills seeded onto disk (reuses ISessionSkillSeeder + TaskRunner.UnionSkillNames,
// exactly like TaskRunner.RunAsync/ContinueAsync) and the same run environment variables
// (reuses ClaudeProcess's MCP_TOOL_TIMEOUT). Exe/Args reuse WindowsTerminalLauncher's
// --resume argument construction. Guards mirror WorkerHub.ResumeTaskInTerminal, except a
// never-run task (no persisted SessionId) is not an error here -- it's a fresh-start spec.
//
// The run-scoped "claudedo_run" MCP server (AskUser/SuggestImprovement) that TaskRunner
// wires per headless run is intentionally NOT reused: it exists so an unattended run can
// ask the user a question, which is moot when the user is already driving the session by
// hand. The always-on `mcp__claudedo__*` tools remain available via the globally-registered
// MCP server (installer's RegisterMcpStep), exactly as they already are for a plain
// `--resume` pickup in a Windows Terminal window.
public sealed class InteractiveLaunchSpecService : IInteractiveLaunchSpecService
{
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
private readonly ISessionSkillSeeder _skillSeeder;
private readonly ISessionSkillRegistry _skillRegistry;
private readonly string _claudePath;
public InteractiveLaunchSpecService(
IDbContextFactory<ClaudeDoDbContext> dbFactory,
ISessionSkillSeeder skillSeeder,
ISessionSkillRegistry skillRegistry,
WorkerConfig cfg)
{
_dbFactory = dbFactory;
_skillSeeder = skillSeeder;
_skillRegistry = skillRegistry;
_claudePath = cfg.ClaudeBin;
}
public async Task<LaunchSpec> BuildForTaskAsync(string taskId, CancellationToken ct)
{
await using var ctx = await _dbFactory.CreateDbContextAsync(ct);
var task = await new TaskRepository(ctx).GetByIdAsync(taskId, ct)
?? throw new KeyNotFoundException();
if (task.Status is TaskStatus.Running or TaskStatus.Queued)
throw new InvalidOperationException("Can't open an interactive session for a running or queued task -- interrupt it first.");
var worktree = await new WorktreeRepository(ctx).GetByTaskIdAsync(taskId, ct);
if (worktree is null || worktree.State is not (WorktreeState.Active or WorktreeState.Kept))
throw new InvalidOperationException("This task has no active worktree to open a session in.");
if (!Directory.Exists(worktree.Path))
throw new InvalidOperationException("The task's worktree directory no longer exists.");
var listConfig = await new ListRepository(ctx).GetConfigAsync(task.ListId, ct);
var globalSettings = await new AppSettingsRepository(ctx).GetAsync(ct);
var run = await new TaskRunRepository(ctx).GetLatestByTaskIdAsync(taskId, ct);
var requestedSkills = TaskRunner.UnionSkillNames(task.SessionSkills, listConfig?.SessionSkills, globalSettings.SessionSkills);
var skillNames = await FilterToInstalledSkillsAsync(requestedSkills, ct);
await _skillSeeder.SeedAsync(worktree.Path, skillNames, isWorktree: true, ct);
var resolvedClaude = WindowsTerminalLauncher.Resolve(_claudePath)
?? throw new InvalidOperationException($"claude executable not found: {_claudePath}");
var args = run?.SessionId is { Length: > 0 } sessionId
? WindowsTerminalLauncher.BuildResumeArgs(sessionId)
: Array.Empty<string>();
// Same run environment variable ClaudeProcess sets for every headless run: the
// AskUser MCP tool call caps at 60s unless raised, and lifting it is harmless for
// every other tool.
var env = new Dictionary<string, string>
{
["MCP_TOOL_TIMEOUT"] = "200000",
};
return new LaunchSpec(worktree.Path, resolvedClaude, args, env);
}
private async Task<IReadOnlyList<string>> FilterToInstalledSkillsAsync(IReadOnlyList<string> requested, CancellationToken ct)
{
if (requested.Count == 0) return requested;
var installed = (await _skillRegistry.ListAsync(ct))
.Select(s => s.Name)
.ToHashSet(StringComparer.Ordinal);
return requested.Where(installed.Contains).ToList();
}
}
@@ -0,0 +1,10 @@
namespace ClaudeDo.Worker.Runner;
public interface IInteractiveLaunchSpecService
{
/// <summary>Builds a LaunchSpec for opening an interactive session in an existing task's
/// worktree. Throws KeyNotFoundException if the task doesn't exist, InvalidOperationException
/// if it's Running/Queued or has no usable worktree. A task that has never run (no persisted
/// SessionId) is not an error -- the spec omits --resume for a fresh start.</summary>
Task<LaunchSpec> BuildForTaskAsync(string taskId, CancellationToken ct);
}
+10
View File
@@ -0,0 +1,10 @@
namespace ClaudeDo.Worker.Runner;
// What an embedded ConPTY terminal (UI process) needs to start a real `claude` process for
// a task's worktree, with the same setup as an autonomous run (session-skills seeded onto
// disk, the same run environment variables) plus the --resume-vs-fresh-start choice.
public sealed record LaunchSpec(
string Cwd,
string Exe,
IReadOnlyList<string> Args,
IReadOnlyDictionary<string, string> Env);