refactor(worker): make the list-handler launch spec single-list and single-repo

This commit is contained in:
Mika Kuns
2026-07-27 15:02:50 +02:00
parent 40eb979924
commit 4877802bcd
11 changed files with 85 additions and 120 deletions
@@ -86,8 +86,8 @@ public interface IWorkerClient : INotifyPropertyChanged
/// no task, no worktree.</summary>
Task<LaunchSpec> GetAdHocLaunchSpecAsync(string directory, CancellationToken ct = default);
/// <summary>Launch spec for an embedded ConPTY "merge helper" session that drives the given
/// tasks to a merged/Done state. listId scopes the session to that list; null = all lists.</summary>
Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct = default);
/// tasks to a merged/Done state. listId scopes the session (and cwd) to that list.</summary>
Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string listId, 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);
+1 -1
View File
@@ -522,7 +522,7 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerC
public async Task<LaunchSpec> GetAdHocLaunchSpecAsync(string directory, CancellationToken ct = default)
=> await _hub.InvokeAsync<LaunchSpec>("GetAdHocLaunchSpec", directory, ct);
public async Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct = default)
public async Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string listId, CancellationToken ct = default)
=> await _hub.InvokeAsync<LaunchSpec>("GetMergeHelperLaunchSpec", taskIds, listId, ct);
public async Task<LaunchSpec> GetPlanningStartLaunchSpecAsync(string taskId, CancellationToken ct = default)
@@ -16,8 +16,8 @@ namespace ClaudeDo.Ui.ViewModels.Islands;
public enum ListKind { Smart, Virtual, User }
/// <summary>Confirmed merge-helper run: the scope list (null = all lists) and the ordered selected task ids.</summary>
public sealed record MergeHelperRequest(string? ListId, IReadOnlyList<string> TaskIds);
/// <summary>Confirmed handler run: the scope list and the ordered selected task ids.</summary>
public sealed record MergeHelperRequest(string ListId, IReadOnlyList<string> TaskIds);
public sealed partial class ListsIslandViewModel : ViewModelBase, IDisposable
{
@@ -322,23 +322,20 @@ public sealed partial class MissionControlViewModel : ViewModelBase, IDisposable
}
}
// Merge-helper session over a hand-picked set of tasks ("Let Claude handle it").
// List-handler session over a hand-picked set of tasks ("Let Claude handle it").
// Ad-hoc style: no owning task, never deduped — every run opens a fresh pane.
public async System.Threading.Tasks.Task OpenMergeHelperConPtySessionAsync(string? listId, IReadOnlyList<string> taskIds)
public async System.Threading.Tasks.Task OpenMergeHelperConPtySessionAsync(string listId, IReadOnlyList<string> taskIds)
{
if (taskIds is not { Count: > 0 }) return;
var title = Loc.T("missionControl.mergeHelperTitle");
if (listId is not null)
try
{
try
{
await using var ctx = await _dbFactory.CreateDbContextAsync();
var list = await ctx.Lists.AsNoTracking().FirstOrDefaultAsync(l => l.Id == listId);
if (list?.Name is { Length: > 0 } name) title = $"{title} — {name}";
}
catch { /* best-effort title lookup */ }
await using var ctx = await _dbFactory.CreateDbContextAsync();
var list = await ctx.Lists.AsNoTracking().FirstOrDefaultAsync(l => l.Id == listId);
if (list?.Name is { Length: > 0 } name) title = $"{title} — {name}";
}
catch { /* best-effort title lookup */ }
try
{
+2 -2
View File
@@ -678,8 +678,8 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
// Builds the launch spec for an embedded ConPTY "merge helper" session that drives the given
// tasks to a merged/Done state via the mcp__claudedo__* tools. listId scopes the brief label
// and cwd to that list; null means all lists.
public Task<LaunchSpec> GetMergeHelperLaunchSpec(string[] taskIds, string? listId) => HubGuard(() =>
// and cwd to that list.
public Task<LaunchSpec> GetMergeHelperLaunchSpec(string[] taskIds, string listId) => HubGuard(() =>
{
if (_interactiveLaunchSpec is null)
throw new InvalidOperationException("Interactive launch spec service is not configured.");
@@ -163,51 +163,28 @@ public sealed class InteractiveLaunchSpecService : IInteractiveLaunchSpecService
private const string MergeHelperAllowedTools =
"mcp__claudedo__*,Read,Grep,Glob,Edit,Bash,WebFetch,WebSearch,Skill";
public async Task<LaunchSpec> BuildForMergeHelperAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct)
public async Task<LaunchSpec> BuildForMergeHelperAsync(IReadOnlyList<string> taskIds, string listId, CancellationToken ct)
{
if (taskIds.Count == 0)
throw new InvalidOperationException("No tasks selected for the merge helper.");
throw new InvalidOperationException("No tasks selected for the list handler.");
await using var ctx = await _dbFactory.CreateDbContextAsync(ct);
var taskRepo = new TaskRepository(ctx);
var listRepo = new ListRepository(ctx);
var listsById = new Dictionary<string, ListEntity?>();
var briefLines = new List<string>();
var repoDirs = new List<string>(); // distinct, existing, in first-seen order
var list = await listRepo.GetByIdAsync(listId, ct)
?? throw new KeyNotFoundException($"List not found: {listId}");
var repoDir = list.WorkingDir;
if (string.IsNullOrEmpty(repoDir) || !Directory.Exists(repoDir))
throw new InvalidOperationException($"list '{list.Name}' has no existing working directory");
var briefLines = new List<string>();
foreach (var id in taskIds)
{
var task = await taskRepo.GetByIdAsync(id, ct)
?? throw new KeyNotFoundException($"Task not found: {id}");
if (!listsById.TryGetValue(task.ListId, out var list))
listsById[task.ListId] = list = await listRepo.GetByIdAsync(task.ListId, ct);
var workingDir = list?.WorkingDir;
if (!string.IsNullOrEmpty(workingDir) && Directory.Exists(workingDir) && !repoDirs.Contains(workingDir))
repoDirs.Add(workingDir);
briefLines.Add(
$"- [{task.Status}] {task.Title} (id: {task.Id}, list: {list?.Name ?? ""}, " +
$"repo: {(string.IsNullOrEmpty(workingDir) ? "" : workingDir)})");
}
if (repoDirs.Count == 0)
throw new InvalidOperationException("none of the selected tasks are in a working directory");
string scopeLabel;
string cwd;
if (listId is not null)
{
var scopeList = await listRepo.GetByIdAsync(listId, ct)
?? throw new KeyNotFoundException($"List not found: {listId}");
scopeLabel = $"List: {scopeList.Name}";
cwd = scopeList.WorkingDir is { Length: > 0 } wd && Directory.Exists(wd) ? wd : repoDirs[0];
}
else
{
scopeLabel = "All lists";
cwd = repoDirs[0];
briefLines.Add($"- [{task.Status}] {task.Title} (id: {task.Id})");
}
var sessionDir = Path.Combine(Paths.AppDataRoot(), "merge-helper-sessions", Guid.NewGuid().ToString());
@@ -220,7 +197,8 @@ public sealed class InteractiveLaunchSpecService : IInteractiveLaunchSpecService
await File.WriteAllTextAsync(briefPath, PromptFiles.Render(PromptKind.MergeHelperInitial,
new Dictionary<string, string>
{
["scope"] = scopeLabel,
["scope"] = $"List: {list.Name}",
["repo"] = repoDir,
["tasks"] = string.Join("\n", briefLines),
}), ct);
@@ -235,21 +213,18 @@ public sealed class InteractiveLaunchSpecService : IInteractiveLaunchSpecService
{
"--permission-mode", "default",
"--allowedTools", MergeHelperAllowedTools,
"--add-dir", sessionDir,
"--add-dir", sessionDir, repoDir,
"--append-system-prompt-file", systemPromptPath,
$"Read the file {briefPath} first. It lists the tasks you must handle and their status. " +
"After reading it, begin the session as your instructions describe.",
};
args.AddRange(repoDirs);
args.Add("--append-system-prompt-file");
args.Add(systemPromptPath);
args.Add(
$"Read the file {briefPath} first. It lists the tasks you must merge and their status. " +
"After reading it, begin the merge-helper session as your instructions describe.");
var env = new Dictionary<string, string>
{
["MCP_TOOL_TIMEOUT"] = "200000",
};
return new LaunchSpec(cwd, resolvedClaude, args, env);
return new LaunchSpec(repoDir, resolvedClaude, args, env);
}
// The positional prompt claude opens the interactive session on. Empty (no positional arg)
@@ -30,8 +30,8 @@ public interface IInteractiveLaunchSpecService
/// <summary>Builds a LaunchSpec for an embedded ConPTY "merge helper" session that drives the
/// given tasks to a merged/Done state via the mcp__claudedo__* tools. Writes a per-session
/// system prompt + task brief under ~/.todo-app/merge-helper-sessions/&lt;guid&gt; and exposes
/// that dir plus every distinct existing repo dir via --add-dir. listId scopes the brief label
/// and the cwd to that list; null means all lists (cwd = first existing repo dir). Throws
/// InvalidOperationException if taskIds is empty or no task has an existing working directory.</summary>
Task<LaunchSpec> BuildForMergeHelperAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct);
/// that dir plus the list's repo dir via --add-dir. cwd is the list's working directory.
/// Throws KeyNotFoundException if the list doesn't exist; InvalidOperationException if
/// taskIds is empty or the list has no existing working directory.</summary>
Task<LaunchSpec> BuildForMergeHelperAsync(IReadOnlyList<string> taskIds, string listId, CancellationToken ct);
}
+1 -1
View File
@@ -100,7 +100,7 @@ public abstract class StubWorkerClient : IWorkerClient
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public virtual Task<LaunchSpec> GetAdHocLaunchSpecAsync(string directory, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(directory, "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public virtual Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct = default)
public virtual Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string listId, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public virtual Task<LaunchSpec> GetPlanningStartLaunchSpecAsync(string taskId, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
@@ -408,7 +408,7 @@ public class MissionControlViewModelTests : IDisposable
private sealed class ThrowingMergeHelperLaunchSpecWorker : StubWorkerClient
{
public override Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct = default)
public override Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string listId, CancellationToken ct = default)
=> throw new InvalidOperationException("spec failed");
}
@@ -418,7 +418,7 @@ public class MissionControlViewModelTests : IDisposable
var worker = new FakeWorker();
using var vm = BuildVm(worker);
await vm.OpenMergeHelperConPtySessionAsync(null, new[] { "t1", "t2" });
await vm.OpenMergeHelperConPtySessionAsync("L1", new[] { "t1", "t2" });
Assert.Single(vm.ConPtySessions);
Assert.Null(vm.ConPtySessions[0].TaskId);
@@ -432,8 +432,8 @@ public class MissionControlViewModelTests : IDisposable
var worker = new FakeWorker();
using var vm = BuildVm(worker);
await vm.OpenMergeHelperConPtySessionAsync(null, new[] { "t1" });
await vm.OpenMergeHelperConPtySessionAsync(null, new[] { "t1" });
await vm.OpenMergeHelperConPtySessionAsync("L1", new[] { "t1" });
await vm.OpenMergeHelperConPtySessionAsync("L1", new[] { "t1" });
Assert.Equal(2, vm.ConPtySessions.Count);
}
@@ -444,7 +444,7 @@ public class MissionControlViewModelTests : IDisposable
var worker = new FakeWorker();
using var vm = BuildVm(worker);
await vm.OpenMergeHelperConPtySessionAsync(null, Array.Empty<string>());
await vm.OpenMergeHelperConPtySessionAsync("L1", Array.Empty<string>());
Assert.Empty(vm.ConPtySessions);
Assert.Empty(vm.Panes);
@@ -458,7 +458,7 @@ public class MissionControlViewModelTests : IDisposable
string? error = null;
vm.ErrorReported += msg => error = msg;
await vm.OpenMergeHelperConPtySessionAsync(null, new[] { "t1" });
await vm.OpenMergeHelperConPtySessionAsync("L1", new[] { "t1" });
Assert.Empty(vm.ConPtySessions);
Assert.Empty(vm.Panes);
@@ -363,13 +363,14 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
[Fact]
public async Task BuildForMergeHelperAsync_EmptyTaskIds_ThrowsInvalidOperation()
{
var listId = await SeedListAsync(workingDir: _tempDir);
var svc = BuildService();
await Assert.ThrowsAsync<InvalidOperationException>(
() => svc.BuildForMergeHelperAsync(Array.Empty<string>(), null, CancellationToken.None));
() => svc.BuildForMergeHelperAsync(Array.Empty<string>(), listId, CancellationToken.None));
}
[Fact]
public async Task BuildForMergeHelperAsync_NoExistingWorkingDirs_ThrowsInvalidOperation()
public async Task BuildForMergeHelperAsync_ListWithoutExistingWorkingDir_ThrowsInvalidOperation()
{
var listId = await SeedListAsync(workingDir: Path.Combine(_tempDir, "gone"));
var taskId = Guid.NewGuid().ToString();
@@ -377,53 +378,56 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
var svc = BuildService();
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => svc.BuildForMergeHelperAsync(new[] { taskId }, null, CancellationToken.None));
() => svc.BuildForMergeHelperAsync(new[] { taskId }, listId, CancellationToken.None));
Assert.Contains("working directory", ex.Message);
}
[Fact]
public async Task BuildForMergeHelperAsync_TasksAcrossTwoRepos_BuildsGlobalScopeSpec()
public async Task BuildForMergeHelperAsync_UnknownList_Throws()
{
var repoA = Path.Combine(_tempDir, "repoA");
var repoB = Path.Combine(_tempDir, "repoB");
Directory.CreateDirectory(repoA);
Directory.CreateDirectory(repoB);
var listA = await SeedListAsync(workingDir: repoA, name: "Alpha");
var listB = await SeedListAsync(workingDir: repoB, name: "Beta");
var t1 = Guid.NewGuid().ToString();
var t2 = Guid.NewGuid().ToString();
var t3 = Guid.NewGuid().ToString();
await SeedTaskAsync(t1, listA, TaskStatus.WaitingForReview, title: "First task");
await SeedTaskAsync(t2, listB, TaskStatus.Idle, title: "Second task");
await SeedTaskAsync(t3, listA, TaskStatus.Failed, title: "Third task"); // same repo as t1 -> distinct
var listId = await SeedListAsync(workingDir: _tempDir);
var taskId = Guid.NewGuid().ToString();
await SeedTaskAsync(taskId, listId, TaskStatus.Idle);
var svc = BuildService();
var spec = await svc.BuildForMergeHelperAsync(new[] { t1, t2, t3 }, null, CancellationToken.None);
await Assert.ThrowsAsync<KeyNotFoundException>(
() => svc.BuildForMergeHelperAsync(new[] { taskId }, "no-such-list", CancellationToken.None));
}
[Fact]
public async Task BuildForMergeHelperAsync_BuildsListScopedSpecWithSingleRepo()
{
var repo = Path.Combine(_tempDir, "repoOnly");
Directory.CreateDirectory(repo);
var listId = await SeedListAsync(workingDir: repo, name: "Alpha");
var t1 = Guid.NewGuid().ToString();
var t2 = Guid.NewGuid().ToString();
await SeedTaskAsync(t1, listId, TaskStatus.WaitingForReview, title: "First task");
await SeedTaskAsync(t2, listId, TaskStatus.Idle, title: "Second task");
var svc = BuildService();
var spec = await svc.BuildForMergeHelperAsync(new[] { t1, t2 }, listId, CancellationToken.None);
var sessionDir = TrackSessionDir(spec);
// cwd: no listId -> first existing repo dir.
Assert.Equal(repoA, spec.Cwd);
Assert.Equal(repo, spec.Cwd);
Assert.Equal(_claudeStubPath, spec.Exe);
var args = spec.Args.ToList();
// --permission-mode default
var pmIdx = args.IndexOf("--permission-mode");
Assert.True(pmIdx >= 0);
Assert.Equal("default", args[pmIdx + 1]);
// allowedTools string for the merge helper
var atIdx = args.IndexOf("--allowedTools");
Assert.Equal("mcp__claudedo__*,Read,Grep,Glob,Edit,Bash,WebFetch,WebSearch,Skill", args[atIdx + 1]);
// --add-dir: session dir + BOTH distinct repo dirs (repoA only once)
// --add-dir: session dir + the list's single repo dir
var addIdx = args.IndexOf("--add-dir");
var appendIdx = args.IndexOf("--append-system-prompt-file");
var addDirs = args.GetRange(addIdx + 1, appendIdx - addIdx - 1);
Assert.Equal(new[] { sessionDir, repoA, repoB }, addDirs);
Assert.Equal(new[] { sessionDir, repo }, addDirs);
// system prompt file follows --append-system-prompt-file
var systemPromptPath = args[appendIdx + 1];
Assert.Equal(Path.Combine(sessionDir, "system-prompt.md"), systemPromptPath);
Assert.True(File.Exists(systemPromptPath));
@@ -434,43 +438,32 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
Assert.Contains(briefPath, kickoff);
Assert.DoesNotContain('\n', kickoff);
// brief exists, carries the scope label and every task's title
Assert.True(File.Exists(briefPath));
var brief = File.ReadAllText(briefPath);
Assert.Contains("Scope: All lists", brief);
Assert.Contains("First task", brief);
Assert.Contains("Second task", brief);
Assert.Contains("Third task", brief);
Assert.Equal("200000", spec.Env["MCP_TOOL_TIMEOUT"]);
}
[Fact]
public async Task BuildForMergeHelperAsync_WithListId_UsesListWorkingDirAsCwdAndListScope()
public async Task BuildForMergeHelperAsync_BriefNamesListRepoAndEveryTask()
{
var repoA = Path.Combine(_tempDir, "repoA2");
var repoB = Path.Combine(_tempDir, "repoB2");
Directory.CreateDirectory(repoA);
Directory.CreateDirectory(repoB);
var repo = Path.Combine(_tempDir, "repoBrief");
Directory.CreateDirectory(repo);
var listA = await SeedListAsync(workingDir: repoA, name: "Alpha");
var listB = await SeedListAsync(workingDir: repoB, name: "Beta");
var listId = await SeedListAsync(workingDir: repo, name: "Alpha");
var t1 = Guid.NewGuid().ToString();
var t2 = Guid.NewGuid().ToString();
await SeedTaskAsync(t1, listA, TaskStatus.WaitingForReview, title: "Task in Alpha");
await SeedTaskAsync(t2, listB, TaskStatus.WaitingForReview, title: "Task in Beta");
await SeedTaskAsync(t1, listId, TaskStatus.WaitingForReview, title: "First task");
await SeedTaskAsync(t2, listId, TaskStatus.Idle, title: "Second task");
var svc = BuildService();
// Scope on listB even though listA's task comes first: cwd must be listB's repo.
var spec = await svc.BuildForMergeHelperAsync(new[] { t1, t2 }, listB, CancellationToken.None);
var spec = await svc.BuildForMergeHelperAsync(new[] { t1, t2 }, listId, CancellationToken.None);
var sessionDir = TrackSessionDir(spec);
Assert.Equal(repoB, spec.Cwd);
var brief = File.ReadAllText(Path.Combine(sessionDir, "brief.md"));
Assert.Contains("Scope: List: Beta", brief);
Assert.Contains("Task in Alpha", brief);
Assert.Contains("Task in Beta", brief);
Assert.Contains("Scope: List: Alpha", brief);
Assert.Contains($"Repo: {repo}", brief);
Assert.Contains("First task", brief);
Assert.Contains("Second task", brief);
Assert.Contains(t1, brief);
Assert.Contains(t2, brief);
}
[Fact]
@@ -75,7 +75,7 @@ sealed class FakeWorkerClient : IWorkerClient
public Task SubmitTaskForReviewAsync(string taskId, CancellationToken ct = default) => Task.CompletedTask;
public Task<LaunchSpec> GetInteractiveLaunchSpecAsync(string taskId, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct = default)
public Task<LaunchSpec> GetMergeHelperLaunchSpecAsync(IReadOnlyList<string> taskIds, string listId, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public Task<LaunchSpec> GetAdHocLaunchSpecAsync(string directory, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(directory, "claude", Array.Empty<string>(), new Dictionary<string, string>()));